问:
Using removeClass to adjust css on div not working
I am passing the value from a dropdwon to then show and hide a seperate div and to also add/remove a class to the same element. The show/hide works fine but the new class added (mine) is added but not removed.

Does anyone know how to remove the class when div is hidden, using code below?

```<code>$(this).find("option:selected").each(function(){
            var optionValue = $(this).attr("value");
            if(optionValue){
                $(".details-tcs").not("." + optionValue).hide();
                $("." + optionValue).show();
                $("." + optionValue).addClass("mine");

            } else{
                $(".details-tcs").hide();
                $(".details-tcs").removeClass("mine");
            }
        });
</code>```

Here is what I get when I change the dropdown around.

```<code><div class="details-tcs SC mine" style="display: none;">
stuff
</div>
<div class="details-tcs AI mine" style="display: block;">
stuff
</div>
<div class="details-tcs BB mine" style="display: none;">
stuff
</div>
</code>```

It leaves the 'mine' showing once added.

The dropdown value is either SC, or AI or BB from -

```<code>jQuery("select").change(function()
</code>```

答:
The attribute value is not updated on an element when its value changes; it serves only as initial value. That means if your select elements are initially empty, $(this).attr("value"); gets you "" (an empty string). When coerced to a Boolean, as in if (optionValue), an empty string is evaluated to false. If it does have an initial value, that attribute is never going to change, so $(this).attr("value"); will always return a non-empty string, which, when coerced to a Boolean as in if (optionValue), evaluates to true.

You are probably looking for the property value instead:

```<code>var optionValue = $(this).prop("value");
</code>```

Body:
I am passing the value from a dropdwon to then show and hide a seperate div and to also add/remove a class to the same element. The show/hide works fine but the new class added (mine) is added but not removed.

Does anyone know how to remove the class when div is hidden, using code below?

$(this).find("option:selected").each(function(){
            var optionValue = $(this).attr("value");
            if(optionValue){
                $(".details-tcs").not("." + optionValue).hide();
                $("." + optionValue).show();
                $("." + optionValue).addClass("mine");

            } else{
                $(".details-tcs").hide();
                $(".details-tcs").removeClass("mine");
            }
        });

Here is what I get when I change the dropdown around.

stuff

stuff

stuff

It leaves the 'mine' showing once added.

The dropdown value is either SC, or AI or BB from -

jQuery("select").change(function()

Body:
The attribute value is not updated on an element when its value changes; it serves only as initial value. That means if your select elements are initially empty, $(this).attr("value"); gets you "" (an empty string). When coerced to a Boolean, as in if (optionValue), an empty string is evaluated to false. If it does have an initial value, that attribute is never going to change, so $(this).attr("value"); will always return a non-empty string, which, when coerced to a Boolean as in if (optionValue), evaluates to true.

You are probably looking for the property value instead:

var optionValue = $(this).prop("value");


来源: stackexchange

问:
Python Pandas: Error tokenizing data. C error: EOF inside string starting when reading 1GB CSV file
I'm reading a 1 GB CSV file in chunks of 10,000 rows. The file has 1106012 rows and 171 columns, other smaller sized file does not show any error and finish off successfully but when i read this 1 GB file it shows error every time on exactly line number 1106011 which is a second last line of file, i can manually remove that line but that is not the solution because i have hundreds of other file of that same size and i cannot fix all the lines manually. can anyone help me with that please.

```<code>def extract_csv_to_sql(input_file_name, header_row, size_of_chunk, eachRow):

        df = pd.read_csv(input_file_name,
                         header=None,
                         nrows=size_of_chunk,
                         skiprows=eachRow,
                         low_memory=False,
                         error_bad_lines=False,
                         sep=',')
                         # engine='python'
                         # quoting=csv.QUOTE_NONE
                         # encoding='utf-8'

        df.columns = header_row
        df = df.drop_duplicates(keep='first')
        df = df.apply(lambda x: x.astype(str).str.lower())

        return df
</code>```

I'm then calling this function within a loop and works just fine.

```<code>huge_chunk_return = extract_csv_to_sql(huge_input_filename, huge_header_row, the_size_of_chunk_H, each_Row_H)
</code>```

I read this Pandas ParserError EOF character when reading multiple csv files to HDF5, this read_csv() & EOF character in string cause parsing issue and this https://github.com/pandas-dev/pandas/issues/11654 and many more and tried to include read_csv parameter such as

engine='python'

quoting=csv.QUOTE_NONE // Hangs and even the python shell, don't know why

encoding='utf-8'

but none of it worked, its still throwing the following error

Error:

```<code>Traceback (most recent call last):
  File "C:\Users\WCan\Desktop\wcan_new_python\pandas_test_3.py", line 115, in <module>
    huge_chunk_return = extract_csv_to_sql(huge_input_filename, huge_header_row, the_size_of_chunk_H, each_Row_H)
  File "C:\Users\WCan\Desktop\wcan_new_python\pandas_test_3.py", line 24, in extract_csv_to_sql
    sep=',')
  File "C:\Users\WCan\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\io\parsers.py", line 655, in parser_f
    return _read(filepath_or_buffer, kwds)
  File "C:\Users\WCan\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\io\parsers.py", line 411, in _read
    data = parser.read(nrows)
  File "C:\Users\WCan\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\io\parsers.py", line 1005, in read
    ret = self._engine.read(nrows)
  File "C:\Users\WCan\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\io\parsers.py", line 1748, in read
    data = self._reader.read(nrows)
  File "pandas\_libs\parsers.pyx", line 893, in pandas._libs.parsers.TextReader.read (pandas\_libs\parsers.c:10885)
  File "pandas\_libs\parsers.pyx", line 966, in pandas._libs.parsers.TextReader._read_rows (pandas\_libs\parsers.c:11884)
  File "pandas\_libs\parsers.pyx", line 953, in pandas._libs.parsers.TextReader._tokenize_rows (pandas\_libs\parsers.c:11755)
  File "pandas\_libs\parsers.pyx", line 2184, in pandas._libs.parsers.raise_parser_error (pandas\_libs\parsers.c:28765)
pandas.errors.ParserError: Error tokenizing data. C error: EOF inside string starting at line 1106011
>>>
</code>```

答:
I inquired many solutions, some of them worked but It affected the calculous used this one and it will skip the line that is causing the error:

```<code>pd.read_csv(file,engine='python', error_bad_lines=False)
</code>```

#engine='python' provides a better output

ContentLicense: CC BY-SA 3.0

Body:
I'm reading a 1 GB CSV file in chunks of 10,000 rows. The file has 1106012 rows and 171 columns, other smaller sized file does not show any error and finish off successfully but when i read this 1 GB file it shows error every time on exactly line number 1106011 which is a second last line of file, i can manually remove that line but that is not the solution because i have hundreds of other file of that same size and i cannot fix all the lines manually. can anyone help me with that please.

def extract_csv_to_sql(input_file_name, header_row, size_of_chunk, eachRow):

        df = pd.read_csv(input_file_name,
                         header=None,
                         nrows=size_of_chunk,
                         skiprows=eachRow,
                         low_memory=False,
                         error_bad_lines=False,
                         sep=',')
                         # engine='python'
                         # quoting=csv.QUOTE_NONE
                         # encoding='utf-8'

        df.columns = header_row
        df = df.drop_duplicates(keep='first')
        df = df.apply(lambda x: x.astype(str).str.lower())

        return df

I'm then calling this function within a loop and works just fine.

huge_chunk_return = extract_csv_to_sql(huge_input_filename, huge_header_row, the_size_of_chunk_H, each_Row_H)

I read this Pandas ParserError EOF character when reading multiple csv files to HDF5, this read_csv() & EOF character in string cause parsing issue and this https://github.com/pandas-dev/pandas/issues/11654 and many more and tried to include read_csv parameter such as

engine='python'

quoting=csv.QUOTE_NONE // Hangs and even the python shell, don't know why

encoding='utf-8'

but none of it worked, its still throwing the following error

Error:

Traceback (most recent call last):
  File "C:\Users\WCan\Desktop\wcan_new_python\pandas_test_3.py", line 115, in <module>
    huge_chunk_return = extract_csv_to_sql(huge_input_filename, huge_header_row, the_size_of_chunk_H, each_Row_H)
  File "C:\Users\WCan\Desktop\wcan_new_python\pandas_test_3.py", line 24, in extract_csv_to_sql
    sep=',')
  File "C:\Users\WCan\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\io\parsers.py", line 655, in parser_f
    return _read(filepath_or_buffer, kwds)
  File "C:\Users\WCan\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\io\parsers.py", line 411, in _read
    data = parser.read(nrows)
  File "C:\Users\WCan\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\io\parsers.py", line 1005, in read
    ret = self._engine.read(nrows)
  File "C:\Users\WCan\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\io\parsers.py", line 1748, in read
    data = self._reader.read(nrows)
  File "pandas\_libs\parsers.pyx", line 893, in pandas._libs.parsers.TextReader.read (pandas\_libs\parsers.c:10885)
  File "pandas\_libs\parsers.pyx", line 966, in pandas._libs.parsers.TextReader._read_rows (pandas\_libs\parsers.c:11884)
  File "pandas\_libs\parsers.pyx", line 953, in pandas._libs.parsers.TextReader._tokenize_rows (pandas\_libs\parsers.c:11755)
  File "pandas\_libs\parsers.pyx", line 2184, in pandas._libs.parsers.raise_parser_error (pandas\_libs\parsers.c:28765)
pandas.errors.ParserError: Error tokenizing data. C error: EOF inside string starting at line 1106011
>>>

Body:
I inquired many solutions, some of them worked but It affected the calculous used this one and it will skip the line that is causing the error:

pd.read_csv(file,engine='python', error_bad_lines=False)

#engine='python' provides a better output

ContentLicense: CC BY-SA 4.0


问:
Pandas: How to store cProfile output in a pandas DataFrame?
There already exist some posts discussing python profiling using cProfile, as well as the challenges of analyzing the output due to the fact that the output file restats from the sample code below is not a plain text file. The snippet below is only a sample from docs.python.org/2/library/profile, and not directly reproducible.

```<code>import cProfile
import re
cProfile.run('re.compile("foo|bar")', 'restats')
</code>```

There is one discussion here: Profile a python script using cProfile into an external file, and on the docs.python.org there are more details on how to analyze the output using pstats.Stats (still only a sample, and not reproducible):

```<code>import pstats
p = pstats.Stats('restats')
p.strip_dirs().sort_stats(-1).print_stats()
</code>```

I may be missing some very important details here, but I would really like to store the output in a pandas DataFrame and do further analysis from there.

I thought it would be pretty simple since the output in iPython from running cProfile.run() looks fairly tidy:

```<code>In[]:
cProfile.run('re.compile("foo|bar")'

Out[]:
</code>```

Any suggestions on how to get this into a pandas DataFrame in the same format?

答:
I know this already has an answer, but for anyone who doesn't want to go to the trouble of downloading another module, here's a rough and ready script that should get close:

```<code>%%capture profile_results    ## uses %%capture magic to send stdout to variable
cProfile.run("your_function( **run_parms )")
</code>```

Run the above first, to populate profile_results with the contents of stout, which contains the usual printed output of cProfile.

```<code>## Parse the stdout text and split it into a table
data=[]
started=False

for l in profile_results.stdout.split("\n"):
    if not started:
        if l=="   ncalls  tottime  percall  cumtime  percall filename:lineno(function)":
            started=True
            data.append(l)
    else:
        data.append(l)
content=[]
for l in data:
    fs = l.find(" ",8)
    content.append(tuple([l[0:fs] , l[fs:fs+9], l[fs+9:fs+18], l[fs+18:fs+27], l[fs+27:fs+36], l[fs+36:]]))
prof_df = pd.DataFrame(content[1:], columns=content[0])
</code>```

It wont win any prizes for elegance or pleasant style, but it does force that table of results into a filterable dataframe format.

```<code>prof_df
</code>```

Body:
There already exist some posts discussing python profiling using cProfile, as well as the challenges of analyzing the output due to the fact that the output file restats from the sample code below is not a plain text file. The snippet below is only a sample from docs.python.org/2/library/profile, and not directly reproducible.

import cProfile
import re
cProfile.run('re.compile("foo|bar")', 'restats')

There is one discussion here: Profile a python script using cProfile into an external file, and on the docs.python.org there are more details on how to analyze the output using pstats.Stats (still only a sample, and not reproducible):

import pstats
p = pstats.Stats('restats')
p.strip_dirs().sort_stats(-1).print_stats()

I may be missing some very important details here, but I would really like to store the output in a pandas DataFrame and do further analysis from there.

I thought it would be pretty simple since the output in iPython from running cProfile.run() looks fairly tidy:

In[]:
cProfile.run('re.compile("foo|bar")'

Out[]:

Any suggestions on how to get this into a pandas DataFrame in the same format?

Body:
I know this already has an answer, but for anyone who doesn't want to go to the trouble of downloading another module, here's a rough and ready script that should get close:

%%capture profile_results    ## uses %%capture magic to send stdout to variable
cProfile.run("your_function( **run_parms )")

Run the above first, to populate profile_results with the contents of stout, which contains the usual printed output of cProfile.

## Parse the stdout text and split it into a table
data=[]
started=False

for l in profile_results.stdout.split("\n"):
    if not started:
        if l=="   ncalls  tottime  percall  cumtime  percall filename:lineno(function)":
            started=True
            data.append(l)
    else:
        data.append(l)
content=[]
for l in data:
    fs = l.find(" ",8)
    content.append(tuple([l[0:fs] , l[fs:fs+9], l[fs+9:fs+18], l[fs+18:fs+27], l[fs+27:fs+36], l[fs+36:]]))
prof_df = pd.DataFrame(content[1:], columns=content[0])

It wont win any prizes for elegance or pleasant style, but it does force that table of results into a filterable dataframe format.

prof_df


问:
"infinite" sql statement?
I've got a very strange sql-related problem.

I'm accessing a MSSQL Server 2005 with PHP (odbc), when I profile the sql statement the following is executed:

```<code>declare @p1 int
set @p1=180150003
declare @p3 int
set @p3=2
declare @p4 int
set @p4=1
declare @p5 int
set @p5=-1
exec sp_cursoropen @p1 output,N'SELECT  fieldA,  fieldB, fieldC, fieldD, fieldE FROM mytable WHERE fieldB IS NULL',@p3 output,@p4 output,@p5 output
select @p1, @p3, @p4, @p5

exec sp_cursorfetch 180150003,2,1,1
</code>```

On my own server it's working fine, on the customer-server the sp_cursorfetch reads infinite rows and loads the full cpu.
When I try to execute the statement itself

```<code>SELECT  fieldA,  fieldB, fieldC, fieldD, fieldE FROM mytable WHERE fieldB IS NULL
</code>```

in SQL Server Management Studio it works fine (under 1sec).

Any ideas?

Edit:
the main difference between the servers is that my server is a x86 (Win2003) and the server of the customer is a x64 (Win2008).

Edit2: Added Where-Clause

答: There's no WHERE clause in that SELECT statement, so you'll be doing a table scan over every row in that table.  If your customer has many more rows than your local server, that would explain the time discrepancy.</p>

OwnerDisplayName: chris

ContentLicense: CC BY-SA 2.5

Title: "infinite" sql statement?

Body:
I've got a very strange sql-related problem.

I'm accessing a MSSQL Server 2005 with PHP (odbc), when I profile the sql statement the following is executed:

declare @p1 int
set @p1=180150003
declare @p3 int
set @p3=2
declare @p4 int
set @p4=1
declare @p5 int
set @p5=-1
exec sp_cursoropen @p1 output,N'SELECT  fieldA,  fieldB, fieldC, fieldD, fieldE FROM mytable WHERE fieldB IS NULL',@p3 output,@p4 output,@p5 output
select @p1, @p3, @p4, @p5

exec sp_cursorfetch 180150003,2,1,1

On my own server it's working fine, on the customer-server the sp_cursorfetch reads infinite rows and loads the full cpu.
When I try to execute the statement itself

SELECT  fieldA,  fieldB, fieldC, fieldD, fieldE FROM mytable WHERE fieldB IS NULL

in SQL Server Management Studio it works fine (under 1sec).

Any ideas?

Edit:
the main difference between the servers is that my server is a x86 (Win2003) and the server of the customer is a x64 (Win2008).

Edit2: Added Where-Clause

LastEditorDisplayName: DJ


问:
browser specific css attributes
Where can I find a complete "browser specific css attributes" reference?

I mean some attributes such as -moz-border-radius that is just for Firefox or -webkit-min-device-pixel-ratio. These examples work just in a specified web browser. I want a complete reference for these attributes.

答:
You can take a look at this page: http://caniuse.com/

It also shows most, if not all, HTML5 and CSS3 features and their support.

Title: browser specific css attributes


问:
Refresh data in a JLabel
I have a program which calculates an integer and then uses the value within a JLabel. On intital creation everything is fine with the initialized value, but when I change the value of the int within the label I can't seem to find a way to update the JLabel. The relevant code is as follows:

```<code>    JLabel carbLbl;
    int totCarbs = 0;

    public Main() {
        carbLbl = new JLabel("Total Carbs: " + totCarbs);
        carbLbl.setFont(new Font("KidSans", Font.PLAIN, 38));
        carbLbl.setAlignmentX(Component.RIGHT_ALIGNMENT);

    void addFoodToTable() {
        String[] s = new String[3];
        s = (String[]) foodData.get(foodChoice.getSelectedIndex());
        foodList.addRow(s);
        totCarbs += Integer.parseInt(s[2]);
        carbLbl.repaint();
    }
}
</code>```

There's obviously much more code, but it's too long to include the entire script. Is there a way I can have the label update whenever I invoke the addFoodToTable() method?

答:
Is there not a way to simply update the JLabel using the initial constructor parameters?

```<code>carbLbl = new JLabel("Total Carbs: " + totCarbs);
</code>```

What parameters? There is only a single parameter, the String to be displayed.

The compiler concatenates the hard coded String with the value of your "totCarbs" variable to create a single String.

The compiler will essentially treat the above code like:

```<code>String text = "Total Carbs" + totCarbs;
carbLbl = new JLabel( text );
</code>```

The JLabel has no idea how the String was created (ie. that a variable was used to build the string).

I understand the concept of concatenation, but I just feel like that's a workaround

It is not a work around. The API of the setText(...) method states you provide a single String. So, if you want to update the label you need to provide the entire String.

Title: Refresh data in a JLabel

Body:
I have a program which calculates an integer and then uses the value within a JLabel. On intital creation everything is fine with the initialized value, but when I change the value of the int within the label I can't seem to find a way to update the JLabel. The relevant code is as follows:

    JLabel carbLbl;
    int totCarbs = 0;

    public Main() {
        carbLbl = new JLabel("Total Carbs: " + totCarbs);
        carbLbl.setFont(new Font("KidSans", Font.PLAIN, 38));
        carbLbl.setAlignmentX(Component.RIGHT_ALIGNMENT);

    void addFoodToTable() {
        String[] s = new String[3];
        s = (String[]) foodData.get(foodChoice.getSelectedIndex());
        foodList.addRow(s);
        totCarbs += Integer.parseInt(s[2]);
        carbLbl.repaint();
    }
}

There's obviously much more code, but it's too long to include the entire script. Is there a way I can have the label update whenever I invoke the addFoodToTable() method?

Body:
Is there not a way to simply update the JLabel using the initial constructor parameters?

carbLbl = new JLabel("Total Carbs: " + totCarbs);

What parameters? There is only a single parameter, the String to be displayed.

The compiler concatenates the hard coded String with the value of your "totCarbs" variable to create a single String.

The compiler will essentially treat the above code like:

String text = "Total Carbs" + totCarbs;
carbLbl = new JLabel( text );

The JLabel has no idea how the String was created (ie. that a variable was used to build the string).

I understand the concept of concatenation, but I just feel like that's a workaround

It is not a work around. The API of the setText(...) method states you provide a single String. So, if you want to update the label you need to provide the entire String.


问:
Difference between const reference and pass by value in c++?
If I have a function with all const references as arguments and another function with values...so in both the cases value will not get modified..so why is it preferred to use const reference?</p>

答: Passing by value, basicaly creates a local copy of the argument, so passing by reference is better, but you might want to avoid the function to alter the variable you pass by reference, let's say you just want to print it on the screen, then you mark it as const so it cannot be changed, and you avoid copying it making your program a bit more efficient. There can be other reasons to pass by reference, like, for instance, if some object cannot be copied.


问:
merge and update not present values
I am trying to merge two dataframes such that if any not columns present in df1's variables source should take from df2's rows. I tried the merge below but no works. Please help.

```<code>df1 <- data.frame(source = c("Pr1", "Pr2","Pr3"),
                     date = c("Jan 2018","Feb 2018","Mar 2018"),
                     Freq = c(100,20,30))
df2 <- data.frame(source = c("Pr1","Pr2","Pr1"),
                     date = c("Sep 2018","Aug 2018","Jan 2018"),
                     Freq = c(0,0,0))

df <- merge(df1,df2,by = c("source","date"))
</code>```

Expected Output:

```<code>  source     date Freq
1    Pr1 Jan 2018  100
2    Pr2 Feb 2018   20
3    Pr3 Mar 2018   30
4    Pr1 Sep 2018    0
5    Pr2 Aug 2018    0
</code>```

答:
Maybe you can set all = TRUE when you used merge and apply aggregate for update, i.e.,

```<code>df <- aggregate(Freq~.,merge(df1,df2,all = TRUE),FUN = max)
</code>```

such that

```<code>> df
  source     date Freq
1    Pr2 Feb 2018   20
2    Pr1 Jan 2018  100
3    Pr3 Mar 2018   30
4    Pr2 Aug 2018    0
5    Pr1 Sep 2018    0
</code>```

Title: merge and update not present values

Body:
I am trying to merge two dataframes such that if any not columns present in df1's variables source should take from df2's rows. I tried the merge below but no works. Please help.

df1 <- data.frame(source = c("Pr1", "Pr2","Pr3"),
                     date = c("Jan 2018","Feb 2018","Mar 2018"),
                     Freq = c(100,20,30))
df2 <- data.frame(source = c("Pr1","Pr2","Pr1"),
                     date = c("Sep 2018","Aug 2018","Jan 2018"),
                     Freq = c(0,0,0))

df <- merge(df1,df2,by = c("source","date"))

Expected Output:

  source     date Freq
1    Pr1 Jan 2018  100
2    Pr2 Feb 2018   20
3    Pr3 Mar 2018   30
4    Pr1 Sep 2018    0
5    Pr2 Aug 2018    0

Body:
Maybe you can set all = TRUE when you used merge and apply aggregate for update, i.e.,

df <- aggregate(Freq~.,merge(df1,df2,all = TRUE),FUN = max)

such that

> df
  source     date Freq
1    Pr2 Feb 2018   20
2    Pr1 Jan 2018  100
3    Pr3 Mar 2018   30
4    Pr2 Aug 2018    0
5    Pr1 Sep 2018    0


问:
MongoDB slice array and retrieve only that array field in projection
I have a mongodb schema where documents are as per below structure ,

```<code>{"_id":"5e4aaadefrbff2150c42ed5b",
"data":[{"time":"15:24:31","amount":"34"},{"time":"15:24:33","amount":"38"},,{"time":"15:24:35","amount":"95"}],
"code":"S04",
"rollnumber":4,
"intime":"2020-02-16T12:24:21.921Z"}
</code>```

And in my node.js code i am fetching data in this way to find the last array value,

```<code>mycollection.find({ code: "S04", rollnumber: 4 }, { "_id": 0, code: 0, rollnumber: 0, intime: 0, data: { $slice: -1 } }, (err, result) => {
            if (err) { console.log('err', err); }
            console.log(result)
            res.json(result);
        });
</code>```

The problem is, i want only array result hence put all other keys:0 . It doesn't work when i put only data:1, data: { $slice: -1 }

It works when in put data:1 without slice operator. In production the list is going to be a big so i can not put all the keys with :0 in query. Please suggest how to put $slice  with :1 to display only filtered array.

答:
It doesn't work like that, if you include _id it should work, but it you just need data then alternatively you can try this :

```<code>db.collection.aggregate([
              {$match : {code: "S04", rollnumber: 4}},
              {$project : { _id :0, data : {$slice : [ "$data", -1 ]}}}
])
</code>```

Test : MongoDB-Playground

Body:
I have a mongodb schema where documents are as per below structure ,

{"_id":"5e4aaadefrbff2150c42ed5b",
"data":[{"time":"15:24:31","amount":"34"},{"time":"15:24:33","amount":"38"},,{"time":"15:24:35","amount":"95"}],
"code":"S04",
"rollnumber":4,
"intime":"2020-02-16T12:24:21.921Z"}

And in my node.js code i am fetching data in this way to find the last array value,

mycollection.find({ code: "S04", rollnumber: 4 }, { "_id": 0, code: 0, rollnumber: 0, intime: 0, data: { $slice: -1 } }, (err, result) => {
            if (err) { console.log('err', err); }
            console.log(result)
            res.json(result);
        });

The problem is, i want only array result hence put all other keys:0 . It doesn't work when i put only data:1, data: { $slice: -1 }

It works when in put data:1 without slice operator. In production the list is going to be a big so i can not put all the keys with :0 in query. Please suggest how to put $slice  with :1 to display only filtered array.

Body:
It doesn't work like that, if you include _id it should work, but it you just need data then alternatively you can try this :

db.collection.aggregate([
              {$match : {code: "S04", rollnumber: 4}},
              {$project : { _id :0, data : {$slice : [ "$data", -1 ]}}}
])

Test : MongoDB-Playground


问:
Does putting a command in single quotes have any effect in a bash script?
I've stumbled upon a script where the author puts every external command (that is not a builtin or function) in single quotes. As I have never seen that coding style before, I'm wondering, it there any difference between the following two examples:

'cat' $myfile

vs.

cat $myfile

Please ignore the fact that the author chose not to quote the variable holding the file name. I would definitely put that in double quotes and I'm aware of the effect of quotes around the variable. I'm merely interested in whether the quotes around the command have any effect. Both examples work fine, but it is my understanding that the single quotes are superfluous here. Is that correct?

Thanks!

答:
Yes, it has an effect, though mostly for a really arcane reason:

Consider this weird construct

```<code>alias cat='echo x'
cat foo # would output x foo
'cat' foo # Would output the content of the file foo
</code>```

Putting it inside quotes causes bash not to run the alias. One could have achieved this effect also with

```<code>command cat foo # Also outputs the file foo
</code>```

The difference is that putting the command in quotes only skips alias definitions, while using command would also skip a function definition. Since aliases are usually not enabled in scripts, using the quotes are rarely of use.

Body:
Yes, it has an effect, though mostly for a really arcane reason:

Consider this weird construct

alias cat='echo x'
cat foo # would output x foo
'cat' foo # Would output the content of the file foo

Putting it inside quotes causes bash not to run the alias. One could have achieved this effect also with

command cat foo # Also outputs the file foo

The difference is that putting the command in quotes only skips alias definitions, while using command would also skip a function definition. Since aliases are usually not enabled in scripts, using the quotes are rarely of use.


问:
how can i solve this problem with Node package manager?
I try to run this install:

npm install nw@0.44.1-sdk nw-builder -D
```

<p>But it gives me this problem. if I try to install another package, I don't get this message.</p>

<p>I also clear npm cache and delete node_modules</p>

<p>And I also setup company proxy</p>

<blockquote>
  <pre class="lang-none prettyprint-override"><code>tunneling socket could not be established, statusCode=407
npm WARN test@1.0.0 No description
npm WARN test@1.0.0 No repository field.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! nw@0.44.1-sdk postinstall: `node scripts/install.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the nw@0.44.1-sdk postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\H90431283\AppData\Roaming\npm-cache\_logs\2020-02-18T14_48_15_391Z-debug.log
</code>```

答:
According to this answer, the problem relies on proxy configuration. You need to properly setup NPM proxy configuration:

```<code>npm config set proxy http://yourproxyaddress:port
npm config set https-proxy http://yourproxyaddress:port
npm config set strict-ssl false
</code>```

Fully featured discussion is to be found on Github: https://github.com/sass/node-sass/issues/2202

Body:
I try to run this install:

npm install nw@0.44.1-sdk nw-builder -D

But it gives me this problem. if I try to install another package, I don't get this message.

I also clear npm cache and delete node_modules

And I also setup company proxy

tunneling socket could not be established, statusCode=407
npm WARN test@1.0.0 No description
npm WARN test@1.0.0 No repository field.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! nw@0.44.1-sdk postinstall: `node scripts/install.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the nw@0.44.1-sdk postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\H90431283\AppData\Roaming\npm-cache\_logs\2020-02-18T14_48_15_391Z-debug.log

Body:
According to this answer, the problem relies on proxy configuration. You need to properly setup NPM proxy configuration:

npm config set proxy http://yourproxyaddress:port
npm config set https-proxy http://yourproxyaddress:port
npm config set strict-ssl false

Fully featured discussion is to be found on Github: https://github.com/sass/node-sass/issues/2202


问:
check or change keyboard typing language from server or client side
how can we check or change keyboard typing language from server or client side ?</p>

答:
Not exactly what you want but...

You could fake it by intercepting the keypress of your user in client-side javascript and then adding characters to the textbox in javascript.


问:
s3 images not loading after copying it from one bucket to another of same account
I have copied images from one bucket to another and now i am unable to access images. Error shows
AccessDenied message.

I have verified file exists in bucket but unable to access it. If i remove same image and upload it again then it is working.

Please suggest any reason if anything i missed during copying bucket data from one to another.

Link which was working with old bucket and now not accessible with new bucket

```<code>https://abc.s3.amazonaws.com/uploads/profile/image/16923/client_thumb_CINDERELLA_12
</code>```

答:
Copy (or whatever put action) in S3 is by default private because that's the deault ACL behavior, see here. This is why you get access denied even though the source file has public access enabled. Therefore you need to specify the ACL to public-read during the copy, in your case (cli sample):

```<code>aws s3 cp s3://mySourceBucket/test.txt s3://myDestinationBucket/test.txt --acl public-read
</code>```

Note that according to AWS, if you use --acl, your IAM policy must include the S3:PutObjectAcl action.

--acl (string) Sets the ACL for the object when the command is performed. If you use this parameter you must have the "s3:PutObjectAcl" permission included in the list of actions for your IAM policy. Only accepts values of private, public-read, public-read-write, authenticated-read, aws-exec-read, bucket-owner-read, bucket-owner-full-control and log-delivery-write. See Canned ACL for details

Body:
I have copied images from one bucket to another and now i am unable to access images. Error shows
AccessDenied message.

I have verified file exists in bucket but unable to access it. If i remove same image and upload it again then it is working.

Please suggest any reason if anything i missed during copying bucket data from one to another.

Link which was working with old bucket and now not accessible with new bucket

https://abc.s3.amazonaws.com/uploads/profile/image/16923/client_thumb_CINDERELLA_12

Body:
Copy (or whatever put action) in S3 is by default private because that's the deault ACL behavior, see here. This is why you get access denied even though the source file has public access enabled. Therefore you need to specify the ACL to public-read during the copy, in your case (cli sample):

aws s3 cp s3://mySourceBucket/test.txt s3://myDestinationBucket/test.txt --acl public-read

Note that according to AWS, if you use --acl, your IAM policy must include the S3:PutObjectAcl action.

--acl (string) Sets the ACL for the object when the command is performed. If you use this parameter you must have the "s3:PutObjectAcl" permission included in the list of actions for your IAM policy. Only accepts values of private, public-read, public-read-write, authenticated-read, aws-exec-read, bucket-owner-read, bucket-owner-full-control and log-delivery-write. See Canned ACL for details


问:
read Local audio file STT Google speech-to-text
I don't find how to send a local file using the Google STT in curl command line.
As followed in their tuto, here my request.json :

```<code>{
"config": {
      "encoding":"FLAC",
      "sample_rate": 16000,
      "language_code": "fr-FR"
  },
  "audio": {
      "uri":"audio-file.flac"
  }
}
</code>```

my command line is:

```<code>curl -s -X POST -H "Content-Type: application/json" --data-binary @request.json "https://speech.googleapis.com/v1beta1/speech:syncrecognize?key=MY_API_KEY"
</code>```

But I receive the error result:

```<code>{
  "error": {
    "code": 400,
    "message": "RecognitionAudio not set.",
    "status": "INVALID_ARGUMENT"
  }
}
</code>```

How can I write the request.json to send a local audio file ??
Thanks for help
:)

答:
Google doesn't provide an option to specify local file path in json object while using curl command.We are require to convert audio file into base64 and pass the output into json object

```<code> base64 source_audio_file -w 0 > dest_base64_audio_file_content
</code>```

Alternatively one of the best approach to pass localfile is to use gcloud ml command.

```<code>gcloud ml speech recognize 'Clip48_Mike.wav' --language-code='en-US'
</code>```

Example:

NOTE:
Following command to activate gcloud account if not already done.

```<code>gcloud auth activate-service-account --key-file /tmp/account-name.json
</code>```

Body:
I don't find how to send a local file using the Google STT in curl command line.
As followed in their tuto, here my request.json :

{
"config": {
      "encoding":"FLAC",
      "sample_rate": 16000,
      "language_code": "fr-FR"
  },
  "audio": {
      "uri":"audio-file.flac"
  }
}

my command line is:

curl -s -X POST -H "Content-Type: application/json" --data-binary @request.json "https://speech.googleapis.com/v1beta1/speech:syncrecognize?key=MY_API_KEY"

But I receive the error result:

{
  "error": {
    "code": 400,
    "message": "RecognitionAudio not set.",
    "status": "INVALID_ARGUMENT"
  }
}

How can I write the request.json to send a local audio file ??
Thanks for help
:)

Body:
Google doesn't provide an option to specify local file path in json object while using curl command.We are require to convert audio file into base64 and pass the output into json object

 base64 source_audio_file -w 0 > dest_base64_audio_file_content

Alternatively one of the best approach to pass localfile is to use gcloud ml command.

gcloud ml speech recognize 'Clip48_Mike.wav' --language-code='en-US'

Example:

NOTE:
Following command to activate gcloud account if not already done.

gcloud auth activate-service-account --key-file /tmp/account-name.json


问:
Should I create optimized UIImages before viewing them in SwiftUI?
I have an app that has to show multiple images that are large in dimension, which can use up lots of memory.

I'm only familiar with SwiftUI and don't have much experience using UIKit, but according to this WWDC's iOS Memory Deep Dive presentation: there are multiple ways you can reduce memory usage when rendering images in UIKit.

Its possible because rendering images in UIKit takes multiple steps which allows more room for modifications and gives you more flexibility, but in SwiftUI, it's so simple there is not as much room for modifications:

```<code>Image("image name")
                .resizable()
                .frame(width:100,height:100)
</code>```

So does SwiftUI already optimized the image's dimensions and color space with the above code, or is it more memory efficient to use UIKit to optimize the image, then pass the optimized UIImage to SwiftUI for viewing?

Is using UIImages rendered (and optimized) from UIKit for image viewing SwiftUI overall a better practice than just using Image("image name")?

Any answer would be appreciated.

答:
You can use any of

```<code>init(nsImage: NSImage)
</code>```

or

```<code>init(uiImage: UIImage)
</code>```

to take advantage of all knowledge you already have from UIKit or AppKit

Body:
I have an app that has to show multiple images that are large in dimension, which can use up lots of memory.

I'm only familiar with SwiftUI and don't have much experience using UIKit, but according to this WWDC's iOS Memory Deep Dive presentation: there are multiple ways you can reduce memory usage when rendering images in UIKit.

Its possible because rendering images in UIKit takes multiple steps which allows more room for modifications and gives you more flexibility, but in SwiftUI, it's so simple there is not as much room for modifications:

Image("image name")
                .resizable()
                .frame(width:100,height:100)

So does SwiftUI already optimized the image's dimensions and color space with the above code, or is it more memory efficient to use UIKit to optimize the image, then pass the optimized UIImage to SwiftUI for viewing?

Is using UIImages rendered (and optimized) from UIKit for image viewing SwiftUI overall a better practice than just using Image("image name")?

Any answer would be appreciated.

Body:
You can use any of

init(nsImage: NSImage)

or

init(uiImage: UIImage)

to take advantage of all knowledge you already have from UIKit or AppKit


问:
Adding more folders to the Source - Power Query
I have problem with adding many folders to Source in Power Query. In company we are using one big Excel file as database but if anyone of us is modifying something in this file everyone of us has to change all the paths in Power Query editor. Is there a way to add multiple paths in Source? We were trying with OR statement or filtering folders but it doesn't work :(

The line for which we need that looks like that:

```<code>let
    Source = Folder.Files("C:\Users\my_account\OneDrive\Desktop\RI calculator\Inventory")
</code>```

We were trying to do something like

```<code>Source = Folder.Files("C:\Users\my_account\OneDrive\Desktop\RI calculator\Inventory" OR "C:\Users\colleague_account\Desktop\RI calculator\Inventory")
</code>```

but it doesn't work. Do you have an idea how to add more paths to the source? Thank you in advance!

答:
Why don't you just set up the source directory as a variable referencing an excel cell that you can change?

If  you had a cell range named Directory, pull it in the query with

```<code>let Source = Folder.Files(Excel.CurrentWorkbook(){[Name="Directory"]}[Content]{0}[Column1])
</code>```

Body:
I have problem with adding many folders to Source in Power Query. In company we are using one big Excel file as database but if anyone of us is modifying something in this file everyone of us has to change all the paths in Power Query editor. Is there a way to add multiple paths in Source? We were trying with OR statement or filtering folders but it doesn't work :(

The line for which we need that looks like that:

let
    Source = Folder.Files("C:\Users\my_account\OneDrive\Desktop\RI calculator\Inventory")

We were trying to do something like

Source = Folder.Files("C:\Users\my_account\OneDrive\Desktop\RI calculator\Inventory" OR "C:\Users\colleague_account\Desktop\RI calculator\Inventory")

but it doesn't work. Do you have an idea how to add more paths to the source? Thank you in advance!

Body:
Why don't you just set up the source directory as a variable referencing an excel cell that you can change?

If  you had a cell range named Directory, pull it in the query with

let Source = Folder.Files(Excel.CurrentWorkbook(){[Name="Directory"]}[Content]{0}[Column1])


问:
How to set multiple attributes for calender object at once?
This is my existing code snippet:

```<code>Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
</code>```

I just want to assign those attributes at once, something like:

```<code>Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND, 0);
</code>```

I am not sure it is possible or not, because I am new to java. Please help me if there is other way around to achive this.

If possible, please give others solutions also. Objective is to set the given cal object to 00:00:00.000A.M.

Edit 1: I think this question was clear and understandable. Please consider upvoting as I couldn't ask anymore questions on stackoverflow.

答:
The old Calendar class can be set by the current generation of java time classes:</p>

```<code>// Current time classes:
LocalDate today = LocalDate.now();
// LocalDate today = LocalDate.of(2020, 2, 18);
LocalDateTime morning = today.atStartOfDay();

// Old classes:
Calendar cal = Calendar.getInstance();
cal.setTime(new Date(morning.toEpochSecond()));
</code>```

Body:
This is my existing code snippet:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);

I just want to assign those attributes at once, something like:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND, 0);

I am not sure it is possible or not, because I am new to java. Please help me if there is other way around to achive this.

If possible, please give others solutions also. Objective is to set the given cal object to 00:00:00.000A.M.

Edit 1: I think this question was clear and understandable. Please consider upvoting as I couldn't ask anymore questions on stackoverflow.

Body:
The old Calendar class can be set by the current generation of java time classes:

// Current time classes:
LocalDate today = LocalDate.now();
// LocalDate today = LocalDate.of(2020, 2, 18);
LocalDateTime morning = today.atStartOfDay();

// Old classes:
Calendar cal = Calendar.getInstance();
cal.setTime(new Date(morning.toEpochSecond()));


问:
Python Click: How to change the value of `info_name` for the global context
In a Python script using Click for the command line handling, I would like to change the info_name in the global context (in order to modify the help output).

Here is a contrived minimal example mycmd.py where I try using the context_settings:

```<code>import click

CONTEXT_SETTINGS = dict(info_name="hallo")

@click.command('mycmd', context_settings=CONTEXT_SETTINGS)
@click.pass_context
def click_cli(ctx):
   pass

click_cli()
</code>```

However when I run this script with python mycmd.py --help I get the traceback:

```<code>...
  File ".../click/core.py", line 639, in make_context
    ctx = Context(self, info_name=info_name, parent=parent, **extra)
TypeError: type object got multiple values for keyword argument 'info_name'
</code>```

So the problem is that the arguments in **extra (that's where the context_settings end up) cannot overwrite the hard-coded info_name=info_name parameter. How can I do this?

答:
Use the prog_name parameter for the cli function, to change the help name (info_name) like:

```<code>cli(prog_name='hallo')
</code>```

Test Code:

```<code>import click

@click.command('mycmd')
@click.pass_context
def cli(ctx):
    pass

cli(['--help'], prog_name='hallo')
</code>```

Results:

```<code>Usage: hallo [OPTIONS]

Options:
  --help  Show this message and exit.
</code>```

Body:
In a Python script using Click for the command line handling, I would like to change the info_name in the global context (in order to modify the help output).

Here is a contrived minimal example mycmd.py where I try using the context_settings:

import click

CONTEXT_SETTINGS = dict(info_name="hallo")

@click.command('mycmd', context_settings=CONTEXT_SETTINGS)
@click.pass_context
def click_cli(ctx):
   pass

click_cli()

However when I run this script with python mycmd.py --help I get the traceback:

...
  File ".../click/core.py", line 639, in make_context
    ctx = Context(self, info_name=info_name, parent=parent, **extra)
TypeError: type object got multiple values for keyword argument 'info_name'

So the problem is that the arguments in **extra (that's where the context_settings end up) cannot overwrite the hard-coded info_name=info_name parameter. How can I do this?

Body:
Use the prog_name parameter for the cli function, to change the help name (info_name) like:

cli(prog_name='hallo')

Test Code:

import click

@click.command('mycmd')
@click.pass_context
def cli(ctx):
    pass

cli(['--help'], prog_name='hallo')

Results:

Usage: hallo [OPTIONS]

Options:
  --help  Show this message and exit.


问:
how to verify user on sign up using mobile otp in django?
my urls.py
'''

```<code>from django.urls import path, include
from . import views
urlpatterns = [
    path('enter_otp',views.otp_call,name='otp_confirmed')
]'''
</code>```

my views.py

'''

```<code>def signup(request):
    if request.method == 'POST':
        username = request.POST["username"]
        last_name = request.POST["last_name"]
        first_name = request.POST["first_name"]
        date_of_birth = request.POST["birthday"]
        email = request.POST["email"]
        password = request.POST["password"]
        Phone = request.POST["phone"]
        gender = request.POST["gender"]
        if User.objects.filter(username=username).exists():
            messages.info(request,'username already taken')
            return render(request,"signup.html")
        if User.objects.filter(phone_no=Phone).exists():
            messages.error(request,'Phone number already in use')
            return render(request,"signup.html")
        else:
            sent = otp()
            print(sent)
            return otp_call(un=username,pswrd= password,mail = email, fn=first_name,ln=last_name,pn=Phone,dob=date_of_birth,gen=gender,otp=sent)
    else:
        return render(request,"signup.html")

def otp_call(request,**kwargs):
    if request.method == 'POST':
        trials = 0
        while trials<3:
            input_otp= request.POST["six_digit"]
            if input_otp == otp:
                signedup_user = User.objects.create_user(
                    username=un,
                    password=pswrd,
                    email=mail,
                    first_name=fn,
                    last_name =ln,
                    phone_no=pn,
                    date_of_birth=dob,
                    gender= gen
                )
                signedup_user.save()
                break
                return redirect('login')
            if input_otp != otp:
                trials+=1
                messages.error(request,"wrong otp")
                return render(request,'otp_recieve.html')
    else:
        return render(request,'otp_recieve.html')
</code>```

'''

I have html to confirm the otp with post request and csrf_token but I its not a right way I know because Urls.py will be needing parameeters too how do I verify users using otp through there mobile and the otp() in signup() is just a random 6 digit key generator please help me

答:
You can send the otp generated to your backend in request body as payload from front end. You can write a ajax call to do this

Then two access the data from backed , just

```<code>import requests
otp=req['otp']
</code>```

Body:
my urls.py
'''

from django.urls import path, include
from . import views
urlpatterns = [
    path('enter_otp',views.otp_call,name='otp_confirmed')
]'''

my views.py

'''

def signup(request):
    if request.method == 'POST':
        username = request.POST["username"]
        last_name = request.POST["last_name"]
        first_name = request.POST["first_name"]
        date_of_birth = request.POST["birthday"]
        email = request.POST["email"]
        password = request.POST["password"]
        Phone = request.POST["phone"]
        gender = request.POST["gender"]
        if User.objects.filter(username=username).exists():
            messages.info(request,'username already taken')
            return render(request,"signup.html")
        if User.objects.filter(phone_no=Phone).exists():
            messages.error(request,'Phone number already in use')
            return render(request,"signup.html")
        else:
            sent = otp()
            print(sent)
            return otp_call(un=username,pswrd= password,mail = email, fn=first_name,ln=last_name,pn=Phone,dob=date_of_birth,gen=gender,otp=sent)
    else:
        return render(request,"signup.html")

def otp_call(request,**kwargs):
    if request.method == 'POST':
        trials = 0
        while trials<3:
            input_otp= request.POST["six_digit"]
            if input_otp == otp:
                signedup_user = User.objects.create_user(
                    username=un,
                    password=pswrd,
                    email=mail,
                    first_name=fn,
                    last_name =ln,
                    phone_no=pn,
                    date_of_birth=dob,
                    gender= gen
                )
                signedup_user.save()
                break
                return redirect('login')
            if input_otp != otp:
                trials+=1
                messages.error(request,"wrong otp")
                return render(request,'otp_recieve.html')
    else:
        return render(request,'otp_recieve.html')

'''

I have html to confirm the otp with post request and csrf_token but I its not a right way I know because Urls.py will be needing parameeters too how do I verify users using otp through there mobile and the otp() in signup() is just a random 6 digit key generator please help me

Body:
You can send the otp generated to your backend in request body as payload from front end. You can write a ajax call to do this

Then two access the data from backed , just

import requests
otp=req['otp']


问:
Multiple docker images with same image_id
When I type docker images , I see multiple images with the same IMAGE_ID. Each of these images size is 1.1GB. My question is, do each of theses images actually take up 1.1GB? Or does docker use some sort of hashing based off of the image ID to ensure that duplicate images are not actually created?

$ docker images
REPOSITORY     TAG                  IMAGE ID            CREATED             SIZE
dockertest1    latest               992b4d8867c4        52 minutes ago      1.1GB
dockertest2    latest               992b4d8867c4        52 minutes ago      1.1GB
```

答:
What you are seeing is that dockertest1 and dockertest2 points to the same image that is 1.1GB of size. So only 1.1GB is used to store the image.

See Duplicate images with same id in Docker for more information.


问:
How to create a new column in a dataframe, with either 1 or 0 based on percentage of results in previous columns?
I have a data frame with 144 rows and 48 columns. It contains results from various prediction models as either 1 or 0. I want to go through a row, find the percentage of 1's in that row and add a new column with either 1 if the percentage is greater than 80, else 0.

I know how to do this in excel with if and countif/count%, but here I don't really know how to do it. I hope I provided enough info, I am sorry if I did not. Thank you very much for any advice.

答:
You can find the percentage of 1's in each row with:

```<code>df['percentage'] = df.mean(axis=1)
</code>```

Then to create your new binary column you can use np.where:

```<code>df['new'] = np.where(df['percentage'] > 0.8, 1, 0)
</code>```

This works the same way as the excel =IF (condition, value if true, value if false).

Example with dummy data:

```<code>import pandas as pd
import numpy as np

df = pd.DataFrame({'var1':[0,0,1],'var2':[0,1,1], 'var3':[1,1,1]})
df['percentage'] = df.mean(axis=1)
df['new'] = np.where(df['percentage'] > 0.8, 1, 0)

print(df)
</code>```

Output:

```<code>   var1  var2  var3  percentage  new
0     0     0     1    0.333333    0
1     0     1     1    0.666667    0
2     1     1     1    1.000000    1
</code>```

Body:
You can find the percentage of 1's in each row with:

df['percentage'] = df.mean(axis=1)

Then to create your new binary column you can use np.where:

df['new'] = np.where(df['percentage'] > 0.8, 1, 0)

This works the same way as the excel =IF (condition, value if true, value if false).

Example with dummy data:

import pandas as pd
import numpy as np

df = pd.DataFrame({'var1':[0,0,1],'var2':[0,1,1], 'var3':[1,1,1]})
df['percentage'] = df.mean(axis=1)
df['new'] = np.where(df['percentage'] > 0.8, 1, 0)

print(df)

Output:

   var1  var2  var3  percentage  new
0     0     0     1    0.333333    0
1     0     1     1    0.666667    0
2     1     1     1    1.000000    1


问:
Why does the content of my blocks overflow on the other blocks?
I created a page on Drupal 8 and Bootstrap with a "Learn more" button to expand the information.

When the information is collapsed, the blocks overflow. The gray line and the label overflows in the upper block.

How can I fix this ? Thank you

Here the gray line and the label overflows :

When the information is unfolded it's good :

TWIG :

```<code>  <div class="card mb-5 p-0 overflow-hidden shadow rounded bg-white">
    {{ drupal_view('boutique_professionnel_page_diaporama', 'block_1') }}
    <div class="card-body pt-0">
      <div id="readmorecollapse">
        <div class="collapse" id="collapserm" aria-expanded="false">
          <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 p-0 border-bottom">
            <div class="mb-4">
              <div class="mr-4 float-left rounded-lg overflow-hidden">
                {{ store.field_professionnel_logo }}
              </div>
              <h1 class="mt-0">{{ store_entity.name.value }}</h1>
              {{ store.field_professionnel_description }}
            </div>
          </div>
          <div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 bs-left pl-0 mt-3">
            <div class="mb-3">
              {{ drupal_entity('user', store_entity.uid.target_id, 'store_default') }}
            </div>
            <div class="mb-3">
              {{ store.field_professionnel_ets_id }}
            </div>
            <div class="mb-3">
              <a class="text-decoration-none text-primary" href="mailto:{{ store_entity.mail.value }}">{{ store.mail }}</a>
            </div>
            <div class="mb-3">
              <a class="text-decoration-none text-primary" href="tel:{{ store_entity.field_professionnel_telephone.value }}">{{ store.field_professionnel_telephone }}</a>
            </div>
          </div>
          <div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 bs-right pr-0 mt-3">
            <div class="mb-3">
              <a class="text-decoration-none text-primary" href="geo:{{ store_entity.field_localisation.value }}">{{ store.address }}</a>
            </div>
            <div class="mb-3">
              {{ store.field_professionnel_accueil }}
            </div>
            <div class="mb-3">
              {{ store.field_professionnel_horaires }}
            </div>
          </div>
        </div>
        <div class="readmorebutton">
          <a role="button" class="collapsed btn btn-default btn-xs" data-toggle="collapse" href="#collapserm" aria-expanded="false" aria-controls="collapserm">
          </a>
        </div>
      </div>
    </div>
    <div class="card-footer d-flex flex-wrap justify-content-start pt-0">
      <div class="mt-3 mr-3">
        {{ store.flag_report_store }}
      </div>
      <div class="mt-3 mr-3">
        {{ store.flag_like_store }}
      </div>
      <div class="mt-3 mr-3">
        {{ drupal_block('shariff_block') }}
      </div>
    </div>
  </div>
</code>```

CSS :

```<code>#readmorecollapse div.collapse[aria-expanded="false"] {
    height: 100px !important;
    overflow: hidden;
    visibility: visible;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}

#readmorecollapse div.collapsing[aria-expanded="false"] {
    height: 42px !important;
}

#readmorecollapse .readmorebutton a {
    width: 100%;
}

#readmorecollapse .readmorebutton .collapsed  {
    box-shadow: 0px -10px 25px 0px rgba(255, 255, 253, 0.8);
}

#readmorecollapse .readmorebutton a.collapsed:after  {
    content: 'Afficher toutes les infos';
}

#readmorecollapse .readmorebutton a:not(.collapsed):after {
    content: 'Cacher';
}
</code>```

答:
The problem is that you need to set overflow: hidden; to the first child of div#collapserm. The css code must be:

/* Here you need to remove the overflow */
#readmorecollapse div.collapse[aria-expanded="false"] {
    height: 100px !important;
    visibility: visible;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}

/* Then add a new rule for the first child */
#readmorecollapse div.collapse[aria-expanded="false"] div:nth-child(1) {
    overflow: hidden;
}

#readmorecollapse div.collapsing[aria-expanded="false"] {
    height: 42px !important;
}

#readmorecollapse .readmorebutton a {
    width: 100%;
}

#readmorecollapse .readmorebutton .collapsed  {
    box-shadow: 0px -10px 25px 0px rgba(255, 255, 253, 0.8);
}

#readmorecollapse .readmorebutton a.collapsed:after  {
    content: 'Afficher toutes les infos';
}

#readmorecollapse .readmorebutton a:not(.collapsed):after {
    content: 'Cacher';
}
```

Body:
I created a page on Drupal 8 and Bootstrap with a "Learn more" button to expand the information.

When the information is collapsed, the blocks overflow. The gray line and the label overflows in the upper block.

How can I fix this ? Thank you

Here the gray line and the label overflows :

When the information is unfolded it's good :

TWIG :

    {{ drupal_view('boutique_professionnel_page_diaporama', 'block_1') }}

                {{ store.field_professionnel_logo }}

{{ store_entity.name.value }}

              {{ store.field_professionnel_description }}

              {{ drupal_entity('user', store_entity.uid.target_id, 'store_default') }}

              {{ store.field_professionnel_ets_id }}

              {{ store.mail }}

              {{ store.field_professionnel_telephone }}

              {{ store.address }}

              {{ store.field_professionnel_accueil }}

              {{ store.field_professionnel_horaires }}

        {{ store.flag_report_store }}

        {{ store.flag_like_store }}

        {{ drupal_block('shariff_block') }}

CSS :

#readmorecollapse div.collapse[aria-expanded="false"] {
    height: 100px !important;
    overflow: hidden;
    visibility: visible;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}

#readmorecollapse div.collapsing[aria-expanded="false"] {
    height: 42px !important;
}

#readmorecollapse .readmorebutton a {
    width: 100%;
}

#readmorecollapse .readmorebutton .collapsed  {
    box-shadow: 0px -10px 25px 0px rgba(255, 255, 253, 0.8);
}

#readmorecollapse .readmorebutton a.collapsed:after  {
    content: 'Afficher toutes les infos';
}

#readmorecollapse .readmorebutton a:not(.collapsed):after {
    content: 'Cacher';
}


问:
How do I capture video from my laptop's camera using C#
I'm new to C# and I'm trying to capture video from my laptop's camera using C#. I found some info at MSDN VideoCaptureDevices and CaptureSource. Also I added windowsbase.dll into my references.  The above class and methods I'm not able to use.

How can the above classes be used without using Silverlight concepts?

答:
Outside of Silverlight, the Microsoft Expression Encoder SDK might do the job.
In fact it has another API to communicate to devices.</p>


问:
Why will the python matplotlib graph not show?
For some reason I cannot get a matplotlib graph to show. When I run the code, it doesn't output anything and it shouldn't, only the graph should be displayed, but its not. Any help will be much appreciated.
I'm trying to get the graph to fetch info from the database, but unfortunately no luck.</p>

```<code>import sqlite3
import time
import datetime
import random
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib import style
style.use('bmh')

conn = sqlite3.connect('tutorial.db')
c = conn.cursor()

def create_table():
    c.execute('CREATE TABLE IF NOT EXISTS stuffToPlot(unix REAL, datestamp TEXT, keyword TEXT, value REAL)')

def data_entry():
        c.execute("INSERT INTO stuffToPlot VALUES(1451255552, '2020-02-18', 'Python', 8)")
        conn.commit()
        c.close()
        conn.close()

def dynamic_data_entry():
    unix = time.time()
    date = str(datetime.datetime.fromtimestamp(unix).strftime('%Y-%m-%d %H:%M:%S'))
    keyword = 'Python'
    value = random.randrange(0,10)
    c.execute("INSERT INTO stuffToPlot (unix, datestamp, keyword, value) VALUES (?, ?, ?, ?)",
              (unix, date, keyword, value))
    conn.commit()

def read_from_db():
    c.execute("SELECT keyword, unix FROM stuffToPlot WHERE unix > 1452618731")
    #data = c.fetchall()
    #print(data)
    for row in c.fetchall():
        print(row)

def graph_data():
    c.execute('SELECT unix, value FROM stuffToPlot')
    dates = []
    values = []
    for row in c.fetchall():
        #print(row[0])
        #print(datetime.fromtimestamp(row[0]))
        dates.append(datetime.datetime.fromtimestamp(row[0]))
        values.append(row[1])
    plt.plot_date(dates, values, '-')
    plt.show()

##create_table()
###data_entry()
##for i in range(10):
##    dynamic_data_entry()
##    time.sleep(1)
##read_from_db()
c.close()
conn.close()
</code>```

答:
```<code>graph_data()
</code>```

should solve the issue.

======

Edited. This tutorial has many mistakes. After some editions:

```<code>import sqlite3
import time
import datetime
import random
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib import style
style.use('bmh')

conn = sqlite3.connect('tutorial.db')
c = conn.cursor()

def create_table():
    c.execute('CREATE TABLE IF NOT EXISTS stuffToPlot(unix REAL, datestamp TEXT, keyword TEXT, value REAL)')

def data_entry():
        c.execute("INSERT INTO stuffToPlot VALUES(1451255552, '2020-02-18', 'Python', 8)")
        conn.commit()

def dynamic_data_entry():
    unix = time.time()
    date = str(datetime.datetime.fromtimestamp(unix).strftime('%Y-%m-%d %H:%M:%S'))
    keyword = 'Python'
    value = random.randrange(0,10)
    c.execute("INSERT INTO stuffToPlot (unix, datestamp, keyword, value) VALUES (?, ?, ?, ?)",
              (unix, date, keyword, value))
    conn.commit()

def read_from_db():
    c.execute("SELECT keyword, unix FROM stuffToPlot WHERE unix > 1452618731")
    for row in c.fetchall():
        print(row)

def graph_data():
    c.execute('SELECT unix, value FROM stuffToPlot')
    dates = []
    values = []
    for row in c.fetchall():
        dates.append(datetime.datetime.fromtimestamp(row[0]))
        values.append(row[1])
    plt.plot_date(dates, values, '-')
    plt.show()

create_table()

for i in range(10):
    dynamic_data_entry()
    time.sleep(1)
read_from_db()
graph_data()
</code>```

And the output is following:

The issue was here that data_entry function inserts an outlier that contaminated the graph (all other dates was inserted with today's date).

Body:
For some reason I cannot get a matplotlib graph to show. When I run the code, it doesn't output anything and it shouldn't, only the graph should be displayed, but its not. Any help will be much appreciated.
I'm trying to get the graph to fetch info from the database, but unfortunately no luck.

import sqlite3
import time
import datetime
import random
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib import style
style.use('bmh')

conn = sqlite3.connect('tutorial.db')
c = conn.cursor()

def create_table():
    c.execute('CREATE TABLE IF NOT EXISTS stuffToPlot(unix REAL, datestamp TEXT, keyword TEXT, value REAL)')

def data_entry():
        c.execute("INSERT INTO stuffToPlot VALUES(1451255552, '2020-02-18', 'Python', 8)")
        conn.commit()
        c.close()
        conn.close()

def dynamic_data_entry():
    unix = time.time()
    date = str(datetime.datetime.fromtimestamp(unix).strftime('%Y-%m-%d %H:%M:%S'))
    keyword = 'Python'
    value = random.randrange(0,10)
    c.execute("INSERT INTO stuffToPlot (unix, datestamp, keyword, value) VALUES (?, ?, ?, ?)",
              (unix, date, keyword, value))
    conn.commit()

def read_from_db():
    c.execute("SELECT keyword, unix FROM stuffToPlot WHERE unix > 1452618731")
    #data = c.fetchall()
    #print(data)
    for row in c.fetchall():
        print(row)

def graph_data():
    c.execute('SELECT unix, value FROM stuffToPlot')
    dates = []
    values = []
    for row in c.fetchall():
        #print(row[0])
        #print(datetime.fromtimestamp(row[0]))
        dates.append(datetime.datetime.fromtimestamp(row[0]))
        values.append(row[1])
    plt.plot_date(dates, values, '-')
    plt.show()

##create_table()
###data_entry()
##for i in range(10):
##    dynamic_data_entry()
##    time.sleep(1)
##read_from_db()
c.close()
conn.close()

Body:
graph_data()

should solve the issue.

======

Edited. This tutorial has many mistakes. After some editions:

import sqlite3
import time
import datetime
import random
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib import style
style.use('bmh')

conn = sqlite3.connect('tutorial.db')
c = conn.cursor()

def create_table():
    c.execute('CREATE TABLE IF NOT EXISTS stuffToPlot(unix REAL, datestamp TEXT, keyword TEXT, value REAL)')

def data_entry():
        c.execute("INSERT INTO stuffToPlot VALUES(1451255552, '2020-02-18', 'Python', 8)")
        conn.commit()

def dynamic_data_entry():
    unix = time.time()
    date = str(datetime.datetime.fromtimestamp(unix).strftime('%Y-%m-%d %H:%M:%S'))
    keyword = 'Python'
    value = random.randrange(0,10)
    c.execute("INSERT INTO stuffToPlot (unix, datestamp, keyword, value) VALUES (?, ?, ?, ?)",
              (unix, date, keyword, value))
    conn.commit()

def read_from_db():
    c.execute("SELECT keyword, unix FROM stuffToPlot WHERE unix > 1452618731")
    for row in c.fetchall():
        print(row)

def graph_data():
    c.execute('SELECT unix, value FROM stuffToPlot')
    dates = []
    values = []
    for row in c.fetchall():
        dates.append(datetime.datetime.fromtimestamp(row[0]))
        values.append(row[1])
    plt.plot_date(dates, values, '-')
    plt.show()

create_table()

for i in range(10):
    dynamic_data_entry()
    time.sleep(1)
read_from_db()
graph_data()

And the output is following:

The issue was here that data_entry function inserts an outlier that contaminated the graph (all other dates was inserted with today's date).


问:
MySQL innacurate calculation with average and datetime
I'm having problems with time average calculations. I have a table with a lot of records, the table structure is user id, begin and end time of work (if you want, you can download the table script here) and I need to get the effective working time average of each user, so I go like this for the average:

```<code>select iduser, sec_to_time(avg(timestampdiff(second, begin, end)))
from test
group by iduser;
</code>```

So far so good, it returns:

```<code>USER1 00:25:55.9327
USER2 05:47:44.8713
USER3 03:13:43.4724
</code>```

However, the problem is when I try to calculate the average of all users (no grouping):

```<code>select sec_to_time(avg(timestampdiff(second,begin, end))),avg(timestampdiff(second,begin, end))
from test;
</code>```

it returns '03:26:18.9014', but according to my calculations, it should return 03:09:07.333. I checked with constant values and excel test

```<code>select sec_to_time((time_to_sec("00:25:55.9327")+time_to_sec("05:47:44.8713")+time_to_sec("3:13:43.4724"))/3);
</code>```

So far I don't understand why it's returning '03:26:18.9014', it's innacurate according to the other calculations. Do anybody have an idea why is this happening?

答:
If you run this query

```<code>select  count(iduser) as cnt,
    sum(timestampdiff(SECOND, `begin`, `end`)) as tot,
    avg(timestampdiff(SECOND, `begin`, `end`)) as aver,
    sec_to_time(avg(timestampdiff(SECOND, `begin`, `end`))) as tim
from test ;
</code>```

RESULT

```<code>cnt     tot         aver        tim
2903    35935951    12378.9015  03:26:18.9014
</code>```

You get all the parts so that you can do your own calculations and it appears correct

Body:
I'm having problems with time average calculations. I have a table with a lot of records, the table structure is user id, begin and end time of work (if you want, you can download the table script here) and I need to get the effective working time average of each user, so I go like this for the average:

select iduser, sec_to_time(avg(timestampdiff(second, begin, end)))
from test
group by iduser;

So far so good, it returns:

USER1 00:25:55.9327
USER2 05:47:44.8713
USER3 03:13:43.4724

However, the problem is when I try to calculate the average of all users (no grouping):

select sec_to_time(avg(timestampdiff(second,begin, end))),avg(timestampdiff(second,begin, end))
from test;

it returns '03:26:18.9014', but according to my calculations, it should return 03:09:07.333. I checked with constant values and excel test

select sec_to_time((time_to_sec("00:25:55.9327")+time_to_sec("05:47:44.8713")+time_to_sec("3:13:43.4724"))/3);

So far I don't understand why it's returning '03:26:18.9014', it's innacurate according to the other calculations. Do anybody have an idea why is this happening?

Body:
If you run this query

select  count(iduser) as cnt,
    sum(timestampdiff(SECOND, `begin`, `end`)) as tot,
    avg(timestampdiff(SECOND, `begin`, `end`)) as aver,
    sec_to_time(avg(timestampdiff(SECOND, `begin`, `end`))) as tim
from test ;

RESULT

cnt     tot         aver        tim
2903    35935951    12378.9015  03:26:18.9014

You get all the parts so that you can do your own calculations and it appears correct


问:
Generate groovydoc and include sub directories
I have groovy scripts in different locations under a parent directory. Directory structure is kinda like this:

```<code>magento
└── magento.groovy
└── models
    ├── cart.groovy
    ├── catalog.groovy
    ├── customer.groovy
    ├── directory.groovy
    ├── filter.groovy
    ├── inventory.groovy
    ├── products.groovy
    └── salesorder.groovy
</code>```

I want to generate the groovy doc and include every groovy script under the parent directory.

I tried running the command on the parent directory and it only gets those in it and apparently, those in sub folder are not included :

```<code>groovydoc \
-classpath /opt/groovy-2.4.4/lib/ \
-d /opt/groovy-test/test/magento \
-windowtitle "Magento Groovydoc Example" \
-header "Test Groovy doc for Magento" \
-doctitle "Magento Test Groovydoc"  *.groovy
</code>```

If there is a better way other than the command line? I also tried this plugin but no luck https://github.com/rvowles/groovydoc-maven-plugin

Thanks!

答:
This bash script works for me</p>

```<code>source_files=`find {path-to-your-dir}/magento/ -type f \( \
    \( \
    -name "*.java" \
    -or -name "*.groovy" \
    \) \
    ! \
    \( \
     -name "PastingSomeFileNamesHereYouCanExludeSomething.java" \
     -or -name "SomeAdditionalFile.groovy" \
    \) \
    \)`

groovydoc -verbose --debug -public\
 -d {path-to-your-magento-dir-docs}\
 -doctitle "Title"\
 -header "Header"\
 -footer "Footer"\
 -windowtitle "WindowTitle"\
 $source_files
</code>```

Body:
I have groovy scripts in different locations under a parent directory. Directory structure is kinda like this:

magento
└── magento.groovy
└── models
    ├── cart.groovy
    ├── catalog.groovy
    ├── customer.groovy
    ├── directory.groovy
    ├── filter.groovy
    ├── inventory.groovy
    ├── products.groovy
    └── salesorder.groovy

I want to generate the groovy doc and include every groovy script under the parent directory.

I tried running the command on the parent directory and it only gets those in it and apparently, those in sub folder are not included :

groovydoc \
-classpath /opt/groovy-2.4.4/lib/ \
-d /opt/groovy-test/test/magento \
-windowtitle "Magento Groovydoc Example" \
-header "Test Groovy doc for Magento" \
-doctitle "Magento Test Groovydoc"  *.groovy

If there is a better way other than the command line? I also tried this plugin but no luck https://github.com/rvowles/groovydoc-maven-plugin

Thanks!

Body:
This bash script works for me

source_files=`find {path-to-your-dir}/magento/ -type f \( \
    \( \
    -name "*.java" \
    -or -name "*.groovy" \
    \) \
    ! \
    \( \
     -name "PastingSomeFileNamesHereYouCanExludeSomething.java" \
     -or -name "SomeAdditionalFile.groovy" \
    \) \
    \)`

groovydoc -verbose --debug -public\
 -d {path-to-your-magento-dir-docs}\
 -doctitle "Title"\
 -header "Header"\
 -footer "Footer"\
 -windowtitle "WindowTitle"\
 $source_files


问:
Heatmap Renderer ArcGIS Javascript 4.4 based on number of points and their locality to each other in the layer only
I have been reviewing the documentation for the heatmap renderer but I would like to tag it to my feature layer without visualising based on the "field" but based on the number of points and their locality between each other. Could anyone advise me how to?</p>

```<code>var earthquakeLayer = new FeatureLayer({
  // url to a point dataset
});

// visualization based on field

var heatmapParams = {
  layer: earthquakeLayer,
  view: view,
  field: "magnitude"
};

// when the promise resolves, apply the renderer to the layer
heatmapRendererCreator.createRenderer(heatmapParams)
  .then(function(response){
    earthquakeLayer.renderer = response.renderer;
  });
</code>```

答: I think what you are actually looking for clustering features (ArcGIS API Doc - FeatureReductionCluster). There are several examples there, take a look if it fits your needs.</p>

Body:
I have been reviewing the documentation for the heatmap renderer but I would like to tag it to my feature layer without visualising based on the "field" but based on the number of points and their locality between each other. Could anyone advise me how to?

var earthquakeLayer = new FeatureLayer({
  // url to a point dataset
});

// visualization based on field

var heatmapParams = {
  layer: earthquakeLayer,
  view: view,
  field: "magnitude"
};

// when the promise resolves, apply the renderer to the layer
heatmapRendererCreator.createRenderer(heatmapParams)
  .then(function(response){
    earthquakeLayer.renderer = response.renderer;
  });


问:
Kotlin continuation doesn't resume
I'm trying to get my head around suspendCoroutine and suspendCancellableCoroutine. I think they could be useful in the following case:

When the coroutine is launched, check if the user is logged in.

If not, ask for credentials and pause the currently executing coroutine.

When the credentials are submitted, resume the coroutine from the same line where it was suspended.

This compiles but never makes it past "delay over", i.e. the continuation never resumes:

```<code>import kotlinx.coroutines.*

fun main(args: Array<String>) {
    println("Hello, world!")

    runBlocking {
        launch {
            postComment()
        }
    }
}

var isLoggedIn = false
var loginContinuation: CancellableContinuation<Unit>? = null

suspend fun postComment() {
    if (!isLoggedIn) {
        showLoginForm()

        suspendCancellableCoroutine<Unit> {
            loginContinuation = it
        }
    }

    // call the api or whatever
    delay(1000)

    println("comment posted!")
}

suspend fun showLoginForm() {
    println("show login form")

    // simulate delay while user enters credentials
    delay(1000)
    println("delay over")
    isLoggedIn = true

    // resume coroutine on submit
    loginContinuation?.resume(Unit) { println("login cancelled") }
}
</code>```

I've tried everything I can think of, including moving the call to suspendCancellableCoroutine outside of the login check, wrapping the contents of showLoginForm in withContext(Dispatchers.IO),  using coroutineScope.launch(newSingleThreadContext("MyOwnThread"), etc. The impression I get from reading the internet is that this is a valid use case. What am I doing wrong?

答:
Passing around Continuations is messy and can easily lead to the error you have...one function finishes before the continuation has even been assigned to the continuation property.

Since the login form is what you want to turn into a suspend function, that's where you should use suspendCoroutine. suspendCoroutine is low level code that you should put as low as possible so your main program logic can use easy-to-read sequential coroutines without the nested launch/suspendCoroutine calls.

```<code>var isLoggedIn = false

suspend fun postComment() {
    if (!isLoggedIn) {
        showLoginForm()
    }

    println("is logged in: $isLoggedIn")

    if (isLoggedIn) {
        // call the api or whatever
        delay(1000)
        println("comment posted!")
    }
}

suspend fun showLoginForm(): Unit = suspendCancellableCoroutine { cont ->
    println("Login or leave blank to cancel:")

    //Simulate user login or cancel with console input
    val userInput = readLine()
    isLoggedIn = !userInput.isNullOrBlank()
    cont.resume(Unit)
}
</code>```

I didn't use delay() in showLoginForm() because you can't call suspend functions within a suspendCancellableCoroutine block. Those last three lines could also be wrapped in a scope.launch and use delay instead of readLine, but in reality, your UI interaction wouldn't be a coroutine with a delay anyway.

EDIT:

Trying to pass a continuation to another Activity would be especially messy. Google does not even recommend using multiple Activities in an app because it is difficult to pass objects between them. To do it with Fragments, you could maybe write your LoginFragment class to have a private continuation property like this:

```<code>class LoginFragment(): Fragment {

    private val continuation: Continuation<Boolean>? = null
    private var loginComplete = false

    suspend fun show(manager: FragmentManager, @IdRes containerViewId: Int, tag: String? = null): Boolean = suspendCancelableCoroutine { cont ->
        continuation = cont
        retainInstance = true
        manager.beginTransaction().apply {
            replace(containerViewId, this@LoginFragment, tag)
            addToBackStack(null)
            commit()
        }
    }

    // Call this when login is complete:
    private fun onLoginSuccessful() {
        loginComplete = true
        activity?.fragmentManager?.popBackStack()
    }

    override fun onDestroy() {
        super.onDestroy()
        continuation?.resume(loginComplete)
    }
}
</code>```

Then you would show this fragment from another fragment like this:

```<code>lifecycleScope.launch {
    val loggedIn = LoginFragment().show(requireActivity().fragmentManager, R.id.fragContainer)
    // respond to login state here
}
</code>```

So long as you are using a Fragment's lifecycleScope rather than an Activity's lifecycleScope and the first Fragment also uses retainInstance = true, I think you should be safe from screen rotations. But I haven't done this myself.

Title: Kotlin continuation doesn't resume

Body:
I'm trying to get my head around suspendCoroutine and suspendCancellableCoroutine. I think they could be useful in the following case:

When the coroutine is launched, check if the user is logged in.

If not, ask for credentials and pause the currently executing coroutine.

When the credentials are submitted, resume the coroutine from the same line where it was suspended.

This compiles but never makes it past "delay over", i.e. the continuation never resumes:

import kotlinx.coroutines.*

fun main(args: Array<String>) {
    println("Hello, world!")

    runBlocking {
        launch {
            postComment()
        }
    }
}

var isLoggedIn = false
var loginContinuation: CancellableContinuation<Unit>? = null

suspend fun postComment() {
    if (!isLoggedIn) {
        showLoginForm()

        suspendCancellableCoroutine<Unit> {
            loginContinuation = it
        }
    }

    // call the api or whatever
    delay(1000)

    println("comment posted!")
}

suspend fun showLoginForm() {
    println("show login form")

    // simulate delay while user enters credentials
    delay(1000)
    println("delay over")
    isLoggedIn = true

    // resume coroutine on submit
    loginContinuation?.resume(Unit) { println("login cancelled") }
}

I've tried everything I can think of, including moving the call to suspendCancellableCoroutine outside of the login check, wrapping the contents of showLoginForm in withContext(Dispatchers.IO),  using coroutineScope.launch(newSingleThreadContext("MyOwnThread"), etc. The impression I get from reading the internet is that this is a valid use case. What am I doing wrong?

Body:
Passing around Continuations is messy and can easily lead to the error you have...one function finishes before the continuation has even been assigned to the continuation property.

Since the login form is what you want to turn into a suspend function, that's where you should use suspendCoroutine. suspendCoroutine is low level code that you should put as low as possible so your main program logic can use easy-to-read sequential coroutines without the nested launch/suspendCoroutine calls.

var isLoggedIn = false

suspend fun postComment() {
    if (!isLoggedIn) {
        showLoginForm()
    }

    println("is logged in: $isLoggedIn")

    if (isLoggedIn) {
        // call the api or whatever
        delay(1000)
        println("comment posted!")
    }
}

suspend fun showLoginForm(): Unit = suspendCancellableCoroutine { cont ->
    println("Login or leave blank to cancel:")

    //Simulate user login or cancel with console input
    val userInput = readLine()
    isLoggedIn = !userInput.isNullOrBlank()
    cont.resume(Unit)
}

I didn't use delay() in showLoginForm() because you can't call suspend functions within a suspendCancellableCoroutine block. Those last three lines could also be wrapped in a scope.launch and use delay instead of readLine, but in reality, your UI interaction wouldn't be a coroutine with a delay anyway.

EDIT:

Trying to pass a continuation to another Activity would be especially messy. Google does not even recommend using multiple Activities in an app because it is difficult to pass objects between them. To do it with Fragments, you could maybe write your LoginFragment class to have a private continuation property like this:

class LoginFragment(): Fragment {

    private val continuation: Continuation<Boolean>? = null
    private var loginComplete = false

    suspend fun show(manager: FragmentManager, @IdRes containerViewId: Int, tag: String? = null): Boolean = suspendCancelableCoroutine { cont ->
        continuation = cont
        retainInstance = true
        manager.beginTransaction().apply {
            replace(containerViewId, this@LoginFragment, tag)
            addToBackStack(null)
            commit()
        }
    }

    // Call this when login is complete:
    private fun onLoginSuccessful() {
        loginComplete = true
        activity?.fragmentManager?.popBackStack()
    }

    override fun onDestroy() {
        super.onDestroy()
        continuation?.resume(loginComplete)
    }
}

Then you would show this fragment from another fragment like this:

lifecycleScope.launch {
    val loggedIn = LoginFragment().show(requireActivity().fragmentManager, R.id.fragContainer)
    // respond to login state here
}

So long as you are using a Fragment's lifecycleScope rather than an Activity's lifecycleScope and the first Fragment also uses retainInstance = true, I think you should be safe from screen rotations. But I haven't done this myself.


问:
How do I add donation functionality to a non-profit website?
I am developing a website for an NGO from scratch.

How do I add functionality that will enable users to make donations via PayPal/Credit card?

答:
You can add a donation button from PayPal very easily.

Register your NGO with PayPal and verify your account.

Login and follow the Steps

Copy the button code and Past it in your site.