问:
MailApp.sendEmail emails the user who is not a recipient
(Note: I edited the title for clarity)

I've been trying to figure out what's causing this problem but to no avail.

I created a Google script that allows a Requester to submit a Google sheet for approval. Upon submission it emails the Requester that it has been submitted. It also emails the Approver with the option to APPROVE or DISAPPROVE. My problem: this same exact mail for Approver is also received by the Requester.

Here's a snapshot of the code for your review and kind support:

```<code>function emailSpreadsheetAsPDF(time, approverEmail, requesterEmail, financeEmail, approvalNeeded) {

var timestamp = time;
var approverEmail = approverEmail;
var requesterEmail = requesterEmail;
var financeEmail = financeEmail;
var approvalNeeded = approvalNeeded;
Logger.log("Approver: " + approverEmail);
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Form"); // Enter the name of the sheet here

//*******************************************
//* Enter the name of the TEMP folder ID here
//*******************************************

var TEMPfolderid = "xxxyyyzzz";     // TEMP folder to store the PDF export
var body4Requester = "\n\nAttached is a PDF copy of the Price Maintenance Form that you submitted. \n\nPlease note that you will be automatically notified via email when: \n(a) Your request is approved (or disapproved), and \n(b) When it is approved and already processed in SAP. \n\nAPAC Finance Team";
var body4Finance = "\n\nAttached is a PDF copy of the Price Maintenance Form submitted by " +  requesterEmail + ". It does not require an approval as per current policy.\n\nKindly process.";

var url = "https://docs.google.com/spreadsheets/d/SS_ID/export?".replace("SS_ID", ss.getId());

// Specify PDF export parameters
var url_ext = 'exportFormat=pdf&format=pdf' // export as pdf / csv / xls / xlsx
     + '&size=A4' // paper size legal / letter / A4
     + '&portrait=false' // orientation, false for landscape
     + '&fitw=true&source=labnol' // fit to page width, false for actual size
     + '&sheetnames=false&printtitle=false' // hide optional headers and footers
     + '&pagenumbers=false&gridlines=false' // hide page numbers and gridlines
     + '&fzr=false' // do not repeat row headers (frozen rows) on each page
     + '&gid='; // the sheet's Id

var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url + url_ext + sheet.getSheetId(), {
        headers : {
            'Authorization' : 'Bearer ' + token
        },
        muteHttpExceptions: true
    });

var pdfFile = response.getBlob();

//Create the file...
var file = DriveApp.createFile(pdfFile).setName(timestamp + ".pdf");

//Store the file's ID for retrieval later during approval and post-SAP processing
var PDFfileID = file.getId();

//Save the file in TEMP folder
DriveApp.getFolderById(TEMPfolderid).addFile(file);

//Now, get the file and email as attachment
var blob = DriveApp.getFileById(file.getId());

// Email with Approve/Disapprove link
var url = ScriptApp.getService().getUrl();

var options = '?approval=%APPROVE%&timestamp=%TIMESTAMP%&reply=%EMAIL%&pdffileid=%FILEID%'
     .replace("%TIMESTAMP%",encodeURIComponent(timestamp))
     .replace("%EMAIL%",requesterEmail)
     .replace("%FILEID%",PDFfileID);
var approve = url+options.replace("%APPROVE%","Approved");
var disapprove = url+options.replace("%APPROVE%","Disapproved");

var html = "<body>"+
            "Attached is the Price Change request<br /><br />"+
            "<a href="+ approve +">Approve</a><br />"+
            "<a href="+ disapprove +">Disapprove</a><br />"+
         "</body>";

if (approvalNeeded == "Yes") {           //send email with Approve and Disapprove option to Approver
    MailApp.sendEmail(approverEmail, "TEST ONLY: Price Maintenance Form for your approval", body4Requester, {
                htmlBody: html,
                attachments : [blob]
                });

    MailApp.sendEmail(requesterEmail, "TEST ONLY: Your Price Maintenance request has been submitted", body4Requester, {
                attachments : [blob]
                });

} else {                                 //send straight to Finance
    MailApp.sendEmail(financeEmail, "TEST ONLY: Price Maintenance Form for processing. No approval neeed", body4Finance, {
                cc:requesterEmail,
                attachments : [blob]
                });
}}
</code>```

Not sure if it's relevant -- I deployed this as a web app with the setting "Execute the app as User accessing the web app".

Many thanks in advance for any advice.

答:
I tried replacing MailApp.sendEmail with GmailApp.sendEmail.
It worked.</p>

Body:
(Note: I edited the title for clarity)

I've been trying to figure out what's causing this problem but to no avail.

I created a Google script that allows a Requester to submit a Google sheet for approval. Upon submission it emails the Requester that it has been submitted. It also emails the Approver with the option to APPROVE or DISAPPROVE. My problem: this same exact mail for Approver is also received by the Requester.

Here's a snapshot of the code for your review and kind support:

function emailSpreadsheetAsPDF(time, approverEmail, requesterEmail, financeEmail, approvalNeeded) {

var timestamp = time;
var approverEmail = approverEmail;
var requesterEmail = requesterEmail;
var financeEmail = financeEmail;
var approvalNeeded = approvalNeeded;
Logger.log("Approver: " + approverEmail);
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Form"); // Enter the name of the sheet here

//*******************************************
//* Enter the name of the TEMP folder ID here
//*******************************************

var TEMPfolderid = "xxxyyyzzz";     // TEMP folder to store the PDF export
var body4Requester = "\n\nAttached is a PDF copy of the Price Maintenance Form that you submitted. \n\nPlease note that you will be automatically notified via email when: \n(a) Your request is approved (or disapproved), and \n(b) When it is approved and already processed in SAP. \n\nAPAC Finance Team";
var body4Finance = "\n\nAttached is a PDF copy of the Price Maintenance Form submitted by " +  requesterEmail + ". It does not require an approval as per current policy.\n\nKindly process.";

var url = "https://docs.google.com/spreadsheets/d/SS_ID/export?".replace("SS_ID", ss.getId());

// Specify PDF export parameters
var url_ext = 'exportFormat=pdf&format=pdf' // export as pdf / csv / xls / xlsx
     + '&size=A4' // paper size legal / letter / A4
     + '&portrait=false' // orientation, false for landscape
     + '&fitw=true&source=labnol' // fit to page width, false for actual size
     + '&sheetnames=false&printtitle=false' // hide optional headers and footers
     + '&pagenumbers=false&gridlines=false' // hide page numbers and gridlines
     + '&fzr=false' // do not repeat row headers (frozen rows) on each page
     + '&gid='; // the sheet's Id

var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url + url_ext + sheet.getSheetId(), {
        headers : {
            'Authorization' : 'Bearer ' + token
        },
        muteHttpExceptions: true
    });

var pdfFile = response.getBlob();

//Create the file...
var file = DriveApp.createFile(pdfFile).setName(timestamp + ".pdf");

//Store the file's ID for retrieval later during approval and post-SAP processing
var PDFfileID = file.getId();

//Save the file in TEMP folder
DriveApp.getFolderById(TEMPfolderid).addFile(file);

//Now, get the file and email as attachment
var blob = DriveApp.getFileById(file.getId());

// Email with Approve/Disapprove link
var url = ScriptApp.getService().getUrl();

var options = '?approval=%APPROVE%&timestamp=%TIMESTAMP%&reply=%EMAIL%&pdffileid=%FILEID%'
     .replace("%TIMESTAMP%",encodeURIComponent(timestamp))
     .replace("%EMAIL%",requesterEmail)
     .replace("%FILEID%",PDFfileID);
var approve = url+options.replace("%APPROVE%","Approved");
var disapprove = url+options.replace("%APPROVE%","Disapproved");

var html = ""+
            "Attached is the Price Change request

"+
            "Approve
"+
            "Disapprove
"+
         "";

if (approvalNeeded == "Yes") {           //send email with Approve and Disapprove option to Approver
    MailApp.sendEmail(approverEmail, "TEST ONLY: Price Maintenance Form for your approval", body4Requester, {
                htmlBody: html,
                attachments : [blob]
                });

    MailApp.sendEmail(requesterEmail, "TEST ONLY: Your Price Maintenance request has been submitted", body4Requester, {
                attachments : [blob]
                });

} else {                                 //send straight to Finance
    MailApp.sendEmail(financeEmail, "TEST ONLY: Price Maintenance Form for processing. No approval neeed", body4Finance, {
                cc:requesterEmail,
                attachments : [blob]
                });
}}

Not sure if it's relevant -- I deployed this as a web app with the setting "Execute the app as User accessing the web app".

Many thanks in advance for any advice.


来源: stackexchange

问:
How to confirm SPA's identity with your proxy server securely?
I have a React app that needs to communicate with several AWS services, each requiring secret keys and I know that I should not hard-code them into the JS.

I found this:
How do I hide API key in create-react-app?

Which basically confirms the following:
* Do not store true secrets in your JS
* Do not use env files either, because they are added to the JS at compile time.
* Use server-side code to deal with secret server-to-server communications, i.e. use a proxy

But my question is now one of clarity on this or "next step". My proxy server now handles all of the private communications with AWS. However, how do I confirm my app's identity to the server? In other words, if open the proxy up, anyone will have access to my AWS content. However, my actual users are not authorized to access my external services directly, so I can't just pass through those credentials.

My idea is to set up an application ID that will redirect only to the associated URL, but is that secure enough?  The appID is in the JS, but the ID will only allow the proxy to send information back to the URL on record.

Thank you,
Wayne

答:
I think your best bet would be to use AWS Cognito.

Users will auth with it, get back a token which can have IAM access rights attached to it if that is what you desire

ContentLicense: CC BY-SA 4.0


问:
How to sort entries in row of a tibble in dplyr?
As an example:

```<code>     V1    V2    V3     X
1     1     5     4    "asa"
2     5     2     3    "sdsf"
</code>```

should become

```<code>     V1    V2    V3     X
1     1     4     5    "asa"
2     2     3     5    "sdsf"
</code>```

Looking for short and fast solutions. It takes quite a while with a for loop and base R commands for a dataframe with ~150,000 rows.

答:
You could pivot it, arrange the rows by size, and then pivot it back again.</p>

```<code>library(dplyr)
library(tidyr)

df %>%
  mutate(row_id = row_number()) %>%
  pivot_longer(V1:V3) %>%
  arrange(row_id, value) %>%
  group_by(row_id) %>%
  mutate(name = paste0("V", row_number())) %>%
  ungroup() %>%
  pivot_wider(id_cols = X:row_id, names_from = name, values_from = value) %>%
  select(-row_id)
</code>```

Body:
As an example:

     V1    V2    V3     X
1     1     5     4    "asa"
2     5     2     3    "sdsf"

should become

     V1    V2    V3     X
1     1     4     5    "asa"
2     2     3     5    "sdsf"

Looking for short and fast solutions. It takes quite a while with a for loop and base R commands for a dataframe with ~150,000 rows.

Body:
You could pivot it, arrange the rows by size, and then pivot it back again.

library(dplyr)
library(tidyr)

df %>%
  mutate(row_id = row_number()) %>%
  pivot_longer(V1:V3) %>%
  arrange(row_id, value) %>%
  group_by(row_id) %>%
  mutate(name = paste0("V", row_number())) %>%
  ungroup() %>%
  pivot_wider(id_cols = X:row_id, names_from = name, values_from = value) %>%
  select(-row_id)


问:
Passing JS array as a List<> to Spring MVC controller
I'm developing the front end to my webapp using ReactJs. Here, I make an API POST passing in a array of objects.

The objects are created in an event handler, as follows:

```<code>eventHandler(id1, id2, e) {
    let payload = this.state.payload;
    let changedItem= {
        changeTo: e,
        id1: id1,
        id2: id2
    };

    let res = [];
    payload.forEach(item=> {
        if (item.id1 !== id1
            || item.id2 !== id2) {
            res.push(control);
        }
    });
    res.push(changedItem);

    this.setState({
        payload: res
    });
}
</code>```

I have verified this works by printing the array after this. Next, I make a POST call, passing in the array:

```<code>onClick() {

    let changedControls = (this.state.payload);

    updateControls(changedControls).then(() => {
        this.setState({
            payload: []
        });
    }).catch((error) => {
         console.log(error);
    })
}
</code>```

The API call is defined in a separate file, as:

```<code>export const updateControls = (changedControls) => {
let uri = '/api/update-controls';
return new Promise((resolve, reject) => {
    axios.post(uri, changedControls).then(response => {
        if (response != null) {
            resolve(response.data)
        }
    }).catch(err => {
        console.log(err.response.data);
    })
})
</code>```

};

Ideally, the next step would have been my Java controller being called, defined as:

```<code>@RequestMapping(value = "/update-controls", method = RequestMethod.POST)
public void updateControls(@RequestParam(value = "updatedControls") List<ControlsUpdate> updatedControls) throws Exception {
    initServiceClientRest();
    String user = getUserId();

    ResponseEntity responseEntity = serviceClientRest.update(updatedControls, user);

    if (responseEntity != null) {
        if (responseEntity.getStatusCode() != HttpStatus.OK) {
            throwErrorMessages(responseEntity);
        }
    }
}
</code>```

I believe this is where the error lies. I get a 400 error, saying: Required List parameter 'updatedControls' is not present'.

Any suggestions?

EDIT: Sorry about the typo in the API POST call! But that wasn't the issue, just a typo I made while copying in the code

EDIT2:

Error:

```<code>feign.FeignException$InternalServerError: status 500 reading serviceClientRest#updateAccessControls(List,String)
at feign.FeignException.errorStatus(FeignException.java:114) ~[feign-core-10.2.3.jar:na]
at feign.FeignException.errorStatus(FeignException.java:86) ~[feign-core-10.2.3.jar:na]
at feign.codec.ErrorDecoder$Default.decode(ErrorDecoder.java:93) ~[feign-core-10.2.3.jar:na]
at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:149) ~[feign-core-10.2.3.jar:na]
at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:78) ~[feign-core-10.2.3.jar:na]
at feign.ReflectiveFeign$FeignInvocationHandler.invoke(ReflectiveFeign.java:103) ~[feign-core-10.2.3.jar:na]
at com.sun.proxy.$Proxy155.updateAccessControls(Unknown Source) ~[na:na]
at ScoringConfigController.updateControls(ScoringConfigController.java:135) ~[main/:na]
</code>```

答:
You're sending your array as a request body right? You have to use @RequestBody instead of @RequestParam

```<code>public void updateControls(@RequestBody List<ControlsUpdate> updatedControls) throws Exception {...}
</code>```

@RequestParam is used for URL query strings

Body:
I'm developing the front end to my webapp using ReactJs. Here, I make an API POST passing in a array of objects.

The objects are created in an event handler, as follows:

eventHandler(id1, id2, e) {
    let payload = this.state.payload;
    let changedItem= {
        changeTo: e,
        id1: id1,
        id2: id2
    };

    let res = [];
    payload.forEach(item=> {
        if (item.id1 !== id1
            || item.id2 !== id2) {
            res.push(control);
        }
    });
    res.push(changedItem);

    this.setState({
        payload: res
    });
}

I have verified this works by printing the array after this. Next, I make a POST call, passing in the array:

onClick() {

    let changedControls = (this.state.payload);

    updateControls(changedControls).then(() => {
        this.setState({
            payload: []
        });
    }).catch((error) => {
         console.log(error);
    })
}

The API call is defined in a separate file, as:

export const updateControls = (changedControls) => {
let uri = '/api/update-controls';
return new Promise((resolve, reject) => {
    axios.post(uri, changedControls).then(response => {
        if (response != null) {
            resolve(response.data)
        }
    }).catch(err => {
        console.log(err.response.data);
    })
})

};

Ideally, the next step would have been my Java controller being called, defined as:

@RequestMapping(value = "/update-controls", method = RequestMethod.POST)
public void updateControls(@RequestParam(value = "updatedControls") List<ControlsUpdate> updatedControls) throws Exception {
    initServiceClientRest();
    String user = getUserId();

    ResponseEntity responseEntity = serviceClientRest.update(updatedControls, user);

    if (responseEntity != null) {
        if (responseEntity.getStatusCode() != HttpStatus.OK) {
            throwErrorMessages(responseEntity);
        }
    }
}

I believe this is where the error lies. I get a 400 error, saying: Required List parameter 'updatedControls' is not present'.

Any suggestions?

EDIT: Sorry about the typo in the API POST call! But that wasn't the issue, just a typo I made while copying in the code

EDIT2:

Error:

feign.FeignException$InternalServerError: status 500 reading serviceClientRest#updateAccessControls(List,String)
at feign.FeignException.errorStatus(FeignException.java:114) ~[feign-core-10.2.3.jar:na]
at feign.FeignException.errorStatus(FeignException.java:86) ~[feign-core-10.2.3.jar:na]
at feign.codec.ErrorDecoder$Default.decode(ErrorDecoder.java:93) ~[feign-core-10.2.3.jar:na]
at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:149) ~[feign-core-10.2.3.jar:na]
at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:78) ~[feign-core-10.2.3.jar:na]
at feign.ReflectiveFeign$FeignInvocationHandler.invoke(ReflectiveFeign.java:103) ~[feign-core-10.2.3.jar:na]
at com.sun.proxy.$Proxy155.updateAccessControls(Unknown Source) ~[na:na]
at ScoringConfigController.updateControls(ScoringConfigController.java:135) ~[main/:na]

Body:
You're sending your array as a request body right? You have to use @RequestBody instead of @RequestParam

public void updateControls(@RequestBody List<ControlsUpdate> updatedControls) throws Exception {...}

@RequestParam is used for URL query strings


问:
How to insert a matrix into another matrix
I'm trying to create a function to insert a matrix in an another(square matrix), for example:</p>

```<code>A = [(1,2,3),(4,5,6),(7,8,9)]
B = [(2,4),(6,8)]

C = funcmatrix(A,B)

result: [1 2 3 0 0
         4 5 6 0 0
         7 8 9 0 0
         0 0 0 2 4
         0 0 0 6 8]
</code>```

答:
An another approach using numpy I found:

```<code>A = np.array([[1,2,3],[4,5,6],[7,8,9]])
B = np.array([[2,4],[6,8]])
</code>```

```<code>bshape = B.shape
ashape = A.shape

a=np.append(A,np.zeros((bshape[0],ashape[0])),axis=0)
b=np.append(np.zeros((ashape[0],bshape[0])),B,axis=0)
</code>```

Now append them together:

```<code>np.append(a,b,axis=-1)
</code>```

I hope this will work on your case

Body:
I'm trying to create a function to insert a matrix in an another(square matrix), for example:

A = [(1,2,3),(4,5,6),(7,8,9)]
B = [(2,4),(6,8)]

C = funcmatrix(A,B)

result: [1 2 3 0 0
         4 5 6 0 0
         7 8 9 0 0
         0 0 0 2 4
         0 0 0 6 8]

Body:
An another approach using numpy I found:

A = np.array([[1,2,3],[4,5,6],[7,8,9]])
B = np.array([[2,4],[6,8]])

bshape = B.shape
ashape = A.shape

a=np.append(A,np.zeros((bshape[0],ashape[0])),axis=0)
b=np.append(np.zeros((ashape[0],bshape[0])),B,axis=0)

Now append them together:

np.append(a,b,axis=-1)

I hope this will work on your case


问:
Creating a circular menu with CSS
I'm trying to create a circular menu in CSS for a school project.

This is what the menu would look like:

I am not looking for the complete source just an idea how you experienced developers would do it.

I was thinking to create 8 triangles and then the middle to place a circlular div with position absolute; but the triangles, since they're created with borders, when you hover them they are not absolutely selectable. It's kinda buggy.

Is it even possible to create this with no images?

EDIT:

The menu will after by animated using jQuery; thus I will be using jQuery and jQuery UI but no other library and no images (i dont need the icons anyway).
As for compatibility, should work on IE9+ / Chrome / Opera 11.52+ / Firefox 4+.

答:
HTML Code

```<code><a class='button ctrl' href='#' tabindex='1'>★</a>
<ul class='tip ctrl'>
    <li class='slice'><div>✦</div></li>
    <li class='slice'><div>✿</div></li>
    <li class='slice'><div>✵</div></li>
    <li class='slice'><div>✪</div></li>
    <li class='slice'><div>☀</div></li>
</ul>
</code>```

CSS Code

```<code>    .ctrl {
        position: absolute;
        top: 75%; left: 50%;
        font: 1.5em/1.13 Verdana, sans-serif;
        transition: .5s;
    }

    a.ctrl, .ctrl div {
        display: block;
        opacity: .56;
        background: #c9c9c9;
        color: #7a8092;
        text-align: center;
        text-decoration: none;
        text-shadow: 0 -1px dimgrey;
      cursor: pointer;
    }

    .button {
        z-index: 2;
        margin: -.625em;
        width: 1.25em; height: 1.25em;
        border-radius: 50%;
        box-shadow: 0 0 3px 1px white;
    }

    .tip {
        z-index: 1;
        /**outline: dotted 1px white;/**/
        margin: -5em;
        width: 10em; height: 10em;
        transform: scale(.001);
        list-style: none;
        opacity: 0;
    }

.slice {
    overflow: hidden;
    position: absolute;
    /**outline: dotted 1px yellow;/**/
    width: 50%; height: 50%;
    transform-origin: 100% 100%;
}
</code>```

Full code : CSSCodeLab

ContentLicense: CC BY-SA 3.0

Title: Creating a circular menu with CSS

Body:
HTML Code

<a class='button ctrl' href='#' tabindex='1'>★</a>
<ul class='tip ctrl'>
    <li class='slice'><div>✦</div></li>
    <li class='slice'><div>✿</div></li>
    <li class='slice'><div>✵</div></li>
    <li class='slice'><div>✪</div></li>
    <li class='slice'><div>☀</div></li>
</ul>

CSS Code

    .ctrl {
        position: absolute;
        top: 75%; left: 50%;
        font: 1.5em/1.13 Verdana, sans-serif;
        transition: .5s;
    }

    a.ctrl, .ctrl div {
        display: block;
        opacity: .56;
        background: #c9c9c9;
        color: #7a8092;
        text-align: center;
        text-decoration: none;
        text-shadow: 0 -1px dimgrey;
      cursor: pointer;
    }

    .button {
        z-index: 2;
        margin: -.625em;
        width: 1.25em; height: 1.25em;
        border-radius: 50%;
        box-shadow: 0 0 3px 1px white;
    }

    .tip {
        z-index: 1;
        /**outline: dotted 1px white;/**/
        margin: -5em;
        width: 10em; height: 10em;
        transform: scale(.001);
        list-style: none;
        opacity: 0;
    }

.slice {
    overflow: hidden;
    position: absolute;
    /**outline: dotted 1px yellow;/**/
    width: 50%; height: 50%;
    transform-origin: 100% 100%;
}

Full code : CSSCodeLab


问:
403 redirect doesn't work
How to force apache to redirect to a 403 error?

I've tried:

```<code>RewriteRule ^forbid/(.*)$ / [R=403,L]
</code>```

this caused 500 server error on the whole site

```<code>RewriteRule ^forbid/(.*)$ - [R=403,L]
</code>```

and

```<code>RewriteRule ^forbid/(.*)$ [R=403,L]
</code>```

these simply don't work

I have the following .htaccess file:

```<code>RewriteEngine on
RewriteRule ^(config|backup)(.*)$ - [F] [NC]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^admin/(.*)$ /admin/index.php?%{QUERY_STRING} [L,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !util
RewriteRule ^(.*)$ index.php?%{QUERY_STRING} [L,QSA]
</code>```

Please, help me!

答:
Try this instead:

```<code>RewriteRule ^forbid/(.*)$ - [F]
</code>```

Source: http://httpd.apache.org/docs/current/rewrite/flags.html#flag_f

Title: 403 redirect doesn't work

Body:
How to force apache to redirect to a 403 error?

I've tried:

RewriteRule ^forbid/(.*)$ / [R=403,L]

this caused 500 server error on the whole site

RewriteRule ^forbid/(.*)$ - [R=403,L]

and

RewriteRule ^forbid/(.*)$ [R=403,L]

these simply don't work

I have the following .htaccess file:

RewriteEngine on
RewriteRule ^(config|backup)(.*)$ - [F] [NC]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^admin/(.*)$ /admin/index.php?%{QUERY_STRING} [L,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !util
RewriteRule ^(.*)$ index.php?%{QUERY_STRING} [L,QSA]

Please, help me!

Body:
Try this instead:

RewriteRule ^forbid/(.*)$ - [F]

Source: http://httpd.apache.org/docs/current/rewrite/flags.html#flag_f


问:
How do I change columns in the same order as in my order matrix, per row
I have a matrix where I stored the order of items of a questionnaire, where the first column contains the name of the item that is first shown, the second column has the second shown item, etc. Each row in this matrix represents a new questionnaire, with the same items but with the order randomized in a different order.

```<code>> order.matrix
     [,1]    [,2]    [,3]
[1,] "Anger" "Happy" "Sad"
[2,] "Happy" "Sad"   "Anger"
[3,] "Sad"   "Anger" "Happy"
</code>```

I have stored the responses on the items in a dataframe:

```<code>> df.responses
  Anger Happy Sad
1     1     2   3
2     3     2   0
3     9     2   1
</code>```

Now, I want to change the order of the responses in df.responses, such that they are analogue to the order of items in the order.matrix, for each row. (As a result, the column names of df.responses shouldn't be in the resulting df anymore.)
The result in this example should look like this:

```<code>> df.result
  V1 V2 V3
1  1  2  3
2  2  0  3
3  1  9  2
</code>```

How can/should I do this?

EDIT, due to comment: I want to replace the item names in order.matrix by its corresponding value in df.responses

答:
Using base R you could loop over the matrix rows and assign the values from your df.responses by selecting the column order by the matrix row values:</p>

```<code># copy df.responses so we won't grow an object in the loop
df.result <- df.responses
# Rename the columns as they won't be correct after
colnames(df.result) <- c("V1","V2","V3")

for (x in 1:nrow(order.matrix)) {
  # replace the line with the value ordered by the matrix line names
  df.result[x,] <- df.responses[x,order.matrix[x,]]
}
</code>```

Body:
I have a matrix where I stored the order of items of a questionnaire, where the first column contains the name of the item that is first shown, the second column has the second shown item, etc. Each row in this matrix represents a new questionnaire, with the same items but with the order randomized in a different order.

> order.matrix
     [,1]    [,2]    [,3]
[1,] "Anger" "Happy" "Sad"
[2,] "Happy" "Sad"   "Anger"
[3,] "Sad"   "Anger" "Happy"

I have stored the responses on the items in a dataframe:

> df.responses
  Anger Happy Sad
1     1     2   3
2     3     2   0
3     9     2   1

Now, I want to change the order of the responses in df.responses, such that they are analogue to the order of items in the order.matrix, for each row. (As a result, the column names of df.responses shouldn't be in the resulting df anymore.)
The result in this example should look like this:

> df.result
  V1 V2 V3
1  1  2  3
2  2  0  3
3  1  9  2

How can/should I do this?

EDIT, due to comment: I want to replace the item names in order.matrix by its corresponding value in df.responses

Body:
Using base R you could loop over the matrix rows and assign the values from your df.responses by selecting the column order by the matrix row values:

# copy df.responses so we won't grow an object in the loop
df.result <- df.responses
# Rename the columns as they won't be correct after
colnames(df.result) <- c("V1","V2","V3")

for (x in 1:nrow(order.matrix)) {
  # replace the line with the value ordered by the matrix line names
  df.result[x,] <- df.responses[x,order.matrix[x,]]
}


问:
Python sqlite3 update deletes my row instead of updating the value
I am trying to update a value x based on a specified row ID y in python using sqlite3. However, the issue I have is that instead of updating the value in the specified column, the script deletes the entire row/entry from the database.

Here is the function

def closeIssue(self, issue_id, resolver_discord_id):
        # This function closes an open issue and assigns the resolver's ID
        self.c.execute("SELECT * FROM issues WHERE issue_id={}".format(issue_id))
        result = self.c.fetchone()
        if not result:
            print("No such record")
        else:
            self.c.execute("UPDATE issues SET issue_status = 'CLOSED' where issue_id = ?", (issue_id))
            self.conn.commit()

        self.__closeDatabase(False)
```

<p>Just for further context, here are below some other parts of the module.</p>

<p>The database maker (and structure):</p>

<pre class="lang-py prettyprint-override"><code>def __buildDatabase(self):
        conn = sqlite3.connect(self.issue_db)
        c = conn.cursor()
        c.execute("""CREATE TABLE issues (
                        issue_id integer,
                        issue_type text,
                        issue_type_verbose text,
                        author_discord integer,
                        issue_content text,
                        issue_status text,
                        issue_creation_timestamp text,
                        issue_closed_timestamp text,
                        resolver_staff_discord integer
                        )""")
        conn.commit()
        print("Database created")
</code>```

What a typical entry looks like:

```<code>[{'issue_id': 1, 'issue_type': 'reports', 'issue_type_verbose': 'Report', 'author_discord': 124123123, 'issue_content': 'report one', 'issue_status': 'OPEN', 'issue_creation_timestamp': '14:29:33 - 20/02/2020', 'issue_closed_timestamp': 'NONE', 'resolver_staff_discord': 'NONE'}, {'issue_id': 2, 'issue_type': 'reports', 'issue_type_verbose': 'Report', 'author_discord': 41312, 'issue_content': 'report two', 'issue_status': 'OPEN', 'issue_creation_timestamp': '14:29:42 - 20/02/2020', 'issue_closed_timestamp': 'NONE', 'resolver_staff_discord': 'NONE'}]
</code>```

I hope you can help me with this, thank you in advance! I've been hitting my head on this issue for the last few hours and cannot seem to find a solution anywhere I look.

答:
I fixed it. I am stupid. Apologies in advance and I guess I deserve it for the last three hours. Turns out the issue was in the way I displayed my test output... it was filtered out for only open cases.
Jesus.
Alright so confirmed this code works as intended.</p>

Body:
I am trying to update a value x based on a specified row ID y in python using sqlite3. However, the issue I have is that instead of updating the value in the specified column, the script deletes the entire row/entry from the database.

Here is the function

def closeIssue(self, issue_id, resolver_discord_id):
        # This function closes an open issue and assigns the resolver's ID
        self.c.execute("SELECT * FROM issues WHERE issue_id={}".format(issue_id))
        result = self.c.fetchone()
        if not result:
            print("No such record")
        else:
            self.c.execute("UPDATE issues SET issue_status = 'CLOSED' where issue_id = ?", (issue_id))
            self.conn.commit()

        self.__closeDatabase(False)

Just for further context, here are below some other parts of the module.

The database maker (and structure):

def __buildDatabase(self):
        conn = sqlite3.connect(self.issue_db)
        c = conn.cursor()
        c.execute("""CREATE TABLE issues (
                        issue_id integer,
                        issue_type text,
                        issue_type_verbose text,
                        author_discord integer,
                        issue_content text,
                        issue_status text,
                        issue_creation_timestamp text,
                        issue_closed_timestamp text,
                        resolver_staff_discord integer
                        )""")
        conn.commit()
        print("Database created")

What a typical entry looks like:

[{'issue_id': 1, 'issue_type': 'reports', 'issue_type_verbose': 'Report', 'author_discord': 124123123, 'issue_content': 'report one', 'issue_status': 'OPEN', 'issue_creation_timestamp': '14:29:33 - 20/02/2020', 'issue_closed_timestamp': 'NONE', 'resolver_staff_discord': 'NONE'}, {'issue_id': 2, 'issue_type': 'reports', 'issue_type_verbose': 'Report', 'author_discord': 41312, 'issue_content': 'report two', 'issue_status': 'OPEN', 'issue_creation_timestamp': '14:29:42 - 20/02/2020', 'issue_closed_timestamp': 'NONE', 'resolver_staff_discord': 'NONE'}]

I hope you can help me with this, thank you in advance! I've been hitting my head on this issue for the last few hours and cannot seem to find a solution anywhere I look.


问:
How does the compiler know where to resume control after an await call
REST calls are basically stateless calls. Then when we make an await call to a third party api, where does the compiler or control stores information about the place from where it needs to process once the await call is completed.</p>

答:
where does the compiler or control stores information about the place from where it needs to process once the await call is completed.

The async keyword does two things: it allows the use of the await keyword and it instructs the compiler to break up the async method into a state machine. The gory details are here, but in summary:

The method is "split" at each use of await, with each "piece" of the method being a different part of the state machine. Then the current state of the state machine is saved (along with the values of local variables). When the awaited task completes, the continuation for that task executes the next step of the state machine.


问:
'coroutine' object has no attribute get || pyppeteer
In python, using pyppeteer, I am opening a webpage and running a JS script in its console and trying to capture the result in a variable but I am getting the following error.

```<code>Traceback (most recent call last):
  File "/home/ndaruto/anaconda3/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/naruto/anaconda3/lib/python3.7/site-packages/django/utils/deprecation.py", line 96, in __call__
    response = self.process_response(request, response)
  File "/home/naruto/anaconda3/lib/python3.7/site-packages/django/middleware/clickjacking.py", line 26, in process_response
    if response.get('X-Frame-Options') is not None:
AttributeError: 'coroutine' object has no attribute 'get'
/home/naruto/anaconda3/lib/python3.7/pathlib.py:704: RuntimeWarning: coroutine 'hmm' was never awaited

return self._str
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
</code>```

Below is the python code :-

```<code>async def hmm(request):
browser = await launch()
page = await browser.newPage()
await page.goto('http://jobs.chegg.com')
ans = await page.evaluate('''() => {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'https://cdnjs.cloudflare.com/ajax/libs/axe-core/3.1.2/axe.min.js';
    document.head.appendChild(script);
    setTimeout(function(){
    axe.run(document, {
        runOnly: {
        type: "tag",
        values: ["wcag2a", "wcag2aa", "best-practice"]
        },
        "rules": {
        "skip-link": { enabled: false }
        }
    }, function(err, results) {
        if (err) throw err;
        console.log(results);
    });
    }, 1000);
}''')
print("ANS IS", ans)
return 1
</code>```

Can someone please suggest how to fix this?

答:
AttributeError: 'coroutine' object has no attribute 'get'
/home/naruto/anaconda3/lib/python3.7/pathlib.py:704: RuntimeWarning: coroutine 'hmm' was never awaited

this means that you call
hmm(request).get()

instead

r = await hmm(request)
r.get()

somewhere in you code around this function

Body:
In python, using pyppeteer, I am opening a webpage and running a JS script in its console and trying to capture the result in a variable but I am getting the following error.

Traceback (most recent call last):
  File "/home/ndaruto/anaconda3/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/naruto/anaconda3/lib/python3.7/site-packages/django/utils/deprecation.py", line 96, in __call__
    response = self.process_response(request, response)
  File "/home/naruto/anaconda3/lib/python3.7/site-packages/django/middleware/clickjacking.py", line 26, in process_response
    if response.get('X-Frame-Options') is not None:
AttributeError: 'coroutine' object has no attribute 'get'
/home/naruto/anaconda3/lib/python3.7/pathlib.py:704: RuntimeWarning: coroutine 'hmm' was never awaited

return self._str
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

Below is the python code :-

async def hmm(request):
browser = await launch()
page = await browser.newPage()
await page.goto('http://jobs.chegg.com')
ans = await page.evaluate('''() => {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'https://cdnjs.cloudflare.com/ajax/libs/axe-core/3.1.2/axe.min.js';
    document.head.appendChild(script);
    setTimeout(function(){
    axe.run(document, {
        runOnly: {
        type: "tag",
        values: ["wcag2a", "wcag2aa", "best-practice"]
        },
        "rules": {
        "skip-link": { enabled: false }
        }
    }, function(err, results) {
        if (err) throw err;
        console.log(results);
    });
    }, 1000);
}''')
print("ANS IS", ans)
return 1

Can someone please suggest how to fix this?


问:
How to make code wait for okay/cancel button selection?
I am using JQuery's $.dialog(), where I open a dialog with OK and Cancel buttons.

I would have expected that when the dialog opens, the code stops, and would first continue, when the user had selected OK or Cancel.

Here is my complete source code
http://pastebin.com/uw7bvtn7

The section where I have the problem is at line 127-151.

```<code>$("#dialog:ui-dialog").dialog("destroy");

$("#dialog-confirm").dialog({
    resizable: false,
    height: 600,
    modal: true,
    open: function() {
    $(this).children('div.dialog-text').replaceWith("<h3><b>Users</b></h3>" + makeDialogTable(users) + "<h3><b>Owners</b></h3>" + makeDialogTable(owners));
    },

    buttons: {
    "Okay": function() {
        $(this).dialog("close");
    },

    Cancel: function() {
        is_okay = 0;
        $(this).dialog("close");
    }
    } // buttons

}); // dialog

alert(is_okay);
</code>```

What the code does right now is to first show the dialog and then the alert(is_okay) on top.

What I would like is that the code first continues when the user have pressed OK or Cancel.

How could that be done?

答:
The code does execute sequentially. The job of $("#dialog-confirm").dialog() is to popup a dialog box. alert(is_okay) won't execute until the lines above it have been executed. But Okay and Cancel are event listeners.

```<code>"Okay": function() {
    $(this).dialog("close");
}
</code>```

The code above assigns event listeners to events. That's all it does, it does not execute those functions, it just assigns those functions to event calls.

I would recommend doing some reading on events and event listeners. If you plan on using JQuery seriously, it will save you a lot of confusion.

Body:
I am using JQuery's $.dialog(), where I open a dialog with OK and Cancel buttons.

I would have expected that when the dialog opens, the code stops, and would first continue, when the user had selected OK or Cancel.

Here is my complete source code
http://pastebin.com/uw7bvtn7

The section where I have the problem is at line 127-151.

$("#dialog:ui-dialog").dialog("destroy");

$("#dialog-confirm").dialog({
    resizable: false,
    height: 600,
    modal: true,
    open: function() {
    $(this).children('div.dialog-text').replaceWith("
Users
" + makeDialogTable(users) + "
Owners
" + makeDialogTable(owners));
    },

    buttons: {
    "Okay": function() {
        $(this).dialog("close");
    },

    Cancel: function() {
        is_okay = 0;
        $(this).dialog("close");
    }
    } // buttons

}); // dialog

alert(is_okay);

What the code does right now is to first show the dialog and then the alert(is_okay) on top.

What I would like is that the code first continues when the user have pressed OK or Cancel.

How could that be done?

Body:
The code does execute sequentially. The job of $("#dialog-confirm").dialog() is to popup a dialog box. alert(is_okay) won't execute until the lines above it have been executed. But Okay and Cancel are event listeners.

"Okay": function() {
    $(this).dialog("close");
}

The code above assigns event listeners to events. That's all it does, it does not execute those functions, it just assigns those functions to event calls.

I would recommend doing some reading on events and event listeners. If you plan on using JQuery seriously, it will save you a lot of confusion.


问:
JavaScript: How do you use Array.prototype.filter() on arrays that contain objects
I was arranging a file tree and I only wanted to show file/folder name that don't have "." at the start of their names. But I always get the same array after I filter it. What do I do?

So here what have I tried:

```<code>const arr = [
  {
    name: ".hidden",
    size: "14"
  },
  {
    name: "View",
    size: "12"
  },
  {
    name: ".secret",
    size: "12"
  },
  {
    name: "Public",
    size: "11"
  }
];
arr.filter(obj => {
  // charCode of "." is 46
  if(obj.name.charCodeOf(0) !== 46) {
    return true
  }
  else {
    return false
  }
});
console.log(arr);
</code>```

Expexted Console:

```<code>[
  {
    name: "View",
    size: "12"
  },
  {
    name: "Public",
    size: "11"
  }
]
</code>```

Reality:

```<code>[
  {
    name: ".hidden",
    size: "14"
  },
  {
    name: "View",
    size: "12"
  },
  {
    name: ".secret",
    size: "12"
  },
  {
    name: "Public",
    size: "11"
  }
]
</code>```

答:
This may be an ideal solution for your issue:</p>

```<code>const arr = [
  {
    name: ".hidden",
    size: "14"
  },
  {
    name: "View",
    size: "12"
  },
  {
    name: ".secret",
    size: "12"
  },
  {
    name: "Public",
    size: "11"
  }
];

const result = arr.filter(obj => !obj.name.startsWith("."));

console.log(result);
</code>```

Body:
I was arranging a file tree and I only wanted to show file/folder name that don't have "." at the start of their names. But I always get the same array after I filter it. What do I do?

So here what have I tried:

const arr = [
  {
    name: ".hidden",
    size: "14"
  },
  {
    name: "View",
    size: "12"
  },
  {
    name: ".secret",
    size: "12"
  },
  {
    name: "Public",
    size: "11"
  }
];
arr.filter(obj => {
  // charCode of "." is 46
  if(obj.name.charCodeOf(0) !== 46) {
    return true
  }
  else {
    return false
  }
});
console.log(arr);

Expexted Console:

[
  {
    name: "View",
    size: "12"
  },
  {
    name: "Public",
    size: "11"
  }
]

Reality:

[
  {
    name: ".hidden",
    size: "14"
  },
  {
    name: "View",
    size: "12"
  },
  {
    name: ".secret",
    size: "12"
  },
  {
    name: "Public",
    size: "11"
  }
]

Body:
This may be an ideal solution for your issue:

const arr = [
  {
    name: ".hidden",
    size: "14"
  },
  {
    name: "View",
    size: "12"
  },
  {
    name: ".secret",
    size: "12"
  },
  {
    name: "Public",
    size: "11"
  }
];

const result = arr.filter(obj => !obj.name.startsWith("."));

console.log(result);


问:
CMake path with special symbols
I'm using CLion and whenever I'm working on a project, it can't be in path with special symbols (such as º, ç, ã...), failing with the following message:

```<code>The C compiler

    "C:/Program Files (x86)/mingw-w64/i686-8.1.0-posix-dwarf-rt_v6-rev0/mingw32/bin/gcc.exe"

  is not able to compile a simple test program.
</code>```

答:
MinGW's make program does not handle non-ASCII characters smoothly. I was able to reproduce this on my machine using a path containing ñ:

```<code>  The C compiler

    "C:/apps/MinGW/bin/gcc.exe"

  is not able to compile a simple test program.

  It fails with the following output:

    Change Dir: C:/workspace/peña/build2/CMakeFiles/CMakeTmp

    Run Build Command(s):C:/apps/MinGW/bin/mingw32-make.exe cmTC_fe654/fast && C:/apps/MinGW/bin/mingw32-make.exe -f CMakeFiles\cmTC_fe654.dir\build.make CMakeFiles/cmTC_fe654.dir/build
    mingw32-make.exe[1]: Entering directory 'C:/workspace/pe±a/build2/CMakeFiles/CMakeTmp'
    Building C object CMakeFiles/cmTC_fe654.dir/testCCompiler.c.obj
    C:\apps\MinGW\bin\gcc.exe    -o CMakeFiles\cmTC_fe654.dir\testCCompiler.c.obj   -c C:\workspace\pe├▒a\build2\CMakeFiles\CMakeTmp\testCCompiler.c
    gcc.exe: error: C:\workspace\pe├▒a\build2\CMakeFiles\CMakeTmp\testCCompiler.c: No such file or directory
    gcc.exe: fatal error: no input files
    compilation terminated.
    CMakeFiles\cmTC_fe654.dir\build.make:81: recipe for target 'CMakeFiles/cmTC_fe654.dir/testCCompiler.c.obj' failed
    mingw32-make.exe[1]: *** [CMakeFiles/cmTC_fe654.dir/testCCompiler.c.obj] Error 1
    mingw32-make.exe[1]: Leaving directory 'C:/workspace/pe±a/build2/CMakeFiles/CMakeTmp'
    Makefile:137: recipe for target 'cmTC_fe654/fast' failed
    mingw32-make.exe: *** [cmTC_fe654/fast] Error 2
</code>```

Note, CMake switches to the temporary build directory with the correct path, but when mingw32-make.exe is executing, the path is now garbled:

```<code>C:/workspace/pe±a/build2/CMakeFiles/CMakeTmp
</code>```

The easiest way to avoid this issue is to simply change your project path to be one that does not contain non-ASCII characters.

Another option would be to use a different generator (something other than MinGW Makefiles). For example, Visual Studio configures and builds correctly, even though the non-ASCII characters are in the project path:

```<code>> cmake -G"Visual Studio 16 2019" ..
Re-run cmake no build system arguments
C:/workspace/peña
-- The CXX compiler identification is MSVC 19.23.28106.4
-- Check for working CXX compiler: C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/VC/Tools/MSVC/14.23.28105/bin/Hostx64/x64/cl.exe
-- Check for working CXX compiler: C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/VC/Tools/MSVC/14.23.28105/bin/Hostx64/x64/cl.exe - works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: C:/workspace/peña/build
</code>```

Title: CMake path with special symbols

Body:
I'm using CLion and whenever I'm working on a project, it can't be in path with special symbols (such as º, ç, ã...), failing with the following message:

The C compiler

    "C:/Program Files (x86)/mingw-w64/i686-8.1.0-posix-dwarf-rt_v6-rev0/mingw32/bin/gcc.exe"

  is not able to compile a simple test program.

Body:
MinGW's make program does not handle non-ASCII characters smoothly. I was able to reproduce this on my machine using a path containing ñ:

  The C compiler

    "C:/apps/MinGW/bin/gcc.exe"

  is not able to compile a simple test program.

  It fails with the following output:

    Change Dir: C:/workspace/peña/build2/CMakeFiles/CMakeTmp

    Run Build Command(s):C:/apps/MinGW/bin/mingw32-make.exe cmTC_fe654/fast && C:/apps/MinGW/bin/mingw32-make.exe -f CMakeFiles\cmTC_fe654.dir\build.make CMakeFiles/cmTC_fe654.dir/build
    mingw32-make.exe[1]: Entering directory 'C:/workspace/pe±a/build2/CMakeFiles/CMakeTmp'
    Building C object CMakeFiles/cmTC_fe654.dir/testCCompiler.c.obj
    C:\apps\MinGW\bin\gcc.exe    -o CMakeFiles\cmTC_fe654.dir\testCCompiler.c.obj   -c C:\workspace\pe├▒a\build2\CMakeFiles\CMakeTmp\testCCompiler.c
    gcc.exe: error: C:\workspace\pe├▒a\build2\CMakeFiles\CMakeTmp\testCCompiler.c: No such file or directory
    gcc.exe: fatal error: no input files
    compilation terminated.
    CMakeFiles\cmTC_fe654.dir\build.make:81: recipe for target 'CMakeFiles/cmTC_fe654.dir/testCCompiler.c.obj' failed
    mingw32-make.exe[1]: *** [CMakeFiles/cmTC_fe654.dir/testCCompiler.c.obj] Error 1
    mingw32-make.exe[1]: Leaving directory 'C:/workspace/pe±a/build2/CMakeFiles/CMakeTmp'
    Makefile:137: recipe for target 'cmTC_fe654/fast' failed
    mingw32-make.exe: *** [cmTC_fe654/fast] Error 2

Note, CMake switches to the temporary build directory with the correct path, but when mingw32-make.exe is executing, the path is now garbled:

C:/workspace/pe±a/build2/CMakeFiles/CMakeTmp

The easiest way to avoid this issue is to simply change your project path to be one that does not contain non-ASCII characters.

Another option would be to use a different generator (something other than MinGW Makefiles). For example, Visual Studio configures and builds correctly, even though the non-ASCII characters are in the project path:

> cmake -G"Visual Studio 16 2019" ..
Re-run cmake no build system arguments
C:/workspace/peña
-- The CXX compiler identification is MSVC 19.23.28106.4
-- Check for working CXX compiler: C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/VC/Tools/MSVC/14.23.28105/bin/Hostx64/x64/cl.exe
-- Check for working CXX compiler: C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/VC/Tools/MSVC/14.23.28105/bin/Hostx64/x64/cl.exe - works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: C:/workspace/peña/build


问:
Python loop through tuple list adding a value from pandas data frame
I am trying to loop through a list of tuples adding a value to the end of each one that corresponds to a value in a column in a pandas data frame.

```<code>df1 = [(1,2),(4,5),(8,9)]

df2 = pd.DataFrame({'Alpha': [2, 4, 8],
                    'Beta': ["a","b","c"]})

df3 = []

for i in df1:
    print(i)

for i,j in df2["Beta"], df1:
    j = j + (i,)
    df3.append(j)

print(df3)
</code>```

I would expect print(df3) to display the following:

```<code>[(1, 2, 'a'), (4, 5, 'b'), (8, 9, 'c')]
</code>```

However, I get an error stating too many values to unpack.

答:
Use zip, list comprehension solution:

```<code>df3 = [j + (i,) for i,j in zip(df2["Beta"], df1)]
</code>```

Your solution should be changed:

```<code>for i,j in zip(df2["Beta"], df1):
    j = j + (i,)
    df3.append(j)
</code>```

```<code>print(df3)
[(1, 2, 'a'), (4, 5, 'b'), (8, 9, 'c')]
</code>```

Body:
I am trying to loop through a list of tuples adding a value to the end of each one that corresponds to a value in a column in a pandas data frame.

df1 = [(1,2),(4,5),(8,9)]

df2 = pd.DataFrame({'Alpha': [2, 4, 8],
                    'Beta': ["a","b","c"]})

df3 = []

for i in df1:
    print(i)

for i,j in df2["Beta"], df1:
    j = j + (i,)
    df3.append(j)

print(df3)

I would expect print(df3) to display the following:

[(1, 2, 'a'), (4, 5, 'b'), (8, 9, 'c')]

However, I get an error stating too many values to unpack.

Body:
Use zip, list comprehension solution:

df3 = [j + (i,) for i,j in zip(df2["Beta"], df1)]

Your solution should be changed:

for i,j in zip(df2["Beta"], df1):
    j = j + (i,)
    df3.append(j)

print(df3)
[(1, 2, 'a'), (4, 5, 'b'), (8, 9, 'c')]


问:
Laravel: Display data using drop down list
I am implementing a drop down menu list to display a list of hotels from my system. I currently have the following code which when i click submit, nothing is happening (no data displayed).

Does anyone know how i can potentially display data once i press submit. I do believe i need code in my controller.

SEARCH.BLADE.PHP

```<code><form action="/search" method="POST" role="search">
   <div class="form-group">
    <select name="country" id="country" class="form-control input-lg dynamic" data-dependent="state">
 @foreach($posts as $post)
  <option value="{{$post->distance}}">{{$post->distance}} </option>
 @endforeach

   <br/>
   <div class="form-group">
    <select name="state" id="state" class="form-control input-lg dynamic" data-dependent="city">
    </select>
   </div>
   <br />
   <div class="form-group">
    <select name="city" id="city" class="form-control input-lg">
    @foreach($posts as $post)
  <option value="{{$post->title}}">{{$post->title}} </option>
 @endforeach
</div>
    </select>
   </div>
  </div>
  {{Form::Submit('submit', ['class' => 'btn btn-primary'])}}
 </body>
</code>```

SearchController.php

```<code>class SearchController extends Controller {
   public function index()
   {
     $posts = Post::all();
     return view('Pages.search')->with('posts', $posts);
   }
</code>```

I do not have much is the search controller but i do believe i need some code in there to display the data.

答:
```<code> use App\Post;

public function index()
        {
            $posts = Post::latest()->get();
            return view('search',compact('posts'));
        }
@foreach($posts as $post)
  <option value="{{$post->id}}">{{$post->title}} </option>
 @endforeach
</code>```

Body:
I am implementing a drop down menu list to display a list of hotels from my system. I currently have the following code which when i click submit, nothing is happening (no data displayed).

Does anyone know how i can potentially display data once i press submit. I do believe i need code in my controller.

SEARCH.BLADE.PHP

<form action="/search" method="POST" role="search">

    <select name="country" id="country" class="form-control input-lg dynamic" data-dependent="state">
 @foreach($posts as $post)
  <option value="{{$post->distance}}">{{$post->distance}} </option>
 @endforeach

    <select name="state" id="state" class="form-control input-lg dynamic" data-dependent="city">
    </select>

    <select name="city" id="city" class="form-control input-lg">
    @foreach($posts as $post)
  <option value="{{$post->title}}">{{$post->title}} </option>
 @endforeach

    </select>

  {{Form::Submit('submit', ['class' => 'btn btn-primary'])}}

SearchController.php

class SearchController extends Controller {
   public function index()
   {
     $posts = Post::all();
     return view('Pages.search')->with('posts', $posts);
   }

I do not have much is the search controller but i do believe i need some code in there to display the data.


问:
Python code for REST calls with cookiejar file
I use following curl commands to fetch data using cookiejar file:

```<code>$ curl -sk -X 'POST' -d "username=name@domain.com&password=mypassword" -c app.cookie-jar -k https://website.com/auth/authenticate
$ curl -sk -X 'GET' -H 'Accept: text/csv' -b app.cookie-jar https://website.com/api/systems > out.csv
</code>```

Can someone help with python script that can help in achieving the same

答:
Using Requests, set up a session to keep track of the cookie:</p>

```<code>import requests

with requests.Session() as s:
    resp = s.post('https://website.com/auth/authenticate', data='username=name@domain.com&password=mypassword')
    resp.raise_for_status()
    resp = s.get('https://website.com/api/systems', headers={'Accept': 'text/csv'})
    resp.raise_for_status()
    with open('out.csv', 'wb') as outf:
        outf.write(resp.content)
</code>```

Body:
I use following curl commands to fetch data using cookiejar file:

$ curl -sk -X 'POST' -d "username=name@domain.com&password=mypassword" -c app.cookie-jar -k https://website.com/auth/authenticate
$ curl -sk -X 'GET' -H 'Accept: text/csv' -b app.cookie-jar https://website.com/api/systems > out.csv

Can someone help with python script that can help in achieving the same

Body:
Using Requests, set up a session to keep track of the cookie:

import requests

with requests.Session() as s:
    resp = s.post('https://website.com/auth/authenticate', data='username=name@domain.com&password=mypassword')
    resp.raise_for_status()
    resp = s.get('https://website.com/api/systems', headers={'Accept': 'text/csv'})
    resp.raise_for_status()
    with open('out.csv', 'wb') as outf:
        outf.write(resp.content)


问:
Troubleshooting the network connection on a Windows 10 PC in LAN
I have a small LAN and one of the PCs (Windows 10) started to behave weird after a Windows update.

Here it how it behaves:

This PC can be seen on the network. If I ping it from other computers, it works.

The shared folders on this PC can be accessed by other computers correctly.

But programs on this PC that must respond to requests made by programs installed on other devices with access this PC in either ethernet or wifi by [IP:Port#] , now don't work anymore.
These programs used to work properly before and I think the change in behavior happened after a Windows update.

An example of such program is "Winpopup LAN Messenger"
( https://www.softpedia.com/get/Internet/Chat/LAN-Messaging-Clients/Winpopup-LAN-Messenger.shtml )

I checked the network advanced sharing settings and it's set like before (Turn on network discovery, Turn on file and printer sharing).

I disabled the firewall / windows defender.

With netstat -an command in cmd prompt I can see that those programs are listening to the UDP ports that they are supposed to listen to, however they don't respond to incoming requests from other machines.

I am really puzzled about this weird new behavior.

Any hints would be really appreciated.

答:
I could figure it out.  All the problems came from the firewall settings.

In Windows Defender Firewall > Allow an app or feature > check both 'Private' and 'Public' for all instances of WinPopup LAN Messenger > click OK
Also, the port used is 1152 and protocol UDP. This port must be opened (also in firewall).


问:
Static function leading to more static functions
I have a class that has a few functions that are useful on their own, which are static. Now these functions depend on other functions that are not useful on their own (but don't interact with class member variables) but are also static, so they are private. Now I have a class with many non-static functions, and couple of static public functions and a few static private functions.

Is this good practice? (should I be making this a community wiki?)

答:
I think you should declare those functions as free functions. If they do not need the members it should be not a big deal.

Maybe you should read this article. I found it very useful to improve my class designs.


问:
Typescript Union Types: Dealing with Interfaces
What's the proper way to handle a situation where you have two interfaces that are similar enough that you want to run them through the same piece of logic:

```<code>interface DescriptionItem {
    Description: string;
    Code: string;
}
interface NamedItem {
    Name: string;
    Code: string;
}

function MyLogic(i: DescriptionItem | NamedItem) {
    var desc = (<DescriptionItem>i).Description || (<NamedItem>i).Name;

    return i.Code + ' - ' + desc;
}
</code>```

This works; however, my question is on improving the var desc = ... line.  Is what I have above the best option?  Or is there a better way to handle this situation in Typescript?

答:
I know this question is very old, but I was playing around with the same problem, as I was learning the difference between | and & when making Type Unions.

there are some options to solve this problem (that is also linter-friendly).
The best way is to use a discriminator in all your interfaces (a narrow interface).

```<code>//First create a super-interface that have the discriminator
interface B
{
    kind:'b1'|'b2' //define discriminator with all the posible values as string-literals (this is where the magic is)
}

interface B1 extends B
{
    kind: 'b1' //now narrow the inherited interfaces literals down to a single
    //after that add your interface specific fields
    data1: string;
    data: string;
}

interface B2 extends B
{
    kind:'b2' //now narrow the inherited interfaces literals down to a single
    //after that add your interface specific fields
    data2: string;
    data: string;
}

//lets initialize 1 B1 type by using the literal value of a B1 interface 'b1'
var b1: B1|B2 = {
    kind:'b1',
    data: 'Hello From Data',
    data1:'Hello From Data1'
    //typescript will not allow you to set data2 as this present a B1 interface
}
//and a B2 Type with the kind 'b2'
var b2: B1|B2 = {
    kind: 'b2',
    data: 'Hello From Data',
    //typescript will not allow you to set data1 as this present a B2 interface
    data2: 'Hello From Data2'
}
</code>```

another option is to check for fields on an object using the "in"-keyword, but this can cause a lot of boilerplate code, as you have to update it every time you change your interface.

```<code>interface B1
{
    data1: string;
    data: string;
}

interface B2
{
    data2: string;
    data: string;
}

var b3: B1|B2 = {
    data: 'Hello From Data',
    data1:'Hello From Data1',
    data2:'Hello From Data2'
}

console.log(b3.data); //this field is common in both interfaces and does not need a check

if('data1' in b3) //check if 'data1' is on object
{
    console.log(b3.data1);
}
if('data2' in b3){
    console.log(b3.data2); //check if 'data2' is on object
}
</code>```

Body:
What's the proper way to handle a situation where you have two interfaces that are similar enough that you want to run them through the same piece of logic:

interface DescriptionItem {
    Description: string;
    Code: string;
}
interface NamedItem {
    Name: string;
    Code: string;
}

function MyLogic(i: DescriptionItem | NamedItem) {
    var desc = (<DescriptionItem>i).Description || (<NamedItem>i).Name;

    return i.Code + ' - ' + desc;
}

This works; however, my question is on improving the var desc = ... line.  Is what I have above the best option?  Or is there a better way to handle this situation in Typescript?

Body:
I know this question is very old, but I was playing around with the same problem, as I was learning the difference between | and & when making Type Unions.

there are some options to solve this problem (that is also linter-friendly).
The best way is to use a discriminator in all your interfaces (a narrow interface).

//First create a super-interface that have the discriminator
interface B
{
    kind:'b1'|'b2' //define discriminator with all the posible values as string-literals (this is where the magic is)
}

interface B1 extends B
{
    kind: 'b1' //now narrow the inherited interfaces literals down to a single
    //after that add your interface specific fields
    data1: string;
    data: string;
}

interface B2 extends B
{
    kind:'b2' //now narrow the inherited interfaces literals down to a single
    //after that add your interface specific fields
    data2: string;
    data: string;
}

//lets initialize 1 B1 type by using the literal value of a B1 interface 'b1'
var b1: B1|B2 = {
    kind:'b1',
    data: 'Hello From Data',
    data1:'Hello From Data1'
    //typescript will not allow you to set data2 as this present a B1 interface
}
//and a B2 Type with the kind 'b2'
var b2: B1|B2 = {
    kind: 'b2',
    data: 'Hello From Data',
    //typescript will not allow you to set data1 as this present a B2 interface
    data2: 'Hello From Data2'
}

another option is to check for fields on an object using the "in"-keyword, but this can cause a lot of boilerplate code, as you have to update it every time you change your interface.

interface B1
{
    data1: string;
    data: string;
}

interface B2
{
    data2: string;
    data: string;
}

var b3: B1|B2 = {
    data: 'Hello From Data',
    data1:'Hello From Data1',
    data2:'Hello From Data2'
}

console.log(b3.data); //this field is common in both interfaces and does not need a check

if('data1' in b3) //check if 'data1' is on object
{
    console.log(b3.data1);
}
if('data2' in b3){
    console.log(b3.data2); //check if 'data2' is on object
}


问:
Fastest way to replace NAs in a large data.table
I have a large data.table, with many missing values scattered throughout its ~200k rows and 200 columns.  I would like to re code those NA values to zeros as efficiently as possible.

I see two options:

1: Convert to a data.frame, and use something like this

2: Some kind of cool data.table sub setting command

I'll be happy with a fairly efficient solution of type 1. Converting to a data.frame and then back to a data.table won't take too long.

答:
To generalize to many columns you could use this approach (using previous sample data but adding a column):

```<code>z = data.table(x = sample(c(NA_integer_, 1), 2e7, TRUE), y = sample(c(NA_integer_, 1), 2e7, TRUE))

z[, names(z) := lapply(.SD, function(x) fifelse(is.na(x), 0, x))]
</code>```

Didn't test for the speed though

Body:
To generalize to many columns you could use this approach (using previous sample data but adding a column):

z = data.table(x = sample(c(NA_integer_, 1), 2e7, TRUE), y = sample(c(NA_integer_, 1), 2e7, TRUE))

z[, names(z) := lapply(.SD, function(x) fifelse(is.na(x), 0, x))]

Didn't test for the speed though


问:
Setting up a graph with 3 variables
```<code>w         = -1.25
pqxf      <- function(y){(1)*(y)} # replace 1 with py and assign a value to py
pqyf      <- function(x){(w * 16)-(w * x)} #
utilityf  <- function(x, y, w) { pqyf(x) * pqxf(y)* w} # the utility       function C,l
hours     <- c(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,20)

#functions are turned into data frames`

pqy     <- data.frame("consumption" =
                    pqyf(c(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,20)))`
pqx     <- data.frame("leisure"=
                           pqxf(c(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,20)))
utility <- data.frame("utility"     =
                    utilityf(c(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,20)))
</code>```

When I try to run this I get an error:

```<code>Error in pqxf(y) : argument "y" is missing, with no default`
</code>```

How do define y ?

答:
Your question is about defining and calling functions in R.

You define the function utilityf to take three arguments x,y,w.
These variables are then used inside the function to invoke other functions.
Since you don't define default values in the declaration of utilityf you need to pass values to the function. How would pqxf you call in utilityf know what y is?

You declare w in your script. However, utilityf does not know that you want it to use w=-1.25.

Try the following:

```<code>w = -1.25
x = c(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,20)
y = c(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,20)

pqxf      <- function(y){(1)*(y)}
pqyf      <- function(x){(w * 16)-(w * x)}
utilityf  <- function(x, y, w) { pqyf(x) * pqxf(y)* w}

utility <- data.frame("utility" = utilityf(x,y,w)
</code>```

or alternatively:

```<code>w = -1.25
x = c(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,20)
y = c(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,20)

pqxf      <- function(y){(1)*(y)}
pqyf      <- function(x){(w * 16)-(w * x)}
utilityf  <- function(x, y) { pqyf(x) * pqxf(y)* w}

utility <- data.frame("utility" = utilityf(x,y)
</code>```

In the last case, the function utilityf takes the 'global' value of w.
In both cases w stays constant since you don't change the value anywhere.

Just a small addition:

You can set default values for your function like

```<code>my_f <- function(w=-1.25) {w*10}
</code>```

Calling the function with and without passing a value for w:

```<code>> my_f()
  [1] -12.5
</code>```

And with a value for w (pi in this case):

```<code>> my_f(pi)
  [1] 31.41593
</code>```

Title: Setting up a graph with 3 variables

Body:
w         = -1.25
pqxf      <- function(y){(1)*(y)} # replace 1 with py and assign a value to py
pqyf      <- function(x){(w * 16)-(w * x)} #
utilityf  <- function(x, y, w) { pqyf(x) * pqxf(y)* w} # the utility       function C,l
hours     <- c(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,20)

#functions are turned into data frames`

pqy     <- data.frame("consumption" =
                    pqyf(c(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,20)))`
pqx     <- data.frame("leisure"=
                           pqxf(c(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,20)))
utility <- data.frame("utility"     =
                    utilityf(c(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,20)))

When I try to run this I get an error:

Error in pqxf(y) : argument "y" is missing, with no default`

How do define y ?

Body:
Your question is about defining and calling functions in R.

You define the function utilityf to take three arguments x,y,w.
These variables are then used inside the function to invoke other functions.
Since you don't define default values in the declaration of utilityf you need to pass values to the function. How would pqxf you call in utilityf know what y is?

You declare w in your script. However, utilityf does not know that you want it to use w=-1.25.

Try the following:

w = -1.25
x = c(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,20)
y = c(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,20)

pqxf      <- function(y){(1)*(y)}
pqyf      <- function(x){(w * 16)-(w * x)}
utilityf  <- function(x, y, w) { pqyf(x) * pqxf(y)* w}

utility <- data.frame("utility" = utilityf(x,y,w)

or alternatively:

w = -1.25
x = c(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,20)
y = c(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,20)

pqxf      <- function(y){(1)*(y)}
pqyf      <- function(x){(w * 16)-(w * x)}
utilityf  <- function(x, y) { pqyf(x) * pqxf(y)* w}

utility <- data.frame("utility" = utilityf(x,y)

In the last case, the function utilityf takes the 'global' value of w.
In both cases w stays constant since you don't change the value anywhere.

Just a small addition:

You can set default values for your function like

my_f <- function(w=-1.25) {w*10}

Calling the function with and without passing a value for w:

> my_f()
  [1] -12.5

And with a value for w (pi in this case):

> my_f(pi)
  [1] 31.41593


问:
ASP.NET Core download from a Network Share (sometimes works?)
I have a pretty standard ASP.NET Core 2.2 web app.
I'm running into an issue with downloading files that are stored on a Network Share. We are using a method of impersonation in code (client requirements) to access the file share. Uploading to the share with the provided credentials works fine, so we know that (a) the impersonation is working and (b) the files ARE at the destination. The issue I am having comes from Downloading the file. It's a pretty standard download link that points to an action in a controller that gets the file information from the database and uses two of the database values (PathToFile and Filename) to get the location of the file and pull it back to the controller, followed by returning a file:

```<code>        var fileRecord = //Get the record from the database.

        byte[] bytes = null;
        if(fileRecord != null)
        {
            try
            {
                string fullPath = $"{fileRecord.PathToFile}\\{fileRecord.Filename}";

                await ImpersonationHelper.Impersonate(async () => { bytes = await System.IO.File.ReadAllBytesAsync(fullPath); }, _settings);

            }
            catch (Exception e)
            {
                return NotFound();
            }
        }

        return File(bytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileRecord.Filename);
</code>```

For reference:

```<code>    public static async Task Impersonate(Action actionToExecute, ApplicationSettings settings)
    {
        IntPtr tokenHandle = new IntPtr(0);

        SafeAccessTokenHandle safeAccessTokenHandle = null;

        ImpersonateLogin login = new ImpersonateLogin(settings);

        Task<bool> returnValue = Task.Run(() => LogonUser(login.username, login.domain, login.password, 2, 0, out safeAccessTokenHandle));

        if (false == returnValue.Result)
        {
            int ret = Marshal.GetLastWin32Error();
            throw new System.ComponentModel.Win32Exception(ret);
        }

        if(safeAccessTokenHandle != null)
        await returnValue.ContinueWith(antecedent => WindowsIdentity.RunImpersonated(safeAccessTokenHandle, () =>
        {
            actionToExecute();
        }));
    }
}
</code>```

Locally, it works fine (we skip the impersonation with an appsetting) and the file comes back and set up as a download in the browser.

On the server, however, it doesn't work, but it also does work. It's strange: Clicking on the link will lead to an error page:

but refreshing this error page (ie. re-requesting that file) over and over again will make it work (usually every 2-4 refreshes will return the file correctly).

Has anyone encountered this, or something like this that can offer some insight?

答:
As it turns out, it (seemingly?) had something to do with the method(s) being async.
Once I removed the (forced) async call to the impersonation, and all async calls right to the "Download" action, it all lined up and works 100% of the time now. From what I could find online, it looks like it was a "timing" issue with async/sync calls. The impersonation would happen AFTER the download file, so the user wouldn't have permission to actually fetch the file to download, but in some cases, the impersonation would happen first, so the file would come back. Making everything "non-async" fixed the issues I was having.</p>

Body:
I have a pretty standard ASP.NET Core 2.2 web app.
I'm running into an issue with downloading files that are stored on a Network Share. We are using a method of impersonation in code (client requirements) to access the file share. Uploading to the share with the provided credentials works fine, so we know that (a) the impersonation is working and (b) the files ARE at the destination. The issue I am having comes from Downloading the file. It's a pretty standard download link that points to an action in a controller that gets the file information from the database and uses two of the database values (PathToFile and Filename) to get the location of the file and pull it back to the controller, followed by returning a file:

        var fileRecord = //Get the record from the database.

        byte[] bytes = null;
        if(fileRecord != null)
        {
            try
            {
                string fullPath = $"{fileRecord.PathToFile}\\{fileRecord.Filename}";

                await ImpersonationHelper.Impersonate(async () => { bytes = await System.IO.File.ReadAllBytesAsync(fullPath); }, _settings);

            }
            catch (Exception e)
            {
                return NotFound();
            }
        }

        return File(bytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileRecord.Filename);

For reference:

    public static async Task Impersonate(Action actionToExecute, ApplicationSettings settings)
    {
        IntPtr tokenHandle = new IntPtr(0);

        SafeAccessTokenHandle safeAccessTokenHandle = null;

        ImpersonateLogin login = new ImpersonateLogin(settings);

        Task<bool> returnValue = Task.Run(() => LogonUser(login.username, login.domain, login.password, 2, 0, out safeAccessTokenHandle));

        if (false == returnValue.Result)
        {
            int ret = Marshal.GetLastWin32Error();
            throw new System.ComponentModel.Win32Exception(ret);
        }

        if(safeAccessTokenHandle != null)
        await returnValue.ContinueWith(antecedent => WindowsIdentity.RunImpersonated(safeAccessTokenHandle, () =>
        {
            actionToExecute();
        }));
    }
}

Locally, it works fine (we skip the impersonation with an appsetting) and the file comes back and set up as a download in the browser.

On the server, however, it doesn't work, but it also does work. It's strange: Clicking on the link will lead to an error page:

but refreshing this error page (ie. re-requesting that file) over and over again will make it work (usually every 2-4 refreshes will return the file correctly).

Has anyone encountered this, or something like this that can offer some insight?


问:
Using unique_ptr in a pair
My code:

```<code>template <typename T>//, T value_if_empty>
class AtomicQueue {
    std::mutex m;
    std::queue<T> q;
    T value_if_empty;

public:
    AtomicQueue(const T& emptyval) : value_if_empty(std::move(emptyval)) {};
    void push(const T& t)
    {
        m.lock();
        q.push(std::move(t));
        m.unlock();
    }
    T pop()
    {
        T a = std::move(value_if_empty);
        m.lock();
        if (!q.empty())
        {
            a = std::move(q.front());
            q.pop();
        }
        m.unlock();
        return a;
    }
};

AtomicQueue<int> A(0);
AtomicQueue<std::unique_ptr<Class1>> B(nullptr);
AtomicQueue < std::pair<int, std::unique_ptr<Class1>>> C({ 0,nullptr });
</code>```

This code compiles if I declare just A and B but fails when C is also declared. The error is 'std::pair<int,std::unique_ptr<Class1,std::default_delete<Class1>>>::pair(const std::pair<int,std::unique_ptr<Class1,std::default_delete<Class1>>> &)': attempting to reference a deleted function

The problem seems to be that std::pair<int, std::unique_ptr<Class1>> does not have a copy constructor. But the same is true for std::unique_ptr<Class1>. So why does the declaration for B compile but C does not? Also, where exactly is the copy constructor being used?
Sorry if the answer is trivial. I am new to using unique_ptr and move constructors.

Side Question: Is there a cleaner or better way to use value_if_empty? I do not want anything other than nullptr being passed when unique_ptr is being used.

Edit: B does not compile either. (as mentioned in a comment by NathanOliver). So, the question now is how do I remove this error?

答:
In

```<code>AtomicQueue(const T& emptyval) : value_if_empty(std::move(emptyval)) {}
</code>```

std::move(emptyval) is not moving as emptyval is const.

You would need overloads:

```<code>AtomicQueue(const T& emptyval) : value_if_empty(emptyval) {}
AtomicQueue(T&& emptyval) : value_if_empty(std::move(emptyval)) {}
</code>```

or change to:

```<code>AtomicQueue(T emptyval) : value_if_empty(std::move(emptyval)) {}
</code>```

Note: Same applies to push.

Title: Using unique_ptr in a pair

Body:
My code:

template <typename T>//, T value_if_empty>
class AtomicQueue {
    std::mutex m;
    std::queue<T> q;
    T value_if_empty;

public:
    AtomicQueue(const T& emptyval) : value_if_empty(std::move(emptyval)) {};
    void push(const T& t)
    {
        m.lock();
        q.push(std::move(t));
        m.unlock();
    }
    T pop()
    {
        T a = std::move(value_if_empty);
        m.lock();
        if (!q.empty())
        {
            a = std::move(q.front());
            q.pop();
        }
        m.unlock();
        return a;
    }
};

AtomicQueue<int> A(0);
AtomicQueue<std::unique_ptr<Class1>> B(nullptr);
AtomicQueue < std::pair<int, std::unique_ptr<Class1>>> C({ 0,nullptr });

This code compiles if I declare just A and B but fails when C is also declared. The error is 'std::pair<int,std::unique_ptr<Class1,std::default_delete<Class1>>>::pair(const std::pair<int,std::unique_ptr<Class1,std::default_delete<Class1>>> &)': attempting to reference a deleted function

The problem seems to be that std::pair<int, std::unique_ptr<Class1>> does not have a copy constructor. But the same is true for std::unique_ptr<Class1>. So why does the declaration for B compile but C does not? Also, where exactly is the copy constructor being used?
Sorry if the answer is trivial. I am new to using unique_ptr and move constructors.

Side Question: Is there a cleaner or better way to use value_if_empty? I do not want anything other than nullptr being passed when unique_ptr is being used.

Edit: B does not compile either. (as mentioned in a comment by NathanOliver). So, the question now is how do I remove this error?

Body:
In

AtomicQueue(const T& emptyval) : value_if_empty(std::move(emptyval)) {}

std::move(emptyval) is not moving as emptyval is const.

You would need overloads:

AtomicQueue(const T& emptyval) : value_if_empty(emptyval) {}
AtomicQueue(T&& emptyval) : value_if_empty(std::move(emptyval)) {}

or change to:

AtomicQueue(T emptyval) : value_if_empty(std::move(emptyval)) {}

Note: Same applies to push.


问:
Memory error when repairing malformed xml
I have some malformed XML that is very large--it lacks a top-level tag and there are duplicate attributes. To get around this, I tested the following solution on a subset of my malformed XML and it works perfectly to add a tag and automatically drop duplicate attributes using BeautifulSoup.

```<code>import sys
from bs4 import BeautifulSoup
import xml.etree.ElementTree as ET

flow_file = sys.stdin.read()

try:
    tree = ET.fromstring(flow_file)
    sys.stdout.write(flow_file)
except:
    flow_file = f"<dispatch>{flow_file}</dispatch>"
    soup = BeautifulSoup(flow_file, 'xml')
    sys.stdout.write(soup)
</code>```

However, since my real file is so large it throws a memory error. Since I need (AFAICT) the full XML to add top-level tags and drop duplicates, I'm not quite sure how to modify my code to handle such large XML. I saw some suggestions for using lxml and iterating, but I'm not clear on how it fits into my needs/processes.

ETA: not sure if helpful, but the whole point of this is to clean up the file so that it can run through NiFi's SplitXML processor.

答:
Since I don't really know, what you do with the data, here is the approach I took on a several GB big xml file:

```<code>import xml.etree.ElementTree as etree

root = False
#iterparse file, get event tags start and end
for event, elem in etree.iterparse("my_big.xml", events=('start', 'end')):
#set first element as rootelement, so we can clear it later
    if event == "start" and root == "False":
        root = elem
#Here we look for a certain end tag
    if event == "end" and elem.tag == "TAGOFINTEREST":
#set found False, so we can break, as soon, as we found our DataOfInterest
        found = False
#iterate through children and iterate over child nodes
#HERE I guess you would work with pandas
        for stuff in elem.getchildren():
#if found == True stop iterating or whatever condition you have
            if found:
                break
             #look for what you need, set found to True and break the
             found = True
#clear elem, in order to save RAM
        elem.clear()

#Might require revision clears RAM after every "end" event
    if event == "end":
        root.clear()
</code>```

I hope this helps.

Body:
I have some malformed XML that is very large--it lacks a top-level tag and there are duplicate attributes. To get around this, I tested the following solution on a subset of my malformed XML and it works perfectly to add a tag and automatically drop duplicate attributes using BeautifulSoup.

import sys
from bs4 import BeautifulSoup
import xml.etree.ElementTree as ET

flow_file = sys.stdin.read()

try:
    tree = ET.fromstring(flow_file)
    sys.stdout.write(flow_file)
except:
    flow_file = f"<dispatch>{flow_file}</dispatch>"
    soup = BeautifulSoup(flow_file, 'xml')
    sys.stdout.write(soup)

However, since my real file is so large it throws a memory error. Since I need (AFAICT) the full XML to add top-level tags and drop duplicates, I'm not quite sure how to modify my code to handle such large XML. I saw some suggestions for using lxml and iterating, but I'm not clear on how it fits into my needs/processes.

ETA: not sure if helpful, but the whole point of this is to clean up the file so that it can run through NiFi's SplitXML processor.

Body:
Since I don't really know, what you do with the data, here is the approach I took on a several GB big xml file:

import xml.etree.ElementTree as etree

root = False
#iterparse file, get event tags start and end
for event, elem in etree.iterparse("my_big.xml", events=('start', 'end')):
#set first element as rootelement, so we can clear it later
    if event == "start" and root == "False":
        root = elem
#Here we look for a certain end tag
    if event == "end" and elem.tag == "TAGOFINTEREST":
#set found False, so we can break, as soon, as we found our DataOfInterest
        found = False
#iterate through children and iterate over child nodes
#HERE I guess you would work with pandas
        for stuff in elem.getchildren():
#if found == True stop iterating or whatever condition you have
            if found:
                break
             #look for what you need, set found to True and break the
             found = True
#clear elem, in order to save RAM
        elem.clear()

#Might require revision clears RAM after every "end" event
    if event == "end":
        root.clear()

I hope this helps.


问:
Master-Detail page with JSP
Hi
I need to create a Master-detail page with JSP, to add ,edit and delete details without form submission and I wondered if you could give some suggestions on how to achieve this (maybe a plugin).

Thanks in advance

答: ... you may want to look at one of the JavaScript frameworks to help you with that unless you want get your hands dirty and want to roll the functionality from scratch. I'm biased toward jQuery for those things. </p>

ContentLicense: CC BY-SA 2.5

Title: Master-Detail page with JSP


问:
Why does 11010100 << 1 equal 110101000, not 10101000?
Why when I try to shift bits for 110101002, the result is 1101010002, not 101010002.

```<code>int a = Integer.parseInt("11010100", 2) << 1;
</code>```

I try to do this:

```<code>int a = (byte)(Integer.parseInt("11010100", 2) << 1);
</code>```

But if the output value is greater than 128, everything goes into minus, which is logical.
How can I make that number of bits does not change?

答:
If you want to set to 0 all bits higher than the bottom 8 bits, you can use bit-wise AND:

```<code>int a = (Integer.parseInt("11010100", 2) << 1) & 0xff;
System.out.println (Integer.toString(a,2));
</code>```

Output:

```<code>10101000
</code>```

Body:
Why when I try to shift bits for 110101002, the result is 1101010002, not 101010002.

int a = Integer.parseInt("11010100", 2) << 1;

I try to do this:

int a = (byte)(Integer.parseInt("11010100", 2) << 1);

But if the output value is greater than 128, everything goes into minus, which is logical.
How can I make that number of bits does not change?

Body:
If you want to set to 0 all bits higher than the bottom 8 bits, you can use bit-wise AND:

int a = (Integer.parseInt("11010100", 2) << 1) & 0xff;
System.out.println (Integer.toString(a,2));

Output:

10101000