问:
WebView Back, Refresh, Forward? Simply doesn't work!
I have tried everything to get my 'forward' and 'back' to work.

Refresh is working [I figured it out by changing the method to read 'webView.reload();' instead of 'webView.refresh();'

Can anyone assist with the forward and back? I have tried 'forward', 'canGoForward' and 'goForward' as well as 'back', 'canGoBack' and 'goBack'. There are no error codes however none of those methods actually do anything.

```<code>public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu); // Add menu items, second value is the id, use this in the onCreateOptionsMenu
    menu.add(0, 1, 0, "Back");
    menu.add(0, 2, 0, "Refresh");
    menu.add(0, 3, 0, "Forward");
    return true; // End of menu configuration
}
public boolean onOptionsItemSelected(MenuItem item){ // Called when you tap a menu item
    switch (item.getItemId()){
        case 1: //If the ID equals 1, go back
            webView.goBack();
        return true;
        case 2 : //If the ID equals 2, refresh
            webView.reload();
        return true;
        case 3: //If the ID equals 3, go forward
            webView.goForward();
        return true;
        }
    return false;
    }
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) { // Enables browsing to previous pages with the hardware back button
    if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) { // Check if the key event was the BACK key and if there's history
        webView.goBack();
        return true;
    }   // If it wasn't the BACK key or there's no web page history, bubble up to the default
        // system behavior (probably exit the activity)
    return super.onKeyDown(keyCode, event);
}
</code>```

}

答:
The code you shared doesn't include the portion where you are creating webview and navigating between urls. So I am just taking a guess at what might be happening.

It seems that webview is an instance field of your class whose portion you have shown in the question.  Could it be that webView is being recreated every time you navigate to a new page? That is, the code is something like:

```<code>webview = new WebView(this);
webview.loadUrl("http://slashdot.org/");
</code>```

If this is what is being done, all you need is to create the 'webView' once and just call loadUrl everytime you need to navigate to new url. This way the webview instance will be able to retain the history.

Body:
I have tried everything to get my 'forward' and 'back' to work.

Refresh is working [I figured it out by changing the method to read 'webView.reload();' instead of 'webView.refresh();'

Can anyone assist with the forward and back? I have tried 'forward', 'canGoForward' and 'goForward' as well as 'back', 'canGoBack' and 'goBack'. There are no error codes however none of those methods actually do anything.

public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu); // Add menu items, second value is the id, use this in the onCreateOptionsMenu
    menu.add(0, 1, 0, "Back");
    menu.add(0, 2, 0, "Refresh");
    menu.add(0, 3, 0, "Forward");
    return true; // End of menu configuration
}
public boolean onOptionsItemSelected(MenuItem item){ // Called when you tap a menu item
    switch (item.getItemId()){
        case 1: //If the ID equals 1, go back
            webView.goBack();
        return true;
        case 2 : //If the ID equals 2, refresh
            webView.reload();
        return true;
        case 3: //If the ID equals 3, go forward
            webView.goForward();
        return true;
        }
    return false;
    }
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) { // Enables browsing to previous pages with the hardware back button
    if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) { // Check if the key event was the BACK key and if there's history
        webView.goBack();
        return true;
    }   // If it wasn't the BACK key or there's no web page history, bubble up to the default
        // system behavior (probably exit the activity)
    return super.onKeyDown(keyCode, event);
}

}

Body:
The code you shared doesn't include the portion where you are creating webview and navigating between urls. So I am just taking a guess at what might be happening.

It seems that webview is an instance field of your class whose portion you have shown in the question.  Could it be that webView is being recreated every time you navigate to a new page? That is, the code is something like:

webview = new WebView(this);
webview.loadUrl("http://slashdot.org/");

If this is what is being done, all you need is to create the 'webView' once and just call loadUrl everytime you need to navigate to new url. This way the webview instance will be able to retain the history.


来源: stackexchange

问:
Create a Google Sheet then publishing it via Google Apps Script
Using Google Apps Script, I know how to create a new sheet:

```<code>var newSheet = SpreadsheetApp.create("newSheet");
</code>```

And I know how to publish this sheet by hand from the created sheet:

File ==> Publish to the web.

But how can I publish and get the URL for the published sheet I created without the point/click method above? I would like a piece of code that resembles:

```<code>var newSheet = SpreadsheetApp.create("newSheet");
var pubSheet = newSheet.publish();
var pubURL   = pubSheet.getURL();
</code>```

答:
Building off of Pierre's input to answer Preston's question about how to get the url of the newly published webpage:

The url will follow this format 'https://docs.google.com/spreadsheets/d/'+fileId+'/pubhtml. Thanks to @tanaike for this insight.

Here is how I took the code provided by Pierre and used it to publish the active sheet and then paste the published url in a free cell in another sheet.

function getFirstEmptyRow() {
  var spr = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Zapier");
  var column = spr.getRange('A:A');
  var values = column.getValues(); // get all data in one call
  var ct = 0;
  while ( values[ct][0] != "" ) {
    ct++;
  }
  //Browser.msgBox(ct);
  return (ct+1);
}

function publishToWeb(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var fileId = ss.getId();
  var revisions = Drive.Revisions.list(fileId);
  var items = revisions.items;
  var revisionId =items[items.length-1].id;
  var resource = Drive.Revisions.get(fileId, revisionId);
  resource.published = true;
  resource.publishAuto = true;
  resource.publishedOutsideDomain = true;
  Drive.Revisions.update(resource, fileId, revisionId);

  var row = getFirstEmptyRow();
  var zapier = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Zapier");

  var url = zapier.getRange(row, 2);

  url.setValue('https://docs.google.com/spreadsheets/d/'+fileId+'/pubhtml');

}```

ContentLicense: CC BY-SA 3.0

Body:
Using Google Apps Script, I know how to create a new sheet:

var newSheet = SpreadsheetApp.create("newSheet");

And I know how to publish this sheet by hand from the created sheet:

File ==> Publish to the web.

But how can I publish and get the URL for the published sheet I created without the point/click method above? I would like a piece of code that resembles:

var newSheet = SpreadsheetApp.create("newSheet");
var pubSheet = newSheet.publish();
var pubURL   = pubSheet.getURL();

ContentLicense: CC BY-SA 4.0


问:
how to set google-chrome as git default browser
I want GIT to open the help pages in Chrome browser by default though the Windows 7 default browser is IE which I can't change for other reasons. I have added the following to the git config file.

```<code>[web]
    browser = chrome
[browser "chrome"]
    cmd = C:/Program Files (x86)/Google/Chrome/Application/chrome.exe
    path = C:/Program Files (x86)/Google/Chrome/Application/
</code>```

But it still opens IE browser. In git's bash environment it gives the message "Launching default browser to display HTML ...".  On Git Gui, it throws a lengthier message

```<code>The browser chrome is not available as 'C:/Program Files (x86)/Google/Chrome/Application/'.
The browser chrome is not available as 'C:/Program Files (x86)/Google/Chrome/Application/'.
    while executing
"exec {C:/Program Files (x86)/Git/bin/sh.exe} {C:/Program Files (x86)/Git/libexec/git-core/git-web--browse} {file:C:/Program Files (x86)/Git/doc/git/ht..."
    ("eval" body line 1)
    invoked from within
"eval exec $opt $cmdp $args"
    (procedure "git" line 23)
    invoked from within
"git "web--browse" $url"
    (procedure "start_browser" line 2)
    invoked from within
"start_browser {file:C:/Program Files (x86)/Git/doc/git/html/index.html}"
    (menu invoke)
</code>```

Could someone help me resolve this?

EDIT: Also tried

```<code>[web]
    browser = chrome
[browser "chrome"]
    path = C:/Program Files (x86)/Google/Chrome/Application/chrome.exe
</code>```

Now I am able to open online documentation in chrome from Git Gui. But it does not work in git bash.

答:
I found Ash Wilson's answer helpful:

```<code>[web]
    browser = chrome
[browser "chrome"]
    path = C:/Program Files (x86)/Google/Chrome/Application/chrome.exe
</code>```

To write directly to .gitconfig from bash I used:

git config --global browser."chrome".path "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"
```

Body:
I want GIT to open the help pages in Chrome browser by default though the Windows 7 default browser is IE which I can't change for other reasons. I have added the following to the git config file.

[web]
    browser = chrome
[browser "chrome"]
    cmd = C:/Program Files (x86)/Google/Chrome/Application/chrome.exe
    path = C:/Program Files (x86)/Google/Chrome/Application/

But it still opens IE browser. In git's bash environment it gives the message "Launching default browser to display HTML ...".  On Git Gui, it throws a lengthier message

The browser chrome is not available as 'C:/Program Files (x86)/Google/Chrome/Application/'.
The browser chrome is not available as 'C:/Program Files (x86)/Google/Chrome/Application/'.
    while executing
"exec {C:/Program Files (x86)/Git/bin/sh.exe} {C:/Program Files (x86)/Git/libexec/git-core/git-web--browse} {file:C:/Program Files (x86)/Git/doc/git/ht..."
    ("eval" body line 1)
    invoked from within
"eval exec $opt $cmdp $args"
    (procedure "git" line 23)
    invoked from within
"git "web--browse" $url"
    (procedure "start_browser" line 2)
    invoked from within
"start_browser {file:C:/Program Files (x86)/Git/doc/git/html/index.html}"
    (menu invoke)

Could someone help me resolve this?

EDIT: Also tried

[web]
    browser = chrome
[browser "chrome"]
    path = C:/Program Files (x86)/Google/Chrome/Application/chrome.exe

Now I am able to open online documentation in chrome from Git Gui. But it does not work in git bash.

Body:
I found Ash Wilson's answer helpful:

[web]
    browser = chrome
[browser "chrome"]
    path = C:/Program Files (x86)/Google/Chrome/Application/chrome.exe

To write directly to .gitconfig from bash I used:

git config --global browser."chrome".path "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"


问:
Linkedin show 3 different image when sharing
Linkedin show different 3 image when trying to share. Here is then head tags

```<code><meta property="og:site_name" content="OkyTalk">
<meta property="og:title" content="OkyTalk ">
<meta property="og:type" content="website">
<meta property="og:url" content="https://okytalk.com/teachers/profile/displayProffesional">
<meta property="og:image" content="https://okytalk.com/media/okytalk/img/share.jpg">
<meta property="og:image:type" content="image/jpeg">
<meta property="og:image:width" content="470">
<meta property="og:image:height" content="246">
</code>```

Any Ideas how to show only one ? Others share(facebook, twitter, google+) works fine.

答:
Things certainly have changed since 2015!  For instance, the entire company of LinkedIn has been bought by Microsoft, and almost all the old documentation for LinkedIn on LinkedIn.com just 404's.  I'm going to post in case others still have this problem.

To quote from the Microsoft LinkedIn Share Documentation, you want your share URL actually to be...

```<code>https://www.linkedin.com/sharing/share-offsite/?url={url}
</code>```

Your og: tags appear to be correct, and they should be properly interpreted today, in 2020.  It seems that they were only officially supported in 2017, two years after your question.  Take a look at the LinkedIn Developer Docs: Making Your Website Shareable on LinkedIn.  These should work...

<meta property='og:title' content='Title of the article"/>

<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>

<meta property='og:description' content='Description that will show in the preview"/>

<meta property='og:url' content='//www.example.com/URL of the article" />

Don't forget, once you're all coded and done, you can test your page!  Take the URL of your site (example.com, not linkedin.com/share?site=example.com), and input it into the LinkedIn Post Inspector.

Here's an online demo I created with 20+ share services (100% no monetary income, it is designed as a test site).  Take a look at the source code, and see how it's making the LinkedIn URL work with og: tags.

Hope all this info helps someone!

Body:
Linkedin show different 3 image when trying to share. Here is then head tags

<meta property="og:site_name" content="OkyTalk">
<meta property="og:title" content="OkyTalk ">
<meta property="og:type" content="website">
<meta property="og:url" content="https://okytalk.com/teachers/profile/displayProffesional">
<meta property="og:image" content="https://okytalk.com/media/okytalk/img/share.jpg">
<meta property="og:image:type" content="image/jpeg">
<meta property="og:image:width" content="470">
<meta property="og:image:height" content="246">

Any Ideas how to show only one ? Others share(facebook, twitter, google+) works fine.

Body:
Things certainly have changed since 2015!  For instance, the entire company of LinkedIn has been bought by Microsoft, and almost all the old documentation for LinkedIn on LinkedIn.com just 404's.  I'm going to post in case others still have this problem.

To quote from the Microsoft LinkedIn Share Documentation, you want your share URL actually to be...

https://www.linkedin.com/sharing/share-offsite/?url={url}

Your og: tags appear to be correct, and they should be properly interpreted today, in 2020.  It seems that they were only officially supported in 2017, two years after your question.  Take a look at the LinkedIn Developer Docs: Making Your Website Shareable on LinkedIn.  These should work...

<meta property='og:title' content='Title of the article"/>

<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>

<meta property='og:description' content='Description that will show in the preview"/>

<meta property='og:url' content='//www.example.com/URL of the article" />

Don't forget, once you're all coded and done, you can test your page!  Take the URL of your site (example.com, not linkedin.com/share?site=example.com), and input it into the LinkedIn Post Inspector.

Here's an online demo I created with 20+ share services (100% no monetary income, it is designed as a test site).  Take a look at the source code, and see how it's making the LinkedIn URL work with og: tags.

Hope all this info helps someone!


问:
How do I remove directories from Indexing in Android Studio?
I have a large project folder that contains many sub projects. Only 4 are part of the Android project, the rest are C code.

However, it appears that Android Studio is indexing ALL of it, which takes a long time.

How do I exclude these other directories from indexing?

There no way to explicitly do it, and the Module Settings only lists the Android projects so I cannot remove the other folders from there.

答:
(optional) Switch to project view if you can't see the folders you want to exclude

Right click the folder you want to exclude

In the contextual menu click "Mark directory as" --> "Excluded"

It should look like this:

(optional) If you want to include a folder, click "Mark directory as" --> "Cancel exclusion"


问:
try/except issue statement in python 3
Hello I am new to Python and learning basics. I am curious to understand try/except statements in Python and I want to ask whether I should keep as little as possible in try block/portion as mentioned below (Please refer Following Code Working Properly) or try to keep as much in try block/portion (Please refer Following Code Not Working Properly When I Enter Any String but it works when I enter float/integer).

So, these are the two scenarios almost the same but the other code (in which I am keeping minimum code) is giving me an error when I enter a string.

Why is that doing it? What should I do in that case if I want to keep as little as possible in try/except blocks? Any leads would be highly appreciated. What's the alternate correct solution of my second code in which I am keeping minimum lines of code?  - What adjustment I am supposed to make in it to work for me? Please help.

```<code>NameError: name 'fahr' is not defined
</code>```

```<code>***# Following Code Working Properly:***
inp = input('Enter Fahrenheit Temperature:')
try:
    fahr = float(inp)
    cel = (fahr - 32.0) * 5.0 / 9.0
    print(cel)
except:
    print('Please enter a number')
</code>```

```<code>***# Following Code Not Working Properly:***
inp = input('Enter Fahrenheit Temperature:')

try:
    fahr = float(inp)
except:
    print('Please enter a number')

fahr = float(inp) # Even if I comment it, it doesn't make any difference when it comes to entering float in an input but it raises red flag if I enter string.
cel = (fahr - 32.0) * 5.0 / 9.0
print(cel)
</code>```

答:
Less in the try expression is preferable

It is preferable that the code you enter the try: block should only contains the bits that may directly produce the error in interest. This way, it would be easier to track its source and not to get distracted by any surrounding and presumably safe code.

In doing so, think about control flow

The first snippet of code runs correctly because when the error is raised in line 4, the control flow jumps directly to the except block, so any statements that depend on the fahr variable do not get affected. However, in the second snippet, if the error is raised and the control flow jumps to the except block, the fahr variable does not get defined, making the subsequent statements that depend on it raise the NameError error that you talk about.
A safer method is to define an alternate, default fahr = 0 for example in the except block or to use an else: block, where the control flow jumps to if no errors are raised in the try: block.

Make your error handling specific

Always try and make the error you anticipate may be raised explicit in your code. this is by putting the base class of the group of errors after the except keyword and before the colon. For example,

except ValueError:
```

Title: try/except issue statement in python 3

Body:
Hello I am new to Python and learning basics. I am curious to understand try/except statements in Python and I want to ask whether I should keep as little as possible in try block/portion as mentioned below (Please refer Following Code Working Properly) or try to keep as much in try block/portion (Please refer Following Code Not Working Properly When I Enter Any String but it works when I enter float/integer).

So, these are the two scenarios almost the same but the other code (in which I am keeping minimum code) is giving me an error when I enter a string.

Why is that doing it? What should I do in that case if I want to keep as little as possible in try/except blocks? Any leads would be highly appreciated. What's the alternate correct solution of my second code in which I am keeping minimum lines of code?  - What adjustment I am supposed to make in it to work for me? Please help.

NameError: name 'fahr' is not defined

***# Following Code Working Properly:***
inp = input('Enter Fahrenheit Temperature:')
try:
    fahr = float(inp)
    cel = (fahr - 32.0) * 5.0 / 9.0
    print(cel)
except:
    print('Please enter a number')

***# Following Code Not Working Properly:***
inp = input('Enter Fahrenheit Temperature:')

try:
    fahr = float(inp)
except:
    print('Please enter a number')

fahr = float(inp) # Even if I comment it, it doesn't make any difference when it comes to entering float in an input but it raises red flag if I enter string.
cel = (fahr - 32.0) * 5.0 / 9.0
print(cel)


问:
I want efficient data structure to store items and their counts and search for min of them?
I want efficient data structure to store items and their counts and search for min of them?

I have a number of items, and a count of each item, I want a data sturucture to store the items and their counts. in my script each time i will search about an item and update its count, also I want to find the item that has the min count, and some times I want the count of some items. would you please tell me which data structure to use with low space and low cost search operations?

答:
List is good option to use here and you can use stream API(Java 8 and above) to do operations like finding min and counting elements based on some condition.

You can find stream usage example here

https://www.baeldung.com/java-8-streams


问:
How to increment every number in a vector without the error "cannot borrow as mutable more than once at a time"?
This code is supposed to increment each value in a vector by 1:

```<code>fn main() {
    let mut v = vec![2, 3, 1, 4, 2, 5];
    let i = v.iter_mut();
    for j in i {
        *j += 1;
        println!("{}", j);
    }
    println!("{:?}", &mut v);
}
</code>```

It doesn't work because of the borrowing rules of Rust:

error[E0499]: cannot borrow `v` as mutable more than once at a time
 --> src/main.rs:8:27
  |
3 |     let i = v.iter_mut();
  |             - first mutable borrow occurs here
...
8 |     println!("{:?}", &mut v);
  |                           ^ second mutable borrow occurs here
9 | }
  | - first borrow ends here
```

How can I accomplish this task?

答:
You call also just use map and collect like,

```<code>>> let mut v = vec![5,1,4,2,3];
>> v.iter_mut().map(|x| *x += 1).collect::<Vec<_>>();
>> v
[6, 2, 5, 3, 4]
</code>```

Body:
This code is supposed to increment each value in a vector by 1:

fn main() {
    let mut v = vec![2, 3, 1, 4, 2, 5];
    let i = v.iter_mut();
    for j in i {
        *j += 1;
        println!("{}", j);
    }
    println!("{:?}", &mut v);
}

It doesn't work because of the borrowing rules of Rust:

error[E0499]: cannot borrow `v` as mutable more than once at a time
 --> src/main.rs:8:27
  |
3 |     let i = v.iter_mut();
  |             - first mutable borrow occurs here
...
8 |     println!("{:?}", &mut v);
  |                           ^ second mutable borrow occurs here
9 | }
  | - first borrow ends here

How can I accomplish this task?

Body:
You call also just use map and collect like,

>> let mut v = vec![5,1,4,2,3];
>> v.iter_mut().map(|x| *x += 1).collect::<Vec<_>>();
>> v
[6, 2, 5, 3, 4]


问:
Literal eval of Python object from command-line arg
I have a slightly messy pipeline whereby a Python script takes in some parameters from a user, stored internally as a dictionary:

```<code>{'robot': 'A', 'hours': 24, 'stations': [15, 17, 21], 'log': False}
</code>```

and appends its string representation to a command to be run in a container

```
python robot.py {'robot': 'A', 'hours': 24, 'stations': [15, 17, 21], 'log': False}
```

In robot.py (inside the container), I'd like to parse it like this:

```<code>import sys
from ast import literal_eval

if __name__ == '__main__':
    params = literal_eval(sys.argv[1])
    do_stuff(params)
</code>```

Currently this fails because of parsing errors, as Python attempts to split up the input in some way.

Two questions:

is this a horrible idea? (If so, what should I do instead?)

if not, how can I literal_eval the dict as one argument? I expect to get lists, booleans, strings, ints, etc. as params.

答:
First, you need to quote the argument, as the shell will do all manner of processing before python even runs (and most of that will probably just produce a syntax error):

```<code>python robot.py "{'robot': 'A', 'hours': 24, 'stations': [15, 17, 21], 'log': False}"
</code>```

Second, just because the script is written in Python doesn't mean the input has to be valid Python code. Use a language-agnostic format like JSON for these applications.

```<code>python robot.py '{"robot": "A", "hours": 24, "stations": [15, 17, 21], "log": False}'
</code>```

with your code using the json module rather than the ast module.

```<code>import sys
import json

if __name__ == '__main__':
    params = json.loads(sys.argv[1])
    do_stuff(params)
</code>```

Body:
I have a slightly messy pipeline whereby a Python script takes in some parameters from a user, stored internally as a dictionary:

{'robot': 'A', 'hours': 24, 'stations': [15, 17, 21], 'log': False}

and appends its string representation to a command to be run in a container

python robot.py {'robot': 'A', 'hours': 24, 'stations': [15, 17, 21], 'log': False}

In robot.py (inside the container), I'd like to parse it like this:

import sys
from ast import literal_eval

if __name__ == '__main__':
    params = literal_eval(sys.argv[1])
    do_stuff(params)

Currently this fails because of parsing errors, as Python attempts to split up the input in some way.

Two questions:

is this a horrible idea? (If so, what should I do instead?)

if not, how can I literal_eval the dict as one argument? I expect to get lists, booleans, strings, ints, etc. as params.

Body:
First, you need to quote the argument, as the shell will do all manner of processing before python even runs (and most of that will probably just produce a syntax error):

python robot.py "{'robot': 'A', 'hours': 24, 'stations': [15, 17, 21], 'log': False}"

Second, just because the script is written in Python doesn't mean the input has to be valid Python code. Use a language-agnostic format like JSON for these applications.

python robot.py '{"robot": "A", "hours": 24, "stations": [15, 17, 21], "log": False}'

with your code using the json module rather than the ast module.

import sys
import json

if __name__ == '__main__':
    params = json.loads(sys.argv[1])
    do_stuff(params)


问:
How to leave erlang shell without shutting down erlang VM
I searched for this and found that the command is Ctrl-D, but that is not working for me.

Rest all options are shutting the VM down.

I am using erlang 19.3 with erlang.mk

Ctrl-D is working supposedly for rest of the logins and shell. This is so strange. Any help is appreciated.

答:
You can quit with the command:

q().
```

<p>This might not work because of the previous commands. If that is the case then forget the previous commands by first running the command below f() the q() above:</p>

<pre class="lang-erlang prettyprint-override"><code>f().
</code>```

This takes you out of the erlang shell.

After leaving the shell you can view running processes. View running processes in linux/mac by running the command below on your terminal, if you are using windows then use windows task manager to see if erlang is running:

ps -ax
```

Body:
You can quit with the command:

q().

This might not work because of the previous commands. If that is the case then forget the previous commands by first running the command below f() the q() above:

f().

This takes you out of the erlang shell.

After leaving the shell you can view running processes. View running processes in linux/mac by running the command below on your terminal, if you are using windows then use windows task manager to see if erlang is running:

ps -ax


问:
read/write data in libsvm format
How do I read/write libsvm data into/from R?

The libsvm format is sparse data like

```<code><class/target>[ <attribute number>:<attribute value>]*
</code>```

(cf. Compressed Row Storage (CRS)) e.g.,

```<code>1 10:3.4 123:0.5 34567:0.231
0.2 22:1 456:03
</code>```

I am sure I can whip some something myself, but I would much rather use something off the shelf. However, R library foreign does not seem to provide the necessary functionality.

答:
The question was asked a long time ago and has several answer. Most answers didn't work for me since my data comes in a long format, and I cant one-hot encode it in R. So here is my take. I wrote a function to one-hot encode the data, and save it without having to first transform the matrix into a sparse one.

RCPP code:

```<code>// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
#include <Rcpp.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace Rcpp;

// Reading data frame from R and saving it as an libFM file

// [[Rcpp::export]]
std::string createNumber(int x, double y) {
  std::string s1 = std::to_string(x);
  std::string s2 = std::to_string(y);
  std::string X_elem = s1 + ":" + s2;
  return X_elem;
}

// [[Rcpp::export]]
std::string createRowLibFM(arma::rowvec row_to_fm, arma::vec factor_levels, arma::vec position) {
  int n = factor_levels.n_elem;
  std::string total =  std::to_string(row_to_fm[0]);
  for (int i = 1; i < n; i++) {
    if (factor_levels[i] > 1) {
      total = total + " " + createNumber(position[i - 1] + row_to_fm[i], 1);
    }
    if (factor_levels[i] == 1) {
      total = total + " " + createNumber(position[i], row_to_fm[i]);
    }
  }
  return total;
}

// [[Rcpp::export]]
void writeFile(std::string file, arma::mat all_data, arma::vec factor_levels) {
  int n = all_data.n_rows;
  arma::vec position = arma::cumsum(factor_levels);
  std::ofstream temp_file;
  temp_file.open (file.c_str());
  for (int i = 0; i < n; i++) {
    std::string temp_row = createRowLibFM(all_data.row(i), factor_levels, position);
    temp_file << temp_row + "\n";
  }
  temp_file.close();
}
</code>```

R function acting as wrapper for it:

```<code>writeFileFM <- function(temp.data, path = 'test.txt') {
  ### Dealing with y function
  if (!(any(colnames(temp.data) %in% 'y'))) {
    stop('No y column is given')
  } else {
    temp.data <- temp.data %>% select(y, everything()) ## y is required to be first column for writeFile
  }
  ### Dealing with factors/strings
  temp.classes <- sapply(temp.data, class)
  class.num    <- rep(0, length(temp.classes))
  map.list     <- list()
  for (i in 2:length(temp.classes)) { ### since y is always the first column
    if (any(temp.classes[i] %in% c('factor', 'character'))) {
      temp.col         <- as.factor(temp.data[ ,i]) ### incase it is character
      temp.unique      <- levels(temp.col)
      factors.new      <- seq(0, length(temp.unique) - 1, 1)
      levels(temp.col) <- factors.new
      temp.data[ ,i]   <- temp.col
      ### Saving changes
      class.num[i]  <- length(temp.unique)
      map.list[[i - 1]] <- data.frame('original.value'  = temp.unique,
                                      'transform.value' = factors.new)
    } else {
      class.num[i]  <- 1  ### Numeric values require only 1 column
    }
  }
  ### Writing file
  print('Writing file to disc')
  writeFile(all_data = sapply(temp.data, as.numeric), file = path, factor_levels = class.num)
  return(map.list)
}
</code>```

Comparing it on fake data.

```<code>### Creating data to save
set.seed(999)
n <- 10000
factor.lvl1 <- 3
factor.lvl2 <- 2
temp.data <- data.frame('x1' = sample(stri_rand_strings(factor.lvl1, 7), n, replace = TRUE),
                        'x2' = sample(stri_rand_strings(factor.lvl2, 4), n, replace = TRUE),
                        'x3' = rnorm(n),
                        'x4' = rnorm(n),
                        'y'  = rnorm(n))

### Comparing to other method
library(data.table)
library(e1071)

microbenchmark::microbenchmark(
  temp.data.table <- model.matrix( ~ 0 + x1 + x2 + x3 + x4, data = temp.data,
                                   contrasts = list(x2 = contrasts(temp.data$x2, contrasts = FALSE))),
  write.matrix.csr(temp.data.table, 'out.txt'),
  writeFileFM(temp.data))
</code>```

Results.

```<code>  min       lq       mean    median        uq
   1.3061   1.6725   1.890942   1.92475   2.07725
 629.9863 653.4345 676.108548 672.52510 687.88330
 270.8217 275.1353 283.537898 281.42100 289.39160
      max neval cld
   3.2328   100 a
 793.7040   100   c
 328.0863   100  b
</code>```

It is faster than the e1071 option, and while that option fails when increasing the number of observations, the method suggested is still applicable.

Title: read/write data in libsvm format

Body:
How do I read/write libsvm data into/from R?

The libsvm format is sparse data like

<class/target>[ <attribute number>:<attribute value>]*

(cf. Compressed Row Storage (CRS)) e.g.,

1 10:3.4 123:0.5 34567:0.231
0.2 22:1 456:03

I am sure I can whip some something myself, but I would much rather use something off the shelf. However, R library foreign does not seem to provide the necessary functionality.

Body:
The question was asked a long time ago and has several answer. Most answers didn't work for me since my data comes in a long format, and I cant one-hot encode it in R. So here is my take. I wrote a function to one-hot encode the data, and save it without having to first transform the matrix into a sparse one.

RCPP code:

// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
#include <Rcpp.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace Rcpp;

// Reading data frame from R and saving it as an libFM file

// [[Rcpp::export]]
std::string createNumber(int x, double y) {
  std::string s1 = std::to_string(x);
  std::string s2 = std::to_string(y);
  std::string X_elem = s1 + ":" + s2;
  return X_elem;
}

// [[Rcpp::export]]
std::string createRowLibFM(arma::rowvec row_to_fm, arma::vec factor_levels, arma::vec position) {
  int n = factor_levels.n_elem;
  std::string total =  std::to_string(row_to_fm[0]);
  for (int i = 1; i < n; i++) {
    if (factor_levels[i] > 1) {
      total = total + " " + createNumber(position[i - 1] + row_to_fm[i], 1);
    }
    if (factor_levels[i] == 1) {
      total = total + " " + createNumber(position[i], row_to_fm[i]);
    }
  }
  return total;
}

// [[Rcpp::export]]
void writeFile(std::string file, arma::mat all_data, arma::vec factor_levels) {
  int n = all_data.n_rows;
  arma::vec position = arma::cumsum(factor_levels);
  std::ofstream temp_file;
  temp_file.open (file.c_str());
  for (int i = 0; i < n; i++) {
    std::string temp_row = createRowLibFM(all_data.row(i), factor_levels, position);
    temp_file << temp_row + "\n";
  }
  temp_file.close();
}

R function acting as wrapper for it:

writeFileFM <- function(temp.data, path = 'test.txt') {
  ### Dealing with y function
  if (!(any(colnames(temp.data) %in% 'y'))) {
    stop('No y column is given')
  } else {
    temp.data <- temp.data %>% select(y, everything()) ## y is required to be first column for writeFile
  }
  ### Dealing with factors/strings
  temp.classes <- sapply(temp.data, class)
  class.num    <- rep(0, length(temp.classes))
  map.list     <- list()
  for (i in 2:length(temp.classes)) { ### since y is always the first column
    if (any(temp.classes[i] %in% c('factor', 'character'))) {
      temp.col         <- as.factor(temp.data[ ,i]) ### incase it is character
      temp.unique      <- levels(temp.col)
      factors.new      <- seq(0, length(temp.unique) - 1, 1)
      levels(temp.col) <- factors.new
      temp.data[ ,i]   <- temp.col
      ### Saving changes
      class.num[i]  <- length(temp.unique)
      map.list[[i - 1]] <- data.frame('original.value'  = temp.unique,
                                      'transform.value' = factors.new)
    } else {
      class.num[i]  <- 1  ### Numeric values require only 1 column
    }
  }
  ### Writing file
  print('Writing file to disc')
  writeFile(all_data = sapply(temp.data, as.numeric), file = path, factor_levels = class.num)
  return(map.list)
}

Comparing it on fake data.

### Creating data to save
set.seed(999)
n <- 10000
factor.lvl1 <- 3
factor.lvl2 <- 2
temp.data <- data.frame('x1' = sample(stri_rand_strings(factor.lvl1, 7), n, replace = TRUE),
                        'x2' = sample(stri_rand_strings(factor.lvl2, 4), n, replace = TRUE),
                        'x3' = rnorm(n),
                        'x4' = rnorm(n),
                        'y'  = rnorm(n))

### Comparing to other method
library(data.table)
library(e1071)

microbenchmark::microbenchmark(
  temp.data.table <- model.matrix( ~ 0 + x1 + x2 + x3 + x4, data = temp.data,
                                   contrasts = list(x2 = contrasts(temp.data$x2, contrasts = FALSE))),
  write.matrix.csr(temp.data.table, 'out.txt'),
  writeFileFM(temp.data))

Results.

  min       lq       mean    median        uq
   1.3061   1.6725   1.890942   1.92475   2.07725
 629.9863 653.4345 676.108548 672.52510 687.88330
 270.8217 275.1353 283.537898 281.42100 289.39160
      max neval cld
   3.2328   100 a
 793.7040   100   c
 328.0863   100  b

It is faster than the e1071 option, and while that option fails when increasing the number of observations, the method suggested is still applicable.


问:
Mapping specific interface implementation to interface destination
I have several mappings in my AutoMapper profile for the same source and destination types. The destination type is an interface which has several concrete implementations.
Depending on the scenario, I would map to the appropriate concrete implementation of IEmployeeDto.

// Model
public class Department
{
  public List<Employee> Employees { get; set; }
}

public class DepartmentDto
{
  public List<IEmployeeDto> Employees { get; set; }
}

public class EmployeeDto1 : IEmployeeDto
{
  ...
}

public class EmployeeDto2 : IEmployeeDto
{
  ...
}

// Mappings
profile.CreateMap<Employee, IEmployeeDto>()
  .As<EmployeeDto1>();

profile.CreateMap<Employee, IEmployeeDto>()
  .As<EmployeeDto2>();
```

<p>I'm using Entity Framework as well.
In runtime, I'm using projections to map:</p>

<pre class="lang-cs prettyprint-override"><code>var department = context.Departments
  .ProjectTo<DeparmentDto>(config)
  .SingleOrDefaultAsync(d => d.Name == departmentName);

//In this specific use case, I'm expecting EmployeeDto2 instead of EmployeeDto1
var employees = department.Employees;
</code>```

Is there any way to hint which concrete implementation of the destination type should be mapped to?

答:
You "hint" which concrete implementation it should use by specifying an AutoMapper mapping which has been configured to use the specific type. When you write

```<code>profile.CreateMap<Employee, IEmployeeDto>().As<EmployeeDto1>();
</code>```

it will use the specific EmployeeDto1 class when a Employee object should be mapped to a IEmployeeDto instance. If you want a different mapping simply change the configured mapping in the AutoMapper configuration or use a different AutoMapper configuration itself (which has the different mapping configured). You can have multiple instances of MapperConfiguration objects, each with it's own configuration. The ProjectTo() method requires a configuration to use, so you can swap the configuration depending on your requirements.

Body:
I have several mappings in my AutoMapper profile for the same source and destination types. The destination type is an interface which has several concrete implementations.
Depending on the scenario, I would map to the appropriate concrete implementation of IEmployeeDto.

// Model
public class Department
{
  public List<Employee> Employees { get; set; }
}

public class DepartmentDto
{
  public List<IEmployeeDto> Employees { get; set; }
}

public class EmployeeDto1 : IEmployeeDto
{
  ...
}

public class EmployeeDto2 : IEmployeeDto
{
  ...
}

// Mappings
profile.CreateMap<Employee, IEmployeeDto>()
  .As<EmployeeDto1>();

profile.CreateMap<Employee, IEmployeeDto>()
  .As<EmployeeDto2>();

I'm using Entity Framework as well.
In runtime, I'm using projections to map:

var department = context.Departments
  .ProjectTo<DeparmentDto>(config)
  .SingleOrDefaultAsync(d => d.Name == departmentName);

//In this specific use case, I'm expecting EmployeeDto2 instead of EmployeeDto1
var employees = department.Employees;

Is there any way to hint which concrete implementation of the destination type should be mapped to?

Body:
You "hint" which concrete implementation it should use by specifying an AutoMapper mapping which has been configured to use the specific type. When you write

profile.CreateMap<Employee, IEmployeeDto>().As<EmployeeDto1>();

it will use the specific EmployeeDto1 class when a Employee object should be mapped to a IEmployeeDto instance. If you want a different mapping simply change the configured mapping in the AutoMapper configuration or use a different AutoMapper configuration itself (which has the different mapping configured). You can have multiple instances of MapperConfiguration objects, each with it's own configuration. The ProjectTo() method requires a configuration to use, so you can swap the configuration depending on your requirements.


问:
react tests- display:none in stylesheet doesn't work in but works when inline
I am testing if a div is set to display: none. I have set it as such in the stylesheet but the tests tell me that it is still display: block. When I change to inline CSS the tests acknowledge that it is indeed display: none.

and Yes, I did remember to import the stylesheet because the element is invisible in the browser.

Part of the react component

```<code>      <div className="navbar-buttons">
        <button type="button">Sign In</button>
      </div>
</code>```

stylesheet

```<code>.navbar-buttons{
  display: none;
}
</code>```

The test assertion

```<code>   expect(signinBtns).toHaveStyle('display: none')
</code>```

The test result printed to terminal

```<code>    expect(element).toHaveStyle()

    - Expected

    - display: none;
    + display: block;
</code>```

How do I get the tests to recognize the style attributes if they are in a stylesheet?

答: You can't check if the style attributes are applied via tests, unless it's inline style. You can only check for the class name if it's applied or not and assume it's the right class.</p>

Body:
I am testing if a div is set to display: none. I have set it as such in the stylesheet but the tests tell me that it is still display: block. When I change to inline CSS the tests acknowledge that it is indeed display: none.

and Yes, I did remember to import the stylesheet because the element is invisible in the browser.

Part of the react component

        <button type="button">Sign In</button>

stylesheet

.navbar-buttons{
  display: none;
}

The test assertion

   expect(signinBtns).toHaveStyle('display: none')

The test result printed to terminal

    expect(element).toHaveStyle()

    - Expected

    - display: none;
    + display: block;

How do I get the tests to recognize the style attributes if they are in a stylesheet?


问:
How do I read bot DMs and forward it to a channel using discord.py?
I'm trying to make a bot that recieves DMs and forwards the message to a specific channel in a server along with the username and user id of whoever sent the DM. Here's what I've tried. It doesn't seem to work, although I think there's a possibility that the rest of my code may be affecting it.

```<code>@client.event
async def on_message(message):
    channel = client.get_channel(714242239215304745)
    if message.guild is None and message.author != client.user:
        embed = discord.Embed(
            title = 'Support requested!',
            description = '{}' .format(message.content),
            color = discord.Color.from_rgb(r=159, g=255, b=255)
            )
        embed.set_footer(text='Requested by {} | ID-{}' .format(message.author, message.author.id))
        await channel.send(embed=embed)
        print("Support requested by {} | ID-{}!" .format(message.author, message.author.id))
        print("Content: '{}'." .format(message.content))
    await client.process_commands(message)
</code>```

The rest of my code can be found here.

答:
Try using message.channel == message.author.dm_channel, and f-strings opposed to .format().

@client.event
async def on_message(message):
    channel = client.get_channel(714242239215304745) # are you sure this channel exists?
    if message.channel == message.author.dm_channel: # do not use guild == None, as group dms might satisfy this, and you can't message yourself, no need to check client user
        embed = discord.Embed(
            title = 'Support requested!',
            description = f'{message.content}',
            color = 0x9fffff
            )
        embed.set_footer(text=f'Requested by {message.author.display_name} | ID-{message.author.id}')
        await channel.send(embed=embed)
        print("Support requested by {} | ID-{}!" .format(message.author, message.author.id))
        print("Content: '{}'." .format(message.content))
    await client.process_commands(message)
```

Body:
I'm trying to make a bot that recieves DMs and forwards the message to a specific channel in a server along with the username and user id of whoever sent the DM. Here's what I've tried. It doesn't seem to work, although I think there's a possibility that the rest of my code may be affecting it.

@client.event
async def on_message(message):
    channel = client.get_channel(714242239215304745)
    if message.guild is None and message.author != client.user:
        embed = discord.Embed(
            title = 'Support requested!',
            description = '{}' .format(message.content),
            color = discord.Color.from_rgb(r=159, g=255, b=255)
            )
        embed.set_footer(text='Requested by {} | ID-{}' .format(message.author, message.author.id))
        await channel.send(embed=embed)
        print("Support requested by {} | ID-{}!" .format(message.author, message.author.id))
        print("Content: '{}'." .format(message.content))
    await client.process_commands(message)

The rest of my code can be found here.


问:
mysql query: how to get the number of yes/no votes per day
I have to create a mysql query to get a voting distribution of each day exceeding a particular date, something like this...

```<code>    date          yes_votes    no_votes
------------------------------------------
    2010-01-07    21           22
    2010-01-07    2            0
</code>```

My table is like this..

```<code>    post_votes
--------------------------
    id(longint)
    date(timestamp)
    flag(tinyint) // this stores the yes/no votes 1-yes, 2-no
</code>```

I am stuck at this....

```<code>SELECT COUNT(*) AS count, DATE(date) FROM post_votes WHERE date > '2010-07-01' GROUP BY DATE(date)
</code>```

this gives the total number of votes per day, but not the distribution that I want.

答:
I had that problem too. The best solution of that I can think of, is to split the "flag" in two fields, like:

```<code>upvote(tinyint)
downvote(tinyint)
</code>```

Then you are able to count them very easy and without mysql-voodoo:

```<code>SELECT
  SUM(upvote) AS up,
  SUM(downvote) AS down,
  DATE(`date`) AS Created_at
FROM post_votes
WHERE Created_at > '2010-07-01'
GROUP BY Created_at
</code>```

Btw.: You should not name a column date, because it's a MySQL-Keyword.

Body:
I have to create a mysql query to get a voting distribution of each day exceeding a particular date, something like this...

    date          yes_votes    no_votes
------------------------------------------
    2010-01-07    21           22
    2010-01-07    2            0

My table is like this..

    post_votes
--------------------------
    id(longint)
    date(timestamp)
    flag(tinyint) // this stores the yes/no votes 1-yes, 2-no

I am stuck at this....

SELECT COUNT(*) AS count, DATE(date) FROM post_votes WHERE date > '2010-07-01' GROUP BY DATE(date)

this gives the total number of votes per day, but not the distribution that I want.

Body:
I had that problem too. The best solution of that I can think of, is to split the "flag" in two fields, like:

upvote(tinyint)
downvote(tinyint)

Then you are able to count them very easy and without mysql-voodoo:

SELECT
  SUM(upvote) AS up,
  SUM(downvote) AS down,
  DATE(`date`) AS Created_at
FROM post_votes
WHERE Created_at > '2010-07-01'
GROUP BY Created_at

Btw.: You should not name a column date, because it's a MySQL-Keyword.


问:
Cross-browser solution for replacing the use of event.layerX and event.layerY
I'm trying to adapt some code from a simple app that uses Raphael to allow users to draw circles and rectangles on a canvas. (original code at https://gist.github.com/673186)

The original code used an older version of jQuery and worked fine.  See http://jsfiddle.net/GHZSd/

Using an updated version of jQuery, however, breaks the example.  See http://jsfiddle.net/GHZSd/1/

The reason for this is that event.layerX and event.layerY are no longer defined in the new version of jQuery.  My question is - what code I can use to replace those values?  I've tried a couple things just by doing some math (event.originalEvent.layerX/layerX still exist for now so I'm just trying to add/subtract some stuff that will result in those values) but so far what works on one browser doesn't work on all of them.

Sorry if this has been asked before but I wasn't able to find a concrete answer on Stack Overflow or anywhere else.

答:
```<code>const bbox = e.target.getBoundingClientRect();
const x = e.clientX - bbox.left;
const y = e.clientY - bbox.top;
</code>```


问:
How to get proportions of different observation types per total and per year in pandas
I am not entirely new to data science, but rather novice with pandas.

My data looks like this:

```<code>    Date        Obser_Type
0   2001-01-05  A
1   2002-02-06  A
2   2002-02-06  B
3   2004-03-07  C
4   2005-04-08  B
5   2006-05-09  A
6   2007-06-10  C
7   2007-07-11  B
</code>```

I would like to get the following output with the proportions for the different kinds of observations as of total (i.e. accumulated from the beginning up to and including the specified year) and within each year:

```<code>    Year    A_%_total   B_%_total   C_%_total   A_%_Year    B_%_Year    C_%_Year
0   2001    100         0           0           100         0           0
1   2002    67          33          0           50          50          0
2   2004    50          25          25          0           0           100
3   2005    40          40          20          0           100         0
4   2006    50          33          17          100         0           0
5   2007    37,5        37,5        25          0           50          50
</code>```

I tried various approaches involving groupby, multiindexing, count etc but to no avail. I got either errors or something unsatisfying.
After extensively digging Stack Overflow and the rest of the internet for days, I am stumped.

The medieval way would be a bucket of loops and ifs, but what is the proper way to do this?

答:
Thank you very much for your answer. However, i probably should have made it more clear that the actual dataframe is much bigger and has much more types of observations than A B C, so listing them manually would be inconvenient. My scope here is just the statistics for the different types of observations, not their associated numerical values.

I was able to build something and would like to share:

```<code># convert dates to datetimes
#
df[‚Date'] = pd.to_datetime(df[‚Date'])

# get years from the dates
#
df[‚Year'] = df.Date.dt.year

# get total number of observations per type of observation and year in tabular form
#
grouped = df.groupby(['Year', 'Obser_Type']).count().unstack(1)

                     Date
Obser_Type  A   B     C
Year
2001      1.0   NaN   NaN
2002      1.0   1.0   NaN
2004      NaN   NaN   1.0
2005      NaN   1.0   NaN
2006      1.0   NaN   NaN
2007      NaN   1.0   1.0

# sum total number of observations per type over all years
#
grouped.loc['Total_Obs_per_Type',:] = grouped.sum(axis=0)

                                  Date
        Obser_Type     A       B    C
              Year
              2001   1.0    NaN    NaN
              2002   1.0    1.0    NaN
              2004   NaN    NaN    1.0
              2005   NaN    1.0    NaN
              2006   1.0    NaN    NaN
              2007   NaN    1.0    1.0
Total_Obs_per_Type   3.0    3.0    2.0

# at this point the columns have a multiindex
#
grouped.columns

    MultiIndex([('Date', 'A'),
                ('Date', 'B'),
                ('Date', 'C')],
                names=[None, 'Obser_Type'])

# i only needed the second layer which looks like this
#
grouped.columns.get_level_values(1)

    Index(['A', 'B', 'C'], dtype='object', name='Obser_Type')

# so i flattened the index
#
grouped.columns = grouped.columns.get_level_values(1)

# now i can easily address the columns
#
grouped.columns

    Index(['A', 'B', 'C'], dtype='object', name='Obser_Type')

# create list of columns with observation types
# this refers to columns "A B C"
#
types_list = grouped.columns.values.tolist()

# create list to later access the columns with the cumulative sum of observations per type
# this refers to columns "A_cum  B_cum  C_cum"
#
types_cum_list = []

# calculate cumulative sum for the different kinds of observations
#
for columnName in types_list:
    # create new columns with modified name and calculate for each type of observation the cumulative sum of observations
    #
    grouped[columnName+'_cum'] = grouped[columnName].cumsum()

    # put the new column names in the list of columns with cumulative sum of observations per type
    #
    types_cum_list.append(columnName+'_cum')

# this gives

        Obser_Type    A     B     C  A_cum  B_cum   C_cum
              Year
              2001  1.0   NaN   NaN   1.0   NaN     NaN
              2002  1.0   1.0   NaN   2.0   1.0     NaN
              2004  NaN   NaN   1.0   NaN   NaN     1.0
              2005  NaN   1.0   NaN   NaN   2.0     NaN
              2006  1.0   NaN   NaN   3.0   NaN     NaN
              2007  NaN   1.0   1.0   NaN   3.0     2.0
Total_Obs_per_Type  3.0   3.0   2.0   6.0   6.0     4.0

# create new column with total number of observations for all types of observation within a single year
#
grouped['All_Obs_Y'] = grouped.loc[:,types_list].sum(axis=1)

# this gives

        Obser_Type    A     B     C  A_cum  B_cum   C_cum  All_Obs_Y
              Year
              2001  1.0   NaN   NaN   1.0   NaN     NaN    1.0
              2002  1.0   1.0   NaN   2.0   1.0     NaN    2.0
              2004  NaN   NaN   1.0   NaN   NaN     1.0    1.0
              2005  NaN   1.0   NaN   NaN   2.0     NaN    1.0
              2006  1.0   NaN   NaN   3.0   NaN     NaN    1.0
              2007  NaN   1.0   1.0   NaN   3.0     2.0    2.0
Total_Obs_per_Type  3.0   3.0   2.0   6.0   6.0     4.0    8.0

# create new columns with cumulative sum of all kinds observations up to each year
#
grouped['All_Obs_Cum'] = grouped['All_Obs_Y'].cumsum()

# this gives
# sorry i could not work out the formatting and i am not allowed yet to include screenshots

Obser_Type           A  B   C   A_cum   B_cum   C_cum   All_Obs_Y   All_Obs_Cum
Year
2001                1.0 NaN NaN 1.0 NaN NaN 1.0 1.0
2002                1.0 1.0 NaN 2.0 1.0 NaN 2.0 3.0
2004                NaN NaN 1.0 NaN NaN 1.0 1.0 4.0
2005                NaN 1.0 NaN NaN 2.0 NaN 1.0 5.0
2006                1.0 NaN NaN 3.0 NaN NaN 1.0 6.0
2007                NaN 1.0 1.0 NaN 3.0 2.0 2.0 8.0
Total_Obs_per_Type  3.0 3.0 2.0 6.0 6.0 4.0 8.0 16.0

# create list of columns with the percentages each type of observation has within the observations of each year
# this refers to columns "A_%_Y  B_%_Y  C_Y_%"
#
types_percent_Y_list = []

# calculate the percentages each type of observation has within each year
#
for columnName in types_list:

    # calculate percentages
    #
    grouped[columnName+'_%_Y'] = grouped[columnName] / grouped['All_Obs_Y']

    # put the new columns names in list of columns with percentages each type of observation has within a year for later access
    #
    types_percent_Y_list.append(columnName+'_%_Y')

# this gives

Obser_Type  A   B   C   A_cum   B_cum   C_cum   All_Obs_Y   All_Obs_Cum A_%_Y   B_%_Y   C_%_Y
Year
2001    1.0 NaN NaN 1.0 NaN NaN 1.0 1.0 1.000   NaN NaN
2002    1.0 1.0 NaN 2.0 1.0 NaN 2.0 3.0 0.500   0.500   NaN
2004    NaN NaN 1.0 NaN NaN 1.0 1.0 4.0 NaN NaN 1.00
2005    NaN 1.0 NaN NaN 2.0 NaN 1.0 5.0 NaN 1.000   NaN
2006    1.0 NaN NaN 3.0 NaN NaN 1.0 6.0 1.000   NaN NaN
2007    NaN 1.0 1.0 NaN 3.0 2.0 2.0 8.0 NaN 0.500   0.50
Total_Obs_per_Type  3.0 3.0 2.0 6.0 6.0 4.0 8.0 16.0    0.375   0.375   0.25

# replace the NaNs in the types_cum columns, otherwise the calculation of the cumulative percentages in the next step would not work
#
# types_cum_list :
# if there is no observation for e.g. type B in the first year (2001) we put a count of 0 for that year,
# that is, in the first row.
# If there is no observation for type B in a later year (e.g. 2004) the cumulative count of Bs
# from the beginning up to that year does not change in that year, so we replace the NaN there with
# the last non-NaN value preceding it
#
# replace NaNs in first row by 0
#
for columnName in types_cum_list:
    grouped.update(grouped.iloc[:1][columnName].fillna(value=0))
# replace NaNs in later rows with preceding non-NaN value
#
for columnName in types_cum_list:
    grouped[columnName].fillna(method='ffill' , inplace=True)

# this gives

Obser_Type  A   B   C   A_cum   B_cum   C_cum   All_Obs_Y   All_Obs_Cum A_%_Y   B_%_Y   C_%_Y
Year
2001    1.0 NaN NaN 1.0 0.0 0.0 1.0 1.0 1.000   NaN NaN
2002    1.0 1.0 NaN 2.0 1.0 0.0 2.0 3.0 0.500   0.500   NaN
2004    NaN NaN 1.0 2.0 1.0 1.0 1.0 4.0 NaN NaN 1.00
2005    NaN 1.0 NaN 2.0 2.0 1.0 1.0 5.0 NaN 1.000   NaN
2006    1.0 NaN NaN 3.0 2.0 1.0 1.0 6.0 1.000   NaN NaN
2007    NaN 1.0 1.0 3.0 3.0 2.0 2.0 8.0 NaN 0.500   0.50
Total_Obs_per_Type  3.0 3.0 2.0 6.0 6.0 4.0 8.0 16.0    0.375   0.375   0.25

# create list of the columns with the cumulative percentages of the different observation types from the beginning up to that year
# this refers to columns "A_cum_%  B_cum_%  C_cum_%"
#
types_cum_percent_list = []

# calculate cumulative proportions of different types of observations from beginning up to each year
#
for columnName in types_cum_list:

    # if we had not taken care of the NaNs in the types_cum columns this would produce incorrect numbers
    #
    grouped[columnName+'_%'] = grouped[columnName] / grouped['All_Obs_Cum']

    # put the new columns in their respective list so we can access them conveniently later
    #
    types_cum_percent_list.append(columnName+'_%')

# this gives

Obser_Type  A   B   C   A_cum   B_cum   C_cum   All_Obs_Y   All_Obs_Cum A_%_Y   B_%_Y   C_%_Y   A_cum_% B_cum_% C_cum_%
Year
2001    1.0 NaN NaN 1.0 0.0 0.0 1.0 1.0 1.000   NaN NaN 1.000000    0.000000    0.000000
2002    1.0 1.0 NaN 2.0 1.0 0.0 2.0 3.0 0.500   0.500   NaN 0.666667    0.333333    0.000000
2004    NaN NaN 1.0 2.0 1.0 1.0 1.0 4.0 NaN NaN 1.00    0.500000    0.250000    0.250000
2005    NaN 1.0 NaN 2.0 2.0 1.0 1.0 5.0 NaN 1.000   NaN 0.400000    0.400000    0.200000
2006    1.0 NaN NaN 3.0 2.0 1.0 1.0 6.0 1.000   NaN NaN 0.500000    0.333333    0.166667
2007    NaN 1.0 1.0 3.0 3.0 2.0 2.0 8.0 NaN 0.500   0.50    0.375000    0.375000    0.250000
Total_Obs_per_Type  3.0 3.0 2.0 6.0 6.0 4.0 8.0 16.0    0.375   0.375   0.25    0.375000    0.375000    0.250000

# to conclude i replace the remaining NaNs to make plotting easier

# replace NaNs in columns in types_list
#
# if there is no observation for a type of observation in a year we put a count of 0 for that year
#
for columnName in types_list:
    grouped[columnName].fillna(value=0, inplace=True)

# replace NaNs in columns in types_percent_Y_list
#
# if there is no observation for a type of observation in a year we put a percentage of 0 for that year
#
for columnName in types_percent_Y_list:
    grouped[columnName].fillna(value=0, inplace=True)

Obser_Type  A   B   C   A_cum   B_cum   C_cum   All_Obs_Y   All_Obs_Cum A_%_Y   B_%_Y   C_%_Y   A_cum_% B_cum_% C_cum_%
Year
2001    1.0 0.0 0.0 1.0 0.0 0.0 1.0 1.0 1.000   0.000   0.00    1.000000    0.000000    0.000000
2002    1.0 1.0 0.0 2.0 1.0 0.0 2.0 3.0 0.500   0.500   0.00    0.666667    0.333333    0.000000
2004    0.0 0.0 1.0 2.0 1.0 1.0 1.0 4.0 0.000   0.000   1.00    0.500000    0.250000    0.250000
2005    0.0 1.0 0.0 2.0 2.0 1.0 1.0 5.0 0.000   1.000   0.00    0.400000    0.400000    0.200000
2006    1.0 0.0 0.0 3.0 2.0 1.0 1.0 6.0 1.000   0.000   0.00    0.500000    0.333333    0.166667
2007    0.0 1.0 1.0 3.0 3.0 2.0 2.0 8.0 0.000   0.500   0.50    0.375000    0.375000    0.250000
Total_Obs_per_Type  3.0 3.0 2.0 6.0 6.0 4.0 8.0 16.0    0.375   0.375   0.25    0.375000    0.375000    0.250000
</code>```

This has the functionylity and flexibility i was looking for. But as i am still learning pandas suggestions for improvement are appreciated.

Body:
I am not entirely new to data science, but rather novice with pandas.

My data looks like this:

    Date        Obser_Type
0   2001-01-05  A
1   2002-02-06  A
2   2002-02-06  B
3   2004-03-07  C
4   2005-04-08  B
5   2006-05-09  A
6   2007-06-10  C
7   2007-07-11  B

I would like to get the following output with the proportions for the different kinds of observations as of total (i.e. accumulated from the beginning up to and including the specified year) and within each year:

    Year    A_%_total   B_%_total   C_%_total   A_%_Year    B_%_Year    C_%_Year
0   2001    100         0           0           100         0           0
1   2002    67          33          0           50          50          0
2   2004    50          25          25          0           0           100
3   2005    40          40          20          0           100         0
4   2006    50          33          17          100         0           0
5   2007    37,5        37,5        25          0           50          50

I tried various approaches involving groupby, multiindexing, count etc but to no avail. I got either errors or something unsatisfying.
After extensively digging Stack Overflow and the rest of the internet for days, I am stumped.

The medieval way would be a bucket of loops and ifs, but what is the proper way to do this?

Body:
Thank you very much for your answer. However, i probably should have made it more clear that the actual dataframe is much bigger and has much more types of observations than A B C, so listing them manually would be inconvenient. My scope here is just the statistics for the different types of observations, not their associated numerical values.

I was able to build something and would like to share:

# convert dates to datetimes
#
df[‚Date'] = pd.to_datetime(df[‚Date'])

# get years from the dates
#
df[‚Year'] = df.Date.dt.year

# get total number of observations per type of observation and year in tabular form
#
grouped = df.groupby(['Year', 'Obser_Type']).count().unstack(1)

                     Date
Obser_Type  A   B     C
Year
2001      1.0   NaN   NaN
2002      1.0   1.0   NaN
2004      NaN   NaN   1.0
2005      NaN   1.0   NaN
2006      1.0   NaN   NaN
2007      NaN   1.0   1.0

# sum total number of observations per type over all years
#
grouped.loc['Total_Obs_per_Type',:] = grouped.sum(axis=0)

                                  Date
        Obser_Type     A       B    C
              Year
              2001   1.0    NaN    NaN
              2002   1.0    1.0    NaN
              2004   NaN    NaN    1.0
              2005   NaN    1.0    NaN
              2006   1.0    NaN    NaN
              2007   NaN    1.0    1.0
Total_Obs_per_Type   3.0    3.0    2.0

# at this point the columns have a multiindex
#
grouped.columns

    MultiIndex([('Date', 'A'),
                ('Date', 'B'),
                ('Date', 'C')],
                names=[None, 'Obser_Type'])

# i only needed the second layer which looks like this
#
grouped.columns.get_level_values(1)

    Index(['A', 'B', 'C'], dtype='object', name='Obser_Type')

# so i flattened the index
#
grouped.columns = grouped.columns.get_level_values(1)

# now i can easily address the columns
#
grouped.columns

    Index(['A', 'B', 'C'], dtype='object', name='Obser_Type')

# create list of columns with observation types
# this refers to columns "A B C"
#
types_list = grouped.columns.values.tolist()

# create list to later access the columns with the cumulative sum of observations per type
# this refers to columns "A_cum  B_cum  C_cum"
#
types_cum_list = []

# calculate cumulative sum for the different kinds of observations
#
for columnName in types_list:
    # create new columns with modified name and calculate for each type of observation the cumulative sum of observations
    #
    grouped[columnName+'_cum'] = grouped[columnName].cumsum()

    # put the new column names in the list of columns with cumulative sum of observations per type
    #
    types_cum_list.append(columnName+'_cum')

# this gives

        Obser_Type    A     B     C  A_cum  B_cum   C_cum
              Year
              2001  1.0   NaN   NaN   1.0   NaN     NaN
              2002  1.0   1.0   NaN   2.0   1.0     NaN
              2004  NaN   NaN   1.0   NaN   NaN     1.0
              2005  NaN   1.0   NaN   NaN   2.0     NaN
              2006  1.0   NaN   NaN   3.0   NaN     NaN
              2007  NaN   1.0   1.0   NaN   3.0     2.0
Total_Obs_per_Type  3.0   3.0   2.0   6.0   6.0     4.0

# create new column with total number of observations for all types of observation within a single year
#
grouped['All_Obs_Y'] = grouped.loc[:,types_list].sum(axis=1)

# this gives

        Obser_Type    A     B     C  A_cum  B_cum   C_cum  All_Obs_Y
              Year
              2001  1.0   NaN   NaN   1.0   NaN     NaN    1.0
              2002  1.0   1.0   NaN   2.0   1.0     NaN    2.0
              2004  NaN   NaN   1.0   NaN   NaN     1.0    1.0
              2005  NaN   1.0   NaN   NaN   2.0     NaN    1.0
              2006  1.0   NaN   NaN   3.0   NaN     NaN    1.0
              2007  NaN   1.0   1.0   NaN   3.0     2.0    2.0
Total_Obs_per_Type  3.0   3.0   2.0   6.0   6.0     4.0    8.0

# create new columns with cumulative sum of all kinds observations up to each year
#
grouped['All_Obs_Cum'] = grouped['All_Obs_Y'].cumsum()

# this gives
# sorry i could not work out the formatting and i am not allowed yet to include screenshots

Obser_Type           A  B   C   A_cum   B_cum   C_cum   All_Obs_Y   All_Obs_Cum
Year
2001                1.0 NaN NaN 1.0 NaN NaN 1.0 1.0
2002                1.0 1.0 NaN 2.0 1.0 NaN 2.0 3.0
2004                NaN NaN 1.0 NaN NaN 1.0 1.0 4.0
2005                NaN 1.0 NaN NaN 2.0 NaN 1.0 5.0
2006                1.0 NaN NaN 3.0 NaN NaN 1.0 6.0
2007                NaN 1.0 1.0 NaN 3.0 2.0 2.0 8.0
Total_Obs_per_Type  3.0 3.0 2.0 6.0 6.0 4.0 8.0 16.0

# create list of columns with the percentages each type of observation has within the observations of each year
# this refers to columns "A_%_Y  B_%_Y  C_Y_%"
#
types_percent_Y_list = []

# calculate the percentages each type of observation has within each year
#
for columnName in types_list:

    # calculate percentages
    #
    grouped[columnName+'_%_Y'] = grouped[columnName] / grouped['All_Obs_Y']

    # put the new columns names in list of columns with percentages each type of observation has within a year for later access
    #
    types_percent_Y_list.append(columnName+'_%_Y')

# this gives

Obser_Type  A   B   C   A_cum   B_cum   C_cum   All_Obs_Y   All_Obs_Cum A_%_Y   B_%_Y   C_%_Y
Year
2001    1.0 NaN NaN 1.0 NaN NaN 1.0 1.0 1.000   NaN NaN
2002    1.0 1.0 NaN 2.0 1.0 NaN 2.0 3.0 0.500   0.500   NaN
2004    NaN NaN 1.0 NaN NaN 1.0 1.0 4.0 NaN NaN 1.00
2005    NaN 1.0 NaN NaN 2.0 NaN 1.0 5.0 NaN 1.000   NaN
2006    1.0 NaN NaN 3.0 NaN NaN 1.0 6.0 1.000   NaN NaN
2007    NaN 1.0 1.0 NaN 3.0 2.0 2.0 8.0 NaN 0.500   0.50
Total_Obs_per_Type  3.0 3.0 2.0 6.0 6.0 4.0 8.0 16.0    0.375   0.375   0.25

# replace the NaNs in the types_cum columns, otherwise the calculation of the cumulative percentages in the next step would not work
#
# types_cum_list :
# if there is no observation for e.g. type B in the first year (2001) we put a count of 0 for that year,
# that is, in the first row.
# If there is no observation for type B in a later year (e.g. 2004) the cumulative count of Bs
# from the beginning up to that year does not change in that year, so we replace the NaN there with
# the last non-NaN value preceding it
#
# replace NaNs in first row by 0
#
for columnName in types_cum_list:
    grouped.update(grouped.iloc[:1][columnName].fillna(value=0))
# replace NaNs in later rows with preceding non-NaN value
#
for columnName in types_cum_list:
    grouped[columnName].fillna(method='ffill' , inplace=True)

# this gives

Obser_Type  A   B   C   A_cum   B_cum   C_cum   All_Obs_Y   All_Obs_Cum A_%_Y   B_%_Y   C_%_Y
Year
2001    1.0 NaN NaN 1.0 0.0 0.0 1.0 1.0 1.000   NaN NaN
2002    1.0 1.0 NaN 2.0 1.0 0.0 2.0 3.0 0.500   0.500   NaN
2004    NaN NaN 1.0 2.0 1.0 1.0 1.0 4.0 NaN NaN 1.00
2005    NaN 1.0 NaN 2.0 2.0 1.0 1.0 5.0 NaN 1.000   NaN
2006    1.0 NaN NaN 3.0 2.0 1.0 1.0 6.0 1.000   NaN NaN
2007    NaN 1.0 1.0 3.0 3.0 2.0 2.0 8.0 NaN 0.500   0.50
Total_Obs_per_Type  3.0 3.0 2.0 6.0 6.0 4.0 8.0 16.0    0.375   0.375   0.25

# create list of the columns with the cumulative percentages of the different observation types from the beginning up to that year
# this refers to columns "A_cum_%  B_cum_%  C_cum_%"
#
types_cum_percent_list = []

# calculate cumulative proportions of different types of observations from beginning up to each year
#
for columnName in types_cum_list:

    # if we had not taken care of the NaNs in the types_cum columns this would produce incorrect numbers
    #
    grouped[columnName+'_%'] = grouped[columnName] / grouped['All_Obs_Cum']

    # put the new columns in their respective list so we can access them conveniently later
    #
    types_cum_percent_list.append(columnName+'_%')

# this gives

Obser_Type  A   B   C   A_cum   B_cum   C_cum   All_Obs_Y   All_Obs_Cum A_%_Y   B_%_Y   C_%_Y   A_cum_% B_cum_% C_cum_%
Year
2001    1.0 NaN NaN 1.0 0.0 0.0 1.0 1.0 1.000   NaN NaN 1.000000    0.000000    0.000000
2002    1.0 1.0 NaN 2.0 1.0 0.0 2.0 3.0 0.500   0.500   NaN 0.666667    0.333333    0.000000
2004    NaN NaN 1.0 2.0 1.0 1.0 1.0 4.0 NaN NaN 1.00    0.500000    0.250000    0.250000
2005    NaN 1.0 NaN 2.0 2.0 1.0 1.0 5.0 NaN 1.000   NaN 0.400000    0.400000    0.200000
2006    1.0 NaN NaN 3.0 2.0 1.0 1.0 6.0 1.000   NaN NaN 0.500000    0.333333    0.166667
2007    NaN 1.0 1.0 3.0 3.0 2.0 2.0 8.0 NaN 0.500   0.50    0.375000    0.375000    0.250000
Total_Obs_per_Type  3.0 3.0 2.0 6.0 6.0 4.0 8.0 16.0    0.375   0.375   0.25    0.375000    0.375000    0.250000

# to conclude i replace the remaining NaNs to make plotting easier

# replace NaNs in columns in types_list
#
# if there is no observation for a type of observation in a year we put a count of 0 for that year
#
for columnName in types_list:
    grouped[columnName].fillna(value=0, inplace=True)

# replace NaNs in columns in types_percent_Y_list
#
# if there is no observation for a type of observation in a year we put a percentage of 0 for that year
#
for columnName in types_percent_Y_list:
    grouped[columnName].fillna(value=0, inplace=True)

Obser_Type  A   B   C   A_cum   B_cum   C_cum   All_Obs_Y   All_Obs_Cum A_%_Y   B_%_Y   C_%_Y   A_cum_% B_cum_% C_cum_%
Year
2001    1.0 0.0 0.0 1.0 0.0 0.0 1.0 1.0 1.000   0.000   0.00    1.000000    0.000000    0.000000
2002    1.0 1.0 0.0 2.0 1.0 0.0 2.0 3.0 0.500   0.500   0.00    0.666667    0.333333    0.000000
2004    0.0 0.0 1.0 2.0 1.0 1.0 1.0 4.0 0.000   0.000   1.00    0.500000    0.250000    0.250000
2005    0.0 1.0 0.0 2.0 2.0 1.0 1.0 5.0 0.000   1.000   0.00    0.400000    0.400000    0.200000
2006    1.0 0.0 0.0 3.0 2.0 1.0 1.0 6.0 1.000   0.000   0.00    0.500000    0.333333    0.166667
2007    0.0 1.0 1.0 3.0 3.0 2.0 2.0 8.0 0.000   0.500   0.50    0.375000    0.375000    0.250000
Total_Obs_per_Type  3.0 3.0 2.0 6.0 6.0 4.0 8.0 16.0    0.375   0.375   0.25    0.375000    0.375000    0.250000

This has the functionylity and flexibility i was looking for. But as i am still learning pandas suggestions for improvement are appreciated.


问:
Time difference query using MS SQL
I'm trying to take out difference between two times, first and second time using AM , PM
I've columns:

```<code>FirstTime    SecondTime
10:14:42 PM  1:05:25 AM.
</code>```

When i'm using DateDiff function it return wrong value and also i want access this in whole table not for single row and max is required on particular table

I've tried following queries:

```<code>select DATEDIFF(MINUTE, first_time, second_time) AS 'Duration'  FROM tbl_weight

SELECT max (DATEDIFF(MINUTE, first_time, second_time)) AS 'Duration' , sr_no
    FROM tbl_weight where first_weight != '0' and  second_weight != '0' group by sr_no  ;
</code>```

but in both it return wrong value.

答:
You can use case expression :

```<code>select case when convert(datetime, firsttime) < convert(datetime, secondtime)
            then dateadd(second, datediff(second, secondtime, firsttime), 0)
            else dateadd(second, datediff(second, firsttime, secondtime), 0)
       end
</code>```

Title: Time difference query using MS SQL

Body:
I'm trying to take out difference between two times, first and second time using AM , PM
I've columns:

FirstTime    SecondTime
10:14:42 PM  1:05:25 AM.

When i'm using DateDiff function it return wrong value and also i want access this in whole table not for single row and max is required on particular table

I've tried following queries:

select DATEDIFF(MINUTE, first_time, second_time) AS 'Duration'  FROM tbl_weight

SELECT max (DATEDIFF(MINUTE, first_time, second_time)) AS 'Duration' , sr_no
    FROM tbl_weight where first_weight != '0' and  second_weight != '0' group by sr_no  ;

but in both it return wrong value.

Body:
You can use case expression :

select case when convert(datetime, firsttime) < convert(datetime, secondtime)
            then dateadd(second, datediff(second, secondtime, firsttime), 0)
            else dateadd(second, datediff(second, firsttime, secondtime), 0)
       end


问:
Javascript: go to error page when any variable is undefined or null
I want to redirect to error page in the application , when any of the variable in the whole app is undefined or null.

Instead of crashing app, I want to redirect to error page.

Any help would be great.

Thank You.

答:
First of all, having a variable with a value of undefined or null is not necessarily an error. If in your case you consider it to be an error, you have two options in my opinion:

Use TypeScript and try-catch block

TypeScript does all the type-checking for you, and if you were careful with defining all the types correctly, an exception should be thrown when any of them becomes null or undefined, where you can then catch it inside a try-catch and redirect the user to the error page.

```<code>try {
  ...
} catch (Exception ex) {
  window.location.href = "https://www.example.com/error";
}
</code>```

Continuously check for values

If you are not into using TypeScript, you can do the checking manually, either every time interval:

```<code>setInterval(checkAllValues(), 1000)
</code>```

or upon certain operations that you suspect it might yield null or undefined.

```<code>let myValue = doSomeOperations();
if (myValue === undefined || myValue === null) {
  window.location.href = "https://www.example.com/error";
}
</code>```

This solution might not very practical, as it requires you to know all the variables and might need to keep a centralised store for keeping them, but it should work fine for simple projects.

Body:
First of all, having a variable with a value of undefined or null is not necessarily an error. If in your case you consider it to be an error, you have two options in my opinion:

Use TypeScript and try-catch block

TypeScript does all the type-checking for you, and if you were careful with defining all the types correctly, an exception should be thrown when any of them becomes null or undefined, where you can then catch it inside a try-catch and redirect the user to the error page.

try {
  ...
} catch (Exception ex) {
  window.location.href = "https://www.example.com/error";
}

Continuously check for values

If you are not into using TypeScript, you can do the checking manually, either every time interval:

setInterval(checkAllValues(), 1000)

or upon certain operations that you suspect it might yield null or undefined.

let myValue = doSomeOperations();
if (myValue === undefined || myValue === null) {
  window.location.href = "https://www.example.com/error";
}

This solution might not very practical, as it requires you to know all the variables and might need to keep a centralised store for keeping them, but it should work fine for simple projects.


问:
Can I preselect items in TYPO3's select elements in TCA?
I am configuring a custom backend field in pages TCA. There, I added a new select type field, with the renderType selectCheckBox. The items to be selected are filled via an itemsProcFunc that uses a custom PHP function.

Is there a way to preselect certain, or all of the items when returning them in the itemsProcFunc via $PA[items]?

答:
Two ways exist depending on use case:

For content records added added through the new content wizard, see pageTSconfig defValues (bottom of page https://docs.typo3.org/m/typo3/reference-tsconfig/master/en-us/PageTsconfig/Mod.html). This is not the implementation you should use, as you mention you want this to be done for the pages table, but I mention it for completeness in case other users come to this question through searches.

For any record type including content records, see FormEngine processors (which unfortunately are significantly harder to use) - https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/FormEngine/Rendering/Index.html


问:
What is default session timeout in ASP.NET?
What is the default session timeout value in ASP.NET?</p>

答:
It depends on either the configuration or programmatic change.

Therefore the most reliable way to check the current value is at runtime via code.

See the HttpSessionState.Timeout property; default value is 20 minutes.

You can access this propery in ASP.NET via HttpContext:

```<code>this.HttpContext.Session.Timeout // ASP.NET MVC controller
Page.Session.Timeout // ASP.NET Web Forms code-behind
HttpContext.Current.Session.Timeout // Elsewhere
</code>```

OwnerDisplayName: roushan

ContentLicense: CC BY-SA 2.5

Body:
It depends on either the configuration or programmatic change.

Therefore the most reliable way to check the current value is at runtime via code.

See the HttpSessionState.Timeout property; default value is 20 minutes.

You can access this propery in ASP.NET via HttpContext:

this.HttpContext.Session.Timeout // ASP.NET MVC controller
Page.Session.Timeout // ASP.NET Web Forms code-behind
HttpContext.Current.Session.Timeout // Elsewhere


问:
How to avoid error messages in Eclipse 2020-03 for GWT ui.xml files (Language Server)
In my GWT 2.8 based project Eclipse 2020-03 shows me lots of error message under Markers -> Language Servers
I am sure that these are not errors. For some reason, Eclipse cannot interpret ui.xml files correctly. The application compiles and runs fine:

My eclipse wide settings for XML validation are as follows:

There are not project-specific settings for this

Here is an extract (not the complete source!!!) of one example of a something.ui.xml file. The project contains lots of those files:

```<code><!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder
    xmlns:ui="urn:ui:com.google.gwt.uibinder"
    xmlns:g="urn:import:com.google.gwt.user.client.ui"
    xmlns:b="urn:import:org.gwtbootstrap3.client.ui"
    xmlns:a="urn:import:com.myapp.client.widgets"
    ui:generateFormat="com.google.gwt.i18n.rebind.format.PropertiesFormat"
    ui:generateKeys="com.google.gwt.i18n.server.keygen.MD5KeyGenerator"
    ui:generateLocales="default" >

<ui:with type="com.myapp.resources.text.CommonMessages" field="msgs" />
<ui:with type="com.myapp.resources.text.SummaryMessages" field="sMsgs" />

<b:Modal closable="true" fade="true" dataBackdrop="STATIC" dataKeyboard="true"
    b:id="dialog"
    ui:field="dialog">
    <b:ModalHeader title="{sMsgs.transferOwnership}" />
    <b:ModalBody>
        <g:HTML><ui:text from="{sMsgs.transferOwnershipDescription}"/></g:HTML>

        <b:ListBox
            ui:field="userListBox"
            multipleSelect="false"
            width="100%"
             />

        <b:Alert type="DANGER" ui:field="participantWarning">
            <b:Icon type="WARNING"/>
            <g:HTML><ui:text from="{sMsgs.transferOwnershipNotParticipantWarning}" /></g:HTML>
        </b:Alert>
    </b:ModalBody>
    <b:ModalFooter>
</code>```

These are the error messages:

Mouseover on the error always shows:

although it is declared above:
[...]

```<code>xmlns:b="urn:import:org.gwtbootstrap3.client.ui"
</code>```

[...]

Import: The application compiles and runs fine. So I just want to suppress those error messages (show in error) as they are not really error messages. :-)

These resources might be helpful:

Why are there multiple Angular language server tabs in my Eclipse console

答:
By "must be declared", it means declared in a Document Type Definition (DTD) or XML Schema, also known as "grammar".

The line you quoted:

```<code>xmlns:b="urn:import:org.gwtbootstrap3.client.ui"
</code>```

It says there's a namespace "b", but this line has no other meaning. It doesn't, for instance, declare which elements (like Alert) are valid in that namespace.

If you are not worried about validating your XML, and only wish to turn off the error messages, I would suggest you change your options:

No grammar specified: Warning → Ignore

This will stop Eclipse trying to validate the XML against a grammar, but should still show errors for malformed XML (tags closed twice etc.). You can configure this option on a per-project basis, if you prefer.

The alternative would be to provide a DTD or Schema and reference it in the XML. You will probably have to write such a grammar yourself unless gwtbootstrap3 provides one (which I don't think it does).

To clear existing validation errors, you may have to manually delete them.

Body:
In my GWT 2.8 based project Eclipse 2020-03 shows me lots of error message under Markers -> Language Servers
I am sure that these are not errors. For some reason, Eclipse cannot interpret ui.xml files correctly. The application compiles and runs fine:

My eclipse wide settings for XML validation are as follows:

There are not project-specific settings for this

Here is an extract (not the complete source!!!) of one example of a something.ui.xml file. The project contains lots of those files:

<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder
    xmlns:ui="urn:ui:com.google.gwt.uibinder"
    xmlns:g="urn:import:com.google.gwt.user.client.ui"
    xmlns:b="urn:import:org.gwtbootstrap3.client.ui"
    xmlns:a="urn:import:com.myapp.client.widgets"
    ui:generateFormat="com.google.gwt.i18n.rebind.format.PropertiesFormat"
    ui:generateKeys="com.google.gwt.i18n.server.keygen.MD5KeyGenerator"
    ui:generateLocales="default" >

<ui:with type="com.myapp.resources.text.CommonMessages" field="msgs" />
<ui:with type="com.myapp.resources.text.SummaryMessages" field="sMsgs" />

        <g:HTML><ui:text from="{sMsgs.transferOwnershipDescription}"/></g:HTML>

            <g:HTML><ui:text from="{sMsgs.transferOwnershipNotParticipantWarning}" /></g:HTML>

These are the error messages:

Mouseover on the error always shows:

although it is declared above:
[...]

xmlns:b="urn:import:org.gwtbootstrap3.client.ui"

[...]

Import: The application compiles and runs fine. So I just want to suppress those error messages (show in error) as they are not really error messages. :-)

These resources might be helpful:

Why are there multiple Angular language server tabs in my Eclipse console

Body:
By "must be declared", it means declared in a Document Type Definition (DTD) or XML Schema, also known as "grammar".

The line you quoted:

xmlns:b="urn:import:org.gwtbootstrap3.client.ui"

It says there's a namespace "b", but this line has no other meaning. It doesn't, for instance, declare which elements (like Alert) are valid in that namespace.

If you are not worried about validating your XML, and only wish to turn off the error messages, I would suggest you change your options:

No grammar specified: Warning → Ignore

This will stop Eclipse trying to validate the XML against a grammar, but should still show errors for malformed XML (tags closed twice etc.). You can configure this option on a per-project basis, if you prefer.

The alternative would be to provide a DTD or Schema and reference it in the XML. You will probably have to write such a grammar yourself unless gwtbootstrap3 provides one (which I don't think it does).

To clear existing validation errors, you may have to manually delete them.


问:
Pass id parameter in fetch query (ReactJS)
I am new in javscript development, and I have some trouble with passing id parameter in query URL.
I am passing ID value in body now, which is not right, I guess in REST approach.

How can I pass Id: event.target.DepartmentId.value, into URL like https://localhost:5001/api/departments/{id} ?

handleSubmit(event){
    event.preventDefault();
    fetch("https://localhost:5001/api/departments/", {
        method: "PUT",
        headers:{
            "Accept":"application/json",
            "Content-Type":"application/json",
            "Origin": "*"
        },
        body: JSON.stringify({
            Id: event.target.DepartmentId.value,
            Name: event.target.DepartmentName.value
        })
    })
    .then(res=>res.json())
    .then((result)=>
    {
        this.setState({snackbaropen: true, snackbarmsg: "Edited successfully!"})

    },
    (error) =>{
        this.setState({snackbaropen: true, snackbarmsg: "failed"})
    }
    )
}```

Thanks for any help!

答:
This worked. And the literals didn't.</p>

```<code>  localhost:5001/api/departments" + event.target.DepartmentId.value
</code>```

Body:
I am new in javscript development, and I have some trouble with passing id parameter in query URL.
I am passing ID value in body now, which is not right, I guess in REST approach.

How can I pass Id: event.target.DepartmentId.value, into URL like https://localhost:5001/api/departments/{id} ?

handleSubmit(event){
    event.preventDefault();
    fetch("https://localhost:5001/api/departments/", {
        method: "PUT",
        headers:{
            "Accept":"application/json",
            "Content-Type":"application/json",
            "Origin": "*"
        },
        body: JSON.stringify({
            Id: event.target.DepartmentId.value,
            Name: event.target.DepartmentName.value
        })
    })
    .then(res=>res.json())
    .then((result)=>
    {
        this.setState({snackbaropen: true, snackbarmsg: "Edited successfully!"})

    },
    (error) =>{
        this.setState({snackbaropen: true, snackbarmsg: "failed"})
    }
    )
}

Thanks for any help!

Body:
This worked. And the literals didn't.

  localhost:5001/api/departments" + event.target.DepartmentId.value


答:
Currently this fails because of parsing errors, as Python attempts to split up the input in some way.

No; the input is split up by your shell, before Python ever receives it.

is this a horrible idea?

Probably; you could probably come up with a scheme that lets users specify arbitrary data on the command line, working around standard shell parsing and following standard conventions for arguments, but it sounds like a lot of work - for both you and the user. As shown  in the other answer, it's also possible on the command line to quote the data and have it passed as a single token - but this gets unwieldy very quickly.

(If so, what should I do instead?)

You could have the user supply the name of a preferences file on the command line, and open, read and parse that. I would recommend that you use the JSON format (with built-in support from the standard library json module) rather than expecting Python literals.

Or if there are only a few options such as shown, you could follow standard command-line conventions. Your input line might look something like robot.py A --hours=24 --stations=15:17:21 --log (omitting log when no logging should be done). The standard library argparse module can help with parsing that sort of thing, although you'd have to make sense of the stations string yourself.

Title: Literal eval of Python object from command-line arg

Body:
I have a slightly messy pipeline whereby a Python script takes in some parameters from a user, stored internally as a dictionary:

{'robot': 'A', 'hours': 24, 'stations': [15, 17, 21], 'log': False}

and appends its string representation to a command to be run in a container

python robot.py {'robot': 'A', 'hours': 24, 'stations': [15, 17, 21], 'log': False}

In robot.py (inside the container), I'd like to parse it like this:

import sys
from ast import literal_eval

if __name__ == '__main__':
    params = literal_eval(sys.argv[1])
    do_stuff(params)

Currently this fails because of parsing errors, as Python attempts to split up the input in some way.

Two questions:

is this a horrible idea? (If so, what should I do instead?)

if not, how can I literal_eval the dict as one argument? I expect to get lists, booleans, strings, ints, etc. as params.