问:
Propublica API json data into Google Sheets
This is my first post. I am a Google Sheets devotee using add-ons for anything complex. Sans add-on, I lurk (skulk) for snippets that sometimes work. Tired of illegitimate grifting I can't learn from and going back to basics.. I have been working on the below code for several days and after viewing videos and reading tutorials I am stuck.

Accessing: Propublica Campaign Finance API in Google Sheets to download one of several tables I intend to use. 2 functions in my code: getData and populateSheet. Logs show data each time. Sheet shows only the header row.

Here is my public spreadsheet:

https://docs.google.com/spreadsheets/d/11imT4T5wrvacZ0dRn-mjYA53EB5zsEvKFw4hcTcfJeg/edit?usp=sharing

Propublica Campaign Finance API instructions:

"The Campaign Finance API uses a RESTful style. The API only accepts GET requests. All requests begin with: https://api.propublica.org/campaign-finance/v1/.
The API key must be included in all API requests to the server, set as a header: X-API-Key: PROPUBLICA_API_KEY

Here is the code I am using:

```<code>var URL = 'https://api.propublica.org/campaign-finance/v1/2018/committees/leadership.json'
var params = {
  headers: {'X-API-Key': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'}
  }

function getData() {
    var response = UrlFetchApp.fetch(URL,params); //Fetch data from a given API URL
    var json = response.getContentText(); //Get data content responded from API URL. This is returned as text
    var data = JSON.parse(json); //Parse the text data as JSON
    Logger.log(data) //This will log the JSON response from API
    return data //Return JSON object recevied from API

}

function populateSheet() {
    var data = getData(); //Get JSON data from the above function
    var sheet = SpreadsheetApp.getActiveSheet();
    var lastRowCount = sheet.getLastRow();
    var header = ['id','relative_uri','name','address','city','state','zip','treasurer','party','fec_uri','candidate','leadership','super_pac','sponsor_name','designation','filing_frequency','committee_type','interest_group'];

    sheet.clear();
    sheet.getRange(1, 1, 1, header.length).setValues([header]);

    for (var i = 0; i < data.length; i++) {
        var row = [];
        var nextRow = sheet.getLastRow() + 1;
        row.push(data[i].id, data[i].relative_uri, data[i].name, data[i].address, data[i].city, data[i].state, data[i].zip, data[i].treasurer, data[i].party, data[i].fec_uri, data[i].candidate, data[i].leadership, data[i].super_pac, data[i].sponsor_name, data[i].designation, data[i].filing_frequency, data[i].committee_type, data[i].interest_group)
        sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);

    }
}
</code>```

Thank you in advance for any guidance you may provide (even "go read this and learn")..

答:
How about this modification?

Modification points :

The data you want is at data.results.

In order to know this, I confirmed your shared spreadsheet. https://docs.google.com/spreadsheets/d/11imT4T5wrvacZ0dRn-mjYA53EB5zsEvKFw4hcTcfJeg/edit?usp=sharing.

You can import the data to spreadsheet using setValues() at once.

The modified script which reflected above is as follows.

Modified script :

```<code>function populateSheet() {
  var data = getData(); //Get JSON data from the above function
  var sheet = SpreadsheetApp.getActiveSheet();
  var lastRowCount = sheet.getLastRow();
  var header = ['id','relative_uri','name','address','city','state','zip','treasurer','party','fec_uri','candidate','leadership','super_pac','sponsor_name','designation','filing_frequency','committee_type','interest_group'];
  sheet.clear();
  sheet.getRange(1, 1, 1, header.length).setValues([header]);

  // I added below.
  var res = [];
  data.results.forEach(function(e) {
    var temp = [];
    header.forEach(function(h) {
      temp.push(e[h]);
    });
    res.push(temp);
  });

  var nextRow = sheet.getLastRow() + 1;
  sheet.getRange(nextRow, 1, res.length, res[0].length).setValues(res); // Modified
}
</code>```

Note :

I think that getData() works.

If I misunderstand your question, I'm sorry.

Edit :

In order to retrieve the data more than 20, please use a query parameter of offset.

The API provides JSON and XML responses for every type of request, and supports JSONP callbacks. Responses that are not date-based or containing aggregate totals return the first 20 results; pagination is available via an offset query string parameter using multiples of 20.

Reference: https://propublica.github.io/campaign-finance-api-docs/#responses

For example, when you want to retrieve next 20-40 data, please modify the endpoint as follows. And please run again.

From :

```<code>var URL = 'https://api.propublica.org/campaign-finance/v1/2018/committees/leadership.json'
</code>```

To :

```<code>var URL = 'https://api.propublica.org/campaign-finance/v1/2018/committees/leadership.json?offset=20'
</code>```

Body:
This is my first post. I am a Google Sheets devotee using add-ons for anything complex. Sans add-on, I lurk (skulk) for snippets that sometimes work. Tired of illegitimate grifting I can't learn from and going back to basics.. I have been working on the below code for several days and after viewing videos and reading tutorials I am stuck.

Accessing: Propublica Campaign Finance API in Google Sheets to download one of several tables I intend to use. 2 functions in my code: getData and populateSheet. Logs show data each time. Sheet shows only the header row.

Here is my public spreadsheet:

https://docs.google.com/spreadsheets/d/11imT4T5wrvacZ0dRn-mjYA53EB5zsEvKFw4hcTcfJeg/edit?usp=sharing

Propublica Campaign Finance API instructions:

"The Campaign Finance API uses a RESTful style. The API only accepts GET requests. All requests begin with: https://api.propublica.org/campaign-finance/v1/.
The API key must be included in all API requests to the server, set as a header: X-API-Key: PROPUBLICA_API_KEY

Here is the code I am using:

var URL = 'https://api.propublica.org/campaign-finance/v1/2018/committees/leadership.json'
var params = {
  headers: {'X-API-Key': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'}
  }

function getData() {
    var response = UrlFetchApp.fetch(URL,params); //Fetch data from a given API URL
    var json = response.getContentText(); //Get data content responded from API URL. This is returned as text
    var data = JSON.parse(json); //Parse the text data as JSON
    Logger.log(data) //This will log the JSON response from API
    return data //Return JSON object recevied from API

}

function populateSheet() {
    var data = getData(); //Get JSON data from the above function
    var sheet = SpreadsheetApp.getActiveSheet();
    var lastRowCount = sheet.getLastRow();
    var header = ['id','relative_uri','name','address','city','state','zip','treasurer','party','fec_uri','candidate','leadership','super_pac','sponsor_name','designation','filing_frequency','committee_type','interest_group'];

    sheet.clear();
    sheet.getRange(1, 1, 1, header.length).setValues([header]);

    for (var i = 0; i < data.length; i++) {
        var row = [];
        var nextRow = sheet.getLastRow() + 1;
        row.push(data[i].id, data[i].relative_uri, data[i].name, data[i].address, data[i].city, data[i].state, data[i].zip, data[i].treasurer, data[i].party, data[i].fec_uri, data[i].candidate, data[i].leadership, data[i].super_pac, data[i].sponsor_name, data[i].designation, data[i].filing_frequency, data[i].committee_type, data[i].interest_group)
        sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);

    }
}

Thank you in advance for any guidance you may provide (even "go read this and learn")..

Body:
How about this modification?

Modification points :

The data you want is at data.results.

In order to know this, I confirmed your shared spreadsheet. https://docs.google.com/spreadsheets/d/11imT4T5wrvacZ0dRn-mjYA53EB5zsEvKFw4hcTcfJeg/edit?usp=sharing.

You can import the data to spreadsheet using setValues() at once.

The modified script which reflected above is as follows.

Modified script :

function populateSheet() {
  var data = getData(); //Get JSON data from the above function
  var sheet = SpreadsheetApp.getActiveSheet();
  var lastRowCount = sheet.getLastRow();
  var header = ['id','relative_uri','name','address','city','state','zip','treasurer','party','fec_uri','candidate','leadership','super_pac','sponsor_name','designation','filing_frequency','committee_type','interest_group'];
  sheet.clear();
  sheet.getRange(1, 1, 1, header.length).setValues([header]);

  // I added below.
  var res = [];
  data.results.forEach(function(e) {
    var temp = [];
    header.forEach(function(h) {
      temp.push(e[h]);
    });
    res.push(temp);
  });

  var nextRow = sheet.getLastRow() + 1;
  sheet.getRange(nextRow, 1, res.length, res[0].length).setValues(res); // Modified
}

Note :

I think that getData() works.

If I misunderstand your question, I'm sorry.

Edit :

In order to retrieve the data more than 20, please use a query parameter of offset.

The API provides JSON and XML responses for every type of request, and supports JSONP callbacks. Responses that are not date-based or containing aggregate totals return the first 20 results; pagination is available via an offset query string parameter using multiples of 20.

Reference: https://propublica.github.io/campaign-finance-api-docs/#responses

For example, when you want to retrieve next 20-40 data, please modify the endpoint as follows. And please run again.

From :

var URL = 'https://api.propublica.org/campaign-finance/v1/2018/committees/leadership.json'

To :

var URL = 'https://api.propublica.org/campaign-finance/v1/2018/committees/leadership.json?offset=20'


来源: stackexchange

问:
How to reload the ion-page after pop() in ionic2
I have 2 pages Page1 and Page2. I have used this.nav.pop() in Page2 and it will pop the Page2 and Page1 will enable but i want to refresh the Page1.
Thank you in advance.

答:
I simply load the details in page 1 in an ionViewWillEnter function (using Ionic 2). This handles both the initial load and any refresh when popping back to page 1.

Documentation is here.

ionViewWillEnter

  "Runs when the page is about to enter and become the active page."

ContentLicense: CC BY-SA 3.0


问:
How to ignore unpacked parts of a tuple as argument of a lambda?
In Python, by convention, the underscore (_) is often used to throw away parts of an unpacked tuple, like so

```<code>>>> tup = (1,2,3)
>>> meaningfulVariableName,_,_ = tup
>>> meaningfulVariableName
1
</code>```

I'm trying to do the same for a tuple argument of a lambda. It seems unfair that it can only be done with 2-tuples...

```<code>>>> map(lambda (meaningfulVariableName,_): meaningfulVariableName*2, [(1,10), (2,20), (3,30)]) # This is fine
[2, 4, 6]

>>> map(lambda (meaningfulVariableName,_,_): meaningfulVariableName*2, [(1,10,100), (2,20,200), (3,30,300)]) # But I need this!
SyntaxError: duplicate argument '_' in function definition (<pyshell#24>, line 1)
</code>```

Any ideas why, and what the best way to achieve this is?

答:
You are often better off to use list comprehensions rather than lambdas:

```<code>some_list = [(1, 10, 100), (2, 20, 200), (3, 30, 300)]
processed_list = [2 * x for x, dummy1, dummy2 in some_list]
</code>```

If you really insist, you could use _ instead of dummy1 and dummy2 here.  However, I recommend against this, since I've frequently seen this causing confusion. People often think _ is some kind of special syntax (which it is e.g. in Haskell and Rust), while it is just some unusual variable name without any special properties.  This confusion is completely avoidable by using names like dummy1.  Moreover, _ clashes with the common gettext alias, and it also does have a special meaning in the interactive interpreter, so overall I prefer using dummy to avoid all the confusion.

Body:
In Python, by convention, the underscore (_) is often used to throw away parts of an unpacked tuple, like so

>>> tup = (1,2,3)
>>> meaningfulVariableName,_,_ = tup
>>> meaningfulVariableName
1

I'm trying to do the same for a tuple argument of a lambda. It seems unfair that it can only be done with 2-tuples...

>>> map(lambda (meaningfulVariableName,_): meaningfulVariableName*2, [(1,10), (2,20), (3,30)]) # This is fine
[2, 4, 6]

>>> map(lambda (meaningfulVariableName,_,_): meaningfulVariableName*2, [(1,10,100), (2,20,200), (3,30,300)]) # But I need this!
SyntaxError: duplicate argument '_' in function definition (<pyshell#24>, line 1)

Any ideas why, and what the best way to achieve this is?

Body:
You are often better off to use list comprehensions rather than lambdas:

some_list = [(1, 10, 100), (2, 20, 200), (3, 30, 300)]
processed_list = [2 * x for x, dummy1, dummy2 in some_list]

If you really insist, you could use _ instead of dummy1 and dummy2 here.  However, I recommend against this, since I've frequently seen this causing confusion. People often think _ is some kind of special syntax (which it is e.g. in Haskell and Rust), while it is just some unusual variable name without any special properties.  This confusion is completely avoidable by using names like dummy1.  Moreover, _ clashes with the common gettext alias, and it also does have a special meaning in the interactive interpreter, so overall I prefer using dummy to avoid all the confusion.


问:
Run crontab job with P4
I have a shell script which in turn calls a python script. But before the python script runs I am setting up the environment variables in order to have the right P4 configurations.

```<code>shell: /home/ag/ump_prod/run.sh
python script: /home/ag/ump_prod/cron.py
Environment conf: /home/ag/ump_prod/env.conf
</code>```

The python script executes command line P4 commands via the subprocess module.
Here is the code for the shell script

```<code>#!/bin/sh
. /home/ag/ump_prod/env.conf
python /home/ag/ump_prod/cron.py
</code>```

env.conf

```<code>export SHELL=/bin/bash
export USER=ag
export MAIL=/var/mail/ag
export HOME=/home/ag
export LOGNAME=ag
export P4CONFIG=/home/ag/ump_prod/.perforce
</code>```

The perforce config /home/ag/ump_prod/.perforce :

```<code>P4CLIENT=ag_ump
P4EDITOR=/usr/bin/vim
P4PORT=rsh:ssh -2 -q -a -x -l p4server p4.****.com /bin/true
P4USER=ag
</code>```

Manually running the shell script executes it without any issues.
However, when I run it via cronjob it complains that it cannot connect to the server.

Error Message:

```<code>['TCP receive failed.\n', 'read: socket stdio: Connection reset by peer\n', 'Perforce client error:\n', '\tTCP receive failed.\n', '\tread: socket stdio: Connection reset by peer\n']
</code>```

Please let me know where I could be going wrong in setting the environment variables for P4 configs. Thanks in advance!

答: I found the solution: I needed to start the ssh-agent dynamically for the cronjob as well. It is just like how you login for the first time and start the ssh-agent. We need to tell cronjob too to include eval ssh-agent

Title: Run crontab job with P4

Body:
I have a shell script which in turn calls a python script. But before the python script runs I am setting up the environment variables in order to have the right P4 configurations.

shell: /home/ag/ump_prod/run.sh
python script: /home/ag/ump_prod/cron.py
Environment conf: /home/ag/ump_prod/env.conf

The python script executes command line P4 commands via the subprocess module.
Here is the code for the shell script

#!/bin/sh
. /home/ag/ump_prod/env.conf
python /home/ag/ump_prod/cron.py

env.conf

export SHELL=/bin/bash
export USER=ag
export MAIL=/var/mail/ag
export HOME=/home/ag
export LOGNAME=ag
export P4CONFIG=/home/ag/ump_prod/.perforce

The perforce config /home/ag/ump_prod/.perforce :

P4CLIENT=ag_ump
P4EDITOR=/usr/bin/vim
P4PORT=rsh:ssh -2 -q -a -x -l p4server p4.****.com /bin/true
P4USER=ag

Manually running the shell script executes it without any issues.
However, when I run it via cronjob it complains that it cannot connect to the server.

Error Message:

['TCP receive failed.\n', 'read: socket stdio: Connection reset by peer\n', 'Perforce client error:\n', '\tTCP receive failed.\n', '\tread: socket stdio: Connection reset by peer\n']

Please let me know where I could be going wrong in setting the environment variables for P4 configs. Thanks in advance!


问:
Java, repeated logic block with different objects, cleaning code
I want to clean up some code that makes my head hurt:

```<code>    activityStandardAttributeValue
            .setProduct((standardAttributeForm != null && standardAttributeForm
                    .getProduct() != null) ? standardAttributeForm
                            .getProduct()
                            : (groupedStandardAttributeForm != null ? groupedStandardAttributeForm
                                    .getProduct() : null));
    activityStandardAttributeValue
            .setProject((standardAttributeForm != null && standardAttributeForm
                    .getProject() != null) ? standardAttributeForm
                    .getProject()
                    : (groupedStandardAttributeForm != null ? groupedStandardAttributeForm
                    .getProject() : null));
</code>```

I could simply change it to a easier to read form like:

```<code>    Product product = null;
    if(standardAttributeForm != null && standardAttributeForm.getProduct() != null) {
        product = standardAttributeForm.getProduct();
    } else if (groupedStandardAttributeForm != null && groupedStandardAttributeForm.getProduct() != null) {
        product = groupedStandardAttributeForm.getProduct();
    }
    activityStandardAttributeValue.setProduct(product);

    Project project = null;
    if(standardAttributeForm != null && standardAttributeForm.getProduct() != null) {
        project = standardAttributeForm.getProject();
    } else if (groupedStandardAttributeForm != null && groupedStandardAttributeForm.getProject() != null) {
        project = groupedStandardAttributeForm.getProject();
    }
</code>```

The problem is that this same basic logic is repeated about 16 times for different properties and it isn't really much cleaner. I would like to create a generic way to do this without having to repeat the same basic logic. The tricky part is that standartAtributeForm or groupedStandardAttributeForm could be null.

Any help is appreciated.

答:
This isn't really an answer, but it's too big to post in a comment (and relies on the formatting):

Simply using better formatting makes it easier to read. Here is your code passed through google-java-format:

```<code>activityStandardAttributeValue.setProduct(
    (standardAttributeForm != null && standardAttributeForm.getProduct() != null)
        ? standardAttributeForm.getProduct()
        : (groupedStandardAttributeForm != null
            ? groupedStandardAttributeForm.getProduct()
            : null));
activityStandardAttributeValue.setProject(
    (standardAttributeForm != null && standardAttributeForm.getProject() != null)
        ? standardAttributeForm.getProject()
        : (groupedStandardAttributeForm != null
            ? groupedStandardAttributeForm.getProject()
            : null));
</code>```

I suppose you could do something like this:

```<code><T> getThing(Function<Form, T> extractor, T... forms) {
  for (T form : forms) {
    if (form != null) {
      T thing = extractor.apply(form);
      if (thing != null) return thing;
    }
  }
  return null;
}
</code>```

Then:

```<code>activityStandardAttributeValue.setProduct(
    getThing(Form::getProduct, standardAttributeForm, groupedStandardAttributeForm));
activityStandardAttributeValue.setProject(
    getThing(Form::getProject, standardAttributeForm, groupedStandardAttributeForm));
</code>```

Body:
I want to clean up some code that makes my head hurt:

    activityStandardAttributeValue
            .setProduct((standardAttributeForm != null && standardAttributeForm
                    .getProduct() != null) ? standardAttributeForm
                            .getProduct()
                            : (groupedStandardAttributeForm != null ? groupedStandardAttributeForm
                                    .getProduct() : null));
    activityStandardAttributeValue
            .setProject((standardAttributeForm != null && standardAttributeForm
                    .getProject() != null) ? standardAttributeForm
                    .getProject()
                    : (groupedStandardAttributeForm != null ? groupedStandardAttributeForm
                    .getProject() : null));

I could simply change it to a easier to read form like:

    Product product = null;
    if(standardAttributeForm != null && standardAttributeForm.getProduct() != null) {
        product = standardAttributeForm.getProduct();
    } else if (groupedStandardAttributeForm != null && groupedStandardAttributeForm.getProduct() != null) {
        product = groupedStandardAttributeForm.getProduct();
    }
    activityStandardAttributeValue.setProduct(product);

    Project project = null;
    if(standardAttributeForm != null && standardAttributeForm.getProduct() != null) {
        project = standardAttributeForm.getProject();
    } else if (groupedStandardAttributeForm != null && groupedStandardAttributeForm.getProject() != null) {
        project = groupedStandardAttributeForm.getProject();
    }

The problem is that this same basic logic is repeated about 16 times for different properties and it isn't really much cleaner. I would like to create a generic way to do this without having to repeat the same basic logic. The tricky part is that standartAtributeForm or groupedStandardAttributeForm could be null.

Any help is appreciated.

Body:
This isn't really an answer, but it's too big to post in a comment (and relies on the formatting):

Simply using better formatting makes it easier to read. Here is your code passed through google-java-format:

activityStandardAttributeValue.setProduct(
    (standardAttributeForm != null && standardAttributeForm.getProduct() != null)
        ? standardAttributeForm.getProduct()
        : (groupedStandardAttributeForm != null
            ? groupedStandardAttributeForm.getProduct()
            : null));
activityStandardAttributeValue.setProject(
    (standardAttributeForm != null && standardAttributeForm.getProject() != null)
        ? standardAttributeForm.getProject()
        : (groupedStandardAttributeForm != null
            ? groupedStandardAttributeForm.getProject()
            : null));

I suppose you could do something like this:

<T> getThing(Function<Form, T> extractor, T... forms) {
  for (T form : forms) {
    if (form != null) {
      T thing = extractor.apply(form);
      if (thing != null) return thing;
    }
  }
  return null;
}

Then:

activityStandardAttributeValue.setProduct(
    getThing(Form::getProduct, standardAttributeForm, groupedStandardAttributeForm));
activityStandardAttributeValue.setProject(
    getThing(Form::getProject, standardAttributeForm, groupedStandardAttributeForm));


问:
Multiplication with different columns
```<code>A        B      C       D
a    -0.17   1.98   0.051
b     0.1    1.99   0.001
c    -0.2    0.245  0.003
d     0.25   0      2
</code>```

I have a dataframe in which I have B column with - and + values, So in case of - values, I want to multiply its corresponding C and D column with (-1), hence my C and D respective rows will be -ve.

Then I want to multiply B columns each rows values with its consecutive C and D rows and a new down row with the sum of total C and D.

The final dataframe should look like this after the calculation.

```<code>A        B       C        D
a    -0.17  0.3366  0.00867
b     0.1   0.199   0.0001
c    -0.2   0.049   0.0006
d     0.25  0       0.5
            0.5846  0.50937
</code>```

Thank you for the help.

Title: Multiplication with different columns

Body:
A        B      C       D
a    -0.17   1.98   0.051
b     0.1    1.99   0.001
c    -0.2    0.245  0.003
d     0.25   0      2

I have a dataframe in which I have B column with - and + values, So in case of - values, I want to multiply its corresponding C and D column with (-1), hence my C and D respective rows will be -ve.

Then I want to multiply B columns each rows values with its consecutive C and D rows and a new down row with the sum of total C and D.

The final dataframe should look like this after the calculation.

A        B       C        D
a    -0.17  0.3366  0.00867
b     0.1   0.199   0.0001
c    -0.2   0.049   0.0006
d     0.25  0       0.5
            0.5846  0.50937

Thank you for the help.

Body:
Multiply the last 2 columns with the 'B' column, take the abs, assign it to those columns, and rbind the colSums of 'C' and 'D' to create the new row

df1[3:4] <- abs(df1[3:4] * df1[,2])
rbind(df1, c(A = NA, B= NA, colSums(df1[3:4])))
#     A     B      C       D
#1    a -0.17 0.3366 0.00867
#2    b  0.10 0.1990 0.00010
#3    c -0.20 0.0490 0.00060
#4    d  0.25 0.0000 0.50000
#5 <NA>    NA 0.5846 0.50937

Update

If the dataset is data.table,

library(data.table)
setDT(df1)
df1[, (3:4) := abs(.SD*B), .SDcols = 3:4]
rbind(df1, c(A= NA, B= NA, df1[, lapply(.SD, sum), .SDcols = C:D]))

data

df1 <- structure(list(A = c("a", "b", "c", "d"), B = c(-0.17, 0.1, -0.2,
0.25), C = c(1.98, 1.99, 0.245, 0), D = c(0.051, 0.001, 0.003,
2)), .Names = c("A", "B", "C", "D"), class = "data.frame", row.names = c(NA,
-4L))


问:
React-native scroll to top with pull to refresh iOS
I have a react-native app, that I want to scroll to top when the FlatList is refreshing in iOS. I can scroll to the top of the FlaList by using:

```<code>this.componentRef.FlatList.scrollToOffset({x: 0, y: 0, animated: true});
</code>```

Now, the list has Pull-to-refresh on, so I would like to scroll above the refreshing indicator in iOS.

I tried:

```<code>this.componentRef.FlatList.scrollToOffset({x: 0, y: -20, animated: true});
</code>```

and declaring the RefreshControl with a ref  as refreshcontrol (using callback ref declaration):

```<code>this.componentRef.FlatList.refreshcontrol.scrollToOffset({x: 0, y: 0, animated: true});
</code>```

and

```<code>this.componentRef.refreshcontrol.scrollToOffset({x: 0, y: 0, animated: true});
</code>```

But none work. Is anyone aware of a way I can scroll above the refreshing indicator, if its on? This only happens in iOS as Android's refreshing indicator works differently.

UPDATE:

As scrollToOffset is not available for the RefrehControl component, it won;t work. Which brings me back to how can I scroll above a RefreshControl in a FlatList. My last attempt:

```<code>this.FlatList.scrollToOffset({x: 0, y: 0, animated: true});
</code>```

Still scrolls to the beginning of the list, yet the "RefreshControl" is visually hidden.

I also tried adding an empty ScrollView above and scrolling to it, because it is empty, it did not work. Any ideas?

UPDATE 2

To clarify, this is how everything is called (simplified):

_scrollAndRefresh method in Main.js:

```<code>  _scrollAndRefresh = () => {
     this.setState({
       loading: true
     }, () => {
       this.CustomFlatList._scrollToTop();
     });
  }
</code>```

Rendering the component in Main.js:

```<code>  <CustomFlatList ref={(ref) => {
      this.CustomFlatList = ref}}
    onRefresh={this._handleRefresh} loading={this.state.loading}/>
</code>```

_handleRefresh method in Main.js:

```<code>  _handleRefresh = () => {
    this.setState({
      loading: true
    }, () => {
      // REFRESH ACTION
    })
  };
</code>```

_scrollToTop method CustomFlatList.js:

```<code>  _scrollToTop = () => {
    if (Platform.OS === 'ios' && this.props.loading) {
      this.FlatList.scrollToOffset({x: 0, y: 0, animated: true});
    }
    else {
      this.FlatList.scrollToOffset({x: 0, y: 0, animated: true});
    }
  }
</code>```

And FlatList CustomFlatList.js:

```<code><FlatList
  ref={(ref) => { this.FlatList = ref; }}
  refreshControl={<RefreshControl
            refreshing={this.props.loading}
            onRefresh={this.props.onRefresh}
        />}
/>
</code>```

答:
I have something like this in my app:

```<code><FlatList
    refreshControl={
        <RefreshControl
            refreshing={this.state.refreshing}
            onRefresh={() => this._onRefresh()}
        />}
    data=...
/>
</code>```

Maybe something like this would work:

```<code>this.componentRef.FlatList.scrollToOffset({x: 0, y: 0, animated: true});
this.setState({refreshing: true});
this._onRefresh();
this.setState({refreshing: false});
</code>```

Body:
I have a react-native app, that I want to scroll to top when the FlatList is refreshing in iOS. I can scroll to the top of the FlaList by using:

this.componentRef.FlatList.scrollToOffset({x: 0, y: 0, animated: true});

Now, the list has Pull-to-refresh on, so I would like to scroll above the refreshing indicator in iOS.

I tried:

this.componentRef.FlatList.scrollToOffset({x: 0, y: -20, animated: true});

and declaring the RefreshControl with a ref  as refreshcontrol (using callback ref declaration):

this.componentRef.FlatList.refreshcontrol.scrollToOffset({x: 0, y: 0, animated: true});

and

this.componentRef.refreshcontrol.scrollToOffset({x: 0, y: 0, animated: true});

But none work. Is anyone aware of a way I can scroll above the refreshing indicator, if its on? This only happens in iOS as Android's refreshing indicator works differently.

UPDATE:

As scrollToOffset is not available for the RefrehControl component, it won;t work. Which brings me back to how can I scroll above a RefreshControl in a FlatList. My last attempt:

this.FlatList.scrollToOffset({x: 0, y: 0, animated: true});

Still scrolls to the beginning of the list, yet the "RefreshControl" is visually hidden.

I also tried adding an empty ScrollView above and scrolling to it, because it is empty, it did not work. Any ideas?

UPDATE 2

To clarify, this is how everything is called (simplified):

_scrollAndRefresh method in Main.js:

  _scrollAndRefresh = () => {
     this.setState({
       loading: true
     }, () => {
       this.CustomFlatList._scrollToTop();
     });
  }

Rendering the component in Main.js:

  <CustomFlatList ref={(ref) => {
      this.CustomFlatList = ref}}
    onRefresh={this._handleRefresh} loading={this.state.loading}/>

_handleRefresh method in Main.js:

  _handleRefresh = () => {
    this.setState({
      loading: true
    }, () => {
      // REFRESH ACTION
    })
  };

_scrollToTop method CustomFlatList.js:

  _scrollToTop = () => {
    if (Platform.OS === 'ios' && this.props.loading) {
      this.FlatList.scrollToOffset({x: 0, y: 0, animated: true});
    }
    else {
      this.FlatList.scrollToOffset({x: 0, y: 0, animated: true});
    }
  }

And FlatList CustomFlatList.js:

<FlatList
  ref={(ref) => { this.FlatList = ref; }}
  refreshControl={<RefreshControl
            refreshing={this.props.loading}
            onRefresh={this.props.onRefresh}
        />}
/>

Body:
I have something like this in my app:

<FlatList
    refreshControl={
        <RefreshControl
            refreshing={this.state.refreshing}
            onRefresh={() => this._onRefresh()}
        />}
    data=...
/>

Maybe something like this would work:

this.componentRef.FlatList.scrollToOffset({x: 0, y: 0, animated: true});
this.setState({refreshing: true});
this._onRefresh();
this.setState({refreshing: false});


问:
php: setting a timezone by UTC offset
Using javascript I know that my users timezone is UTC +3.

Now I want to create DateTime object with this knowledge:

```<code>$usersNow = new DateTime('now', new DateTimeZone("+3"));
</code>```

I receive as a respsonse:

```<code>'Unknown or bad timezone (+2)'
</code>```

What am I doing wrong? How can I fix?

答:
Modern answer:

```<code>$usersNow = new DateTime('now', new DateTimeZone('+0300'));
</code>```

Documentation:

http://php.net/manual/en/datetimezone.construct.php

Title: php: setting a timezone by UTC offset

Body:
Using javascript I know that my users timezone is UTC +3.

Now I want to create DateTime object with this knowledge:

$usersNow = new DateTime('now', new DateTimeZone("+3"));

I receive as a respsonse:

'Unknown or bad timezone (+2)'

What am I doing wrong? How can I fix?

Body:
Modern answer:

$usersNow = new DateTime('now', new DateTimeZone('+0300'));

Documentation:

http://php.net/manual/en/datetimezone.construct.php


问:
async await in condition
How can I do this with async/await so both conditions are evaluated together?
Here is the code I'm currently working on. I tried using Result with the condition and receive a deadlock.

```<code>            else if (!string.IsNullOrEmpty(customer))
            {
                var resp = await  _securityService.GetCustomerShiptoAuthorizationAsync(User.Identity.Name, customer, ship);

                response = Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Invalid Username, Password, Customer or Ship.");
            }
</code>```

This is the previous code that is non async/await and conditions are evaluated together.

```<code>            else if (!string.IsNullOrEmpty(customer) && !_securityService.GetCustomerShiptoAuthorization(
                User.Identity.Name,
                customer,
                ship).IsAuthorized)
            {

                response = Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Invalid Username, Password, Customer or Ship.");
            }
</code>```

答:
Put parentheses around the await call.

```<code>else if (!string.IsNullOrEmpty(customer) && !(await _securityService.GetCustomerShiptoAuthorizationAsync(User.Identity.Name, customer, ship).IsAuthorized))
{
    response = Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Invalid Username, Password, Customer or Ship.");
}
</code>```

Title: async await in condition

Body:
How can I do this with async/await so both conditions are evaluated together?
Here is the code I'm currently working on. I tried using Result with the condition and receive a deadlock.

            else if (!string.IsNullOrEmpty(customer))
            {
                var resp = await  _securityService.GetCustomerShiptoAuthorizationAsync(User.Identity.Name, customer, ship);

                response = Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Invalid Username, Password, Customer or Ship.");
            }

This is the previous code that is non async/await and conditions are evaluated together.

            else if (!string.IsNullOrEmpty(customer) && !_securityService.GetCustomerShiptoAuthorization(
                User.Identity.Name,
                customer,
                ship).IsAuthorized)
            {

                response = Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Invalid Username, Password, Customer or Ship.");
            }

Body:
Put parentheses around the await call.

else if (!string.IsNullOrEmpty(customer) && !(await _securityService.GetCustomerShiptoAuthorizationAsync(User.Identity.Name, customer, ship).IsAuthorized))
{
    response = Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Invalid Username, Password, Customer or Ship.");
}


问:
Changing port on WAMP Server
OK, I have a WAMP Server that I have changed the port from 80 to 7080 in the httpd.conf, but now I have an issue where when I go to the localhost it comes up blank.

To actually get the content I want to see I have to go to localhost:7080.

How can I change it so when I go to localhost without the port number and it displays the content I want to see.

I have been trying to resolve this for the best part of the day, literally around 12 hours now and I am still at a loss as to how to resolve this so any assistance would be appreciated.

答:
You can add 127.0.0.1:7080 mylocalhost to C:\Windows\System32\drivers\etc\host file and use mylocalhost as url link,

If you changed port from 80 to 7080, you must use it in browser to load your WAMP server.

I hope it will help.

Title: Changing port on WAMP Server


问:
Need to use stringr to parse text based on location of string
I have the following data set. I used devtools::reproduce() to put a sample of my data in here and I only selected the column I need help with, which is genres.

There are a lot of genres listed below. I am working with a movie database and I want to simply use only the first genre listed in there (in this format: Genre1 | Genre2 | Genre3).

How do I use stringr or another package to parse this string data in the way I want?

The end result is to use it in a regression model.

```<code>> dput(droplevels(head(movie.cpi,4)))
structure(list(num_critic_for_reviews = c(723L, 302L, 813L, 462L
), director_facebook_likes = c(0L, 563L, 22000L, 475L), actor_3_facebook_likes = c(855L,
1000L, 23000L, 530L), actor_1_facebook_likes = c(1000L, 40000L,
27000L, 640L), gross = c(866161204.765035, 364628240.876025,
476821933.103659, 77736216.375), genres = structure(c(2L, 1L,
4L, 3L), .Label = c("Action|Adventure|Fantasy", "Action|Adventure|Fantasy|Sci-Fi",
"Action|Adventure|Sci-Fi", "Action|Thriller"), class = "factor"),
    num_voted_users = c(886204L, 471220L, 1144337L, 212204L),
    cast_total_facebook_likes = c(4834L, 48350L, 106759L, 1873L
    ), facenumber_in_poster = c(0L, 0L, 0L, 1L), num_user_for_reviews = c(3054L,
    1238L, 2701L, 738L), content_rating = structure(c(1L, 1L,
    1L, 1L), .Label = "PG-13", class = "factor"), budget = c(269925874.125874,
    353545586.107091, 266006097.560976, 280583231.707317), title_year = c(2009L,
    2007L, 2012L, 2012L), actor_2_facebook_likes = c(936L, 5000L,
    23000L, 632L), imdb_score = c(7.9, 7.1, 8.5, 6.6), movie_facebook_likes = c(33000L,
    0L, 164000L, 24000L)), .Names = c("num_critic_for_reviews",
"director_facebook_likes", "actor_3_facebook_likes", "actor_1_facebook_likes",
"gross", "genres", "num_voted_users", "cast_total_facebook_likes",
"facenumber_in_poster", "num_user_for_reviews", "content_rating",
"budget", "title_year", "actor_2_facebook_likes", "imdb_score",
"movie_facebook_likes"), row.names = c(NA, 4L), class = "data.frame")
</code>```

答:
Using the following command you can get the first genre extracted out of that column (I stored it in a new column called genre_1):

```<code>movie.cpi$genre_1 <- gsub( "\\|.*$", "", movie.cpi$genres)

movie.cpi[,c("genres", "genre_1")]

##                            genres genre_1
## 1 Action|Adventure|Fantasy|Sci-Fi  Action
## 2        Action|Adventure|Fantasy  Action
## 3                 Action|Thriller  Action
## 4         Action|Adventure|Sci-Fi  Action
</code>```

Body:
I have the following data set. I used devtools::reproduce() to put a sample of my data in here and I only selected the column I need help with, which is genres.

There are a lot of genres listed below. I am working with a movie database and I want to simply use only the first genre listed in there (in this format: Genre1 | Genre2 | Genre3).

How do I use stringr or another package to parse this string data in the way I want?

The end result is to use it in a regression model.

> dput(droplevels(head(movie.cpi,4)))
structure(list(num_critic_for_reviews = c(723L, 302L, 813L, 462L
), director_facebook_likes = c(0L, 563L, 22000L, 475L), actor_3_facebook_likes = c(855L,
1000L, 23000L, 530L), actor_1_facebook_likes = c(1000L, 40000L,
27000L, 640L), gross = c(866161204.765035, 364628240.876025,
476821933.103659, 77736216.375), genres = structure(c(2L, 1L,
4L, 3L), .Label = c("Action|Adventure|Fantasy", "Action|Adventure|Fantasy|Sci-Fi",
"Action|Adventure|Sci-Fi", "Action|Thriller"), class = "factor"),
    num_voted_users = c(886204L, 471220L, 1144337L, 212204L),
    cast_total_facebook_likes = c(4834L, 48350L, 106759L, 1873L
    ), facenumber_in_poster = c(0L, 0L, 0L, 1L), num_user_for_reviews = c(3054L,
    1238L, 2701L, 738L), content_rating = structure(c(1L, 1L,
    1L, 1L), .Label = "PG-13", class = "factor"), budget = c(269925874.125874,
    353545586.107091, 266006097.560976, 280583231.707317), title_year = c(2009L,
    2007L, 2012L, 2012L), actor_2_facebook_likes = c(936L, 5000L,
    23000L, 632L), imdb_score = c(7.9, 7.1, 8.5, 6.6), movie_facebook_likes = c(33000L,
    0L, 164000L, 24000L)), .Names = c("num_critic_for_reviews",
"director_facebook_likes", "actor_3_facebook_likes", "actor_1_facebook_likes",
"gross", "genres", "num_voted_users", "cast_total_facebook_likes",
"facenumber_in_poster", "num_user_for_reviews", "content_rating",
"budget", "title_year", "actor_2_facebook_likes", "imdb_score",
"movie_facebook_likes"), row.names = c(NA, 4L), class = "data.frame")

Body:
Using the following command you can get the first genre extracted out of that column (I stored it in a new column called genre_1):

movie.cpi$genre_1 <- gsub( "\\|.*$", "", movie.cpi$genres)

movie.cpi[,c("genres", "genre_1")]

##                            genres genre_1
## 1 Action|Adventure|Fantasy|Sci-Fi  Action
## 2        Action|Adventure|Fantasy  Action
## 3                 Action|Thriller  Action
## 4         Action|Adventure|Sci-Fi  Action


问:
Make text box read only in a asp.net grid row based on checked columns
In the below grid, I wanted to disable textbox in each row if all the checkboxes in the row are unchecked. And if a check box is checked in a row then need to enable the textbox.

Wanted this in client side using jquery. Please help
Below is the code I have written. Some code line are repeating how to optimize it more ??

 $(function () {
             $('#MainContent_G2 > tbody  > tr').each(function (index, row) {
                 var checkedArr = $(row).find('input[type="checkbox"]:checked');
                 if (checkedArr.length === 0) {
                     var textbox = $(row).find('input[type="text"]');
                     $(textbox).attr('readonly', true);
                 }

                 $(row).find('input[type="checkbox"]').each(function(index, checkbox) {
                     $(checkbox).change(function () {
                         if (this.checked) {
                             $(this).closest("tr").find('input[type="text"]').attr('readonly', false);
                         }

                         var checkedArr = $(row).find('input[type="checkbox"]:checked');
                         if (checkedArr.length === 0) {
                             var textbox = $(row).find('input[type="text"]');
                             $(textbox).attr('readonly', true);
                         }
                     });
                 });

             });
         });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><asp:GridView ID="G2" ShowHeader="False" runat="server" AutoGenerateColumns="False" OnRowDataBound="G2_RowDataBound">
  <HeaderStyle BorderStyle="Solid" HorizontalAlign="Left" BackColor="LightGray" />
  <FooterStyle BorderWidth="1px" BorderStyle="Solid" BackColor="LightGray" />
  <RowStyle CssClass="gridRows" />
  <Columns>
    <asp:BoundField DataField="REVIEWQUESTIONS_DESC" />
    <asp:TemplateField>
      <ItemTemplate>
        <asp:CheckBox ID="chkbox_Yes" runat="server" Checked='<%# Eval("ANSWER_YES")%>' />
      </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField>
      <ItemTemplate>
        <asp:CheckBox ID="chkbox_No" runat="server" Checked='<%# Eval("ANSWER_NO")%>' />
      </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField>
      <ItemTemplate>
        <asp:CheckBox ID="chkbox_NA" runat="server" Checked='<%# Eval("ANSWER_NA")%>' />
      </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField>
      <ItemTemplate>
        <asp:TextBox runat="server" CssClass="NoLine" ID="txtbox_Notes" Text='<%# Eval("INCIDENTREVIEW_NOTES")%>'></asp:TextBox>
      </ItemTemplate>
    </asp:TemplateField>
  </Columns>
</asp:GridView></code>```

答:
You could do something like this:</p>

```<code>Text='<% # Eval("NameYourUsing") %>' Enabled="false"
</code>```

Body:
In the below grid, I wanted to disable textbox in each row if all the checkboxes in the row are unchecked. And if a check box is checked in a row then need to enable the textbox.

Wanted this in client side using jquery. Please help
Below is the code I have written. Some code line are repeating how to optimize it more ??

 $(function () {
             $('#MainContent_G2 > tbody  > tr').each(function (index, row) {
                 var checkedArr = $(row).find('input[type="checkbox"]:checked');
                 if (checkedArr.length === 0) {
                     var textbox = $(row).find('input[type="text"]');
                     $(textbox).attr('readonly', true);
                 }

                 $(row).find('input[type="checkbox"]').each(function(index, checkbox) {
                     $(checkbox).change(function () {
                         if (this.checked) {
                             $(this).closest("tr").find('input[type="text"]').attr('readonly', false);
                         }

                         var checkedArr = $(row).find('input[type="checkbox"]:checked');
                         if (checkedArr.length === 0) {
                             var textbox = $(row).find('input[type="text"]');
                             $(textbox).attr('readonly', true);
                         }
                     });
                 });

             });
         });

<asp:GridView ID="G2" ShowHeader="False" runat="server" AutoGenerateColumns="False" OnRowDataBound="G2_RowDataBound">
  <HeaderStyle BorderStyle="Solid" HorizontalAlign="Left" BackColor="LightGray" />
  <FooterStyle BorderWidth="1px" BorderStyle="Solid" BackColor="LightGray" />
  <RowStyle CssClass="gridRows" />
  <Columns>
    <asp:BoundField DataField="REVIEWQUESTIONS_DESC" />
    <asp:TemplateField>
      <ItemTemplate>
        <asp:CheckBox ID="chkbox_Yes" runat="server" Checked='<%# Eval("ANSWER_YES")%>' />
      </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField>
      <ItemTemplate>
        <asp:CheckBox ID="chkbox_No" runat="server" Checked='<%# Eval("ANSWER_NO")%>' />
      </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField>
      <ItemTemplate>
        <asp:CheckBox ID="chkbox_NA" runat="server" Checked='<%# Eval("ANSWER_NA")%>' />
      </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField>
      <ItemTemplate>
        <asp:TextBox runat="server" CssClass="NoLine" ID="txtbox_Notes" Text='<%# Eval("INCIDENTREVIEW_NOTES")%>'></asp:TextBox>
      </ItemTemplate>
    </asp:TemplateField>
  </Columns>
</asp:GridView>

Body:
You could do something like this:

Text='<% # Eval("NameYourUsing") %>' Enabled="false"


问:
Debugging SSIS Script Component - Breakpoint is enabled but it does not hit
I am working on a SSIS package that has some script components (in C#) inside data flow.

I used break points all the time with it and worked fine without any issue.

But yesterday suddenly it stopped working without throwing any errors or any.
The script works fine without breaking or any error, giving me the expected results as well but does not stop on break points.

I didn't change any visual studio configurations or project configuration.

Google and tried all the solutions others provided.

Clear all cache and all debug objects, rebuild the solution again, restart the machine as well but none of those worked.

Does anyone have this kind of experience?

Environment: Windows 10 Pro, VS 2017

答:
At last found the reason for the issue, the reason is that I used a conditional access operator inside the script.
The compiler compiles the code properly and works fine but the debugger somehow doesn't understand that operator and crashes.
Seems like SSDT use old C# version on debugging.. </p>


问:
Is it possible to create a DateTimeZone from an offset?
The DateTimeZone constructor only accepts a region name:

new DateTimeZone('Europe/London');
```

<p>And not an offset from UTC:</p>

<pre class="lang-php prettyprint-override"><code>new DateTimeZone('+01:00'); // Unknown or bad timezone (+01:00)
</code>```

However, it is possible to obtain such a DateTimeZone from a DateTime:

(new DateTime('2012-12-28T00:00:00+01:00'))->getTimezone()->getName(); // +01:00
```

So this is a bit weird. Is there a way to directly obtain a DateTimeZone from an offset?

答:
Modern answer:

```<code>new DateTimeZone('+0100');
</code>```

Documentation:

http://php.net/manual/en/datetimezone.construct.php

Body:
The DateTimeZone constructor only accepts a region name:

new DateTimeZone('Europe/London');

And not an offset from UTC:

new DateTimeZone('+01:00'); // Unknown or bad timezone (+01:00)

However, it is possible to obtain such a DateTimeZone from a DateTime:

(new DateTime('2012-12-28T00:00:00+01:00'))->getTimezone()->getName(); // +01:00

So this is a bit weird. Is there a way to directly obtain a DateTimeZone from an offset?

Body:
Modern answer:

new DateTimeZone('+0100');

Documentation:

http://php.net/manual/en/datetimezone.construct.php


问:
Pusher inside a laravel project and jquery ?
Here is the thing

first i have a laravel app that requires a real time chat application integrated inside .

i made the html structure so well ( could say like facebook )

a box that list all available users like this

after i click on any user it will pop up a chat box like these

okay sending messages using pusher and laravel echo  from single opened box to another one in another browser is working fine cause in each browser there is a single channel opened i named it send_message_( then i bind user id that i want to notify him ) that works fine  .

but :
the problem is when i open more than one chat box  i that mean there as much as number of channels found in browser  when i hit send from any box  it will notify ( this user that i intend to send a message to him ) and also users that their boxes opened also which is very wrong  .

i initialize pusher in registering popup i don't know if this is right or not

here is the initialization code  :

```<code>function register_popup(box, name , auth_user , user_to )
    {

                Pusher.logToConsole = true;
                // then i will use pusher here
                var pusher = new Pusher('2d203fcacc26d62ef49b', {
                    cluster:'mt1'
                });

                // Subscribe to the channel we specified in our Laravel Event
                var channel = pusher.subscribe('send_message_'+ user_to );

                // Bind a function to a Event (the full Laravel class)
                channel.bind("App\\Events\\MessageWasRecieved" ,   function(response) {

                    // alert(response.message);

                    $('.ul_holder_'+user_to).html();
                    $('.ul_holder_'+user_to).append(

                        `

                            <li>
                                    <div class="_4dt ua1">
                                        <div class="user_image">
                                        <img  src="http://127.0.0.1:8000/uploads/users/`+response.image+`" class="img-circle" alt="">
                                        </div>

                                        <div class="message_content">
                                            <span class="text">`+response.message+`</span>

                                        </div>

                                    </div>

                            </li>

                        `

                    );

                        // $('ul.ul_holder li:last').scrollTop();

                        var chatAudio = new Audio("{{ asset('sound/message.mp3') }}");
                        chatAudio.loop = false;
                        chatAudio.play();

                });

        for(var iii = 0; iii < popups.length; iii++)
        {
            //already registered. Bring it to front.
            if(box == popups[iii])
            {
                Array.remove(popups, iii);

                popups.unshift(box);

                calculate_popups();

                return;
            }
        }

        var id = auth_user ;
        var to_user = user_to ;
        var token = $('input[name=_token]').val();
        var lang = $('input[name=language]').val();

                        // i shall do my ajax logic here

                         $.ajax({

                             cache: false,
                             dataType:'json',
                             url : "check" ,
                             data: { _token:token ,  id:id  , to_user:to_user  },
                             method : 'GET',
                             beforeSend:function(){

                             },
                             success:function(data){

                                conversation = data.conversation_id ;

                                var test = `
                                <div class="message_box" id='`+box+`'>

                                          <div class="message_head">
                                              <span class="message_user ">`+ name +`</span>

                                              <div class="close">
                                                 <a href="javascript:close_popup('`+box+`');"> × </a>
                                              </div>
                                          </div>
                                          <div class="wrapper">

                                          <div class="message_body" >
                                          <ul class='ul_holder_`+box+`' data-body=`+conversation+`>
                                          <button class='btn btn-rounded btn-default text-center old_history_btn' data-conversation-id='`+conversation+`' data-auth-user='`+auth_user+`'>load old history</button>
                                          </ul>
                                          </div>

                                              <div class="message_footer">

                                              <textarea name="" id="" class="message_input" data-auth-id='`+auth_user+`' data-to-user-id='`+user_to+`' data-conversation-id='`+conversation+`'   placeholder="write message"></textarea>
                                              </div>
                                          </div>

                                      </div>
                                `;

                                document.getElementsByClassName("other_area")[0].innerHTML = document.getElementsByClassName("other_area")[0].innerHTML + test;

                                popups.unshift(box);

                                calculate_popups();

                             },

                        });
                        return false ;

    }
</code>```

if i want to restrict this i have an event of keydown that will send  post ajax request to insert my message in database then return a json response when i tried to initialize pusher in success function it doesn't work for first time
then if i hit  send again it sends successfully ,but i find my self entering a loop of repeating messages

here is the code

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

        $(document).on('keydown' , '.message_input', function(e){

            var token = $('input[name=_token]').val();
            var msg  = $(this).val();
            var element = $(this) ;

            var ul = element.parent().parent().find('ul');

            var authenticated_user_id = $(this).attr('data-auth-id');
            var user_id = $(this).attr('data-to-user-id');
            var conversation_id = $(this).attr('data-conversation-id');

            if(!msg == '' && e.keyCode == 13  && !e.shiftKey){

                                $.ajax({

                                    cache: false,
                                    dataType:'json',
                                    url : '{{ url("$lang/post_message")}}' ,
                                    data: {
                                            msg:msg  , authenticated_user_id:authenticated_user_id  , user_id:user_id , conversation_id: conversation_id , _token:token
                                    },
                                    method : 'POST',

                                    success:function(data){

                                        if(data.status == "success"){

                                            var message = data.message  ;

                                           ul.append(

                                                `

                                                    <li>
                                                        <div class="_4dme ua1">
                                                            <div class="message_content_me">
                                                                <span class="text">`+message+`</span>

                                                            </div>
                                                        </div>
                                                    </li>

                                                `

                                            );

                                            element.val('');

                                                var sendingMessage = new Audio("{{ asset('sound/sending_message.mp3') }}");
                                                    sendingMessage.loop = false;
                                                    sendingMessage.play();

                                        }else{

                                            console.log('catch error');
                                        }

                                    }
                                });

                                return false ;

            }

        });

    });
</code>```

i hope i had described my problem correct , that's what is pending so that i could finish the full chat system

thanks

答: This isn't necessarily an answer to your question specifically, but you might want to consider a new product more suited to your specific needs that works similarly to Pusher in a lot of ways. https://pusher.com/chatkit</p>

Body:
Here is the thing

first i have a laravel app that requires a real time chat application integrated inside .

i made the html structure so well ( could say like facebook )

a box that list all available users like this

after i click on any user it will pop up a chat box like these

okay sending messages using pusher and laravel echo  from single opened box to another one in another browser is working fine cause in each browser there is a single channel opened i named it send_message_( then i bind user id that i want to notify him ) that works fine  .

but :
the problem is when i open more than one chat box  i that mean there as much as number of channels found in browser  when i hit send from any box  it will notify ( this user that i intend to send a message to him ) and also users that their boxes opened also which is very wrong  .

i initialize pusher in registering popup i don't know if this is right or not

here is the initialization code  :

function register_popup(box, name , auth_user , user_to )
    {

                Pusher.logToConsole = true;
                // then i will use pusher here
                var pusher = new Pusher('2d203fcacc26d62ef49b', {
                    cluster:'mt1'
                });

                // Subscribe to the channel we specified in our Laravel Event
                var channel = pusher.subscribe('send_message_'+ user_to );

                // Bind a function to a Event (the full Laravel class)
                channel.bind("App\\Events\\MessageWasRecieved" ,   function(response) {

                    // alert(response.message);

                    $('.ul_holder_'+user_to).html();
                    $('.ul_holder_'+user_to).append(

                        `

                                        <img  src="http://127.0.0.1:8000/uploads/users/`+response.image+`" class="img-circle" alt="">

                                            `+response.message+`

                        `

                    );

                        // $('ul.ul_holder li:last').scrollTop();

                        var chatAudio = new Audio("{{ asset('sound/message.mp3') }}");
                        chatAudio.loop = false;
                        chatAudio.play();

                });

        for(var iii = 0; iii < popups.length; iii++)
        {
            //already registered. Bring it to front.
            if(box == popups[iii])
            {
                Array.remove(popups, iii);

                popups.unshift(box);

                calculate_popups();

                return;
            }
        }

        var id = auth_user ;
        var to_user = user_to ;
        var token = $('input[name=_token]').val();
        var lang = $('input[name=language]').val();

                        // i shall do my ajax logic here

                         $.ajax({

                             cache: false,
                             dataType:'json',
                             url : "check" ,
                             data: { _token:token ,  id:id  , to_user:to_user  },
                             method : 'GET',
                             beforeSend:function(){

                             },
                             success:function(data){

                                conversation = data.conversation_id ;

                                var test = `
                                <div class="message_box" id='`+box+`'>

                                              `+ name +`

                                                 <a href="javascript:close_popup('`+box+`');"> ×

                                          <ul class='ul_holder_`+box+`' data-body=`+conversation+`>
                                          <button class='btn btn-rounded btn-default text-center old_history_btn' data-conversation-id='`+conversation+`' data-auth-user='`+auth_user+`'>load old history</button>

                                              <textarea name="" id="" class="message_input" data-auth-id='`+auth_user+`' data-to-user-id='`+user_to+`' data-conversation-id='`+conversation+`'   placeholder="write message"></textarea>

                                `;

                                document.getElementsByClassName("other_area")[0].innerHTML = document.getElementsByClassName("other_area")[0].innerHTML + test;

                                popups.unshift(box);

                                calculate_popups();

                             },

                        });
                        return false ;

    }

if i want to restrict this i have an event of keydown that will send  post ajax request to insert my message in database then return a json response when i tried to initialize pusher in success function it doesn't work for first time
then if i hit  send again it sends successfully ,but i find my self entering a loop of repeating messages

here is the code

 $(document).ready(function(){

        $(document).on('keydown' , '.message_input', function(e){

            var token = $('input[name=_token]').val();
            var msg  = $(this).val();
            var element = $(this) ;

            var ul = element.parent().parent().find('ul');

            var authenticated_user_id = $(this).attr('data-auth-id');
            var user_id = $(this).attr('data-to-user-id');
            var conversation_id = $(this).attr('data-conversation-id');

            if(!msg == '' && e.keyCode == 13  && !e.shiftKey){

                                $.ajax({

                                    cache: false,
                                    dataType:'json',
                                    url : '{{ url("$lang/post_message")}}' ,
                                    data: {
                                            msg:msg  , authenticated_user_id:authenticated_user_id  , user_id:user_id , conversation_id: conversation_id , _token:token
                                    },
                                    method : 'POST',

                                    success:function(data){

                                        if(data.status == "success"){

                                            var message = data.message  ;

                                           ul.append(

                                                `

                                                                `+message+`

                                                `

                                            );

                                            element.val('');

                                                var sendingMessage = new Audio("{{ asset('sound/sending_message.mp3') }}");
                                                    sendingMessage.loop = false;
                                                    sendingMessage.play();

                                        }else{

                                            console.log('catch error');
                                        }

                                    }
                                });

                                return false ;

            }

        });

    });

i hope i had described my problem correct , that's what is pending so that i could finish the full chat system

thanks


问:
count after groupby in Google Dataflow
I have the following in my Google cloud storage

```<code>Advertiser | Event
__________________
100 | Click

101 | Impression

100 | Impression

100 | Impression

101 | Impression
</code>```

My output of the pipeline should be something like

```<code>Advertiser | Count

100 | 3

101 | 2
</code>```

First I used groupByKey, the output is like

```<code>100 Click, Impression, Impression

101 Impression, Impression
</code>```

How to proceed from here?

答:
Instead of a GroupByKey, you may want to use a combine function, which is a composite that optimizes before and after the group by key. Your pipeline can look something like this:

Python

```<code>collection_contents = [(100, 'Click'),
                       (101, 'Impression'),
                       (100, 'Impression'),
                       (100, 'Impression'),
                       (101, 'Impression']

input_collection = pipeline | beam.Create(collection_contents)

counts = input_collection | Count.PerKey()
</code>```

This should output a collection with the shape you are looking for. The Count series of transforms is available in the apache_beam.transforms.combiners.combine.Count module.

Java

The same transforms exist for Java in the org.apache.beam.sdk.transforms package:

```<code>PCollection<KV<Integer, Integer>> resultColl = inputColl.apply(Count.perKey())
</code>```

Title: count after groupby in Google Dataflow

Body:
I have the following in my Google cloud storage

Advertiser | Event
__________________
100 | Click

101 | Impression

100 | Impression

100 | Impression

101 | Impression

My output of the pipeline should be something like

Advertiser | Count

100 | 3

101 | 2

First I used groupByKey, the output is like

100 Click, Impression, Impression

101 Impression, Impression

How to proceed from here?

Body:
Instead of a GroupByKey, you may want to use a combine function, which is a composite that optimizes before and after the group by key. Your pipeline can look something like this:

Python

collection_contents = [(100, 'Click'),
                       (101, 'Impression'),
                       (100, 'Impression'),
                       (100, 'Impression'),
                       (101, 'Impression']

input_collection = pipeline | beam.Create(collection_contents)

counts = input_collection | Count.PerKey()

This should output a collection with the shape you are looking for. The Count series of transforms is available in the apache_beam.transforms.combiners.combine.Count module.

Java

The same transforms exist for Java in the org.apache.beam.sdk.transforms package:

PCollection<KV<Integer, Integer>> resultColl = inputColl.apply(Count.perKey())


问:
ios Instagram api POST Relationship Endpoints using Alamofire - Error
i'm using swift in my app

and i'm trying to post a relationship (Follow) with scope ("follower_list+relationships") using Alamofire

Note: I'm using sandbox users for testing

with this code

```<code>let userid = "testAccount"
    let urlString = "https://api.instagram.com/v1/users/\(userid)/relationship?access_token=\(INSTAGRAM_IDS.INSTAGRAM_Token)&action=follow"

    Alamofire.request(urlString).responseJSON { response in switch response.result {

        case .success(let JSON):

        let response = JSON as! NSDictionary
        let userModel = response

            print("SUCCESS")
            print(userModel)

        case .failure(let error):

            print("ERROR")
            print(error)
        }
    }
</code>```

and also tried this one

```<code>let userid = "testAccount"
    let urlString = "https://api.instagram.com/v1/users/\(userid)/relationship?access_token=\(INSTAGRAM_IDS.INSTAGRAM_Token)"
    let parameters: Parameters = ["action": "follow"]

    Alamofire.request(urlString, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: nil).responseJSON { response in switch response.result {

        case .success(let JSON):

        let response = JSON as! NSDictionary
        let userModel = response

            print("SUCCESS")
            print(userModel)

        case .failure(let error):

            print("ERROR")
            print(error)
        }
    }
</code>```

BUT still got this message ??

ERROR
  responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))

any idea ??

答:
If you're trying to post json I suspect you need to change your encoding with encoding: JSONEncoding.default

The JSONEncoding type creates a JSON representation of the parameters object, which is set as the HTTP body of the request. The Content-Type HTTP header field of an encoded request is set to application/json.

Usage on github

Body:
i'm using swift in my app

and i'm trying to post a relationship (Follow) with scope ("follower_list+relationships") using Alamofire

Note: I'm using sandbox users for testing

with this code

let userid = "testAccount"
    let urlString = "https://api.instagram.com/v1/users/\(userid)/relationship?access_token=\(INSTAGRAM_IDS.INSTAGRAM_Token)&action=follow"

    Alamofire.request(urlString).responseJSON { response in switch response.result {

        case .success(let JSON):

        let response = JSON as! NSDictionary
        let userModel = response

            print("SUCCESS")
            print(userModel)

        case .failure(let error):

            print("ERROR")
            print(error)
        }
    }

and also tried this one

let userid = "testAccount"
    let urlString = "https://api.instagram.com/v1/users/\(userid)/relationship?access_token=\(INSTAGRAM_IDS.INSTAGRAM_Token)"
    let parameters: Parameters = ["action": "follow"]

    Alamofire.request(urlString, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: nil).responseJSON { response in switch response.result {

        case .success(let JSON):

        let response = JSON as! NSDictionary
        let userModel = response

            print("SUCCESS")
            print(userModel)

        case .failure(let error):

            print("ERROR")
            print(error)
        }
    }

BUT still got this message ??

ERROR
  responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))

any idea ??


问:
Remove Backup-SqlDatabase progress bar when complete
I have fully working powershell 3 script that backups up an number of SQL databases. This script is called by a master script that then calls a number of other powershell scripts that do various jobs.

For each database being backed up there is the nice progress bar, but the bars never go away even through everything works and they report 100%.

I do not want to disable the progress bars completely just for then to go away when complete, though I would accept them just disappearing when the backup script is complete.

The command being call is Backup-SqlDatabase -DatabaseObject $Database -BackupFile "$($Path)$($DatabaseName)_db_$($DateStamp).bak" but I cannot see any switches that might help.

I doubt this is relevant but the master script is calling the backup script via Invoke-Command and executing it directly on the SQL server as a specific user.

答:
I think this will be a good solution:

$ProgressPreference=’SilentlyContinue’

I got this tricks from here


问:
Configure Python Path in Visual Studio Code with venv running from bash on Windows
I have a virtual environment set up inside bash for Windows (Ubuntu) and VS Code installed (Windows). The Python project runs well inside the venv in bash but I would like to now debug it through Visual Code.

I'm trying to set the python.pythonPath as follows inside settings.json

```<code>{
    "python.pythonPath": "C:\\repos\\myrepo\\venv\\bin\\python"
}
</code>```

The error returned is "Please validate the path ..."

Note that through bash for Windows, the filesystem is accessible through /mnt/c/

As for the auto-detection of Python, it only lists the python.exe installed on the windows filesystem (which is of no use to me).

https://code.visualstudio.com/docs/python/environments explains that doing this should be sufficient but doesn't seem to work.

答: It doesn't work because WSL isn't officially supported yet by the extension as of version 0.8.0. See https://github.com/Microsoft/vscode-python/issues/67 to up-vote and track the issue for detecting WSL-based virtual environments.</p>

Body:
I have a virtual environment set up inside bash for Windows (Ubuntu) and VS Code installed (Windows). The Python project runs well inside the venv in bash but I would like to now debug it through Visual Code.

I'm trying to set the python.pythonPath as follows inside settings.json

{
    "python.pythonPath": "C:\\repos\\myrepo\\venv\\bin\\python"
}

The error returned is "Please validate the path ..."

Note that through bash for Windows, the filesystem is accessible through /mnt/c/

As for the auto-detection of Python, it only lists the python.exe installed on the windows filesystem (which is of no use to me).

https://code.visualstudio.com/docs/python/environments explains that doing this should be sufficient but doesn't seem to work.


问:
Make a curl request to a url having no file extension?
I have following URL

http://www.davesinclairstpeters.com/auto2_inventorylist?i=37647&c=12452&npg=1&ns=50&echo=2

I want to retrieve content of this url using curl but everytime I make this request it is showing me error, as it is not passing required parameters

Below is my code

```

    $ch = curl_init(); // start CURL
    curl_setopt($ch, CURLOPT_URL, $json_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPGET, true);
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
    $response = curl_exec($ch);

```

答:
This URL yields a page of cars with links to more cars.  Looks like the URL you're starting with is old, or has some sort of expiration factor that's not obvious.

Not knowing which sort of filtering parameters you're shooting for.. hard to say what else my be wrong, other than your starting URL be bad.

working url:

```<code>http://www.davesinclairlincolnstpeters.com/all-inventory/index.htm?listingConfigId=auto-new%2Cauto-used&compositeType=&year=&make=&start=0&sort=&facetbrowse=true&quick=true&preserveSelectsOnBack=true&searchLinkText=SEARCH&showInvTotals=false&showRadius=false&showReset=true&showSubmit=true&facetbrowseGridUnit=BLANK&showSelections=true&dependencies=model%3Amake%2Ccity%3Aprovince%2Ccity%3Astate&suppressAllConditions=false
</code>```

Body:
I have following URL

http://www.davesinclairstpeters.com/auto2_inventorylist?i=37647&c=12452&npg=1&ns=50&echo=2

I want to retrieve content of this url using curl but everytime I make this request it is showing me error, as it is not passing required parameters

Below is my code

    $ch = curl_init(); // start CURL
    curl_setopt($ch, CURLOPT_URL, $json_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPGET, true);
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
    $response = curl_exec($ch);

Body:
This URL yields a page of cars with links to more cars.  Looks like the URL you're starting with is old, or has some sort of expiration factor that's not obvious.

Not knowing which sort of filtering parameters you're shooting for.. hard to say what else my be wrong, other than your starting URL be bad.

working url:

http://www.davesinclairlincolnstpeters.com/all-inventory/index.htm?listingConfigId=auto-new%2Cauto-used&compositeType=&year=&make=&start=0&sort=&facetbrowse=true&quick=true&preserveSelectsOnBack=true&searchLinkText=SEARCH&showInvTotals=false&showRadius=false&showReset=true&showSubmit=true&facetbrowseGridUnit=BLANK&showSelections=true&dependencies=model%3Amake%2Ccity%3Aprovince%2Ccity%3Astate&suppressAllConditions=false


问:
How to configure using Styleguidist with Apollo/GraphQL
I'm trying to use GraphQL to populate fake data for Styleguidist. I'm using Express to make my GraphQL server but I'm unsure how to connect Apollo into Styleguidist? The examples use the index.js file and wrap the root component in an tag for Apollo.

I am unsure how Styleguidist works, I don't know where the index.js file is.

There are ways to configure Styleguidist through webpack, but I don't know how to use webpack to use Apollo.

答:
So you can use Styleguidist in two ways, one by using Create React App then installing an NPM Styleguidist package. Then the other method that I found is starting from an example github registry and replacing the components as you go. I had done the first: where I used Create React App so Webpack was not installed in my main folder but was being used in the NPM module.

With that method I was getting the error:

"Module parse failed: Unexpected token (16:6)
You may need an appropriate loader to handle this file type."

Which means that I needed to configure Webpack. I didn't solve this, but it may just need to have styleguide.config.js file configured to work with Babel. (just a guess)

So, could not (so far), successfully use the Wrapper that solves the problem. So instead I downloaded an example of Styleguidist at https://github.com/styleguidist/example and started fresh. I'm not sure what the difference is, but when I used a wrapper it worked well to add an ApolloProvider wrapper to every component on my page.

To get Apollo 2 to work though you also need to use HttpLink and InMemoryCache. The have a general setup about this at: https://www.apollographql.com/docs/react/basics/setup.html. Under creating a client.

I was using a different port for my GraphQL server because it was using a GraphQL/Express server at port 4000 and Styleguidist by default is at port 6060. So I did two things: passed a uri to the new HttpLink and added a line to the express server to allow cors.

The ref for cors in Express GraphQl and Apollo server:
https://blog.graph.cool/enabling-cors-for-express-graphql-apollo-server-1ef999bfb38d

So my wrapper file looks like:

```<code>import React, { Component } from 'react';
import ApolloClient, { createNetworkInterface } from 'apollo-client';
import { ApolloProvider } from 'react-apollo';
import { HttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';

const link = new HttpLink({
  uri: 'http://localhost:4000/graphql'
});

const client = new ApolloClient({
  link,
  cache: new InMemoryCache()
});

export default class Wrapper extends Component {
  render() {
    return (
      <ApolloProvider client={client}>
        {this.props.children}
      </ApolloProvider>
    );
  }
}
</code>```

and my server file looks like:

```<code>const express = require('express');
const expressGraphQL = require('express-graphql');
const schema = require('./schema/schema');
const cors = require('cors');

const app = express();
app.use(cors());
app.use('/graphql', expressGraphQL({
  schema: schema
  , graphiql: true
}));

app.listen(4000, () => {
  console.log('..listening');
});
</code>```

Body:
So you can use Styleguidist in two ways, one by using Create React App then installing an NPM Styleguidist package. Then the other method that I found is starting from an example github registry and replacing the components as you go. I had done the first: where I used Create React App so Webpack was not installed in my main folder but was being used in the NPM module.

With that method I was getting the error:

"Module parse failed: Unexpected token (16:6)
You may need an appropriate loader to handle this file type."

Which means that I needed to configure Webpack. I didn't solve this, but it may just need to have styleguide.config.js file configured to work with Babel. (just a guess)

So, could not (so far), successfully use the Wrapper that solves the problem. So instead I downloaded an example of Styleguidist at https://github.com/styleguidist/example and started fresh. I'm not sure what the difference is, but when I used a wrapper it worked well to add an ApolloProvider wrapper to every component on my page.

To get Apollo 2 to work though you also need to use HttpLink and InMemoryCache. The have a general setup about this at: https://www.apollographql.com/docs/react/basics/setup.html. Under creating a client.

I was using a different port for my GraphQL server because it was using a GraphQL/Express server at port 4000 and Styleguidist by default is at port 6060. So I did two things: passed a uri to the new HttpLink and added a line to the express server to allow cors.

The ref for cors in Express GraphQl and Apollo server:
https://blog.graph.cool/enabling-cors-for-express-graphql-apollo-server-1ef999bfb38d

So my wrapper file looks like:

import React, { Component } from 'react';
import ApolloClient, { createNetworkInterface } from 'apollo-client';
import { ApolloProvider } from 'react-apollo';
import { HttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';

const link = new HttpLink({
  uri: 'http://localhost:4000/graphql'
});

const client = new ApolloClient({
  link,
  cache: new InMemoryCache()
});

export default class Wrapper extends Component {
  render() {
    return (
      <ApolloProvider client={client}>
        {this.props.children}
      </ApolloProvider>
    );
  }
}

and my server file looks like:

const express = require('express');
const expressGraphQL = require('express-graphql');
const schema = require('./schema/schema');
const cors = require('cors');

const app = express();
app.use(cors());
app.use('/graphql', expressGraphQL({
  schema: schema
  , graphiql: true
}));

app.listen(4000, () => {
  console.log('..listening');
});


问:
Replace 0 by the last value seen in the array (similar to the fillna method with NaN values) in pandas dataframes
I've been trying to create a new boolean array from two initial boolean arrays (df1 and df2) , following this rule:

-If the last True value was seen in df1, the value in df3 is True
-If the last True value was seen in df2, the value in df3 is False

I found a way to do this by substracting the two arrays, then remplacing the 0 values by NaN values, using the .fillnamethod to fill the NaN values, and finally remplacing the -1 values by 0.

The code looks like this (with random arrays given as examples):

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

```<code>df1 = pd.Series((1,1,1,0,0,0,0,0,0,0,
                 0,0,0,0,1,0,0,1,0,0,
                 0,0,0,0,0,1,1,1,0,0,
                 0,0,0,0,0,0,0,0,0,0,
                 0,0,0,1,1,1,0,0,0,0))

df2 = pd.Series((0,0,0,0,0,0,1,1,0,0,
                 0,0,0,0,0,0,0,0,0,0,
                 1,0,0,0,0,0,0,0,0,0,
                 0,0,0,1,0,0,1,0,0,0,
                 0,0,0,0,0,0,0,0,0,0))

df3 = df1-df2
df3 = df3.replace(0,np.nan).fillna(method='ffill')
df3 = df3.replace(-1,0)
</code>```

It does the trick and returns me the array I want, however it seems not optimized to remplace values several times like this, and working around thefillna method to do what I want.

Would anyone know a way to do this more 'properly', and if there is a method similar to the fillna one, but on other values than NaN?

Optimization is really important on this problem, as I'll go through this process a lot of time.

答:
This should be a bit faster (about 6x for 200,000 rows but check for yourself, of course).  After import numpy as np:

```<code>arr = np.select( [df1==1,df2==1], [1,0], default=np.nan )
ser = pd.Series( arr ).ffill()
</code>```

If you aren't familiar with np.select it's pretty similar to np.where but allows multiple conditions.  You could also do a nested np.where but this is more readable.

Below is arr, and what allows you to do a simple ffill without needing to use  replace twice is that you have nan's instead of zeroes.

```<code>array([  1.,   1.,   1.,  nan,  nan,  nan,   0.,   0.,  nan,  nan,  nan,
        nan,  nan,  nan,   1.,  nan,  nan,   1.,  nan,  nan,   0.,  nan,
        nan,  nan,  nan,   1.,   1.,   1.,  nan,  nan,  nan,  nan,  nan,
         0.,  nan,  nan,   0.,  nan,  nan,  nan,  nan,  nan,  nan,   1.,
         1.,   1.,  nan,  nan,  nan,  nan])
</code>```

You might also get a little extra speed by storing df1 & df2 as numpy arrays rather than dataframes/series, but I don't think it would matter too much.

If speed is really a concern, you should try to do everything in numpy rather than pandas (when possible), but I'm not sure of a good numpy analog for pandas ffill.

Body:
I've been trying to create a new boolean array from two initial boolean arrays (df1 and df2) , following this rule:

-If the last True value was seen in df1, the value in df3 is True
-If the last True value was seen in df2, the value in df3 is False

I found a way to do this by substracting the two arrays, then remplacing the 0 values by NaN values, using the .fillnamethod to fill the NaN values, and finally remplacing the -1 values by 0.

The code looks like this (with random arrays given as examples):

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

df1 = pd.Series((1,1,1,0,0,0,0,0,0,0,
                 0,0,0,0,1,0,0,1,0,0,
                 0,0,0,0,0,1,1,1,0,0,
                 0,0,0,0,0,0,0,0,0,0,
                 0,0,0,1,1,1,0,0,0,0))

df2 = pd.Series((0,0,0,0,0,0,1,1,0,0,
                 0,0,0,0,0,0,0,0,0,0,
                 1,0,0,0,0,0,0,0,0,0,
                 0,0,0,1,0,0,1,0,0,0,
                 0,0,0,0,0,0,0,0,0,0))

df3 = df1-df2
df3 = df3.replace(0,np.nan).fillna(method='ffill')
df3 = df3.replace(-1,0)

It does the trick and returns me the array I want, however it seems not optimized to remplace values several times like this, and working around thefillna method to do what I want.

Would anyone know a way to do this more 'properly', and if there is a method similar to the fillna one, but on other values than NaN?

Optimization is really important on this problem, as I'll go through this process a lot of time.

Body:
This should be a bit faster (about 6x for 200,000 rows but check for yourself, of course).  After import numpy as np:

arr = np.select( [df1==1,df2==1], [1,0], default=np.nan )
ser = pd.Series( arr ).ffill()

If you aren't familiar with np.select it's pretty similar to np.where but allows multiple conditions.  You could also do a nested np.where but this is more readable.

Below is arr, and what allows you to do a simple ffill without needing to use  replace twice is that you have nan's instead of zeroes.

array([  1.,   1.,   1.,  nan,  nan,  nan,   0.,   0.,  nan,  nan,  nan,
        nan,  nan,  nan,   1.,  nan,  nan,   1.,  nan,  nan,   0.,  nan,
        nan,  nan,  nan,   1.,   1.,   1.,  nan,  nan,  nan,  nan,  nan,
         0.,  nan,  nan,   0.,  nan,  nan,  nan,  nan,  nan,  nan,   1.,
         1.,   1.,  nan,  nan,  nan,  nan])

You might also get a little extra speed by storing df1 & df2 as numpy arrays rather than dataframes/series, but I don't think it would matter too much.

If speed is really a concern, you should try to do everything in numpy rather than pandas (when possible), but I'm not sure of a good numpy analog for pandas ffill.


问:
Parsing binary message stream in C/C++
I'm writing a decoder for a binary protocol (Javad GRIL protocol). It consists of about a hundred messages, with data in the following format:

```<code>struct MsgData {
    uint8_t num;
    float x, y, z;
    uint8_t elevation;
    ...
};
</code>```

The fields are ANSI-encoded binary numbers which follow each other with no gaps. The simplest way to parse such messages is to cast an input array of bytes to the appropriate type. The problem is that the data in stream are packed, i.e. unaligned.

On x86 this can be solved by using #pragma pack(1). However, that won't work on some other platforms or will incur performance overhead due to further work with misaligned data.

Another way is to write a specific parse function for each message type, but as I've mentioned, the protocol includes hundreds of messages.

Yet another alternative is to use something like the Perl unpack() function and store the message format somewhere. Say, we can #define MsgDataFormat "CfffC" and then call unpack(pMsgBody, MsgDataFormat). This is much shorter but still error-prone and redundant. Moreover, the format can be more complicated because messages can contain arrays, so the parser will be slow and complex.

Is there any common and effective solution? I've read this post and Googled around but didn't find a better way to do it.

Maybe C++ has a solution?

答:
I don't think you can avoid writing specicfic parsing routine for every message in pure C++ (without using pragma).

If all your messages are simple, POD, C-like structures, I think the easiest solution would be to write a code generator: put your structs in a header without other C++ stuff and write a simple parser (a perl/python/bash script using a couple of regular expressions should be enough) -or look for one- that is able to find the variable names in any message; then use it to automatically generate some code for any message to read it, like this:

```<code>YourStreamType & operator>>( YourStreamType &stream, MsgData &msg ) {
    stream >> msg.num >> msg.x >> msg.y >> msg.z >> msg.elevation;
    return stream;
}
</code>```

specialize YourStreamType's operator>> for any basic type your messages contain and you should be done:

```<code>MsgData msg;
your_stream >> msg;
</code>```

Title: Parsing binary message stream in C/C++

Body:
I'm writing a decoder for a binary protocol (Javad GRIL protocol). It consists of about a hundred messages, with data in the following format:

struct MsgData {
    uint8_t num;
    float x, y, z;
    uint8_t elevation;
    ...
};

The fields are ANSI-encoded binary numbers which follow each other with no gaps. The simplest way to parse such messages is to cast an input array of bytes to the appropriate type. The problem is that the data in stream are packed, i.e. unaligned.

On x86 this can be solved by using #pragma pack(1). However, that won't work on some other platforms or will incur performance overhead due to further work with misaligned data.

Another way is to write a specific parse function for each message type, but as I've mentioned, the protocol includes hundreds of messages.

Yet another alternative is to use something like the Perl unpack() function and store the message format somewhere. Say, we can #define MsgDataFormat "CfffC" and then call unpack(pMsgBody, MsgDataFormat). This is much shorter but still error-prone and redundant. Moreover, the format can be more complicated because messages can contain arrays, so the parser will be slow and complex.

Is there any common and effective solution? I've read this post and Googled around but didn't find a better way to do it.

Maybe C++ has a solution?

Body:
I don't think you can avoid writing specicfic parsing routine for every message in pure C++ (without using pragma).

If all your messages are simple, POD, C-like structures, I think the easiest solution would be to write a code generator: put your structs in a header without other C++ stuff and write a simple parser (a perl/python/bash script using a couple of regular expressions should be enough) -or look for one- that is able to find the variable names in any message; then use it to automatically generate some code for any message to read it, like this:

YourStreamType & operator>>( YourStreamType &stream, MsgData &msg ) {
    stream >> msg.num >> msg.x >> msg.y >> msg.z >> msg.elevation;
    return stream;
}

specialize YourStreamType's operator>> for any basic type your messages contain and you should be done:

MsgData msg;
your_stream >> msg;

ContentLicense: CC BY-SA 2.5


问:
Select all elements but the last

I need to select all elements of a div but the last of this code:

```<code><div class="menu">
    <div>
       <a class="link" href="/">link 1</a>
       <div class="subMenu">
           <a class="link" href="/">link 2</a>
           <a class="link" href="/">link 3</a>
           <a class="link" href="/">link 4</a>
       </div>
       <a class="link" href="/">link 5</a>
   </div>
</div>
</code>```

I have tried .menu .link:not(:last-child) but the link 4 is selected as the last child but I want that the last child to be link 5. How can I do it?

Thanks you.

答:
This happens because the link 4 is also the :last-child or :last-of-type of the .subMenu div. You can do it like this instead:

.menu > div > .link:not(:last-of-type),
.subMenu > .link {color:#f00}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="menu">
  <div>
    link 1
    <div class="subMenu">
      link 2
      link 3
      link 4
    </div>
    link 5
  </div>
</div></code>```

Title: Select all elements but the last

Body:
I need to select all elements of a div but the last of this code:

       link 1

           link 2
           link 3
           link 4

       link 5

I have tried .menu .link:not(:last-child) but the link 4 is selected as the last child but I want that the last child to be link 5. How can I do it?

Thanks you.

Body:
This happens because the link 4 is also the :last-child or :last-of-type of the .subMenu div. You can do it like this instead:

.menu > div > .link:not(:last-of-type),
.subMenu > .link {color:#f00}

<div class="menu">
  <div>
    <a class="link" href="#">link 1</a>
    <div class="subMenu">
      <a class="link" href="#">link 2</a>
      <a class="link" href="#">link 3</a>
      <a class="link" href="#">link 4</a>
    </div>
    <a class="link" href="#">link 5</a>
  </div>
</div>


问:
Jekyll multiple pages using the same template
I'm aware you can use _layouts and in your pages do something like

```<code>---
layout: some_layout
title: Home
---
</code>```

So say I have 20 pages. All using the same template but slightly different content and stuff inside.

Instead of creating 20 different pages.html files with different names and different permalinks.

Is there a way to create 1 page.html and based on the permalink change what's inside the {{ content }}?

答:
Just create your-slug.md files. Let them all use the same layout, like this:

```<code>---
layout: some_layout
title: Your title
---
</code>```

In the layout file (some_layout.html) you put some logic, like this:

```<code>{% if page.url contains '/your-slug' %}Put this on the screen.{% endif %}
</code>```

Body:
I'm aware you can use _layouts and in your pages do something like

---
layout: some_layout
title: Home
---

So say I have 20 pages. All using the same template but slightly different content and stuff inside.

Instead of creating 20 different pages.html files with different names and different permalinks.

Is there a way to create 1 page.html and based on the permalink change what's inside the {{ content }}?

Body:
Just create your-slug.md files. Let them all use the same layout, like this:

---
layout: some_layout
title: Your title
---

In the layout file (some_layout.html) you put some logic, like this:

{% if page.url contains '/your-slug' %}Put this on the screen.{% endif %}


问:
Google Sheet API append to a specific sheet
according to the API it seems that I can't specify the sheet where to append the data. It appends everything in the first sheet. Is it really like this?

Beacuse I can create a file with multiple sheets, but then I can't write on the second sheet?

答:
The solution is to specify the sheet title in the {range} parameter found on the awful-as-always Google Sheets API docs.

Below are the request deets on a updating the value on sheet2...

URL:

```<code>PUT https://sheets.googleapis.com/v4/spreadsheets/{someSpreadsheetId}/values/sheet2!A1:D3?valueInputOption=USER_ENTERED
</code>```

BODY:

```<code>{
  "values": [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
  ]
}
</code>```

Note that the title of the second sheet, "sheet2" prepends what I would have considered the range: "A1:D3" with an exclamation delimiter.
    sheet2!A1:D3

Body:
The solution is to specify the sheet title in the {range} parameter found on the awful-as-always Google Sheets API docs.

Below are the request deets on a updating the value on sheet2...

URL:

PUT https://sheets.googleapis.com/v4/spreadsheets/{someSpreadsheetId}/values/sheet2!A1:D3?valueInputOption=USER_ENTERED

BODY:

{
  "values": [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
  ]
}

Note that the title of the second sheet, "sheet2" prepends what I would have considered the range: "A1:D3" with an exclamation delimiter.
    sheet2!A1:D3