问:
pandas - Replaceing values in a column
I have a dataframe df like this:

```<code>            ID_USER  CODE
0          433805  11.0
24          5448   44.0
48          3434   11.0
72          34434  11.0
96          3202   33.0
120         23766  33.0
153         39457  44.0
168         4113   33.0
172         3435   13.0
374         34093  11.0
</code>```

And I try to replace the values from the 'CODE' column with other values.

```<code>11.0 and 44.0 -> 1
33.0 -> 0
all other -> 5
</code>```

So I did among others the following:

```<code>df['CODE'] = df.apply(lambda s:func1(s))

def func1(x):
    if (x['CODE'] == 11.0) or (x['CODE'] == 44.0):
        return 1
    elif (x['CODE'] == 33.0):
        return 0
    else:
        return 5
</code>```

And I get this error:

```<code>KeyError: ('NTL', u'occurred at index ID_UC')
</code>```

How can I solve my problem?

答:
Short answer is that you forgot to specify the axis over which to apply.  By default apply will iterate over every column.  Your function is looking for x['CODE'] and therefore it's safe to assume you meant this to iterate over rows

```<code>df.apply(lambda s:func1(s), axis=1)

0      1
24     1
48     1
72     1
96     0
120    0
153    1
168    0
172    5
374    1
dtype: int64
</code>```

You can shorten this up with

```<code>df.apply(func1, 1)
</code>```

That said, I'd improve your function to assume you are iterating over a pd.Series and not rows of a pd.DataFrame and apply it to the targeted column.

```<code>def func2(x):
    return 1 if (x == 11) or (x == 44) else 0 if (x == 33) else 5

df.CODE.apply(func2)
</code>```

Even better, I like using map + lambda

```<code>m = {11: 1, 44: 1, 33: 0}

df.CODE.map(lambda x: m.get(x, 5))
</code>```

All together

```<code>df.assign(CODE=df.CODE.map(lambda x: m.get(x, 5)))

     ID_USER  CODE
0     433805     1
24      5448     1
48      3434     1
72     34434     1
96      3202     0
120    23766     0
153    39457     1
168     4113     0
172     3435     5
374    34093     1
</code>```

Title: pandas - Replaceing values in a column

Body:
I have a dataframe df like this:

            ID_USER  CODE
0          433805  11.0
24          5448   44.0
48          3434   11.0
72          34434  11.0
96          3202   33.0
120         23766  33.0
153         39457  44.0
168         4113   33.0
172         3435   13.0
374         34093  11.0

And I try to replace the values from the 'CODE' column with other values.

11.0 and 44.0 -> 1
33.0 -> 0
all other -> 5

So I did among others the following:

df['CODE'] = df.apply(lambda s:func1(s))

def func1(x):
    if (x['CODE'] == 11.0) or (x['CODE'] == 44.0):
        return 1
    elif (x['CODE'] == 33.0):
        return 0
    else:
        return 5

And I get this error:

KeyError: ('NTL', u'occurred at index ID_UC')

How can I solve my problem?

Body:
Short answer is that you forgot to specify the axis over which to apply.  By default apply will iterate over every column.  Your function is looking for x['CODE'] and therefore it's safe to assume you meant this to iterate over rows

df.apply(lambda s:func1(s), axis=1)

0      1
24     1
48     1
72     1
96     0
120    0
153    1
168    0
172    5
374    1
dtype: int64

You can shorten this up with

df.apply(func1, 1)

That said, I'd improve your function to assume you are iterating over a pd.Series and not rows of a pd.DataFrame and apply it to the targeted column.

def func2(x):
    return 1 if (x == 11) or (x == 44) else 0 if (x == 33) else 5

df.CODE.apply(func2)

Even better, I like using map + lambda

m = {11: 1, 44: 1, 33: 0}

df.CODE.map(lambda x: m.get(x, 5))

All together

df.assign(CODE=df.CODE.map(lambda x: m.get(x, 5)))

     ID_USER  CODE
0     433805     1
24      5448     1
48      3434     1
72     34434     1
96      3202     0
120    23766     0
153    39457     1
168     4113     0
172     3435     5
374    34093     1


来源: stackexchange

问:
C++ variables declaration within enum declaration
I have the following code:

```<code>#include <iostream>
using namespace std;

enum Week_Day {SAT, SUN, MON, TUE, WED, THU, FRI} wd1 = FRI;

Week_Day wd2 = SAT;

int main()
{
    cout << "\n " << wd1;
    cout << "\n " << wd2;

    cout << "\n\n\n";
}
</code>```

I searched for the difference(s) between the ways wd1 and wd2 were declared, but it seemed to me that it was just a matter of convenience.

Is it true, or I missed something?

Update1:

OK, both wd1 and wd2 are now global variables.

Are there any other differences?

答:
yep at the first one it define the enum and immediately used it to declare the wd1
and second one is another declaration without the need to redefine again.
no difference same code two different places.
another difference would be because of position in code they defined , the first  one is global but the second one is local.
Global means the variable can be used everywhere in your code and everybody  know it. but local variables only have life-cycle inside a block

```<code>{
SomeClass someVar;// defined here

...

// die here, the destructor will be called automatically by the runtime here
}
</code>```

Suggest to read here

ContentLicense: CC BY-SA 3.0

Body:
I have the following code:

#include <iostream>
using namespace std;

enum Week_Day {SAT, SUN, MON, TUE, WED, THU, FRI} wd1 = FRI;

Week_Day wd2 = SAT;

int main()
{
    cout << "\n " << wd1;
    cout << "\n " << wd2;

    cout << "\n\n\n";
}

I searched for the difference(s) between the ways wd1 and wd2 were declared, but it seemed to me that it was just a matter of convenience.

Is it true, or I missed something?

Update1:

OK, both wd1 and wd2 are now global variables.

Are there any other differences?

Body:
yep at the first one it define the enum and immediately used it to declare the wd1
and second one is another declaration without the need to redefine again.
no difference same code two different places.
another difference would be because of position in code they defined , the first  one is global but the second one is local.
Global means the variable can be used everywhere in your code and everybody  know it. but local variables only have life-cycle inside a block

{
SomeClass someVar;// defined here

...

// die here, the destructor will be called automatically by the runtime here
}

Suggest to read here


问:
using sed to find text and delete line using bash on mac os x
I am finding that when I run this bash script to delete two lines that match the pattern, I get  -sed: 1: "/etc/nsmb.conf": extra characters at the end of n command- error when run
Here is the code problem lines:

```<code>sed -i s/[default]/d /etc/nsmb.conf
sed -i s/signing_required=no/d /etc/nsmb.conf
</code>```

pretty basic, but not sure of syntax.  looking up answers it seems Mac OS X may need extra chars but do not know what they may be.  Just trying to remove these two lines in a file:

```<code>[default]
signing_required=no
</code>```

any help is appreciated

答:
Try sed  "/\[default\]/d;/signing_required=no/d" filename.

It seems that your sed got into the filename, still expecting commands (see Benjamins comment for explanation).

Also [default] matches any line which has at least one of those characters.

Try to see the result before using the "-i".

Then return to using "-i.bak" on the file, as Benjamin has commented, that will provide the extension which seems mandatory on Mac OS. (I am not knowledgable on Mac OS, so credit to @Benjamin on that part.)

Body:
I am finding that when I run this bash script to delete two lines that match the pattern, I get  -sed: 1: "/etc/nsmb.conf": extra characters at the end of n command- error when run
Here is the code problem lines:

sed -i s/[default]/d /etc/nsmb.conf
sed -i s/signing_required=no/d /etc/nsmb.conf

pretty basic, but not sure of syntax.  looking up answers it seems Mac OS X may need extra chars but do not know what they may be.  Just trying to remove these two lines in a file:

[default]
signing_required=no

any help is appreciated


问:
force download youtube videos from url in browser (client-site) in javascript
I am working on youtube video downloader site that is using node based server-site. I am using npm package called ytdl-core and this module is returning download link. But, when I click on that link it redirects me to "video preview" instead of "trigger download",

```<code>ytdl(url, function(err, format) {
  if (err) {res.send('the url is invalid please try again...');}
  console.log((format.formats).length);//i am getting value... in console but not outside of the function..
  //this object contains all the download links
  var links = []
  for( var i= 0, len = (format.formats).length; i < len; i++) {
    var el = format.formats[i].container;
    if ( el === 'mp4') {
      var download_url = format.formats[i];
      //this push will store the all links in 'links' object..
      links.push(download_url);
    }
  }
  console.log(links);
});
</code>```

So when I paste the link into my browser, it redirects me to preview instead of trigger download. I am getting link that looks like this:

```<code>https://r8---sn-gxap5ojx-cage.googlevideo.com/videoplayback?upn=P6gEaXLtqOc&ei=ROrcWMzGKsjfoAPtl6XYAg&id=o-AIBZRxwo9AvJU4q02_xR0lfxJbSV3pxpga67Si4bLieu&key=yt6&ip=139.59.64.12&ipbits=0&pl=20&requiressl=yes&initcwndbps=8882500&ratebypass=yes&sparams=clen%2Cdur%2Cei%2Cgir%2Cid%2Cinitcwndbps%2Cip%2Cipbits%2Citag%2Clmt%2Cmime%2Cmm%2Cmn%2Cms%2Cmv%2Cpcm2cms%2Cpl%2Cratebypass%2Crequiressl%2Csource%2Cupn%2Cexpire&itag=18&expire=1490894500&mime=video%2Fmp4&pcm2cms=yes&source=youtube&mv=m&mt=1490872775&ms=au&lmt=1487309879666192&clen=8449602&gir=yes&mn=sn-gxap5ojx-cage&mm=31&dur=221.518&signature=6ED71F39CAA3B6719A8BAAEABD51D568ABF4D7A3.B3EED034140574BAC9733EC5CC28EF4AC9E3F758&title=Kygo Selena Gomez It Ain t Me with Selena Gomez Audio
</code>```

My question is, how can I force download that video to client's browser by clicking button?

答:
i have found very simple solution is that you need add attribute "download='true' into your html code! and it's look like this

```<code><a href='yourdownloadlink.com/example' download='true'>force download!</a>
</code>```

Body:
I am working on youtube video downloader site that is using node based server-site. I am using npm package called ytdl-core and this module is returning download link. But, when I click on that link it redirects me to "video preview" instead of "trigger download",

ytdl(url, function(err, format) {
  if (err) {res.send('the url is invalid please try again...');}
  console.log((format.formats).length);//i am getting value... in console but not outside of the function..
  //this object contains all the download links
  var links = []
  for( var i= 0, len = (format.formats).length; i < len; i++) {
    var el = format.formats[i].container;
    if ( el === 'mp4') {
      var download_url = format.formats[i];
      //this push will store the all links in 'links' object..
      links.push(download_url);
    }
  }
  console.log(links);
});

So when I paste the link into my browser, it redirects me to preview instead of trigger download. I am getting link that looks like this:

https://r8---sn-gxap5ojx-cage.googlevideo.com/videoplayback?upn=P6gEaXLtqOc&ei=ROrcWMzGKsjfoAPtl6XYAg&id=o-AIBZRxwo9AvJU4q02_xR0lfxJbSV3pxpga67Si4bLieu&key=yt6&ip=139.59.64.12&ipbits=0&pl=20&requiressl=yes&initcwndbps=8882500&ratebypass=yes&sparams=clen%2Cdur%2Cei%2Cgir%2Cid%2Cinitcwndbps%2Cip%2Cipbits%2Citag%2Clmt%2Cmime%2Cmm%2Cmn%2Cms%2Cmv%2Cpcm2cms%2Cpl%2Cratebypass%2Crequiressl%2Csource%2Cupn%2Cexpire&itag=18&expire=1490894500&mime=video%2Fmp4&pcm2cms=yes&source=youtube&mv=m&mt=1490872775&ms=au&lmt=1487309879666192&clen=8449602&gir=yes&mn=sn-gxap5ojx-cage&mm=31&dur=221.518&signature=6ED71F39CAA3B6719A8BAAEABD51D568ABF4D7A3.B3EED034140574BAC9733EC5CC28EF4AC9E3F758&title=Kygo Selena Gomez It Ain t Me with Selena Gomez Audio

My question is, how can I force download that video to client's browser by clicking button?

Body:
i have found very simple solution is that you need add attribute "download='true' into your html code! and it's look like this

<a href='yourdownloadlink.com/example' download='true'>force download!</a>


问:
Issue Searching NetSuite - nlapiSearchRecord
I am having trouble understanding what this error means.

org.mozilla.javascript.EcmaError: ReferenceError: "nlapiSearchRecord"
  is not defined. (/SuiteScripts/PreventDuplicateCustomer.js#35)

I am attempting to create a script which searches for a duplicate record based on a specific field which is supposed to be unique. I would like to prevent creating duplicate 'CUSTOMER' records in NetSuite using the following script.
'

Does anyone see anything that jumps of the page as wrong with the code below?

```<code>    // 2.0
define(["N/error", "N/log"], function (err, log) {

    /**
     * User Event 2.0 example showing usage of the Submit events
     *
     * @NApiVersion 2.x
     * @NModuleScope SameAccount
     * @NScriptType UserEventScript
     * @appliedtorecord customer
     */
    var exports = {};

    function beforeSubmit(scriptContext) {
        log.debug({
            "title": "Before Submit",
            "details": "action=" + scriptContext.type
        });

        if (doesCustomerExist(scriptContext)) {
            throw err.create({
                "name": "DUPLICATE_SFDC_ACCOUNT_ID",
                "message": "Customer Already Contains SFDC Account Id",
                "notifyOff": true
            });
        }
    }

    function doesCustomerExist(scriptContext) {
        var sfdcAccountId = scriptContext.newRecord.getValue('custentitysfdc_account_id');
        if(sfdcAccountId == null || sfdcAccountId == '') return false;

        var searchFilter = new nlobjSearchFilter('custentitysfdc_account_id', null, 'is', sfdcAccountId, null);
        var searchResult = nlapiSearchRecord('customer', null, searchFilter, null);

        return (searchResult != null && searchResult.length > 0);
    }

    exports.beforeSubmit = beforeSubmit;
    return exports;
});
</code>```

答:
nlapiSearchRecord() is a SuiteScript 1.0 function and you're trying to call it from a SuiteScript 2.0 script.

You need to add the N/search module to your 2.0 script and use the functionality provided in that module to perform a search.  In the NetSuite help documentation, navigate to SuiteCloud -> SuiteScript 2.0 -> SuiteScript 2.0 API -> SuiteScript 2.0 Modules -> N/Search Module to learn how to perform a search with SuiteScript 2.0.

Body:
I am having trouble understanding what this error means.

org.mozilla.javascript.EcmaError: ReferenceError: "nlapiSearchRecord"
  is not defined. (/SuiteScripts/PreventDuplicateCustomer.js#35)

I am attempting to create a script which searches for a duplicate record based on a specific field which is supposed to be unique. I would like to prevent creating duplicate 'CUSTOMER' records in NetSuite using the following script.
'

Does anyone see anything that jumps of the page as wrong with the code below?

    // 2.0
define(["N/error", "N/log"], function (err, log) {

    /**
     * User Event 2.0 example showing usage of the Submit events
     *
     * @NApiVersion 2.x
     * @NModuleScope SameAccount
     * @NScriptType UserEventScript
     * @appliedtorecord customer
     */
    var exports = {};

    function beforeSubmit(scriptContext) {
        log.debug({
            "title": "Before Submit",
            "details": "action=" + scriptContext.type
        });

        if (doesCustomerExist(scriptContext)) {
            throw err.create({
                "name": "DUPLICATE_SFDC_ACCOUNT_ID",
                "message": "Customer Already Contains SFDC Account Id",
                "notifyOff": true
            });
        }
    }

    function doesCustomerExist(scriptContext) {
        var sfdcAccountId = scriptContext.newRecord.getValue('custentitysfdc_account_id');
        if(sfdcAccountId == null || sfdcAccountId == '') return false;

        var searchFilter = new nlobjSearchFilter('custentitysfdc_account_id', null, 'is', sfdcAccountId, null);
        var searchResult = nlapiSearchRecord('customer', null, searchFilter, null);

        return (searchResult != null && searchResult.length > 0);
    }

    exports.beforeSubmit = beforeSubmit;
    return exports;
});


问:
Pointer instantly 0x0
i have this code. the pointer turns 0x0 immediately before using it. short before, it had the correct address.

```<code>TreeViewColumn *col;
col = preview->get_column(pcFolder); /* col = 0x7fff5fc404a0 */
col->set_resizable(true);            /* col = 0x0 */
</code>```

i use Gtkmm 2.4, but it returns the expected value, it just turns 0x0. whats wrong?

gdb proof:

```<code>151             col = preview->get_column(pcFolder); /* col = 0x7fff5fc404a0 */
(gdb) print col
$1 = ('Gtk::TreeViewColumn' *) 0x7fff5fc404a0
(gdb) print *col
warning: can't find linker symbol for virtual table for `Gtk::TreeViewColumn' value
$2 = {
  <Gtk::Object> = {
    <Glib::Object> = {
      <Glib::ObjectBase> = <invalid address>,
      members of Glib::Object:
      _vptr$Object = 0x7fff5fc06a20,
      static object_class_ = {<No data fields>}
    },
    members of Gtk::Object:
    static object_class_ = {<No data fields>},
    referenced_ = 21,
    gobject_disposed_ = 60
  },
  members of Gtk::TreeViewColumn:
  static treeviewcolumn_class_ = {<No data fields>}
}
(gdb) next
152             col->set_resizable(true);            /* col = 0x0 */
(gdb) print col
$3 = ('Gtk::TreeViewColumn' *) 0x0
(gdb) print *col
Cannot access memory at address 0x0
(gdb) next

Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000000
0x00000001000edc68 in Gtk::TreeViewColumn::set_resizable ()
</code>```

i have no idea what causes this phenomenon. do you have?

Solution:
reading the documentation. the function returning pcFolder counts from 1, get_column() from 0.

答:
```<code>preview->get_column(pcFolder)
</code>```

must be returning 0.

ContentLicense: CC BY-SA 2.5

Title: Pointer instantly 0x0

Body:
i have this code. the pointer turns 0x0 immediately before using it. short before, it had the correct address.

TreeViewColumn *col;
col = preview->get_column(pcFolder); /* col = 0x7fff5fc404a0 */
col->set_resizable(true);            /* col = 0x0 */

i use Gtkmm 2.4, but it returns the expected value, it just turns 0x0. whats wrong?

gdb proof:

151             col = preview->get_column(pcFolder); /* col = 0x7fff5fc404a0 */
(gdb) print col
$1 = ('Gtk::TreeViewColumn' *) 0x7fff5fc404a0
(gdb) print *col
warning: can't find linker symbol for virtual table for `Gtk::TreeViewColumn' value
$2 = {
  <Gtk::Object> = {
    <Glib::Object> = {
      <Glib::ObjectBase> = <invalid address>,
      members of Glib::Object:
      _vptr$Object = 0x7fff5fc06a20,
      static object_class_ = {<No data fields>}
    },
    members of Gtk::Object:
    static object_class_ = {<No data fields>},
    referenced_ = 21,
    gobject_disposed_ = 60
  },
  members of Gtk::TreeViewColumn:
  static treeviewcolumn_class_ = {<No data fields>}
}
(gdb) next
152             col->set_resizable(true);            /* col = 0x0 */
(gdb) print col
$3 = ('Gtk::TreeViewColumn' *) 0x0
(gdb) print *col
Cannot access memory at address 0x0
(gdb) next

Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000000
0x00000001000edc68 in Gtk::TreeViewColumn::set_resizable ()

i have no idea what causes this phenomenon. do you have?

Solution:
reading the documentation. the function returning pcFolder counts from 1, get_column() from 0.

Body:
preview->get_column(pcFolder)

must be returning 0.


问:
WebStorm support for Vue.js directives
How come I can see some Vue.js intellisense support

but v-on:input is not recognized

I use WebStorm 2017.1

答:
To fix the erros in the editor I used this line .

I am not an expert on both Webstorm/PHPStorm and Vue but maybe they are trying to let you use the shorthand function with @ for v-on: and : for v-bind.

Personally I like to use the shorthand way of doing it.

Title: WebStorm support for Vue.js directives

Body:
To fix the erros in the editor I used this line <html xmlns:v-on="http://www.w3.org/1999/xhtml" xmlns:v-bind="http://www.w3.org/1999/xhtml">.

I am not an expert on both Webstorm/PHPStorm and Vue but maybe they are trying to let you use the shorthand function with @ for v-on: and : for v-bind.

Personally I like to use the shorthand way of doing it.


问:
Creating a game board using struct
So I am making a game board for battle ship, but I am trying to use a struct to make it. Currently I am getting an error when trying to create the game board.  I'm trying to make it this way so that when the user inputs coordinates for the ships, or when they are making a move I can easily change symbols and get to the correct coordinate on the array. This is what I am working with right now. I am using 3 file format, so I put all the parts down below.

I could create the board without using a struct, but I'm pretty sure I need to create it this way so that I am able to manipulate the board later.

If this helps this is my current error: Run-Time Check Failure #3 - The variable 'person' is being used without being initialized.

This is in the header file

```<code>typedef struct game_board
{
    int board[10][10];
    int row;
    int col;
    char symbol;
    }Game_Board;

Game_Board initalize_game_board(Game_Board player);
</code>```

The function

```<code>Game_Board initalize_game_board(Game_Board player)
{
    int row_index = 0, col_index = 0;

    printf("  0 1 2 3 4 5 6 7 8 9\n");
    for (row_index = 0; row_index < player.row; row_index++)
    {
        printf("%d ", row_index);
        for (col_index = 0; col_index < player.col; col_index++)
        {
            player.board[row_index][col_index] = player.symbol;
            printf("%c ", player.board[row_index][col_index]);
        }
        printf("\n");
    }
}
</code>```

In the main function

```<code>int main(void)
{
    FILE *outfile = NULL;
    outfile = fopen("battleship.log", "w");

    Game_Board person, computer;
    int who_goes_first = 0;

    strcpy(person.symbol, '~');
    person.row = 10;
    person.col = 10;
    strcpy(computer.symbol, '~');
    computer.row = 10;
    computer.col = 10;

    welcome_screen(outfile);
    printf("Player 1\n");

   initalize_game_board(person);
</code>```

答:
Building on Ryan's answer, strcpy() assumes the source string has a null terminator, to know how many characters are to be copied. In your case, there is no null terminator in the source string. strcpy() will not stop copying till a null character is read from memory. Since you are using a single character, a simple assignment statement will do!

Also, in function initalize_game_board(), consider passing the pointer to the Game_Board structure, instead of the structure itself. When you do this, you can change the contents of the actual structure (struct 'person' in this case), by using the arrow (->) operator, within the function itself. Then you will not have to return the structure  from this function. With your current design, you are creating a temporary copy of the structure, then populating it, and then (probably after modifications!) returning that structure, which will again be copied to the structure 'person'.

Title: Creating a game board using struct

Body:
So I am making a game board for battle ship, but I am trying to use a struct to make it. Currently I am getting an error when trying to create the game board.  I'm trying to make it this way so that when the user inputs coordinates for the ships, or when they are making a move I can easily change symbols and get to the correct coordinate on the array. This is what I am working with right now. I am using 3 file format, so I put all the parts down below.

I could create the board without using a struct, but I'm pretty sure I need to create it this way so that I am able to manipulate the board later.

If this helps this is my current error: Run-Time Check Failure #3 - The variable 'person' is being used without being initialized.

This is in the header file

typedef struct game_board
{
    int board[10][10];
    int row;
    int col;
    char symbol;
    }Game_Board;

Game_Board initalize_game_board(Game_Board player);

The function

Game_Board initalize_game_board(Game_Board player)
{
    int row_index = 0, col_index = 0;

    printf("  0 1 2 3 4 5 6 7 8 9\n");
    for (row_index = 0; row_index < player.row; row_index++)
    {
        printf("%d ", row_index);
        for (col_index = 0; col_index < player.col; col_index++)
        {
            player.board[row_index][col_index] = player.symbol;
            printf("%c ", player.board[row_index][col_index]);
        }
        printf("\n");
    }
}

In the main function

int main(void)
{
    FILE *outfile = NULL;
    outfile = fopen("battleship.log", "w");

    Game_Board person, computer;
    int who_goes_first = 0;

    strcpy(person.symbol, '~');
    person.row = 10;
    person.col = 10;
    strcpy(computer.symbol, '~');
    computer.row = 10;
    computer.col = 10;

    welcome_screen(outfile);
    printf("Player 1\n");

   initalize_game_board(person);


问:
Is it possible to get current mouse cursor size in Javascript/jQuery?
I am using a custom cursor (SVG file) which is activated when hovering a button. I want this cursor to have the same size with default cursor on all platforms.

I wonder if it is possible to get default cursor size and set size of custom cursor accordingly.

A similar question was asked here almost 8 years ago. I was hoping it would be possible with new technologies.

答: There is no method or API of getting the size of the cursor on a user's OS. However, if you're adding a custom cursor, it is recommended you set its size to 32x32 as that is the size that is most compatible across most OS's.</p>


问:
Internal Server Error Django/apache
My Django app was working fine, but now I'm getting a server error, the last thing I did was a reboot to my Centos7 Server and now I'm getting this error:

and this are my logs I'm using apache:

```<code>[Thu Mar 30 14:04:10.571843 2017] [:error] [pid 11335] [remote 10.221.50.100:24] mod_wsgi (pid=11335): Target WSGI script '/opt/btsystem/BTSystem/wsgi.py' cannot be loaded as Python module.
    [Thu Mar 30 14:04:10.571991 2017] [:error] [pid 11335] [remote 10.221.50.100:24] mod_wsgi (pid=11335): Exception occurred processing WSGI script '/opt/btsystem/BTSystem/wsgi.py'.
    [Thu Mar 30 14:04:10.572263 2017] [:error] [pid 11335] [remote 10.221.50.100:24] Traceback (most recent call last):
    [Thu Mar 30 14:04:10.572544 2017] [:error] [pid 11335] [remote 10.221.50.100:24]   File "/opt/btsystem/BTSystem/wsgi.py", line 16, in <module>
    [Thu Mar 30 14:04:10.572795 2017] [:error] [pid 11335] [remote 10.221.50.100:24]     application = get_wsgi_application()
    [Thu Mar 30 14:04:10.572919 2017] [:error] [pid 11335] [remote 10.221.50.100:24]   File "/usr/lib64/python2.7/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application
    [Thu Mar 30 14:04:10.573054 2017] [:error] [pid 11335] [remote 10.221.50.100:24]     django.setup(set_prefix=False)
    [Thu Mar 30 14:04:10.573107 2017] [:error] [pid 11335] [remote 10.221.50.100:24]   File "/usr/lib64/python2.7/site-packages/django/__init__.py", line 22, in setup
    [Thu Mar 30 14:04:10.573170 2017] [:error] [pid 11335] [remote 10.221.50.100:24]     configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
    [Thu Mar 30 14:04:10.573261 2017] [:error] [pid 11335] [remote 10.221.50.100:24]   File "/usr/lib64/python2.7/site-packages/django/utils/log.py", line 75, in configure_logging
    [Thu Mar 30 14:04:10.573312 2017] [:error] [pid 11335] [remote 10.221.50.100:24]     logging_config_func(logging_settings)
    [Thu Mar 30 14:04:10.573369 2017] [:error] [pid 11335] [remote 10.221.50.100:24]   File "/usr/lib64/python2.7/logging/config.py", line 803, in dictConfig
    [Thu Mar 30 14:04:10.573409 2017] [:error] [pid 11335] [remote 10.221.50.100:24]     dictConfigClass(config).configure()
    [Thu Mar 30 14:04:10.573455 2017] [:error] [pid 11335] [remote 10.221.50.100:24]   File "/usr/lib64/python2.7/logging/config.py", line 585, in configure
    [Thu Mar 30 14:04:10.573501 2017] [:error] [pid 11335] [remote 10.221.50.100:24]     '%r: %s' % (name, e))
    [Thu Mar 30 14:04:10.573567 2017] [:error] [pid 11335] [remote 10.221.50.100:24] ValueError: Unable to configure handler 'file': [Errno 13] Permission denied: '/opt/btsystem-logs/btsystem-debug.log'
</code>```

Any idea?

答:
The last line shows that Django doesn't have permission to write to the configured log file.

[Thu Mar 30 14:04:10.573567 2017] [:error] [pid 11335] [remote 10.221.50.100:24] ValueError: Unable to configure handler 'file': [Errno 13] Permission denied: '/opt/btsystem-logs/btsystem-debug.log'

Make sure the file /opt/btsystem-logs/btsystem-debug.log is writeable by the user running the Django server.

Title: Internal Server Error Django/apache

Body:
My Django app was working fine, but now I'm getting a server error, the last thing I did was a reboot to my Centos7 Server and now I'm getting this error:

and this are my logs I'm using apache:

[Thu Mar 30 14:04:10.571843 2017] [:error] [pid 11335] [remote 10.221.50.100:24] mod_wsgi (pid=11335): Target WSGI script '/opt/btsystem/BTSystem/wsgi.py' cannot be loaded as Python module.
    [Thu Mar 30 14:04:10.571991 2017] [:error] [pid 11335] [remote 10.221.50.100:24] mod_wsgi (pid=11335): Exception occurred processing WSGI script '/opt/btsystem/BTSystem/wsgi.py'.
    [Thu Mar 30 14:04:10.572263 2017] [:error] [pid 11335] [remote 10.221.50.100:24] Traceback (most recent call last):
    [Thu Mar 30 14:04:10.572544 2017] [:error] [pid 11335] [remote 10.221.50.100:24]   File "/opt/btsystem/BTSystem/wsgi.py", line 16, in <module>
    [Thu Mar 30 14:04:10.572795 2017] [:error] [pid 11335] [remote 10.221.50.100:24]     application = get_wsgi_application()
    [Thu Mar 30 14:04:10.572919 2017] [:error] [pid 11335] [remote 10.221.50.100:24]   File "/usr/lib64/python2.7/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application
    [Thu Mar 30 14:04:10.573054 2017] [:error] [pid 11335] [remote 10.221.50.100:24]     django.setup(set_prefix=False)
    [Thu Mar 30 14:04:10.573107 2017] [:error] [pid 11335] [remote 10.221.50.100:24]   File "/usr/lib64/python2.7/site-packages/django/__init__.py", line 22, in setup
    [Thu Mar 30 14:04:10.573170 2017] [:error] [pid 11335] [remote 10.221.50.100:24]     configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
    [Thu Mar 30 14:04:10.573261 2017] [:error] [pid 11335] [remote 10.221.50.100:24]   File "/usr/lib64/python2.7/site-packages/django/utils/log.py", line 75, in configure_logging
    [Thu Mar 30 14:04:10.573312 2017] [:error] [pid 11335] [remote 10.221.50.100:24]     logging_config_func(logging_settings)
    [Thu Mar 30 14:04:10.573369 2017] [:error] [pid 11335] [remote 10.221.50.100:24]   File "/usr/lib64/python2.7/logging/config.py", line 803, in dictConfig
    [Thu Mar 30 14:04:10.573409 2017] [:error] [pid 11335] [remote 10.221.50.100:24]     dictConfigClass(config).configure()
    [Thu Mar 30 14:04:10.573455 2017] [:error] [pid 11335] [remote 10.221.50.100:24]   File "/usr/lib64/python2.7/logging/config.py", line 585, in configure
    [Thu Mar 30 14:04:10.573501 2017] [:error] [pid 11335] [remote 10.221.50.100:24]     '%r: %s' % (name, e))
    [Thu Mar 30 14:04:10.573567 2017] [:error] [pid 11335] [remote 10.221.50.100:24] ValueError: Unable to configure handler 'file': [Errno 13] Permission denied: '/opt/btsystem-logs/btsystem-debug.log'

Any idea?


问:
PHP DOM parsing text between
 tags
I am trying to parse some HTML to get the text between two
 tags using DOM with PHP but I don't get any output when I pass in hr into getElementsByTagName:

```<code><?php
    $dom = new DOMDocument();
    $dom->loadHTML("<hr>Text<hr>");
    $hr = $dom->getElementsByTagName("hr");
    for ($i=0; $i<$hr->length; $i++) {
        echo "[". $i . "]" . $hr->item($i)->nodeValue . "</br>";
    }
?>
</code>```

When I run this code, it doesn't output anything however, if I change "hr" to "*" then it outputs:

```<code>[0]Text
[1]Text
[2]
[3]
</code>```

(Why four lines of results?)

I run this code on a webserver which has PHP version 7.1.3 running. I can't use functions such as file_get_html or str_get_html because it returns an error about Undefined call to function ...

Why doesn't the hr tag produce results?

答:
Perhaps what you're looking for is the contents of the text node between two
 elements? In that case we go looking for siblings with an XPath expression:

```<code><?php
$dom = new DOMDocument();
$dom->loadHTML("Some text<hr>The text<hr>Other text");
$xp = new DomXPath($dom);
$result = $xp->query("//text()[(preceding-sibling::hr and following-sibling::hr)]");
foreach ($result as $i=>$node) {
    echo "[$i]$node->textContent<br/>\n";
}
</code>```

Title: PHP DOM parsing text between <hr> tags

Body:
I am trying to parse some HTML to get the text between two
 tags using DOM with PHP but I don't get any output when I pass in hr into getElementsByTagName:

<?php
    $dom = new DOMDocument();
    $dom->loadHTML("
Text
");
    $hr = $dom->getElementsByTagName("hr");
    for ($i=0; $i<$hr->length; $i++) {
        echo "[". $i . "]" . $hr->item($i)->nodeValue . "
";
    }
?>

When I run this code, it doesn't output anything however, if I change "hr" to "*" then it outputs:

[0]Text
[1]Text
[2]
[3]

(Why four lines of results?)

I run this code on a webserver which has PHP version 7.1.3 running. I can't use functions such as file_get_html or str_get_html because it returns an error about Undefined call to function ...

Why doesn't the hr tag produce results?

Body:
Perhaps what you're looking for is the contents of the text node between two <hr> elements? In that case we go looking for siblings with an XPath expression:

<?php
$dom = new DOMDocument();
$dom->loadHTML("Some text<hr>The text<hr>Other text");
$xp = new DomXPath($dom);
$result = $xp->query("//text()[(preceding-sibling::hr and following-sibling::hr)]");
foreach ($result as $i=>$node) {
    echo "[$i]$node->textContent<br/>\n";
}


问:
piping the output to another command
The diff command works only if it has been provided with 2 files. Is it possible to replace one file with the output of another command? The second command mentioned below does not work.</p>

```<code>$ mysqldump -ushantanu -pPassWord test tbl --skip-extended-insert > to_backup.sql

$ diff  `mysqldump -uroot -pPassWord test some_other_tbl --skip-extended-insert` to_backup.sql
-bash: /usr/bin/diff: Argument list too long
</code>```

答:
In bash you can use process substitution.</p>

```<code>diff <(mysqldump ...) to_backup.sql
</code>```

Title: piping the output to another command

Body:
The diff command works only if it has been provided with 2 files. Is it possible to replace one file with the output of another command? The second command mentioned below does not work.

$ mysqldump -ushantanu -pPassWord test tbl --skip-extended-insert > to_backup.sql

$ diff  `mysqldump -uroot -pPassWord test some_other_tbl --skip-extended-insert` to_backup.sql
-bash: /usr/bin/diff: Argument list too long

Body:
In bash you can use process substitution.

diff <(mysqldump ...) to_backup.sql


问:
Adding to local storage only working after refreshing the page after button navigation to another page
I am developing an app that allows user to search for fishing lakes in their area. To do this they can type in their location which then displays fisheries near them that i have identified in the Json data. The search works perfectly with the code below i have written (i know it maybe a little flaky as i am not the best programmer).

```<code>//search
$(document).ready(function(){
    $('#exampleSearch').keyup(function() {
        var searchVal = $('#exampleSearch').val();
        $('#results').empty();
        console.log(searchVal);
        var results = [];
        $.getJSON("/data/locations.json",function(locations) {
            for (var i = 0; i < locations.length; i++) {
                if (locations[i].location.match(searchVal)) {
                    results.push(locations[i]);
                }
            }

            $.each(results, function(index,result) {
                var $resultsLi = $(
                    '<div class="row">'+
                    '<div class="twelve columns profile-information ">'+
                    '<div class="profile-title">'+
                    '<h6>'+result.name+'</h6>'+
                    '</div> ' +
                    ' <img class= "favourites-pic" src="'+ result.image +'" alt="Fishery">'+
                    '<a class="view" href="'+ result.url + '" >View</a>'+
                    '</div>'+
                    ' </div>'
                )
                $("#results").append($resultsLi);
            });
        });
    });
});
</code>```

I have now added a feature where users can now add their search results to their favourites page, by click a Add to favorites button on the page of the fishery they found from their search with the following code:

Javascript:

```<code>//Add to Favourites
$(function() {
    $( ".addFavourites" ).on("click", function() {
        try {
            $(this).attr('disabled', true);

            var locIdToAdd = $(this).closest("p").attr("id");

            var myFavouriteLoc=JSON.parse(localStorage.getItem("favLoc"));

            if (myFavouriteLoc == null) {
                myFavouriteLoc = [];
            }

            if (myFavouriteLoc != null) {
                for ( var j = 0; j < myFavouriteLoc.length; j++) {
                    if ( locIdToAdd == myFavouriteLoc[j]) {
                        alert("This property is already in your favourites");
                        myFavouriteLoc = [];
                    }
                }
            }

            myFavouriteLoc.push(locIdToAdd);

            localStorage.setItem("favLoc", JSON.stringify(myFavouriteLoc));

        } catch (e) {
            if (e == QUOTA_EXCEEDED_ERR) {
                console.log("Error: Local storage limit exceeds");
            } else {
                console.log("ERROR: Saving to local storge.");
            }
        }
    });
});
</code>```

Html:

```<code><p id="loc 1">
    <input class="button-primary green addFavourites" type="submit" value="Add to Favourites">
</p>
</code>```

THE PROBLEM

Upon clicking the 'view' button on the search page results, and navigating to a fishery page. I have a problem where i have to then refresh the page again before the add to favourites button will add anything to the local storage, it is clickable, but nothing happens. once i refresh the page it works fine.

Can anyone help with why i have to refresh the page first? any help is a appreciated :)

答:
I can't see any code relating to loading the list of favourites, but I think it's fair to assume to that when the page loads you're loading the items from storage and placing them in, and then the pages where you add favourites and view favourites don't involve any loading between them. Therefore, of course, loading the items for the favourites list will only be performed on load, and so placing new items into the localStorage without reloading will not add them. So I'm going to cover a few things.

Firstly, don't use == and !=. They perform type coercion, (numbers to strings, strings to numbers, null to undefined, etc.), the rules for which are unintuitive and unmemorable and are best simply avoided, lest they cause difficult to diagnose problems in your code. Use === and !== instead, these behave just like == and != does in other languages. If you want to perform type coercion I'd do so explicitly (e.g. Number('5')).

Secondly, and just as a suggestion, if you implement the local storage as an object, you won't need to loop and can simply use property names. So you can replace

```<code>if (myFavouriteLoc != null) {
    for ( var j = 0; j < myFavouriteLoc.length; j++) {
        if ( locIdToAdd == myFavouriteLoc[j]) {
</code>```

With simply

```<code>if (myFavouriteLoc && myFavouriteLoc[locIdToAdd]) {
    // ...
}
</code>```

The object && object.property idiom will perform a truthy check on both the object and the property, only passing if they are both truthy (not falsy). Here's a list of falsy values.

So, to answer your actual question. I'd say you have two options:

Reload the page on each addition, or

AJAXily add the entry to your views when favourites are added. Favourites will then, of course, need be removed

Going with my assumption in the first paragraph, I'd say that the second option is your best bet, as the constant page refreshes would provide a bad user experience.

So here's the jsfiddle

```<code>(function bindBtns() {
    $('.Table-btn--add').click(function () {
        addBinding($(this));
    });

    $('.Table-btn--remove').click(function () {
        removeBinding($(this));
    });
})();
</code>```

Here is an immediately invoked function, meaning it's run straight away. This will bind the existing buttons' behaviour, depending on whether they are add or remove buttons.

```<code>function addBinding($btn) {
    $btn.parent()
        .detach()
        .appendTo($('#favourites'));
    // add to local storage here
    modifyAttributes($btn);
}
</code>```

Here's the behaviour for the binding, fairly straight forward, but:

Select the buttons parent, i.e. the row

Detach it from the DOM, i.e. the current table

Attach it to the other table

Rebind the button to perform the opposite behaviour, shown below

Place your behaviour for adding or removing from local storage where I've placed the comments.

removeBinding is exactly the same except it appends to the other table.

```<code>function modifyAttributes($btn) {
    if ($btn.hasClass('Table-btn--add')) {
        $btn.text('Remove')
            .removeClass('Table-btn--add')
            .addClass('Table-btn--remove')
            .off('click')
            .click(removeBinding.bind(null, $btn));
    } else if ($btn.hasClass('Table-btn--remove')) {
        $btn.text('Add')
            .removeClass('Table-btn--remove')
            .addClass('Table-btn--add')
            .off('click')
            .click(addBinding.bind(null, $btn));
    }
}
</code>```

Split on whether this is an adding button, or a removing button. (The next steps will be for both versions.)

Update the text to be the opposite, (add -> remove, remove -> add)

Remove the current class

Add the new class

Remove the old click binding

Bind the new click binding. Read about .bind here

In your version you would replace .Table-btn--add with .addFavourites, and place addBinding($(this)) in your try block, and then you can just copy over the other functiona verbatim (I think).

Good luck! Sorry that got so long, and let me know how it goes.

Body:
I am developing an app that allows user to search for fishing lakes in their area. To do this they can type in their location which then displays fisheries near them that i have identified in the Json data. The search works perfectly with the code below i have written (i know it maybe a little flaky as i am not the best programmer).

//search
$(document).ready(function(){
    $('#exampleSearch').keyup(function() {
        var searchVal = $('#exampleSearch').val();
        $('#results').empty();
        console.log(searchVal);
        var results = [];
        $.getJSON("/data/locations.json",function(locations) {
            for (var i = 0; i < locations.length; i++) {
                if (locations[i].location.match(searchVal)) {
                    results.push(locations[i]);
                }
            }

            $.each(results, function(index,result) {
                var $resultsLi = $(
                    '
'+
                    '
'+
                    '
'+
                    '
'+result.name+'
'+
                    '
 ' +
                    ' '+
                    'View'+
                    '
'+
                    '
'
                )
                $("#results").append($resultsLi);
            });
        });
    });
});

I have now added a feature where users can now add their search results to their favourites page, by click a Add to favorites button on the page of the fishery they found from their search with the following code:

Javascript:

//Add to Favourites
$(function() {
    $( ".addFavourites" ).on("click", function() {
        try {
            $(this).attr('disabled', true);

            var locIdToAdd = $(this).closest("p").attr("id");

            var myFavouriteLoc=JSON.parse(localStorage.getItem("favLoc"));

            if (myFavouriteLoc == null) {
                myFavouriteLoc = [];
            }

            if (myFavouriteLoc != null) {
                for ( var j = 0; j < myFavouriteLoc.length; j++) {
                    if ( locIdToAdd == myFavouriteLoc[j]) {
                        alert("This property is already in your favourites");
                        myFavouriteLoc = [];
                    }
                }
            }

            myFavouriteLoc.push(locIdToAdd);

            localStorage.setItem("favLoc", JSON.stringify(myFavouriteLoc));

        } catch (e) {
            if (e == QUOTA_EXCEEDED_ERR) {
                console.log("Error: Local storage limit exceeds");
            } else {
                console.log("ERROR: Saving to local storge.");
            }
        }
    });
});

Html:

    <input class="button-primary green addFavourites" type="submit" value="Add to Favourites">

THE PROBLEM

Upon clicking the 'view' button on the search page results, and navigating to a fishery page. I have a problem where i have to then refresh the page again before the add to favourites button will add anything to the local storage, it is clickable, but nothing happens. once i refresh the page it works fine.

Can anyone help with why i have to refresh the page first? any help is a appreciated :)

Body:
I can't see any code relating to loading the list of favourites, but I think it's fair to assume to that when the page loads you're loading the items from storage and placing them in, and then the pages where you add favourites and view favourites don't involve any loading between them. Therefore, of course, loading the items for the favourites list will only be performed on load, and so placing new items into the localStorage without reloading will not add them. So I'm going to cover a few things.

Firstly, don't use == and !=. They perform type coercion, (numbers to strings, strings to numbers, null to undefined, etc.), the rules for which are unintuitive and unmemorable and are best simply avoided, lest they cause difficult to diagnose problems in your code. Use === and !== instead, these behave just like == and != does in other languages. If you want to perform type coercion I'd do so explicitly (e.g. Number('5')).

Secondly, and just as a suggestion, if you implement the local storage as an object, you won't need to loop and can simply use property names. So you can replace

if (myFavouriteLoc != null) {
    for ( var j = 0; j < myFavouriteLoc.length; j++) {
        if ( locIdToAdd == myFavouriteLoc[j]) {

With simply

if (myFavouriteLoc && myFavouriteLoc[locIdToAdd]) {
    // ...
}

The object && object.property idiom will perform a truthy check on both the object and the property, only passing if they are both truthy (not falsy). Here's a list of falsy values.

So, to answer your actual question. I'd say you have two options:

Reload the page on each addition, or

AJAXily add the entry to your views when favourites are added. Favourites will then, of course, need be removed

Going with my assumption in the first paragraph, I'd say that the second option is your best bet, as the constant page refreshes would provide a bad user experience.

So here's the jsfiddle

(function bindBtns() {
    $('.Table-btn--add').click(function () {
        addBinding($(this));
    });

    $('.Table-btn--remove').click(function () {
        removeBinding($(this));
    });
})();

Here is an immediately invoked function, meaning it's run straight away. This will bind the existing buttons' behaviour, depending on whether they are add or remove buttons.

function addBinding($btn) {
    $btn.parent()
        .detach()
        .appendTo($('#favourites'));
    // add to local storage here
    modifyAttributes($btn);
}

Here's the behaviour for the binding, fairly straight forward, but:

Select the buttons parent, i.e. the row

Detach it from the DOM, i.e. the current table

Attach it to the other table

Rebind the button to perform the opposite behaviour, shown below

Place your behaviour for adding or removing from local storage where I've placed the comments.

removeBinding is exactly the same except it appends to the other table.

function modifyAttributes($btn) {
    if ($btn.hasClass('Table-btn--add')) {
        $btn.text('Remove')
            .removeClass('Table-btn--add')
            .addClass('Table-btn--remove')
            .off('click')
            .click(removeBinding.bind(null, $btn));
    } else if ($btn.hasClass('Table-btn--remove')) {
        $btn.text('Add')
            .removeClass('Table-btn--remove')
            .addClass('Table-btn--add')
            .off('click')
            .click(addBinding.bind(null, $btn));
    }
}

Split on whether this is an adding button, or a removing button. (The next steps will be for both versions.)

Update the text to be the opposite, (add -> remove, remove -> add)

Remove the current class

Add the new class

Remove the old click binding

Bind the new click binding. Read about .bind here

In your version you would replace .Table-btn--add with .addFavourites, and place addBinding($(this)) in your try block, and then you can just copy over the other functiona verbatim (I think).

Good luck! Sorry that got so long, and let me know how it goes.


问:
Remove standard SAS libraries from GUI
I'd like to remove/delete/unassign the standard SAS libraries from my SAS 9.3 GUI.

I've tried two solutions to remove a library which haven't worked:

%sysfunc(libname(maps)) results in:

ERROR 180-322: Statement is not valid or it is used out of proper order.

Comment out the offending start up code in the file sasv9.cfg

I don't have permission to modify (C:\Program Files...) files in that directory

Thanks!

The libraries are:
 - Maps

Mapsgfk

Mapssas

Sashelp

Sasuser

答:
You can remove the map related libnames, at the cost of not having the map files available to you and possibly losing some functionality.

If you copy your basic config file to some other location, either to one of the predefined locations mentioned in Files Used By SAS for your operating system (I link to the Windows version here, but Unix has a similar page);  or to a location specified on the -CONFIG option in your shortcut, like for example:

```<code>"C:\Program Files\SAS94\SASFoundation\9.4\sas.exe" -CONFIG "C:\temp\sasv9_nolibs.cfg"
</code>```

You can do this without having write access to the Program Files directories where the config files are usually stored. If you do that, you can then customize it by removing the -MAPS and related lines.  Then those libraries will not be created; in that case, only SASHELP, SASUSER, and WORK are created, as follows:

Removing SASUSER does not seem to be possible, as while you can remove the -SASUSER option in the config file, it will still create the SASUSER folder.

Removing the -SASHELP option will unfortunately cause SAS to crash on initialization; SASHELP contains many core files for SAS functionality and SAS cannot work without it.  See the following screenshot.

As such, you can get down to 3 libraries, but not further.

Title: Remove standard SAS libraries from GUI

Body:
You can remove the map related libnames, at the cost of not having the map files available to you and possibly losing some functionality.

If you copy your basic config file to some other location, either to one of the predefined locations mentioned in Files Used By SAS for your operating system (I link to the Windows version here, but Unix has a similar page);  or to a location specified on the -CONFIG option in your shortcut, like for example:

"C:\Program Files\SAS94\SASFoundation\9.4\sas.exe" -CONFIG "C:\temp\sasv9_nolibs.cfg"

You can do this without having write access to the Program Files directories where the config files are usually stored. If you do that, you can then customize it by removing the -MAPS and related lines.  Then those libraries will not be created; in that case, only SASHELP, SASUSER, and WORK are created, as follows:

Removing SASUSER does not seem to be possible, as while you can remove the -SASUSER option in the config file, it will still create the SASUSER folder.

Removing the -SASHELP option will unfortunately cause SAS to crash on initialization; SASHELP contains many core files for SAS functionality and SAS cannot work without it.  See the following screenshot.

As such, you can get down to 3 libraries, but not further.


问:
How to uncheck a radio button by clicking on it a second time
I have been searching in a lot of topics but I haven't found anything that really correspond to my problem :

I want to make radio buttons uncheckable (i.e. uncheck a radio button by clicking on it when it's already checked).

I found some solutions using a hidden radio button as a temporary comparison object but this doesn't fits to my existing context, so I would like to do the same without another radio button.

I tried to simply test and change the status/value of the radio button on "onclick" event but it hasn't been very successfull...

Thanks in advance,
Clem.

答:
That's not what radio buttons are. If you try to make this work, you will just confuse your users.

If you want something that can be checked and then unchecked, use a checkbox. Radio buttons are for selecting exactly one of some set of options.


问:
How to Run Shell Script at start in VM Virtualbox Ubuntu 16.04
I am trying to run a shell script which runs at system login. To try, I used an example script, which has two lines
   #!/bin/bash
   echo “Hello World”

I Followed all the instructions mentioned on this website http://www.cyberciti.biz/tips/linux-how-to-run-a-command-when-boots-up.html

Even I did some steps such as editing /etc/rc.local, but still when I login, I do not see Hello world output running on terminal.

Can anyone please explain what is wrong here or may be I am missing something?

答:
Looks to me like Ubuntu 16.04 is a systemd system.

Which means you should create a systemd service to run whatever you'd like @ startup.

Look here https://wiki.ubuntu.com/SystemdForUpstartUsers#Example_Systemd_service

After you made your service, use systemctl to enable it on boot for systemd.

sudo systemctl enable mycustom.service

To start the service.

sudo systemctl start mycustom.service


问:
compute sum of columns in a nested list in R
How do we do column sums on elements of nested lists. I have a nested list of 10  each containing a sublist of 50 elements which are matrices with 4 columns with differing number of rows. Here is a simpler example. I need to add the columns across the lists. I need a vector of colsums.ll<-c(26, 66, 106, 146). I tried to do do.call("rbind",ll) to collapse the list into 1 dataframe and then apply colSums but was not successful. </p>

```<code>    l1<-matrix(c(1:8),nrow=2)
    l2<-matrix(c(1:16),nrow=4)
    l<-list(l1,l2)
    ll<-list(l,l)
     ll
    [[1]]
   [[1]][[1]]
        [,1] [,2] [,3] [,4]
  [1,]    1    3    5    7
  [2,]    2    4    6    8

   [[1]][[2]]
         [,1] [,2] [,3] [,4]
    [1,]    1    5    9   13
    [2,]    2    6   10   14
    [3,]    3    7   11   15
    [4,]    4    8   12   16

    [[2]]
    [[2]][[1]]
         [,1] [,2] [,3] [,4]
    [1,]    1    3    5    7
    [2,]    2    4    6    8

    [[2]][[2]]
        [,1] [,2] [,3] [,4]
    [1,]    1    5    9   13
    [2,]    2    6   10   14
    [3,]    3    7   11   15
    [4,]    4    8   12   16
</code>```

答:
```<code>colSums(do.call(rbind, lapply(lapply(rapply(ll, enquote, how="unlist"), eval), colSums)))
[1]  26  66 106 146
</code>```

Body:
How do we do column sums on elements of nested lists. I have a nested list of 10  each containing a sublist of 50 elements which are matrices with 4 columns with differing number of rows. Here is a simpler example. I need to add the columns across the lists. I need a vector of colsums.ll<-c(26, 66, 106, 146). I tried to do do.call("rbind",ll) to collapse the list into 1 dataframe and then apply colSums but was not successful.

    l1<-matrix(c(1:8),nrow=2)
    l2<-matrix(c(1:16),nrow=4)
    l<-list(l1,l2)
    ll<-list(l,l)
     ll
    [[1]]
   [[1]][[1]]
        [,1] [,2] [,3] [,4]
  [1,]    1    3    5    7
  [2,]    2    4    6    8

   [[1]][[2]]
         [,1] [,2] [,3] [,4]
    [1,]    1    5    9   13
    [2,]    2    6   10   14
    [3,]    3    7   11   15
    [4,]    4    8   12   16

    [[2]]
    [[2]][[1]]
         [,1] [,2] [,3] [,4]
    [1,]    1    3    5    7
    [2,]    2    4    6    8

    [[2]][[2]]
        [,1] [,2] [,3] [,4]
    [1,]    1    5    9   13
    [2,]    2    6   10   14
    [3,]    3    7   11   15
    [4,]    4    8   12   16


问:
Apply Android Gradle plugin using new syntax
How can I apply Android plugin using new Gradle plugin syntax:

```<code>plugins {
    id "..." version "..."
}
</code>```

Instead of:

```<code>buildscript {
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.0'
    }
}

apply plugin: 'com.android.application'
</code>```

答:
This should do it.

```<code>plugins {
  id "com.android.application" version "<desired version>"
}
</code>```

See the DSL at https://docs.gradle.org/current/userguide/plugins.html#sec:plugins_block

The id is what you'd previously "apply".

Body:
How can I apply Android plugin using new Gradle plugin syntax:

plugins {
    id "..." version "..."
}

Instead of:

buildscript {
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.0'
    }
}

apply plugin: 'com.android.application'

Body:
This should do it.

plugins {
  id "com.android.application" version "<desired version>"
}

See the DSL at https://docs.gradle.org/current/userguide/plugins.html#sec:plugins_block

The id is what you'd previously "apply".


问:
Remove duplicates as well as original row
Removing duplicates is no problem, i am hitting an issue where i want to remove not only the duplicate but the original row that incurred the duplicate in a SELECT statement.

```<code>ItemNUMBER  ID    from_DATE   to_DATE   fancy_code
1           100   3/28/2015   4/10/2015    Z5111
2           100   4/18/2015   4/21/2015    Z5112
3           100   5/2/2015    5/5/2015     Z5111
4           100   5/31/2015   6/2/2015     Z5111
5           100   7/31/2015   8/16/2015    A400       --remove
6           100   7/31/2015   8/16/2015    A400       --remove
</code>```

Above is my table, and --remove is what the end goal is.  Any help would be much appreciated!

答:
The brute force method is to use window functions:

```<code>with t as (
      <your query here>
     )
select t.*
from (select t.*,
             count(*) over (partition by ID, from_DATE, to_DATE, fancy_code) as cnt
      from t
     ) t
where cnt = 1;
</code>```

The more intelligent method is to fix the query or the data that is causing the duplicates.  Of course, there are circumstances where such a fix is not possible, so you need to use the brute force method.

Body:
Removing duplicates is no problem, i am hitting an issue where i want to remove not only the duplicate but the original row that incurred the duplicate in a SELECT statement.

ItemNUMBER  ID    from_DATE   to_DATE   fancy_code
1           100   3/28/2015   4/10/2015    Z5111
2           100   4/18/2015   4/21/2015    Z5112
3           100   5/2/2015    5/5/2015     Z5111
4           100   5/31/2015   6/2/2015     Z5111
5           100   7/31/2015   8/16/2015    A400       --remove
6           100   7/31/2015   8/16/2015    A400       --remove

Above is my table, and --remove is what the end goal is.  Any help would be much appreciated!

Body:
The brute force method is to use window functions:

with t as (
      <your query here>
     )
select t.*
from (select t.*,
             count(*) over (partition by ID, from_DATE, to_DATE, fancy_code) as cnt
      from t
     ) t
where cnt = 1;

The more intelligent method is to fix the query or the data that is causing the duplicates.  Of course, there are circumstances where such a fix is not possible, so you need to use the brute force method.


问:
Should an object under the @Mock annotation have its constructor called?
I'm trying to create an unit test mocking some dependencies with Mockito.
Here's the main code:

```<code>import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static org.mockito.Mockito.verify;

@RunWith(MockitoJUnitRunner.class)
public class VolumesPresenterTest {

VolumesPresenter presenter;

@Mock
OrderRepository orderRepository;

@Mock
VolumesRepository volumesRepository;

@Before
public void createPresenter() {
    presenter = new DefaultVolumesPresenter(orderRepository, volumesRepository);
}

@Test
public void testGetVolumes() {
    presenter.getVolumes();
    verify(volumesRepository).getVolumes();
}
}
</code>```

OrderRepository has a single constructor, which receives an Android Context as a param. This is causing the unit test to fail with the following stack trace:

```<code>java.lang.NoClassDefFoundError: android/content/Context

at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2671)
at java.lang.Class.getDeclaredConstructors(Class.java:2020)
at org.mockito.internal.creation.cglib.ClassImposterizer.setConstructorsAccessible(ClassImposterizer.java:85)
at org.mockito.internal.creation.cglib.ClassImposterizer.imposterise(ClassImposterizer.java:71)
at org.mockito.internal.creation.cglib.ClassImposterizer.imposterise(ClassImposterizer.java:49)
at org.mockito.internal.creation.cglib.CglibMockMaker.createMock(CglibMockMaker.java:24)
at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:33)
at org.mockito.internal.MockitoCore.mock(MockitoCore.java:59)
at org.mockito.Mockito.mock(Mockito.java:1285)
at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:33)
at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:16)
at org.mockito.internal.configuration.DefaultAnnotationEngine.createMockFor(DefaultAnnotationEngine.java:43)
at org.mockito.internal.configuration.DefaultAnnotationEngine.process(DefaultAnnotationEngine.java:66)
at org.mockito.internal.configuration.InjectingAnnotationEngine.processIndependentAnnotations(InjectingAnnotationEngine.java:71)
at org.mockito.internal.configuration.InjectingAnnotationEngine.process(InjectingAnnotationEngine.java:55)
at org.mockito.MockitoAnnotations.initMocks(MockitoAnnotations.java:108)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl$1.withBefores(JUnit45AndHigherRunnerImpl.java:27)
at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:276)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.ClassNotFoundException: android.content.Context
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 39 more

Test ignored.
Process finished with exit code 255
</code>```

I understand that I can't use the android framework on unit tests, but I didn't expect the real constructor of OrderRepository to be called. Being a mocked object, I thought it would just be replaced with some other dumb/mock implementation.

My question is: am I missing anything or the constructors of objects annotated with @Mock are indeed supposed to be called? If so, how can I mock a dependency which expects a Context as a param to its constructor?

答:
Mockito does not call the constructor; you can put logging in a simple class's constructor to test this. However, under the hood Mockito sets the accessibility of all constructors to public before creating the class.

You need to have the classpath of your unit tests contain the android libraries so when the constructors are loaded by Mockito it can see Context even though it doesn't actually use them.

EDIT: If you're curious what it's doing under the hood there's an example with explanation in this answer that shows what Mockito's libraries are doing in the last 5 lines of your stacktrace.

Body:
I'm trying to create an unit test mocking some dependencies with Mockito.
Here's the main code:

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static org.mockito.Mockito.verify;

@RunWith(MockitoJUnitRunner.class)
public class VolumesPresenterTest {

VolumesPresenter presenter;

@Mock
OrderRepository orderRepository;

@Mock
VolumesRepository volumesRepository;

@Before
public void createPresenter() {
    presenter = new DefaultVolumesPresenter(orderRepository, volumesRepository);
}

@Test
public void testGetVolumes() {
    presenter.getVolumes();
    verify(volumesRepository).getVolumes();
}
}

OrderRepository has a single constructor, which receives an Android Context as a param. This is causing the unit test to fail with the following stack trace:

java.lang.NoClassDefFoundError: android/content/Context

at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2671)
at java.lang.Class.getDeclaredConstructors(Class.java:2020)
at org.mockito.internal.creation.cglib.ClassImposterizer.setConstructorsAccessible(ClassImposterizer.java:85)
at org.mockito.internal.creation.cglib.ClassImposterizer.imposterise(ClassImposterizer.java:71)
at org.mockito.internal.creation.cglib.ClassImposterizer.imposterise(ClassImposterizer.java:49)
at org.mockito.internal.creation.cglib.CglibMockMaker.createMock(CglibMockMaker.java:24)
at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:33)
at org.mockito.internal.MockitoCore.mock(MockitoCore.java:59)
at org.mockito.Mockito.mock(Mockito.java:1285)
at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:33)
at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:16)
at org.mockito.internal.configuration.DefaultAnnotationEngine.createMockFor(DefaultAnnotationEngine.java:43)
at org.mockito.internal.configuration.DefaultAnnotationEngine.process(DefaultAnnotationEngine.java:66)
at org.mockito.internal.configuration.InjectingAnnotationEngine.processIndependentAnnotations(InjectingAnnotationEngine.java:71)
at org.mockito.internal.configuration.InjectingAnnotationEngine.process(InjectingAnnotationEngine.java:55)
at org.mockito.MockitoAnnotations.initMocks(MockitoAnnotations.java:108)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl$1.withBefores(JUnit45AndHigherRunnerImpl.java:27)
at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:276)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.ClassNotFoundException: android.content.Context
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 39 more

Test ignored.
Process finished with exit code 255

I understand that I can't use the android framework on unit tests, but I didn't expect the real constructor of OrderRepository to be called. Being a mocked object, I thought it would just be replaced with some other dumb/mock implementation.

My question is: am I missing anything or the constructors of objects annotated with @Mock are indeed supposed to be called? If so, how can I mock a dependency which expects a Context as a param to its constructor?


问:
Using Node and Firebase Together
I have an app that POST an image to a 3rd party API. One of the parameters is an imageCallbackURL a webhook callback URL when image is processed.

If I am using Firebase as my backend, could I also create a node server at www.mysite.com/something that their api could POST the edited image to? I'd then have some server side functionality that would store the new image in Firebase storage.

Is this possible?

答:
firebaser here

We just released an integration between Google Cloud Functions and Firebase. You could use a HTTP function to implement a web hook. We even have an example of a WebHook in our list of use-cases.

The details of course depend on what the third party is sending in the WebHook and what you'd want to do with it in the Cloud Function. If you have a better idea on that, I'd recommend updating your question or posting a new one.

Title: Using Node and Firebase Together


问:
should state be nested or flat
For example,

```<code>constructor(props) {
  super(props);
  this.state = {
    interactions: {
      liked: [],
      saved: [],
      receivedLikeRecently: null
  }
}
</code>```

I'm trying to wrap my head around immutability, so if I wanted to now update receivedLikeRecently to true, would I have to do:

```<code>this.setState({
  interactions: {
    receivedLikeRecently: true
  }
});
</code>```

What about the other values?  Do I need to include them as well?

According to the documentation setState does a shallow merge so I assume the other nested properties would not copy over right?  Or am I misunderstanding?

Thanks

答:
You are correct, the nested state updates require more elaborate merging.

There is a concept of state normalization, described for Redux, but applicable to React state as well.
http://redux.js.org/docs/recipes/reducers/NormalizingStateShape.html

The thinking is, think of the state as of a relational data store to ease working with it.

Title: should state be nested or flat

Body:
For example,

constructor(props) {
  super(props);
  this.state = {
    interactions: {
      liked: [],
      saved: [],
      receivedLikeRecently: null
  }
}

I'm trying to wrap my head around immutability, so if I wanted to now update receivedLikeRecently to true, would I have to do:

this.setState({
  interactions: {
    receivedLikeRecently: true
  }
});

What about the other values?  Do I need to include them as well?

According to the documentation setState does a shallow merge so I assume the other nested properties would not copy over right?  Or am I misunderstanding?

Thanks


答:
Here are some ways:

1) Flatten the first level of ll, take the column sums and then take the row sums of the result:

```<code>rowSums(sapply(do.call(c, ll), colSums))
## [1]  26  66 106 146
</code>```

2) Another way is after flattening then rbind all the matrices together and then take colSums of that.  Note that in contrast to (1) this one has no sapply or lapply.

```<code>colSums(do.call(rbind, do.call(c, ll)))
## [1]  26  66 106 146
</code>```

3) The above do not use any packages but could be translated to use magrittr like this where the first pipeline corresponds to (1) and the second to (2)

```<code>library(magrittr)

ll %>% do.call(what = c) %>% sapply(colSums) %>% rowSums
## [1]  26  66 106 146

ll %>% do.call(what = c) %>% do.call(what = rbind) %>% colSums
## [1]  26  66 106 146
</code>```

Title: compute sum of columns in a nested list in R

Body:
Here are some ways:

1) Flatten the first level of ll, take the column sums and then take the row sums of the result:

rowSums(sapply(do.call(c, ll), colSums))
## [1]  26  66 106 146

2) Another way is after flattening then rbind all the matrices together and then take colSums of that.  Note that in contrast to (1) this one has no sapply or lapply.

colSums(do.call(rbind, do.call(c, ll)))
## [1]  26  66 106 146

3) The above do not use any packages but could be translated to use magrittr like this where the first pipeline corresponds to (1) and the second to (2)

library(magrittr)

ll %>% do.call(what = c) %>% sapply(colSums) %>% rowSums
## [1]  26  66 106 146

ll %>% do.call(what = c) %>% do.call(what = rbind) %>% colSums
## [1]  26  66 106 146


问:
Line modification with sed
When I write in the terminal this line:

```<code>echo /site/cdlinux/iso/v0.5/cdlinux-maly-0.5.8.iso | sed "s#.*/##"
</code>```

I get this output:

```<code>cdlinux-maly-0.5.8.iso
</code>```

What do these particular characters (# . * /) mean in this situation?

答:
sed "s#.*/##"

# is treated as sed command sections separator

.*/ - a pattern that will match all characters till encountering the last /(including) within the input string, i.e. /site/cdlinux/iso/v0.5/

## - empty string between two section separators is the replacement part(all matched characters will be replaced with empty string)

The syntax of the s command is ‘s/regexp/replacement/flags’.

  Its basic concept is simple: the s command attempts to match the pattern
  space against the supplied regular expression regexp; if the match
  is successful, then that portion of the pattern space which was
  matched is replaced with replacement.

Title: Line modification with sed

Body:
When I write in the terminal this line:

echo /site/cdlinux/iso/v0.5/cdlinux-maly-0.5.8.iso | sed "s#.*/##"

I get this output:

cdlinux-maly-0.5.8.iso

What do these particular characters (# . * /) mean in this situation?


问:
wordpress external js not loading in my theme
I am making my first wordpress theme but when i tried to load external js in my theme its not loading in my page instead of that it load in wp-admin page

functions.php

```<code>wp_enqueue_script('jquery');
wp_enqueue_script('scripts', get_template_directory_uri() . '/js/scripts.js', array('jquery'),'1.0', true );
</code>```

my script.js

```<code>(function($) {

    alert("it workd!!");
})(jQuery);
</code>```

答:
```<code>wp_enqueue_script('jquery');

 wp_register_script('myscripts', get_template_directory_uri() . '/js/scripts.js', array('jquery'), '1.0.0'); // Custom scripts
 wp_enqueue_script('myscripts'); // Enqueue it!
</code>```

<p>this is working </p>

Body:
I am making my first wordpress theme but when i tried to load external js in my theme its not loading in my page instead of that it load in wp-admin page

functions.php

wp_enqueue_script('jquery');
wp_enqueue_script('scripts', get_template_directory_uri() . '/js/scripts.js', array('jquery'),'1.0', true );

my script.js

(function($) {

    alert("it workd!!");
})(jQuery);

Body:
wp_enqueue_script('jquery');

 wp_register_script('myscripts', get_template_directory_uri() . '/js/scripts.js', array('jquery'), '1.0.0'); // Custom scripts
 wp_enqueue_script('myscripts'); // Enqueue it!

this is working


问:
Attach GPU to App Engine Flexible Environment
I am using App Engine to build an API with workers to do Keras-related tasks in the background. Due to the nature of Keras, it is more efficient to use a GPU instead of CPU to do some of deep learning work.

I understand that I can use GPU and attach it to Compute Engine but as I would rather to go through App Engine route. Is it possible since App Engine Flexible environment is basically a managed VM on Compute Engine? If yes, how can I go about it?

答: GPUs are not currently supported in the App Engine Flexible environment. I'll take it as a feature request to be considered for the product.</p>


问:
IntentService Error: No default Constructor
I am a newbie to Android, and I am trying to use the IntentService but I get an error that it has no default constructor.
I tried restarting the Android Studio it doesn't work.

package com.example.hitesh.kuchbhi;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.TaskStackBuilder;
import android.support.v7.app.NotificationCompat;

import java.util.TreeSet;

public class DisplayNotification extends IntentService {
    public DisplayNotification(String name) {
        super("DisplayNotification");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // my code which even after deleting gives the same error
    }
```
<p>log cat error</p>
```E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.hitesh.kuchbhi, PID: 28899
                  java.lang.RuntimeException: Unable to instantiate service com.example.hitesh.kuchbhi.DisplayNotification: java.lang.InstantiationException: class com.example.hitesh.kuchbhi.DisplayNotification has no zero argument constructor
                      at android.app.ActivityThread.handleCreateService(ActivityThread.java:2728)
                      at android.app.ActivityThread.access$1800(ActivityThread.java:144)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1368)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:135)
                      at android.app.ActivityThread.main(ActivityThread.java:5233)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:372)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)

```

AndroidManifest file Screenshot

答:
Just add a default constructor

```<code>public DisplayNotification() {
    super("DisplayNotification");
}
</code>```

That means a constructor with no parameter

ContentLicense: CC BY-SA 4.0

Body:
I am a newbie to Android, and I am trying to use the IntentService but I get an error that it has no default constructor.
I tried restarting the Android Studio it doesn't work.

package com.example.hitesh.kuchbhi;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.TaskStackBuilder;
import android.support.v7.app.NotificationCompat;

import java.util.TreeSet;

public class DisplayNotification extends IntentService {
    public DisplayNotification(String name) {
        super("DisplayNotification");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // my code which even after deleting gives the same error
    }

log cat error

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.hitesh.kuchbhi, PID: 28899
                  java.lang.RuntimeException: Unable to instantiate service com.example.hitesh.kuchbhi.DisplayNotification: java.lang.InstantiationException: class com.example.hitesh.kuchbhi.DisplayNotification has no zero argument constructor
                      at android.app.ActivityThread.handleCreateService(ActivityThread.java:2728)
                      at android.app.ActivityThread.access$1800(ActivityThread.java:144)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1368)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:135)
                      at android.app.ActivityThread.main(ActivityThread.java:5233)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:372)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)

AndroidManifest file Screenshot

Body:
Just add a default constructor

public DisplayNotification() {
    super("DisplayNotification");
}

That means a constructor with no parameter


问:
VBA Excel make array of sequential numbers
I am working in VBA for Excel at the moment but am really only versed in Matlab. It's important for my work to stay in the memory of vba (not on the worksheets of excel) for time purposes.
What I need to do is make an array of sequential integers, say 4000 through 5000.
In matlab this is really easy, I would just do... i = 4000:5000, or i=4000:1:5000. With the 1 in the second case being my 'step.'
I was wondering what is the best way to achieve this result in vba?
Thanks</p>

答:
Without looping - Just seen Rory's same answer above after posting</p>

```<code>Sub MakeArray()
    Dim x As Long, y As Long, arr As Variant
    x = 4000: y = 5000
    arr = Evaluate("Row(" & x & ":" & y & ")")

    'Show result
    Sheets(1).Range("A1").Resize(y - x + 1) = arr
End Sub
</code>```

Body:
Without looping - Just seen Rory's same answer above after posting

Sub MakeArray()
    Dim x As Long, y As Long, arr As Variant
    x = 4000: y = 5000
    arr = Evaluate("Row(" & x & ":" & y & ")")

    'Show result
    Sheets(1).Range("A1").Resize(y - x + 1) = arr
End Sub


问:
How to create nestable object
At the begining I would like to say hello, so ... Hello. I need to create a nested object structure.
I've got an object (xaml page) like this

```<code><navigation:Page x:Class="ItemTemplateExample.ContentItem"
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
       xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
       xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
       mc:Ignorable="d"
       xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
       d:DesignWidth="200" d:DesignHeight="20"
       Title="ContentItem Page">
<Grid x:Name="LayoutRoot">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="50"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Button x:Name="button1" />
    <ContentControl  Grid.Column="1" x:Name="content1" />
</Grid>
</code>```

Now I would like to use it in nested structure. For Example

```<code><local:ContentItem ButtonText="level 1">
     <local:ContentItem ButtonText="level 2" />
     <local:ContentItem ButtonText="level 2" />
     <local:ContentItem ButtonText="level 2">
          <local:ContentItem ButtonText="level 3" />
     </local:ContentItem>
</local:ContentItem>
</code>```

Where ButtonText will be known value (set when adding nested object) and Content of each object will be object of the same type. I have no idea how to start. Please give me some hint, exmaples. Thank You.

答:
you would like to see HierarchicalDataTemplate in WPF

Seee here

Title: How to create nestable object

Body:
At the begining I would like to say hello, so ... Hello. I need to create a nested object structure.
I've got an object (xaml page) like this

<navigation:Page x:Class="ItemTemplateExample.ContentItem"
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
       xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
       xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
       mc:Ignorable="d"
       xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
       d:DesignWidth="200" d:DesignHeight="20"
       Title="ContentItem Page">
<Grid x:Name="LayoutRoot">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="50"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Button x:Name="button1" />
    <ContentControl  Grid.Column="1" x:Name="content1" />
</Grid>

Now I would like to use it in nested structure. For Example

<local:ContentItem ButtonText="level 1">
     <local:ContentItem ButtonText="level 2" />
     <local:ContentItem ButtonText="level 2" />
     <local:ContentItem ButtonText="level 2">
          <local:ContentItem ButtonText="level 3" />
     </local:ContentItem>
</local:ContentItem>

Where ButtonText will be known value (set when adding nested object) and Content of each object will be object of the same type. I have no idea how to start. Please give me some hint, exmaples. Thank You.


问:
Zurb Foundation 6 - how to stop the pagination items from being hidden on the small screen?
How can I turn off foundation's pagination or stop it from hiding my pagination items on small screens?

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.0/css/foundation.min.css">

You're on page 1

2

3

4

12

13

```

If you view the default pagination on a small screen, it will on show you the first and the last items. But I want all items to be displayed even on the small screen, just like in Bootstrap. Is it possible?

答:
You can use:

```<code>.pagination li {
  display: inline-block !important;
}
</code>```

optionally wrapping it in a media query if you prefer to only force it on small screens.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.0/css/foundation.min.css">

You're on page 1

2

3

4

12

13

```

Body:
How can I turn off foundation's pagination or stop it from hiding my pagination items on small screens?

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.0/css/foundation.min.css">

You're on page 1

2

3

4

12

13

If you view the default pagination on a small screen, it will on show you the first and the last items. But I want all items to be displayed even on the small screen, just like in Bootstrap. Is it possible?

Body:
You can use:

.pagination li {
  display: inline-block !important;
}

optionally wrapping it in a media query if you prefer to only force it on small screens.

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

<!-- Compressed CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.0/css/foundation.min.css">

<!-- Compressed JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.0/js/foundation.min.js"></script>
<style>
.pagination li {
  display: inline-block !important;
}
</style>
<div class="container">
  <ul class="pagination text-center" role="navigation" aria-label="Pagination">
    <li class="current"><span class="show-for-sr">You're on page</span> 1</li>
    <li><a href="#" aria-label="Page 2">2</a></li>
    <li><a href="#" aria-label="Page 3">3</a></li>
    <li><a href="#" aria-label="Page 4">4</a></li>
    <li class="ellipsis"></li>
    <li><a href="#" aria-label="Page 12">12</a></li>
    <li><a href="#" aria-label="Page 13">13</a></li>
  </ul>
</div>

<script>
  $(function() {
    $(document).foundation();
  });
</script>


问:
Gather all records from one table and SUM a field from another table
I'm trying to fetch all of the invoices a client has, then calculate the SUM from payments. Problem is, the SUM from paid_to_date is the same value on all returned rows.

Here's a SQLFiddle.

```<code>SELECT `invoices`.*,
       DATE_FORMAT(`invoices`.`due_date`, '%M %d, %Y') AS `due_date`,
       totals.`paid_to_date`
FROM   `invoices`,
       (SELECT `payments`.`invoice_id`,
               SUM(`payments`.`amount`) `paid_to_date`
        FROM   `payments`
        GROUP  BY `payments`.`invoice_id`) AS totals
WHERE  `invoices`.`client_id` = 1
ORDER  BY `invoices`.`due_date` DESC
</code>```

答:
You need to do a JOIN instead of calling both tables in the FROM statement.

```<code>SELECT `invoices`.*,
       DATE_FORMAT(`invoices`.`due_date`, '%M %d, %Y') AS `due_date`,
       totals.`paid_to_date`
FROM   `invoices`
LEFT JOIN    (SELECT `payments`.`invoice_id`,
                  SUM(`payments`.`amount`) `paid_to_date`
              FROM   `payments`
              GROUP  BY `payments`.`invoice_id`) AS totals
                  ON `invoices`.`ID` = `totals`.`invoice_id`
WHERE  `invoices`.`client_id` = 1
ORDER  BY `invoices`.`due_date` DESC
</code>```

Edit: Changed to LEFT JOIN as I did not know you wanted to see unpaid invoices

Included the SQL Fiddle to prove query functions as intended.
http://sqlfiddle.com/#!9/50f08e/2

As stated in the comment you probably have bad primary and foreign keys.  In your SQL Fiddle I changed your payment invoice ids as they were going to invoices that did not exist.

Body:
I'm trying to fetch all of the invoices a client has, then calculate the SUM from payments. Problem is, the SUM from paid_to_date is the same value on all returned rows.

Here's a SQLFiddle.

SELECT `invoices`.*,
       DATE_FORMAT(`invoices`.`due_date`, '%M %d, %Y') AS `due_date`,
       totals.`paid_to_date`
FROM   `invoices`,
       (SELECT `payments`.`invoice_id`,
               SUM(`payments`.`amount`) `paid_to_date`
        FROM   `payments`
        GROUP  BY `payments`.`invoice_id`) AS totals
WHERE  `invoices`.`client_id` = 1
ORDER  BY `invoices`.`due_date` DESC

Body:
You need to do a JOIN instead of calling both tables in the FROM statement.

SELECT `invoices`.*,
       DATE_FORMAT(`invoices`.`due_date`, '%M %d, %Y') AS `due_date`,
       totals.`paid_to_date`
FROM   `invoices`
LEFT JOIN    (SELECT `payments`.`invoice_id`,
                  SUM(`payments`.`amount`) `paid_to_date`
              FROM   `payments`
              GROUP  BY `payments`.`invoice_id`) AS totals
                  ON `invoices`.`ID` = `totals`.`invoice_id`
WHERE  `invoices`.`client_id` = 1
ORDER  BY `invoices`.`due_date` DESC

Edit: Changed to LEFT JOIN as I did not know you wanted to see unpaid invoices

Included the SQL Fiddle to prove query functions as intended.
http://sqlfiddle.com/#!9/50f08e/2

As stated in the comment you probably have bad primary and foreign keys.  In your SQL Fiddle I changed your payment invoice ids as they were going to invoices that did not exist.


问:
Calling every possible combination of functions
Say I have a bunch of functions, each labelled doThing1, doThing2 etc up to doThing10. I want to call every possible combination of these functions. Each function does not have to be called however each function can only be called once. How could I implement this in efficient manner in python?</p>

答:
Use itertools.permutations(iterable\[, r\]) to get all the permutations and put your functions in a list.

Here is an example:

```<code>import itertools

def doThing1():
    print "thing 1"

def doThing2():
    print "thing 2"

def doThing3():
    print "thing 3"

functions = [doThing1, doThing2, doThing3]

for func_list in itertools.permutations(functions):
    for func in func_list:
        func()
</code>```

Here is the output of that:

```<code>$ python permutations.py
thing 1
thing 2
thing 3
thing 1
thing 3
thing 2
thing 2
thing 1
thing 3
thing 2
thing 3
thing 1
thing 3
thing 1
thing 2
thing 3
thing 2
thing 1
</code>```

Body:
Use itertools.permutations(iterable\[, r\]) to get all the permutations and put your functions in a list.

Here is an example:

import itertools

def doThing1():
    print "thing 1"

def doThing2():
    print "thing 2"

def doThing3():
    print "thing 3"

functions = [doThing1, doThing2, doThing3]

for func_list in itertools.permutations(functions):
    for func in func_list:
        func()

Here is the output of that:

$ python permutations.py
thing 1
thing 2
thing 3
thing 1
thing 3
thing 2
thing 2
thing 1
thing 3
thing 2
thing 3
thing 1
thing 3
thing 1
thing 2
thing 3
thing 2
thing 1