问:
Excluding query result with in and not in
I have two tables:

Person (BusinessEntityID, FirstName, LastName)

Sales (OrderID, CustomerID, OrderDate)

I want to list people that made orders both in 2011 and 2014 but never made orders in 2012 and 2013

I would expect this query to work, but it is still listing orders in 2013

```<code>SELECT
    s.CustomerID,p.LastName,p.FirstName, s.OrderDate
FROM
    Sales.SalesOrderHeader s,Person.Person p
WHERE
    s.CustomerID = p.BusinessEntityID
    AND s.CustomerID IN (SELECT CustomerID
                         FROM Sales.SalesOrderHeader
                         WHERE YEAR(OrderDate) IN (2011, 2014)
                         GROUP BY CustomerID
                         HAVING COUNT(CustomerID) > 1)
    AND s.CustomerID NOT IN (SELECT CustomerID
                             FROM Sales.SalesOrderHeader
                             WHERE YEAR(OrderDate) IN (2012, 2013)
                             GROUP BY CustomerID
                             HAVING COUNT(CustomerID) > 1)
GROUP BY
    s.CustomerID, p.LastName, p.FirstName, s.OrderDate
</code>```

Results:

```<code>CustomerID     LastName    FirstName    OrderDate
---------------------------------------------------------------
11001          Young       Amber        2011-06-17 00:00:00.000
11001          Young       Amber        2013-06-18 00:00:00.000
11001          Young       Amber        2014-05-12 00:00:00.000
11017          Clark       Chloe        2011-06-14 00:00:00.000
11017          Clark       Chloe        2013-06-03 00:00:00.000
11017          Clark       Chloe        2014-03-16 00:00:00.000
11018          Mehta       Joe          2011-06-19 00:00:00.000
11018          Mehta       Joe          2013-06-18 00:00:00.000
11018          Mehta       Joe          2014-03-26 00:00:00.000
</code>```

答:
If you are using SQL Server, I think you can get the results you want with the EXCEPT keyword as in the following query. I am not able to test it right now though so I might be wrong...</p>

```<code>SELECT s.CustomerID,p.LastName,p.FirstName, s.OrderDate
FROM Sales.SalesOrderHeader s,Person.Person p
WHERE s.CustomerID = p.BusinessEntityID
AND Year(s.OrderDate) IN (2011, 2014)

EXCEPT

SELECT s.CustomerID,p.LastName,p.FirstName, s.OrderDate
FROM Sales.SalesOrderHeader s,Person.Person p
WHERE s.CustomerID = p.BusinessEntityID
AND Year(s.OrderDate) IN (2012, 2013)
</code>```

Body:
I have two tables:

Person (BusinessEntityID, FirstName, LastName)

Sales (OrderID, CustomerID, OrderDate)

I want to list people that made orders both in 2011 and 2014 but never made orders in 2012 and 2013

I would expect this query to work, but it is still listing orders in 2013

SELECT
    s.CustomerID,p.LastName,p.FirstName, s.OrderDate
FROM
    Sales.SalesOrderHeader s,Person.Person p
WHERE
    s.CustomerID = p.BusinessEntityID
    AND s.CustomerID IN (SELECT CustomerID
                         FROM Sales.SalesOrderHeader
                         WHERE YEAR(OrderDate) IN (2011, 2014)
                         GROUP BY CustomerID
                         HAVING COUNT(CustomerID) > 1)
    AND s.CustomerID NOT IN (SELECT CustomerID
                             FROM Sales.SalesOrderHeader
                             WHERE YEAR(OrderDate) IN (2012, 2013)
                             GROUP BY CustomerID
                             HAVING COUNT(CustomerID) > 1)
GROUP BY
    s.CustomerID, p.LastName, p.FirstName, s.OrderDate

Results:

CustomerID     LastName    FirstName    OrderDate
---------------------------------------------------------------
11001          Young       Amber        2011-06-17 00:00:00.000
11001          Young       Amber        2013-06-18 00:00:00.000
11001          Young       Amber        2014-05-12 00:00:00.000
11017          Clark       Chloe        2011-06-14 00:00:00.000
11017          Clark       Chloe        2013-06-03 00:00:00.000
11017          Clark       Chloe        2014-03-16 00:00:00.000
11018          Mehta       Joe          2011-06-19 00:00:00.000
11018          Mehta       Joe          2013-06-18 00:00:00.000
11018          Mehta       Joe          2014-03-26 00:00:00.000

Body:
If you are using SQL Server, I think you can get the results you want with the EXCEPT keyword as in the following query. I am not able to test it right now though so I might be wrong...

SELECT s.CustomerID,p.LastName,p.FirstName, s.OrderDate
FROM Sales.SalesOrderHeader s,Person.Person p
WHERE s.CustomerID = p.BusinessEntityID
AND Year(s.OrderDate) IN (2011, 2014)

EXCEPT

SELECT s.CustomerID,p.LastName,p.FirstName, s.OrderDate
FROM Sales.SalesOrderHeader s,Person.Person p
WHERE s.CustomerID = p.BusinessEntityID
AND Year(s.OrderDate) IN (2012, 2013)


来源: stackexchange

问:
Validate JSON file syntax in shell script without installing any package
How can I validate the syntax of a JSON file in shell script without installing any package?</p>

答:
I have yet to find a system where python -mjson.tool doesn't work. So you can do:

```<code>python -mjson.tool "$somefile" > /dev/null
</code>```

The exit code will be nonzero and you get the parse error on stderr if the file is not valid JSON.

Note: The Python libraries don't follow the JSON spec and allow NaN and Infinity as values. So using json.tool will let some errors slip through. Still it's good enough for my use case of catching errors in human-written documents early.

ContentLicense: CC BY-SA 3.0

Body:
I have yet to find a system where python -mjson.tool doesn't work. So you can do:

python -mjson.tool "$somefile" > /dev/null

The exit code will be nonzero and you get the parse error on stderr if the file is not valid JSON.

Note: The Python libraries don't follow the JSON spec and allow NaN and Infinity as values. So using json.tool will let some errors slip through. Still it's good enough for my use case of catching errors in human-written documents early.

ContentLicense: CC BY-SA 4.0


问:
On key press of Enter, click a button in vuejs
Here is my fiddle: DEMO

There is a button called "fb-send", which has to get clicked on key press on "enter" in the input field. How to achieve this?

```<code><input @keyup.enter="" placeholder="Reply here" class="fb-comment-input" />
<i class="material-icons fb-button-right fb-send">⇨</i>
</code>```

Any help would be much appreciated. Thank you.

答:
```<code>        $("form").keypress(function (e) {
            debugger;
            if(e.charCode == 13){
                e.stopImmediatePropagation();
                e.preventDefault();
            }
        });
</code>```

Body:
Here is my fiddle: DEMO

There is a button called "fb-send", which has to get clicked on key press on "enter" in the input field. How to achieve this?

<input @keyup.enter="" placeholder="Reply here" class="fb-comment-input" />
⇨

Any help would be much appreciated. Thank you.


问:
Usage of __slots__?
What is the purpose of __slots__ in Python — especially with respect to when I would want to use it, and when not?

答:
Each python object has a __dict__ atttribute which is a dictionary containing all other attributes. e.g. when you type self.attr python is actually doing self.__dict__['attr']. As you can imagine using a dictionary to store attribute takes some extra space & time for accessing it.

However, when you use __slots__, any object created for that class won't have a __dict__ attribute. Instead, all attribute access is done directly via pointers.

So if want a C style structure rather than a full fledged class you can use __slots__ for compacting size of the objects & reducing attribute access time. A good example is a Point class containing attributes x & y. If you are going to have a lot of points, you can try using __slots__ in order to conserve some memory.

OwnerDisplayName: Jeb

Title: Usage of __slots__?

LastEditorDisplayName: Roger Pate


问:
How to triangulate a polygon without random inner points?
I would like to create triangles a predefined polygon. My requirement is that I don't want to create random points inside of this polygon for processing it with a Delaunay Triangulation algorithm.

The polygon can be concave or convex.

It's totally ok for me to use a Delaunay Triangulation but I don't want to create random points inside the polygon. It would be much nicer if I can create as less points as possible inside this polygon.

I would like to minimize the number of used triangles.

How can I establish this?

Comment: It's more a language agnostic thing, I like to know how to implement this on my own.

答:
You can use Ear Clipping or monotone polygons.  Neither algorithm will introduce extra points.  </p>

<p>(If you choose to form monotone polygons, the monotone polygons are convex, and can be broken into triangle fans directly.)</p>

ContentLicense: CC BY-SA 2.5

Body:
You can use Ear Clipping or monotone polygons.  Neither algorithm will introduce extra points.

(If you choose to form monotone polygons, the monotone polygons are convex, and can be broken into triangle fans directly.)


问:
How to publish a FireFox WebExtension for local installation only?
How can I permanently install my (toy) WebExtension without having to publish it via Mozilla Addons (AMO), when my extension is just a small group of CSS hacks not meant to be published.

The other option, installing it only permanently would be cumbersome to do everytime I need the extension.

EDIT:

To add further input, the page I've linked to says

Zip up your extension's files Edit

At this point your extension will consist of a directory containing a
manifest.json and any other files it needs - scripts, icons, HTML
documents, and so on. You'll need to zip these into a single file for
uploading to AMO.

One trick is that the ZIP file must be a ZIP of the extension's files
themselves, not of the containing directory.

and also

Packaged extensions in Firefox are called "XPI files", which are just
ZIP files with a different extension.

You don't have to use the XPI extension when uploading to AMO.

In about:addons you can install from file, but whatever way I try to package my extension I get:

even after observing and trying the quoted passage above.

The temporary installation works fine.

答:
You can sign your extension by AMO without publish it.

Then just put an xpi file into

```<code>%appdata%\Mozilla\Extensions{ec8030f7-c20a-464f-9b0e-13a3a9e97384}
</code>```

the browser will accept it.

Body:
You can sign your extension by AMO without publish it.

Then just put an xpi file into

%appdata%\Mozilla\Extensions{ec8030f7-c20a-464f-9b0e-13a3a9e97384}

the browser will accept it.


问:
How to correctly malloc a struct in C
Here is my full code, it looks like to work, but it's not working very well.
I would accept any code, that is working like this.

Firstly, the code works, but when I want to add the third name to the struct, it crashes.

Is there any other way to do this?

I need struct, because in the future, I want to add some other params, like age, average, gender, etc.

Please, help me out.

```<code>//The student table
typedef struct students {
    char name[50];
} students;

//Global params
int scount = 0;
students *s;

//Basic functions
void addNewStudent();

int main()
{
    int loop = 1;
    char in;
    int ch;
    printf("Willkommen.\n Wahlen Sie bitte von die folgenden Optionen:\n");
    while (loop)
    {
        printf("\t[1] Neue Student eingeben\n");
        printf("\t[9] Programm beenden\n");

        scanf(" %c", &in);
        while ((ch = getchar()) != '\n');
        switch (in)
        {
        case '1':
            addNewStudent();
            break;
        case '9':
            loop = 0;
            break;
        default: printf("------\nOption nicht gefunden.\n------\n");
            break;
        }
    }
    free(s);
    return 0;
}

void addNewStudent()
{
    int index = 0;
    if (scount == 0)
    {
        s = (students*)malloc(sizeof(students));
    }
    else
    {
        realloc(s, sizeof(students) * scount);
    }

    printf("Geben Sie Bitte die Name:\n");
    fgets(s[scount].name, sizeof(s[scount].name), stdin);

    while (s[scount].name[index] != '\n')
    {
        index++;
    }
    s[scount].name[index] = '\0';
    scount++;
}
</code>```

I'm using Visual Studio.

Thanks for help!

答:
```<code>students *mynew= realloc(s, sizeof(students)* (scount+1));
if( mynew != NULL )
    s=mynew;
</code>```

Otehrwise you are having a memory leak. You didn't use the return value of realloc.

Don't cast the return type of malloc.

As per standard §7.22.2.35

```<code>void *realloc(void *ptr, size_t size)
</code>```

The realloc function deallocates the old object pointed to by ptr and
  returns a pointer to a new object that has the size specified by size.

It is good not to use the same pointer variable on which you are calling malloc because in case it fails you will lose reference to the old one too (unless it is stored by other means).

Also you didn't check the return value of malloc.

```<code>s = malloc(sizeof(students));
if( s == NULL ){
   frpntf(stderr,"%s","Memory allocation failed");
   exit(1);
}
</code>```

Also you should check the return value of fgets().

```<code>if( fgets(s[scount].name, sizeof(s[scount].name), stdin) == NULL){
     fprintf(stderr,"%s","Error in input");
     exit(1);
}
</code>```

Also trying to compile your code it showed this

```<code>warning: ignoring return value of ‘realloc’, declared with attribute warn_unused_result [-Wunused-result]
         realloc(s, sizeof(students) * scount);
         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</code>```

When compiling try not to ignore any warning messages. It showed the problem you had.

Important point: (why scount+1 in realloc?)

When reallocating the general idea is increase the number of students. And for that you need to have extra memory allocated for an student. That's why the scount+1 in the code.(realloc).

Some other points:

```<code>while (s[scount].name[index] != '\n')
{
    index++;
}
s[scount].name[index] = '\0';
</code>```

You can do it like this also

```<code>size_t len = strlen(s[scount].name);
if(len){
   s[scount].name[len-1]='\0';
}
</code>```

To understand why from standard §7.21.7.2

```<code>char *fgets(char * restrict s, int n,FILE * restrict stream)
</code>```

The fgets function reads at most one less than the number of
  characters specified by n from the stream pointed to by stream into
  the array pointed to by s. No additional characters are read after a
  new-line character (which is retained) or after end-of-file. A null
  character is written immediately after the last character read into
  the array.

\0 character was there already in the inputted string. You can get the length of it but you know that the one before the \0 is the \n character 1 that you entered by pressing the Enter key. We are overwriting it with the \0.

1. This is the usual case but not the only one. There are two cases where this might not be the right way to look at the thing.

The input line has n-1 or more characters before the '\n'. The the one before \0 will not be the \n rather it will be some character inputted by the user.

The last line is a stream which may not have a '\n'. (stdin closed). In that case also the input doesn't contain the \n.

So in these cases the idea of removing \n would fail.Discussed in comment. (chux)

A better and safe solution than overwriting this way:

```<code>s[scount].name[strcspn(s[scount].name, "\n")] = '\0';
</code>```

The explanation from the link is that if a \0 is given as input then we will basically write to  s[scount].name[SIZE_MAX] which is not desired.

From the standard §7.24.5.3

```<code>size_t strcspn(const char *s1, const char *s2)
</code>```

The strcspn function computes the length of the maximum initial
  segment of the string pointed to by s1 which consists entirely of
  characters not from the string pointed to by s2.

Title: How to correctly malloc a struct in C

Body:
Here is my full code, it looks like to work, but it's not working very well.
I would accept any code, that is working like this.

Firstly, the code works, but when I want to add the third name to the struct, it crashes.

Is there any other way to do this?

I need struct, because in the future, I want to add some other params, like age, average, gender, etc.

Please, help me out.

//The student table
typedef struct students {
    char name[50];
} students;

//Global params
int scount = 0;
students *s;

//Basic functions
void addNewStudent();

int main()
{
    int loop = 1;
    char in;
    int ch;
    printf("Willkommen.\n Wahlen Sie bitte von die folgenden Optionen:\n");
    while (loop)
    {
        printf("\t[1] Neue Student eingeben\n");
        printf("\t[9] Programm beenden\n");

        scanf(" %c", &in);
        while ((ch = getchar()) != '\n');
        switch (in)
        {
        case '1':
            addNewStudent();
            break;
        case '9':
            loop = 0;
            break;
        default: printf("------\nOption nicht gefunden.\n------\n");
            break;
        }
    }
    free(s);
    return 0;
}

void addNewStudent()
{
    int index = 0;
    if (scount == 0)
    {
        s = (students*)malloc(sizeof(students));
    }
    else
    {
        realloc(s, sizeof(students) * scount);
    }

    printf("Geben Sie Bitte die Name:\n");
    fgets(s[scount].name, sizeof(s[scount].name), stdin);

    while (s[scount].name[index] != '\n')
    {
        index++;
    }
    s[scount].name[index] = '\0';
    scount++;
}

I'm using Visual Studio.

Thanks for help!

Body:
students *mynew= realloc(s, sizeof(students)* (scount+1));
if( mynew != NULL )
    s=mynew;

Otehrwise you are having a memory leak. You didn't use the return value of realloc.

Don't cast the return type of malloc.

As per standard §7.22.2.35

void *realloc(void *ptr, size_t size)

The realloc function deallocates the old object pointed to by ptr and
  returns a pointer to a new object that has the size specified by size.

It is good not to use the same pointer variable on which you are calling malloc because in case it fails you will lose reference to the old one too (unless it is stored by other means).

Also you didn't check the return value of malloc.

s = malloc(sizeof(students));
if( s == NULL ){
   frpntf(stderr,"%s","Memory allocation failed");
   exit(1);
}

Also you should check the return value of fgets().

if( fgets(s[scount].name, sizeof(s[scount].name), stdin) == NULL){
     fprintf(stderr,"%s","Error in input");
     exit(1);
}

Also trying to compile your code it showed this

warning: ignoring return value of ‘realloc’, declared with attribute warn_unused_result [-Wunused-result]
         realloc(s, sizeof(students) * scount);
         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

When compiling try not to ignore any warning messages. It showed the problem you had.

Important point: (why scount+1 in realloc?)

When reallocating the general idea is increase the number of students. And for that you need to have extra memory allocated for an student. That's why the scount+1 in the code.(realloc).

Some other points:

while (s[scount].name[index] != '\n')
{
    index++;
}
s[scount].name[index] = '\0';

You can do it like this also

size_t len = strlen(s[scount].name);
if(len){
   s[scount].name[len-1]='\0';
}

To understand why from standard §7.21.7.2

char *fgets(char * restrict s, int n,FILE * restrict stream)

The fgets function reads at most one less than the number of
  characters specified by n from the stream pointed to by stream into
  the array pointed to by s. No additional characters are read after a
  new-line character (which is retained) or after end-of-file. A null
  character is written immediately after the last character read into
  the array.

\0 character was there already in the inputted string. You can get the length of it but you know that the one before the \0 is the \n character 1 that you entered by pressing the Enter key. We are overwriting it with the \0.

1. This is the usual case but not the only one. There are two cases where this might not be the right way to look at the thing.

The input line has n-1 or more characters before the '\n'. The the one before \0 will not be the \n rather it will be some character inputted by the user.

The last line is a stream which may not have a '\n'. (stdin closed). In that case also the input doesn't contain the \n.

So in these cases the idea of removing \n would fail.Discussed in comment. (chux)

A better and safe solution than overwriting this way:

s[scount].name[strcspn(s[scount].name, "\n")] = '\0';

The explanation from the link is that if a \0 is given as input then we will basically write to  s[scount].name[SIZE_MAX] which is not desired.

From the standard §7.24.5.3

size_t strcspn(const char *s1, const char *s2)

The strcspn function computes the length of the maximum initial
  segment of the string pointed to by s1 which consists entirely of
  characters not from the string pointed to by s2.


问:
python3 pdb display list
The display command of pdb seems to only show an expression when the whole variable is assigned.

```<code>pass
foo = [1, 2, 3]
foo[0] = 8
foo.append(7)
pass
</code>```

The output I get when running the above code with python3 -m pdb bar.py and then entering display foo is:

```<code>> bar.py(2)<module>()
-> foo = [1, 2, 3]
(Pdb) display foo
display foo: ** raised NameError: name 'foo' is not defined **
(Pdb) n
> bar.py(3)<module>()
-> foo[0] = 8
display foo: [1, 2, 3]  [old: ** raised NameError: name 'foo' is not defined **]
(Pdb)
> bar.py(4)<module>()
-> foo.append(7)
(Pdb)
> bar.py(5)<module>()
-> pass
(Pdb) foo
[8, 2, 3, 7]
(Pdb)
</code>```

The NameError and the first output of display are expected.
However it seems that display does not catch that foo changed when its first item was changed or when we appended 7.

Is there a way to tell pdb to list those changes?
It seems that display str(foo) does the job but I am wondering if there is a better solution.

答:
Yes, the way to track those changes is to you 'p' command instead. See this example

```<code>> /home/maksim/Projects/Python/basic/test.py(2)<module>()
-> foo = [1, 2, 3]
(Pdb) s;;l;;p foo
> /home/maksim/Projects/Python/basic/test.py(3)<module>()
-> foo[0] = 8
  1     pass
  2     foo = [1, 2, 3]
  3  -> foo[0] = 8
  4     foo.append(7)
  5     pass
  6
  7
  8
[EOF]
[1, 2, 3]
(Pdb) s;;l;;p foo
> /home/maksim/Projects/Python/basic/test.py(4)<module>()
-> foo.append(7)
  1     pass
  2     foo = [1, 2, 3]
  3     foo[0] = 8
  4  -> foo.append(7)
  5     pass
  6
  7
  8
[EOF]
[8, 2, 3]
(Pdb) s;;l;;p foo
> /home/maksim/Projects/Python/basic/test.py(5)<module>()
-> pass
  1     pass
  2     foo = [1, 2, 3]
  3     foo[0] = 8
  4     foo.append(7)
  5  -> pass
  6
  7
  8
[EOF]
[8, 2, 3, 7]
(Pdb) s;;l;;p foo
--Return--
> /home/maksim/Projects/Python/basic/test.py(5)<module>()->None
-> pass
  1     pass
  2     foo = [1, 2, 3]
  3     foo[0] = 8
  4     foo.append(7)
  5  -> pass
  6
  7
  8
[EOF]
[8, 2, 3, 7]
(Pdb)
</code>```

Title: python3 pdb display list

Body:
The display command of pdb seems to only show an expression when the whole variable is assigned.

pass
foo = [1, 2, 3]
foo[0] = 8
foo.append(7)
pass

The output I get when running the above code with python3 -m pdb bar.py and then entering display foo is:

> bar.py(2)<module>()
-> foo = [1, 2, 3]
(Pdb) display foo
display foo: ** raised NameError: name 'foo' is not defined **
(Pdb) n
> bar.py(3)<module>()
-> foo[0] = 8
display foo: [1, 2, 3]  [old: ** raised NameError: name 'foo' is not defined **]
(Pdb)
> bar.py(4)<module>()
-> foo.append(7)
(Pdb)
> bar.py(5)<module>()
-> pass
(Pdb) foo
[8, 2, 3, 7]
(Pdb)

The NameError and the first output of display are expected.
However it seems that display does not catch that foo changed when its first item was changed or when we appended 7.

Is there a way to tell pdb to list those changes?
It seems that display str(foo) does the job but I am wondering if there is a better solution.

Body:
Yes, the way to track those changes is to you 'p' command instead. See this example

> /home/maksim/Projects/Python/basic/test.py(2)<module>()
-> foo = [1, 2, 3]
(Pdb) s;;l;;p foo
> /home/maksim/Projects/Python/basic/test.py(3)<module>()
-> foo[0] = 8
  1     pass
  2     foo = [1, 2, 3]
  3  -> foo[0] = 8
  4     foo.append(7)
  5     pass
  6
  7
  8
[EOF]
[1, 2, 3]
(Pdb) s;;l;;p foo
> /home/maksim/Projects/Python/basic/test.py(4)<module>()
-> foo.append(7)
  1     pass
  2     foo = [1, 2, 3]
  3     foo[0] = 8
  4  -> foo.append(7)
  5     pass
  6
  7
  8
[EOF]
[8, 2, 3]
(Pdb) s;;l;;p foo
> /home/maksim/Projects/Python/basic/test.py(5)<module>()
-> pass
  1     pass
  2     foo = [1, 2, 3]
  3     foo[0] = 8
  4     foo.append(7)
  5  -> pass
  6
  7
  8
[EOF]
[8, 2, 3, 7]
(Pdb) s;;l;;p foo
--Return--
> /home/maksim/Projects/Python/basic/test.py(5)<module>()->None
-> pass
  1     pass
  2     foo = [1, 2, 3]
  3     foo[0] = 8
  4     foo.append(7)
  5  -> pass
  6
  7
  8
[EOF]
[8, 2, 3, 7]
(Pdb)


问:
strange issue with jQuery
I have a very strange issue with jQuery.

The problem:

```<code>$("#button-prev").attr("disabled", "disabled");
</code>```

This doesn't work. If I check with Firebug I see disabled="" as element attribute

But for example this

```<code>$("#button-prev").attr("disablea", "disabled");
</code>```

works as you should expect. Anyone an idea what it could be?

答:
I believe the attr for that is "true" or "false"...
Try:  $("#button-prev").attr("disabled", true);
Make sure "button-prev" is the ID for the button.</p>

Title: strange issue with jQuery

Body:
I have a very strange issue with jQuery.

The problem:

$("#button-prev").attr("disabled", "disabled");

This doesn't work. If I check with Firebug I see disabled="" as element attribute

But for example this

$("#button-prev").attr("disablea", "disabled");

works as you should expect. Anyone an idea what it could be?


问:
My clickatell API is not working properly, do I need to do HTTP GET or POST
I Purchased an API from clickatell and it  doesn't seem to work even after its checked from the support team.
What should I select HTTP POST for GET

All the settings are fine, but it doesn't send SMS to buyer

答: According to the Clickatell API Documentation here the SMS sending endpoint expects a POST.</p>


问:
vertical headings table - header and row same color
I have a vertical heading html table where i am trying to have the heading and row be the same color, but alternating. The picture illustrates what i want.

Here is my table

```<code>  <table class="dialogTable" cellspacing="0" style="height: 450px">
    <caption><h4>Validation Results</h4></caption>
    <tr>
        <th width="250px">Source Records</th>
        <td width="400px">{{dialogData.totalNumRecords}}</td>
    </tr>
    <tr>
        <th width="250px">New Records</th>
        <td>{{dialogData.numNewRecords}}</td>
    </tr>
    <tr>
        <th width="250px">Updated Records</th>
        <td>{{dialogData.numUpdatedRecords}}</td>
    </tr>
    <tr>
        <th width="250px">Removed Records</th>
        <td>{{dialogData.numDeletedRecords}}</td>
    </tr>
    <tr>
    <th valign="top" width="250px">Error Message</th>
    <td class="dialogstyle" valign="top" >
        <div class="errortext" ng-repeat="error in dialogData.errors" valign="top">{{error}}</div></td>
    </tr>
</table>
</code>```

and the css i have

```<code>.dialogTable {

overflow-y:hidden;
margin-left: 6px;
}

.dialogTable > th:nth-child(even) {
background-color: #eee !important;
}

.dialogTable > th:nth-child(odd) {
background-color: #fff !important;
}
</code>```

right now the headings are all the same color.
Thank you

答:
Looks like you want the whole row and you're on the right track, but you're just targeting the th instead of the whole row.

Try tr instead of th:

```<code>.dialogTable > tr:nth-child(even) {
  background-color: #eee !important;
}

.dialogTable > tr:nth-child(odd) {
  background-color: #fff !important;
}
</code>```

Maybe start with just one of those styles, to make sure your nth-child selector is working.

Body:
I have a vertical heading html table where i am trying to have the heading and row be the same color, but alternating. The picture illustrates what i want.

Here is my table

Validation Results

        Source Records
        {{dialogData.totalNumRecords}}

        New Records
        {{dialogData.numNewRecords}}

        Updated Records
        {{dialogData.numUpdatedRecords}}

        Removed Records
        {{dialogData.numDeletedRecords}}

    Error Message

{{error}}

and the css i have

.dialogTable {

overflow-y:hidden;
margin-left: 6px;
}

.dialogTable > th:nth-child(even) {
background-color: #eee !important;
}

.dialogTable > th:nth-child(odd) {
background-color: #fff !important;
}

right now the headings are all the same color.
Thank you

Body:
Looks like you want the whole row and you're on the right track, but you're just targeting the th instead of the whole row.

Try tr instead of th:

.dialogTable > tr:nth-child(even) {
  background-color: #eee !important;
}

.dialogTable > tr:nth-child(odd) {
  background-color: #fff !important;
}

Maybe start with just one of those styles, to make sure your nth-child selector is working.


答:
Your code is looking for .dialogTable as the direct parent. Which it is not. Try this instead. Also, your code only colors half of the row. Use the table row instead.</p>

```<code>.dialogTable {
overflow-y:hidden;
margin-left: 6px;
}

.dialogTable tr:nth-child(even) {
background-color: #eee !important;
}

.dialogTable tr:nth-child(odd) {
background-color: #fff !important;
}
</code>```

Title: vertical headings table - header and row same color

Body:
Your code is looking for .dialogTable as the direct parent. Which it is not. Try this instead. Also, your code only colors half of the row. Use the table row instead.

.dialogTable {
overflow-y:hidden;
margin-left: 6px;
}

.dialogTable tr:nth-child(even) {
background-color: #eee !important;
}

.dialogTable tr:nth-child(odd) {
background-color: #fff !important;
}


问:
Are there any websites that allow you to perform GET requests using there API?
I'm working on a project where I need to perform a GET request to a domain. It won't work purely in Javascript because the site is cross-origin. Is there a service that when called can return the contents of a page?</p>

答:
this one :) specifically this endpoint over here

/get Returns GET data.

it will reply every time you call it with a response like this

```<code>{
  "args": {},
  "headers": {
    // all the headers will be here
  },
  "origin": "<YOUR IP WILL BE HERE>",
  "url": "https://httpbin.org/get"
}
</code>```

JSON format that you can consume and view to your client/end

Body:
this one :) specifically this endpoint over here

/get Returns GET data.

it will reply every time you call it with a response like this

{
  "args": {},
  "headers": {
    // all the headers will be here
  },
  "origin": "<YOUR IP WILL BE HERE>",
  "url": "https://httpbin.org/get"
}

JSON format that you can consume and view to your client/end


问:
Azure SSL Certificate
I am running into an issue when uploading my SSL certificate to Azure. I have a premium certificate from GoDaddy that has been running in IIS for the past year. As we are migrating to Azure, I exported it to a PFX, went to Azure to add it to my Web App, and received the following error message:

```<code>Failed to update web app settings
Failed to update web app settings for [APP_NAME]: The password is incorrect, or the certificate is not valid
</code>```

I have tried the following:

Ensure password is correct

Export from IIS as pfx

Export from MMC as pfx with full paths available

They all have the same results with the error message. Does anyone have any ideas?

答:
I had a similar issue using the "https://portal.azure.com" trying the approach "App Service - "your app service" - ssl certificates - upload certificate"

When I tried to upload a certificate PFX file nothing happend, no error message, nothing.

The workaround I found was to re-generate the PFX file using openssl and this time add a short and simple password.

"openssl pkcs12 -export -out certificate.pfx -inkey privkey.pem -in cert.pem -certfile chain.pem"

Hope this helps

Title: Azure SSL Certificate

Body:
I am running into an issue when uploading my SSL certificate to Azure. I have a premium certificate from GoDaddy that has been running in IIS for the past year. As we are migrating to Azure, I exported it to a PFX, went to Azure to add it to my Web App, and received the following error message:

Failed to update web app settings
Failed to update web app settings for [APP_NAME]: The password is incorrect, or the certificate is not valid

I have tried the following:

Ensure password is correct

Export from IIS as pfx

Export from MMC as pfx with full paths available

They all have the same results with the error message. Does anyone have any ideas?


问:
Form still posting even after canceling
I've read all the posts on this but can't seem to work out why my form is still posting even after I press cancel on the confirm popup. Any help appreciated. I'm returning the the result of the confirm, so i was expecting the dialog to just disappear and the form to not post.  Im sure its something simple.

Here is my code:

```<code><form action='/auth/deleteUserCascade' method='post' onsubmit='return confirm(\"Are you sure you want to delete this user?\");'>
    <button type='submit' class='btn-link'>
        <i class='fa fa-trash' aria-hidden='true'></i>
    </button>";
</form>
</code>```

答:
<form action='' method='post'>
    <button type='submit' class='btn-link' onclick='return confirm("Are you sure you want to delete this user?");'>
        hello
    </button>";
</form>```

You have some weird things going on in that onsubmit string. Namely, escaping quotes unnecessarily.

Title: Form still posting even after canceling

Body:
I've read all the posts on this but can't seem to work out why my form is still posting even after I press cancel on the confirm popup. Any help appreciated. I'm returning the the result of the confirm, so i was expecting the dialog to just disappear and the form to not post.  Im sure its something simple.

Here is my code:

<form action='/auth/deleteUserCascade' method='post' onsubmit='return confirm(\"Are you sure you want to delete this user?\");'>
    <button type='submit' class='btn-link'>

    </button>";
</form>

Body:
<form action='' method='post'>
    <button type='submit' class='btn-link' onclick='return confirm("Are you sure you want to delete this user?");'>
        <i class='fa fa-trash' aria-hidden='true'>hello</i>
    </button>";
</form>

You have some weird things going on in that onsubmit string. Namely, escaping quotes unnecessarily.


答:
The selectors are wrong. It should be </p>

```<code>.dialogTable tr:nth-child(even) {
   //add bg colour
}
.dialogTable tr:nth-child(odd) {
   //add bg colour
}
</code>```

Body:
The selectors are wrong. It should be

.dialogTable tr:nth-child(even) {
   //add bg colour
}
.dialogTable tr:nth-child(odd) {
   //add bg colour
}


问:
Top Back Bar Button Item back to previous page in webview
I am using Xcode to develop webview. I want to do is when i load a webpage, the webpage may will has other page, so i will click the button icon in that website to another page, and i want the one is when click the top back bar button, it will back to every previous page visit and last back to application home page. Now what I do for now is when i click the top back bar button, it directly go to application home page.
Below is my xcode code:</p>

```<code>@IBOutlet weak var myWebView: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()
    let backarrow = UIImage(named: "navi_back")
    self.navigationController?.navigationBar.backIndicatorImage = backarrow
    self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = backarrow
    if let topItem = self.navigationController?.navigationBar.topItem {
        topItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
    }

    let url = URL(string: "https://www.facebook.com")
    myWebView.loadRequest(URLRequest(url: url!))
}
</code>```

答:
if i understand Correctly you want back button to go back in webView until there are no pages available for backing then you want to go back to your previous viewController

you need to set an action for your backButton

```<code>topItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: self, action: #selector(webViewBack))
</code>```

then check if webview has pages in its back Stack

```<code>func webViewBack(){
if(myWebView.canGoBack == false)
{
 self.navigationController?.popViewController(animated: true)
}
else{
myWebView.goBack()
}
}
</code>```

Body:
I am using Xcode to develop webview. I want to do is when i load a webpage, the webpage may will has other page, so i will click the button icon in that website to another page, and i want the one is when click the top back bar button, it will back to every previous page visit and last back to application home page. Now what I do for now is when i click the top back bar button, it directly go to application home page.
Below is my xcode code:

@IBOutlet weak var myWebView: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()
    let backarrow = UIImage(named: "navi_back")
    self.navigationController?.navigationBar.backIndicatorImage = backarrow
    self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = backarrow
    if let topItem = self.navigationController?.navigationBar.topItem {
        topItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
    }

    let url = URL(string: "https://www.facebook.com")
    myWebView.loadRequest(URLRequest(url: url!))
}

Body:
if i understand Correctly you want back button to go back in webView until there are no pages available for backing then you want to go back to your previous viewController

you need to set an action for your backButton

topItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: self, action: #selector(webViewBack))

then check if webview has pages in its back Stack

func webViewBack(){
if(myWebView.canGoBack == false)
{
 self.navigationController?.popViewController(animated: true)
}
else{
myWebView.goBack()
}
}


问:
Resharper parameters indentation
I believe formating like below is default in ReSharper (assuming new lines were added manually)

```<code>foo.LenghtyNamedProperty.Bar(x,
                             y,
                            );
</code>```

Is it possible in ReSharper to achive indentation reset if opening parenthesis is follwed by new line?

```<code>foo.LenghtyNamedProperty.Bar(
    x,
    y
);
</code>```

答:
If you mean only to pull the arguments to the left (and you decide the line breaks), go to Resharper >> Options >> c# >> Formatting style >> Other >> Align Multiline Constructs >> Call arguments and uncheck it.

If you want to enforce this policy, go to Resharper >> Options >> c# >> Formatting style >> Line Breaks and Wrapping >> Line Wrapping >> Wrap invocation arguments and set it to Chop always and check Prefer wrap after "(" in invocation.

The paths work for Resharper Ultimate 2017.2.2.

Title: Resharper parameters indentation

Body:
I believe formating like below is default in ReSharper (assuming new lines were added manually)

foo.LenghtyNamedProperty.Bar(x,
                             y,
                            );

Is it possible in ReSharper to achive indentation reset if opening parenthesis is follwed by new line?

foo.LenghtyNamedProperty.Bar(
    x,
    y
);


问:
Managing a log file in Grails
Let me reword this entire thread.

I have a web application written using Grails and running on a VM, which is running Linux.

The web application needs to maintain a separate and distinct log file that contains very important information for the user of the application. I only want it to contain information that I am writing to it. Nothing else so I can't use Tomcat logging, etc. I need a separate log file because the user of the application is not savvy enough to read through a Tomcat log.

If I use a log file on the local C: drive it of course works when I run it in debug via IntelliJ but as soon as I war it up and drop it in Tomcat that no longer works and I get a ClassNotFoundException.

```<code> String myCurrentDate = new Date().format( 'yyyyMMddhhmm' )
 def newFile = "C:\\Temp\\MyLogFile-Log-" + myCurrentDate + ".txt.old"
 def file = new File('C:\\Temp\\MyLogFile-Log.txt')
 file.renameTo( new File(newFile) )
 file.delete()
</code>```

What's the best way to do this? Host the log file on the Linux machine? sftp doesn't seem to be the answer either. I need to be able to:

Upon application execution rename the old log file to archive it and then delete the old log file

write to the log file

If I do it on Linux how do I specify the file location?

答:
The recent versions of Grails are delivered with logback support. Usually you find a logback.groovy under grails-app/conf.

The example of a fully functional file:

```<code>import ch.qos.logback.classic.encoder.PatternLayoutEncoder
import ch.qos.logback.core.rolling.RollingFileAppender
import ch.qos.logback.core.rolling.TimeBasedRollingPolicy

appender( 'FILE', RollingFileAppender ){
  file = '/var/log/MyLogFile-Log.log'
  append = true
  encoder( PatternLayoutEncoder ){ pattern = '%d{HH:mm:ss.SSS} [%thread] %level %logger{36} - %msg%n' }
  rollingPolicy( TimeBasedRollingPolicy ){
    fileNamePattern = '/var/log/MyLogFile-Log-%d{yyyy-MM-dd}.log'
    maxHistory = 30
  }
}

logger 'com.your.important.package', INFO

root INFO, 'FILE'
</code>```

Here a RollingFileAppender is used, creating backup-files each day.

Title: Managing a log file in Grails

Body:
Let me reword this entire thread.

I have a web application written using Grails and running on a VM, which is running Linux.

The web application needs to maintain a separate and distinct log file that contains very important information for the user of the application. I only want it to contain information that I am writing to it. Nothing else so I can't use Tomcat logging, etc. I need a separate log file because the user of the application is not savvy enough to read through a Tomcat log.

If I use a log file on the local C: drive it of course works when I run it in debug via IntelliJ but as soon as I war it up and drop it in Tomcat that no longer works and I get a ClassNotFoundException.

 String myCurrentDate = new Date().format( 'yyyyMMddhhmm' )
 def newFile = "C:\\Temp\\MyLogFile-Log-" + myCurrentDate + ".txt.old"
 def file = new File('C:\\Temp\\MyLogFile-Log.txt')
 file.renameTo( new File(newFile) )
 file.delete()

What's the best way to do this? Host the log file on the Linux machine? sftp doesn't seem to be the answer either. I need to be able to:

Upon application execution rename the old log file to archive it and then delete the old log file

write to the log file

If I do it on Linux how do I specify the file location?

Body:
The recent versions of Grails are delivered with logback support. Usually you find a logback.groovy under grails-app/conf.

The example of a fully functional file:

import ch.qos.logback.classic.encoder.PatternLayoutEncoder
import ch.qos.logback.core.rolling.RollingFileAppender
import ch.qos.logback.core.rolling.TimeBasedRollingPolicy

appender( 'FILE', RollingFileAppender ){
  file = '/var/log/MyLogFile-Log.log'
  append = true
  encoder( PatternLayoutEncoder ){ pattern = '%d{HH:mm:ss.SSS} [%thread] %level %logger{36} - %msg%n' }
  rollingPolicy( TimeBasedRollingPolicy ){
    fileNamePattern = '/var/log/MyLogFile-Log-%d{yyyy-MM-dd}.log'
    maxHistory = 30
  }
}

logger 'com.your.important.package', INFO

root INFO, 'FILE'

Here a RollingFileAppender is used, creating backup-files each day.


问:
How to process a list of files in MATLAB
in MATLAB, my function is like this:

```<code> names = {'d:\C001\C001_Deo.csv','d:\C001\C001_Oxy.csv','d:\C001\C001_Tal.csv'}
 data_conversion(names)         %this function creat a folder in C001 to save results
</code>```

I have 100 folders named as C001, C002, ..., C100. Each folder has three .csv files, named like this: C001_Deo.csv, C001_Oxy.csv, C001_Tal.csv,  C002_Deo.csv, C002_Oxy.csv, C002_Tal.csv, ...

Does anyone can help me to write a loop so I can run data_conversion(names) at a time to get all the results. Then I don't need to run it 100 times.
I tried many times but failed. Thanks!

答:
You can try this:</p>

```<code>baseFolder = 'd:\';

for i=1:100
    % get a string for  001 -> 100
    strtmp = num2str(i);
    str = cat(2,repmat('0',1,3-length(strtmp)),strtmp);

    % reconstitute folder path
    folderString = [baseFolder 'C' str filesep];

    % and the 3 file paths
    f1 = [folderString 'C' str '_Deo.csv'];
    f2 = [folderString 'C' str '_Oxy.csv'];
    f3 = [folderString 'C' str '_Tal.csv'];

    % run your data_conversion function
    data_conversion({f1 f2 f3})

end
</code>```

Body:
in MATLAB, my function is like this:

 names = {'d:\C001\C001_Deo.csv','d:\C001\C001_Oxy.csv','d:\C001\C001_Tal.csv'}
 data_conversion(names)         %this function creat a folder in C001 to save results

I have 100 folders named as C001, C002, ..., C100. Each folder has three .csv files, named like this: C001_Deo.csv, C001_Oxy.csv, C001_Tal.csv,  C002_Deo.csv, C002_Oxy.csv, C002_Tal.csv, ...

Does anyone can help me to write a loop so I can run data_conversion(names) at a time to get all the results. Then I don't need to run it 100 times.
I tried many times but failed. Thanks!

Body:
You can try this:

baseFolder = 'd:\';

for i=1:100
    % get a string for  001 -> 100
    strtmp = num2str(i);
    str = cat(2,repmat('0',1,3-length(strtmp)),strtmp);

    % reconstitute folder path
    folderString = [baseFolder 'C' str filesep];

    % and the 3 file paths
    f1 = [folderString 'C' str '_Deo.csv'];
    f2 = [folderString 'C' str '_Oxy.csv'];
    f3 = [folderString 'C' str '_Tal.csv'];

    % run your data_conversion function
    data_conversion({f1 f2 f3})

end


问:
configuring dynamic url's in router
I'm using Codeigniter. Basically what I want is to remove the Controller name (Home) from the url.

Those urls look like:

```<code>http://localhost/mechanicly/Home
http://localhost/mechanicly/Home/about
http://localhost/mechanicly/Home/contactus
</code>```

now there are two ways I can remove the Home controller:

static definition of every url inside route:

```<code>$route['about'] = "Home/about";
$route['contactus'] = "Home/contactus";
</code>```

I can use call backs in routes in Codeigniter:

```<code>$route['(.+)'] = function ( $param ) {

  if( strpos( $param, "Admin" ) !== false ) {
    echo $param;
    return "Admin/".$param;
  }
  else{
    echo $param;
    return "Home/".$param;
  }
</code>```

};

this logic is much better as it is generic and I don't have to create new routes every time for new method inside the controller.

It is working fine for the client controller which is Home but I have another controller named as Admin and I want to redirect Admin requests to the Admin controller and Home request to the Home Controller.

Why does above code work fine for the Home controller but returns

not found

when I validate for the Admin controller?

I am using CI version 3.x

答:
you can create your menu(url´s) from db like

```<code>tbl_menu               tbl_level
----------             -------------
id                     id
fk_level               level
name                   dateUP
dateUP                 active
active
</code>```

In your controllers you need to call the correct menu by session or wherever you want

then you can has this in your route.php

```<code>$route['(.+)'] = 'int_rout/routing/' . json_encode($1);
</code>```

in your controller Int_rout.php

```<code>public function routing ( $param ) {
    $routing = json_decode($param);
    $routing = explode('/', $routing);

    //$menu -> get menu from model
    foreach($menu as $item){
        if($routing[0] === $item->name){
            //$level -> get level from model
            $redirect = $level->level;
        }
    }

    //the final redirect will be like
    //admin/user or admin/user/12
    //public/us
    $params = ( empty($routing[1])) ? '' : '/' . $routing[1];
    redirect($redirect . '/' . $routing[0] . $params, 'refresh');
}
</code>```

Title: configuring dynamic url's in router

Body:
I'm using Codeigniter. Basically what I want is to remove the Controller name (Home) from the url.

Those urls look like:

http://localhost/mechanicly/Home
http://localhost/mechanicly/Home/about
http://localhost/mechanicly/Home/contactus

now there are two ways I can remove the Home controller:

static definition of every url inside route:

$route['about'] = "Home/about";
$route['contactus'] = "Home/contactus";

I can use call backs in routes in Codeigniter:

$route['(.+)'] = function ( $param ) {

  if( strpos( $param, "Admin" ) !== false ) {
    echo $param;
    return "Admin/".$param;
  }
  else{
    echo $param;
    return "Home/".$param;
  }

};

this logic is much better as it is generic and I don't have to create new routes every time for new method inside the controller.

It is working fine for the client controller which is Home but I have another controller named as Admin and I want to redirect Admin requests to the Admin controller and Home request to the Home Controller.

Why does above code work fine for the Home controller but returns

not found

when I validate for the Admin controller?

I am using CI version 3.x

Body:
you can create your menu(url´s) from db like

tbl_menu               tbl_level
----------             -------------
id                     id
fk_level               level
name                   dateUP
dateUP                 active
active

In your controllers you need to call the correct menu by session or wherever you want

then you can has this in your route.php

$route['(.+)'] = 'int_rout/routing/' . json_encode($1);

in your controller Int_rout.php

public function routing ( $param ) {
    $routing = json_decode($param);
    $routing = explode('/', $routing);

    //$menu -> get menu from model
    foreach($menu as $item){
        if($routing[0] === $item->name){
            //$level -> get level from model
            $redirect = $level->level;
        }
    }

    //the final redirect will be like
    //admin/user or admin/user/12
    //public/us
    $params = ( empty($routing[1])) ? '' : '/' . $routing[1];
    redirect($redirect . '/' . $routing[0] . $params, 'refresh');
}


答: Have you tried, if the button is disabled? I just tried it with the "Post Your Answer" button on this page, and although Firebug doesn't show anything in the HTML tab, the DOM tab reveals, that the disabled attribute is set (and behold, I can't click).

Title: strange issue with jQuery

Body:
I have a very strange issue with jQuery.

The problem:

$("#button-prev").attr("disabled", "disabled");

This doesn't work. If I check with Firebug I see disabled="" as element attribute

But for example this

$("#button-prev").attr("disablea", "disabled");

works as you should expect. Anyone an idea what it could be?