问:
Filter R dataframe to n most frequent cases and order by frequency
In a dataframe with repeat values, I want the rows for the most frequent n cases, say the two most frequently occurring. The code below does this, selecting rows where x==3 or x==4 and return the rows in that order.

I don't want to have to use the value 5; however, I want some way of programmatically stating the top 2 most frequent x values, without knowing a threshold (5 in this example) apriori. In addition, I would like to order the resulting dataframe by frequency of occurrence, so x==4 rows come before x==3 rows.

I am presuming it is related to count, top_n or slice_max and arrange but maybe not!

Any hints on how to do this with dplyr would be greatly appreciated.

```<code>require(tidyverse)
adf <- data.frame(x=c(rep(2,5),rep(3,7), rep(4,9), 1), y=1:22)
adf %>% group_by(x) %>% filter(n() > 5)
</code>```

答:
Here is another tidyverse option, where I use add_count to get the number of observations per group, then I filter the 2 groups with the highest number of observations. Then, I arrange by the frequency of occurence.

```<code>library(tidyverse)

adf %>%
  add_count(x) %>%
  filter(n %in% tail(sort(unique(n)),2)) %>%
  arrange(desc(n))
</code>```

Output

```<code>   x  y n
1  4 13 9
2  4 14 9
3  4 15 9
4  4 16 9
5  4 17 9
6  4 18 9
7  4 19 9
8  4 20 9
9  4 21 9
10 3  6 7
11 3  7 7
12 3  8 7
13 3  9 7
14 3 10 7
15 3 11 7
16 3 12 7
</code>```

Data

```<code>adf <- structure(list(x = c(2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4,
4, 4, 4, 4, 4, 4, 4, 1), y = 1:22), class = "data.frame", row.names = c(NA,
-22L))
</code>```

Body:
In a dataframe with repeat values, I want the rows for the most frequent n cases, say the two most frequently occurring. The code below does this, selecting rows where x==3 or x==4 and return the rows in that order.

I don't want to have to use the value 5; however, I want some way of programmatically stating the top 2 most frequent x values, without knowing a threshold (5 in this example) apriori. In addition, I would like to order the resulting dataframe by frequency of occurrence, so x==4 rows come before x==3 rows.

I am presuming it is related to count, top_n or slice_max and arrange but maybe not!

Any hints on how to do this with dplyr would be greatly appreciated.

require(tidyverse)
adf <- data.frame(x=c(rep(2,5),rep(3,7), rep(4,9), 1), y=1:22)
adf %>% group_by(x) %>% filter(n() > 5)

Body:
Here is another tidyverse option, where I use add_count to get the number of observations per group, then I filter the 2 groups with the highest number of observations. Then, I arrange by the frequency of occurence.

library(tidyverse)

adf %>%
  add_count(x) %>%
  filter(n %in% tail(sort(unique(n)),2)) %>%
  arrange(desc(n))

Output

   x  y n
1  4 13 9
2  4 14 9
3  4 15 9
4  4 16 9
5  4 17 9
6  4 18 9
7  4 19 9
8  4 20 9
9  4 21 9
10 3  6 7
11 3  7 7
12 3  8 7
13 3  9 7
14 3 10 7
15 3 11 7
16 3 12 7

Data

adf <- structure(list(x = c(2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4,
4, 4, 4, 4, 4, 4, 4, 1), y = 1:22), class = "data.frame", row.names = c(NA,
-22L))


来源: stackexchange

问:
Bison shift/reduce conflict, cannot remove ambiguity from parser
When I run my bison code in Linux Mint I get these warnings:

```<code>warning: 64 shift/reduce conflicts [-Wconflicts-sr]
</code>```

I cannot find the ambiguity. I've tried to make my implementation hanlde both INT and FLOAT datatypes, but I believe that is the source of the warnings.

My Bison code is below:

```<code>%{
   /**
    * Definition section
    */
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    #include <cstdio>
    #include <iostream>
    using namespace std;

    /**
     * Declare stuff from Flex that Bison needs to know about:
     */

    extern int yylex();
    extern int yyparse();
    extern FILE* yyin;
    extern int line_num;

    void yyerror(const char* s);
%}

/** Bison fundamentally works by asking flex to get the next token,
 * which it returns as an object of type "yystype". Initially (by default),
 * yystype is merely a typedef of "int", but for non-trivial projects, tokens
 * could be of any arbitrary data type. So, to deal with that, the idea is to
 * override yystype's default typedef to a C union instead. Unions can hold all
 * of the types of tokens that Flex could return, and this means we can return
 * ints or floats or string cleanly. Bison implements this mechanism with the
 * %union directive:
 */
%union {
    int ival;
    float fval;
}

/**
 * Define the "Terminal Symbol" toke types. We use (in CAPS by convention),
 * and associate each with a field of the %union:
 */
%token<ival> INT
%token<fval> FLOAT
%token PLUS MINUS MULTIPLY DIVIDE
%token NEWLINE QUIT

%type<ival> expression
%type<fval> mixed_expression

%start calculation

%%

calculation:
           | calculation line
;

line: NEWLINE
    | mixed_expression NEWLINE {printf("\tResult: %f\n", $1);}
    | expression NEWLINE {printf("\tResult: %i\n", $1);}
    | QUIT NEWLINE {printf("bye!\n"); exit(0);}
;

mixed_expression: FLOAT                             {$$ = $1;}
    | mixed_expression PLUS mixed_expression        {$$ = $1 + $3;}
    | mixed_expression MINUS mixed_expression       {$$ = $1 - $3;}
    | mixed_expression MULTIPLY mixed_expression    {$$ = $1 * $3;}
    | mixed_expression DIVIDE mixed_expression      {$$ = $1 / $3;}
    | expression PLUS mixed_expression              {$$ = $1 + $3;}
    | expression MINUS mixed_expression             {$$ = $1 - $3;}
    | expression MULTIPLY mixed_expression          {$$ = $1 * $3;}
    | expression DIVIDE mixed_expression            {$$ = $1 / $3;}
    | mixed_expression PLUS expression              {$$ = $1 + $3;}
    | mixed_expression MINUS expression             {$$ = $1 - $3;}
    | mixed_expression MULTIPLY expression          {$$ = $1 * $3;}
    | mixed_expression DIVIDE expression            {$$ = $1 / $3;}
    | expression DIVIDE expression                  {$$ = $1 / (float)$3;}
;

expression: INT                                     {$$ = $1;}
          | expression PLUS expression              {$$ = $1 + $3;}
          | expression MINUS expression             {$$ = $1 - $3;}
          | expression MULTIPLY expression          {$$ = $1 * $3;}
;

%%

int main(int, char**) {
    // Open a file handle to a particular file:
    FILE *myfile = fopen("numbers.txt", "r");
    // Make sure it is valid:
    if(!myfile) {
        cout << "I can't open numbers.txt!" << endl;
        return -1;
    }
    // Set Flex to read from it instead of defaulting to STDIN:
    yyin = myfile;

    // Parse through the input:
    yyparse();
}

void yyerror(const char *s) {
    cout << "AAAHHHH, parse error on line " << line_num << "! Message: " << s << endl;
    // might as well halt now:
    exit(-1);
}
</code>```

I believe that the issue may be with my implementation of expression and mixed_expression.

答:
The datatype of a computation is semantic, not syntactic; intuitively, one wouldn't expect a grammar to deal with it. Under some very limited circumstances it's possible — your attempt is workable, at least until you decide to implement variables — but it's almost never a good idea.

But that's not what's producing the shift-reduce conflicts. The problem is that your grammar is ambiguous and you have not told Bison how to resolve the ambiguities. The grammar is ambiguous because 4-2*3 could be parsed either as expression(4-2) TIMES expression(3) or as expression(4) MINUS expression(2*3), which obviously have different values. The usual way to resolve this particular ambiguity is through precedence declarations, which you will find deployed in pretty well all of the useful example parsers.

ContentLicense: CC BY-SA 4.0

Body:
When I run my bison code in Linux Mint I get these warnings:

warning: 64 shift/reduce conflicts [-Wconflicts-sr]

I cannot find the ambiguity. I've tried to make my implementation hanlde both INT and FLOAT datatypes, but I believe that is the source of the warnings.

My Bison code is below:

%{
   /**
    * Definition section
    */
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    #include <cstdio>
    #include <iostream>
    using namespace std;

    /**
     * Declare stuff from Flex that Bison needs to know about:
     */

    extern int yylex();
    extern int yyparse();
    extern FILE* yyin;
    extern int line_num;

    void yyerror(const char* s);
%}

/** Bison fundamentally works by asking flex to get the next token,
 * which it returns as an object of type "yystype". Initially (by default),
 * yystype is merely a typedef of "int", but for non-trivial projects, tokens
 * could be of any arbitrary data type. So, to deal with that, the idea is to
 * override yystype's default typedef to a C union instead. Unions can hold all
 * of the types of tokens that Flex could return, and this means we can return
 * ints or floats or string cleanly. Bison implements this mechanism with the
 * %union directive:
 */
%union {
    int ival;
    float fval;
}

/**
 * Define the "Terminal Symbol" toke types. We use (in CAPS by convention),
 * and associate each with a field of the %union:
 */
%token<ival> INT
%token<fval> FLOAT
%token PLUS MINUS MULTIPLY DIVIDE
%token NEWLINE QUIT

%type<ival> expression
%type<fval> mixed_expression

%start calculation

%%

calculation:
           | calculation line
;

line: NEWLINE
    | mixed_expression NEWLINE {printf("\tResult: %f\n", $1);}
    | expression NEWLINE {printf("\tResult: %i\n", $1);}
    | QUIT NEWLINE {printf("bye!\n"); exit(0);}
;

mixed_expression: FLOAT                             {$$ = $1;}
    | mixed_expression PLUS mixed_expression        {$$ = $1 + $3;}
    | mixed_expression MINUS mixed_expression       {$$ = $1 - $3;}
    | mixed_expression MULTIPLY mixed_expression    {$$ = $1 * $3;}
    | mixed_expression DIVIDE mixed_expression      {$$ = $1 / $3;}
    | expression PLUS mixed_expression              {$$ = $1 + $3;}
    | expression MINUS mixed_expression             {$$ = $1 - $3;}
    | expression MULTIPLY mixed_expression          {$$ = $1 * $3;}
    | expression DIVIDE mixed_expression            {$$ = $1 / $3;}
    | mixed_expression PLUS expression              {$$ = $1 + $3;}
    | mixed_expression MINUS expression             {$$ = $1 - $3;}
    | mixed_expression MULTIPLY expression          {$$ = $1 * $3;}
    | mixed_expression DIVIDE expression            {$$ = $1 / $3;}
    | expression DIVIDE expression                  {$$ = $1 / (float)$3;}
;

expression: INT                                     {$$ = $1;}
          | expression PLUS expression              {$$ = $1 + $3;}
          | expression MINUS expression             {$$ = $1 - $3;}
          | expression MULTIPLY expression          {$$ = $1 * $3;}
;

%%

int main(int, char**) {
    // Open a file handle to a particular file:
    FILE *myfile = fopen("numbers.txt", "r");
    // Make sure it is valid:
    if(!myfile) {
        cout << "I can't open numbers.txt!" << endl;
        return -1;
    }
    // Set Flex to read from it instead of defaulting to STDIN:
    yyin = myfile;

    // Parse through the input:
    yyparse();
}

void yyerror(const char *s) {
    cout << "AAAHHHH, parse error on line " << line_num << "! Message: " << s << endl;
    // might as well halt now:
    exit(-1);
}

I believe that the issue may be with my implementation of expression and mixed_expression.


问:
Unable to add a credit/debit card for billing account on Firebase
Sorry if this is not the correct place to put up this question, but I'm unable to find an answer anywhere else.
Here's the problem.
I need to upgrade a client's account on Firebase from Spark plan to Blaze plan (pay as you go plan).
To do that I need to add a credit/debit card as a payment method to their account (billing account).
We have tried 3-4 different credit/debit cards but have failed.
I tried getting help from the help center but was not able to find it there.

At this link - https://console.cloud.google.com/support/chat  - I tried to chat with someone to get help but here's what I got -

I am not the administrator on any billing account - Because I am unable to add a credit/debit card to create a billing account, hence I am not eligible for any help

I cannot get help on Phone because "You do not currently have access to technical phone support"

I am really frustrated by this, I have tried multiple cards, even borrowing other people's credit cards.

I am unable to find help from Google! Community support is the last option left! I just want to know what the issue is with my credit card? Why am I not able to add it as a payment method?

It was not registered for international payments initially, but I got that changed. I do not have any other ideas.

I really hope you guys can help me out.

UPDATE 1:

You must create a billing account first before you can add a card/payment options. Information about it can be found here: https://cloud.google.com/billing/docs/how-to/manage-billing-account

I followed this link, this is something I've tried and this is the step where I am stuck.
Step 1: Identity verification - I am able to successfully complete this step by verifying mobile number and continuing.
Step 2: Verify payment method - this is the step I am stuck at. I have tried adding different cards, as mentioned above, and have faced different issues with different cards. One card did not have international payments enabled, I got that enabled but even then it doesn't work. It does not show any error. It proceeds to the bank's website for two step verification process, I enter the 'One Time Password" for the payment, the payment goes through and it comes back to the same "Payment Information Verification" page.
Screenshots attached below for more info

答:
SOLVED!!

Problem -> Since recurring payments are blocked, we cannot add cards and create billing account. And since I didn't have any billing account, I was not allowed the chat support. When I mailed regarding the same, received reply after 2-3 days stating that we look for some other payment methods(which do not exist as of now if you are in INDIA).

Solution -> Connect with some friend outside India where recurring payments are enabled(for eg. USA, singapore).
Ask them to login firebase from their laptop(do not use their card in India), add billing account and then google will put account on hold for 24-48hrs. go to cards -> add a backup card (India card) -> make it primary card and BOOOOM!!. In probably 24 hrs you can make payments from Indian credit/Debit card. Thank me Later!!


问:
How to correct code so that it runs or inserts formula in column to left of Range for cells that = "Metered"
I have a worksheet where column C has a formula that looks up value if column D = "Metered".
Users, who are mostly farm workers, have the ability to overwrite it (or possibly delete it using the Make Correction button).  Unless column D = "Metered", I don't care if column C is overwritten because data validation makes sure entry is OK.  Users are supposed to Tab past column C unless load is "Metered". As a failsafe, I duplicated the "Metered" lookup formula elsewhere and the results are in column S. I don't get any errors on code below, but it doesn't do anything -- previous versions would do things but not the right things. Clearly, I cannot solve this on my own and very much appreciate any help you can provide.  I want to run the failsafe once a day when the workbook is opened (running on laptops and speed is important).</p>
```<code>Private Sub Workbook_Open()

    Application.OnTime TimeValue("02:57:00"), "SaveBeforeDailyRestart"
    Application.MoveAfterReturnDirection = xlToRight
    Call MeteredLookupRefreshFormula

End Sub

Sub MeteredLookupRefreshFormula()

    Sheet1.Unprotect Password:="Cami8"

    Dim bng As Range
    Set bng = Range("D8:D10009")

    For Each cell In bng
        If Value = "Metered" Then
            bng.Offset(0, -1).Select
            Selection.Value = "S & ActiveCell.Row)"
      Else
    End If

    Next

    Sheet1.Protect Password:="Cami8"

End Sub
</code>```

答:
Loop Through Cells

A Quick Fix (Slow)

To not be dependent on the offset you could additionally do:

```<code>cell.EntireRow.Columns("C").Value = cell.EntireRow.Columns("S").Value
</code>```

Sub MeteredLookupRefreshFormulaQuickFix()

    With Sheet1
        .Unprotect Password:="Cami8"
        With .Range("D8:D10009")
            Dim cell As Range
            For Each cell In .Cells
                If StrComp(CStr(cell.Value), "Metered", vbTextCompare) = 0 Then
                    cell.Offset(0, -1).Value = cell.EntireRow.Columns("S").Value
                End If
            Next cell
        End With
        .Protect Password:="Cami8"
    End With

End Sub
```
<h2>An Improvement (Fast)</h2>
<ul>
<li>If you have many cells containing formulas evaluating to an empty string <code>=""</code> at the bottom of column <code>D</code>, replace <code>xlFormulas</code> with <code>xlValues</code> for these cells not to be processed and speed up even more.</li>
</ul>
<pre class="lang-vb prettyprint-override"><code>''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose:      Refreshes...
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Calls:        RefColumn,GetRange.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Sub MeteredLookupRefreshFormula()

    Const cfcAddress As String = "D8"
    Const dCol As String = "C"
    Const sCol As String = "S"
    Const Criteria As String = "Metered"
    Const pw As String = "Cami8"

    Sheet1.Unprotect Password:=pw

    Dim crg As Range: Set crg = RefColumn(Sheet1.Range(cfcAddress))
    If crg Is Nothing Then Exit Sub ' no data

    Dim cData As Variant: cData = GetRange(crg)
    Dim drg As Range: Set drg = crg.EntireRow.Columns(dCol)
    Dim dData As Variant: dData = GetRange(drg)
    Dim sData As Variant: sData = GetRange(crg.EntireRow.Columns(sCol))

    Dim r As Long
    For r = 1 To UBound(cData, 1)
        If StrComp(CStr(cData(r, 1)), Criteria, vbTextCompare) = 0 Then
            dData(r, 1) = sData(r, 1)
        End If
    Next r

    drg.Value = dData

    Sheet1.Protect Password:=pw

End Sub

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose:      Creates a reference to the one-column range ('crg') whose first
'               cell is defined by the first cell of the range ('FirstCell')
'               and whose last cell is the bottom-most non-empty cell
'               of the first cell's worksheet column.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function RefColumn( _
    ByVal FirstCell As Range) _
As Range
    Const ProcName As String = "RefColumn"
    On Error GoTo ClearError

    With FirstCell.Cells(1)
        Dim lCell As Range
        Set lCell = .Resize(.Worksheet.Rows.Count - .Row + 1) _
            .Find("*", , xlFormulas, , , xlPrevious)
        If lCell Is Nothing Then Exit Function
        Set RefColumn = .Resize(lCell.Row - .Row + 1)
    End With

ProcExit:
    Exit Function
ClearError:
    Debug.Print "'" & ProcName & "' Run-time error '" _
        & Err.Number & "':" & vbLf & "    " & Err.Description
    Resume ProcExit
End Function

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose:      Returns the values of a range ('rg') in a 2D one-based array.
' Remarks:      If ˙rg` refers to a multi-range, only its first area
'               is considered.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function GetRange( _
    ByVal rg As Range) _
As Variant
    Const ProcName As String = "GetRange"
    On Error GoTo ClearError

    If rg.Rows.Count + rg.Columns.Count = 2 Then ' one cell
        Dim Data As Variant: ReDim Data(1 To 1, 1 To 1): Data(1, 1) = rg.Value
        GetRange = Data
    Else ' multiple cells
        GetRange = rg.Value
    End If

ProcExit:
    Exit Function
ClearError:
    Debug.Print "'" & ProcName & "' Run-time error '" _
        & Err.Number & "':" & vbLf & "    " & Err.Description
    Resume ProcExit
End Function
</code>```

Body:
I have a worksheet where column C has a formula that looks up value if column D = "Metered".
Users, who are mostly farm workers, have the ability to overwrite it (or possibly delete it using the Make Correction button).  Unless column D = "Metered", I don't care if column C is overwritten because data validation makes sure entry is OK.  Users are supposed to Tab past column C unless load is "Metered". As a failsafe, I duplicated the "Metered" lookup formula elsewhere and the results are in column S. I don't get any errors on code below, but it doesn't do anything -- previous versions would do things but not the right things. Clearly, I cannot solve this on my own and very much appreciate any help you can provide.  I want to run the failsafe once a day when the workbook is opened (running on laptops and speed is important).

Private Sub Workbook_Open()

    Application.OnTime TimeValue("02:57:00"), "SaveBeforeDailyRestart"
    Application.MoveAfterReturnDirection = xlToRight
    Call MeteredLookupRefreshFormula

End Sub

Sub MeteredLookupRefreshFormula()

    Sheet1.Unprotect Password:="Cami8"

    Dim bng As Range
    Set bng = Range("D8:D10009")

    For Each cell In bng
        If Value = "Metered" Then
            bng.Offset(0, -1).Select
            Selection.Value = "S & ActiveCell.Row)"
      Else
    End If

    Next

    Sheet1.Protect Password:="Cami8"

End Sub

Body:
Loop Through Cells

A Quick Fix (Slow)

To not be dependent on the offset you could additionally do:

cell.EntireRow.Columns("C").Value = cell.EntireRow.Columns("S").Value

Sub MeteredLookupRefreshFormulaQuickFix()

    With Sheet1
        .Unprotect Password:="Cami8"
        With .Range("D8:D10009")
            Dim cell As Range
            For Each cell In .Cells
                If StrComp(CStr(cell.Value), "Metered", vbTextCompare) = 0 Then
                    cell.Offset(0, -1).Value = cell.EntireRow.Columns("S").Value
                End If
            Next cell
        End With
        .Protect Password:="Cami8"
    End With

End Sub

An Improvement (Fast)

If you have many cells containing formulas evaluating to an empty string ="" at the bottom of column D, replace xlFormulas with xlValues for these cells not to be processed and speed up even more.

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose:      Refreshes...
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Calls:        RefColumn,GetRange.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Sub MeteredLookupRefreshFormula()

    Const cfcAddress As String = "D8"
    Const dCol As String = "C"
    Const sCol As String = "S"
    Const Criteria As String = "Metered"
    Const pw As String = "Cami8"

    Sheet1.Unprotect Password:=pw

    Dim crg As Range: Set crg = RefColumn(Sheet1.Range(cfcAddress))
    If crg Is Nothing Then Exit Sub ' no data

    Dim cData As Variant: cData = GetRange(crg)
    Dim drg As Range: Set drg = crg.EntireRow.Columns(dCol)
    Dim dData As Variant: dData = GetRange(drg)
    Dim sData As Variant: sData = GetRange(crg.EntireRow.Columns(sCol))

    Dim r As Long
    For r = 1 To UBound(cData, 1)
        If StrComp(CStr(cData(r, 1)), Criteria, vbTextCompare) = 0 Then
            dData(r, 1) = sData(r, 1)
        End If
    Next r

    drg.Value = dData

    Sheet1.Protect Password:=pw

End Sub

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose:      Creates a reference to the one-column range ('crg') whose first
'               cell is defined by the first cell of the range ('FirstCell')
'               and whose last cell is the bottom-most non-empty cell
'               of the first cell's worksheet column.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function RefColumn( _
    ByVal FirstCell As Range) _
As Range
    Const ProcName As String = "RefColumn"
    On Error GoTo ClearError

    With FirstCell.Cells(1)
        Dim lCell As Range
        Set lCell = .Resize(.Worksheet.Rows.Count - .Row + 1) _
            .Find("*", , xlFormulas, , , xlPrevious)
        If lCell Is Nothing Then Exit Function
        Set RefColumn = .Resize(lCell.Row - .Row + 1)
    End With

ProcExit:
    Exit Function
ClearError:
    Debug.Print "'" & ProcName & "' Run-time error '" _
        & Err.Number & "':" & vbLf & "    " & Err.Description
    Resume ProcExit
End Function

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose:      Returns the values of a range ('rg') in a 2D one-based array.
' Remarks:      If ˙rg` refers to a multi-range, only its first area
'               is considered.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function GetRange( _
    ByVal rg As Range) _
As Variant
    Const ProcName As String = "GetRange"
    On Error GoTo ClearError

    If rg.Rows.Count + rg.Columns.Count = 2 Then ' one cell
        Dim Data As Variant: ReDim Data(1 To 1, 1 To 1): Data(1, 1) = rg.Value
        GetRange = Data
    Else ' multiple cells
        GetRange = rg.Value
    End If

ProcExit:
    Exit Function
ClearError:
    Debug.Print "'" & ProcName & "' Run-time error '" _
        & Err.Number & "':" & vbLf & "    " & Err.Description
    Resume ProcExit
End Function


问:
Daily Sentiment Values
Does anyone have an idea into calculating the average sentiment values for each day?
This is my code get get the sentiment score, but I have tried calculating an average for each of the day, but i havent had any luck

```<code>from nltk.sentiment.vader import SentimentIntensityAnalyzer
import pandas as pd
analyzer = SentimentIntensityAnalyzer()

eth = pd.read_csv("Ethereum_2020_2021_Time_Adjusted.csv")
eth['Sentiment Values'] = eth['Title'].apply(lambda Title: analyzer.polarity_scores(Title))
eth['Title Sentiment Score']  = eth['Sentiment Values'].apply(lambda score_dict: score_dict['compound'])
</code>```

答:
Try using groupby and agg to address the issue.

eth.groupby('Date')['Sentiment Values'].agg('mean')

Title: Daily Sentiment Values

Body:
Does anyone have an idea into calculating the average sentiment values for each day?
This is my code get get the sentiment score, but I have tried calculating an average for each of the day, but i havent had any luck

from nltk.sentiment.vader import SentimentIntensityAnalyzer
import pandas as pd
analyzer = SentimentIntensityAnalyzer()

eth = pd.read_csv("Ethereum_2020_2021_Time_Adjusted.csv")
eth['Sentiment Values'] = eth['Title'].apply(lambda Title: analyzer.polarity_scores(Title))
eth['Title Sentiment Score']  = eth['Sentiment Values'].apply(lambda score_dict: score_dict['compound'])


问:
weblogic.application.ModuleException: java.lang.LinkageError: loader constraint violation: when resolving method "org.slf4j.impl.StaticLoggerBinder.g
I am using weblogic version 12c 12.1.3 and I have updated the log4j jar version to log4j-api:2.17.1 log4j-core:2.17.1, but at the time of deployment in weblogic I am getting this error :-

```<code>weblogic.application.ModuleException: java.lang.LinkageError: loader constraint violation: when resolving method "org.slf4j.impl.StaticLoggerBinder.getLoggerFactory()Lorg/slf4j/ILoggerFactory;" the class loader (instance of weblogic/utils/classloaders/ChangeAwareClassLoader) of the current class, org/slf4j/LoggerFactory, and the class loader (instance of sun/misc/Launcher$AppClassLoader) for the method's defining class, org/slf4j/impl/StaticLoggerBinder, have different Class objects for the type org/slf4j/ILoggerFactory used in the signature
               at weblogic.application.internal.ExtensibleModuleWrapper.start(ExtensibleModuleWrapper.java:140)
               at weblogic.application.internal.flow.ModuleListenerInvoker.start(ModuleListenerInvoker.java:124)
               at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:216)
               at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:211)
               at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:42)
               Truncated. see log file for complete stacktrace
Caused By: java.lang.LinkageError: loader constraint violation: when resolving method "org.slf4j.impl.StaticLoggerBinder.getLoggerFactory()Lorg/slf4j/ILoggerFactory;" the class loader (instance of weblogic/utils/classloaders/ChangeAwareClassLoader) of the current class, org/slf4j/LoggerFactory, and the class loader (instance of sun/misc/Launcher$AppClassLoader) for the method's defining class, org/slf4j/impl/StaticLoggerBinder, have different Class objects for the type org/slf4j/ILoggerFactory used in the signature
               at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:273)
               at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:241)
               at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:254)
</code>```

Any solution on this ?

答:
I have this in my weblogic.xml file.  Not sure if this will fix your problem but worth a try...</p>
```<code><weblogic-web-app xmlns="http://xmlns.oracle.com/weblogic/weblogic-web-app" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.oracle.com/weblogic/weblogic-web-app http://xmlns.oracle.com/weblogic/weblogic-web-app/1.4/weblogic-web-app.xsd">
  ...
  <container-descriptor>
    <prefer-application-packages>
      <package-name>org.slf4j.*</package-name>
      <package-name>org.springframework.*</package-name>
    </prefer-application-packages>

    <prefer-application-resources>
      <resource-name>org/slf4j/impl/StaticLoggerBinder.class</resource-name>
    </prefer-application-resources>
  </container-descriptor>

</weblogic-web-app>
</code>```

Body:
I am using weblogic version 12c 12.1.3 and I have updated the log4j jar version to log4j-api:2.17.1 log4j-core:2.17.1, but at the time of deployment in weblogic I am getting this error :-

weblogic.application.ModuleException: java.lang.LinkageError: loader constraint violation: when resolving method "org.slf4j.impl.StaticLoggerBinder.getLoggerFactory()Lorg/slf4j/ILoggerFactory;" the class loader (instance of weblogic/utils/classloaders/ChangeAwareClassLoader) of the current class, org/slf4j/LoggerFactory, and the class loader (instance of sun/misc/Launcher$AppClassLoader) for the method's defining class, org/slf4j/impl/StaticLoggerBinder, have different Class objects for the type org/slf4j/ILoggerFactory used in the signature
               at weblogic.application.internal.ExtensibleModuleWrapper.start(ExtensibleModuleWrapper.java:140)
               at weblogic.application.internal.flow.ModuleListenerInvoker.start(ModuleListenerInvoker.java:124)
               at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:216)
               at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:211)
               at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:42)
               Truncated. see log file for complete stacktrace
Caused By: java.lang.LinkageError: loader constraint violation: when resolving method "org.slf4j.impl.StaticLoggerBinder.getLoggerFactory()Lorg/slf4j/ILoggerFactory;" the class loader (instance of weblogic/utils/classloaders/ChangeAwareClassLoader) of the current class, org/slf4j/LoggerFactory, and the class loader (instance of sun/misc/Launcher$AppClassLoader) for the method's defining class, org/slf4j/impl/StaticLoggerBinder, have different Class objects for the type org/slf4j/ILoggerFactory used in the signature
               at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:273)
               at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:241)
               at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:254)

Any solution on this ?

Body:
I have this in my weblogic.xml file.  Not sure if this will fix your problem but worth a try...

<weblogic-web-app xmlns="http://xmlns.oracle.com/weblogic/weblogic-web-app" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.oracle.com/weblogic/weblogic-web-app http://xmlns.oracle.com/weblogic/weblogic-web-app/1.4/weblogic-web-app.xsd">
  ...
  <container-descriptor>
    <prefer-application-packages>
      <package-name>org.slf4j.*</package-name>
      <package-name>org.springframework.*</package-name>
    </prefer-application-packages>

    <prefer-application-resources>
      <resource-name>org/slf4j/impl/StaticLoggerBinder.class</resource-name>
    </prefer-application-resources>
  </container-descriptor>

</weblogic-web-app>


问:
Traefik: Restore cloudflare real ip securely?
Cloudflare proxy includes a header named CF-Connecting-IP with the user's real ip. I would like to have traefik read this header and create a X-Real-Ip header with it's contents, but only if the source ip is a trusted/whitelisted one.

In the past I've used nginx and was able to do this using the http_realip_module

Is there a way to achieve something like this with traefik?

答:
I found those two plugins for traefik, that are capable of modifying the header:

https://github.com/XciD/traefik-plugin-rewrite-headers
or if you are already using pilot:
https://pilot.traefik.io/plugins/605afbe6a5f67ab9a1b0e540/rewrite-header

But based on the Cloudflare Documentation the CF-Connecting-IP header shares the real ip with the X-Forwarded-For header. The builtin traefik middleware https://doc.traefik.io/traefik/middlewares/http/ipwhitelist/ uses the x-forwarded-for header for allowing/denying access.


问:
Authentication login error: "Unhandled Rejection (TypeError): Failed to fetch"
I am learning on how to set up the authenticaton on my web-app. I have finished my back end encryption and connection to my database and currently I'm building my register component in the front end.
I working with MERN stack, and **I have tested all my routes with Postman, and worked successfully. ** The new users were posted to my database.

Do you know what triggers this error in my login form and what I can I do to sort it out?

Thanks in advance.

[

Register.js in client side.

```<code>import React, {useState} from 'react'

// The form passes tis value to a the state, which will  then be posted when clicking Submit in the form which triggers registerUser()

 function Register() {
   const[user, setUser] = useState({
     userName:"",
     email:"",
     password:"",
     profilePicture:"",
   });

  async function registerUser(event) {
    /* prevent the default behaviour caused by the event itself.
     Keep it from attempting to refresh the browser as the browser
    tries to submit the form to some back end server that doesn't exist */

    event.preventDefault()
       await fetch('http://localhost:5000/members/add', {
        method: 'POST',
        headers:{
          'Content-Type':'application/json;',
        },
        body: JSON.stringify({
          userName: user.userName,
          email: user.email,
          password: user.password,
          profilePicture: user.profilePicture,
        })
      }).then(data => data.json())
   }

  return(
    <div>
    <div className="login-wrapper">
      <h1>Register</h1>
      <p>Welcome to our app, please register.</p>
      <form onSubmit={e=> registerUser(e)}>
        <label>
          <p>Username</p>
          <input type="text" onChange={e => setUser((x)=>({ ...x, userName:e.target.value,}))} />
        </label>< br/>
        <label>
          <p>Profile Picture</p>
          <input type="text" onChange={e => setUser((x)=>({ ...x, profilePicture:e.target.value,}))} />
        </label>< br/>
        <label>
          <p>Email</p>
          <input type="email" onChange={e => setUser((x)=>({ ...x, email:e.target.value,}))}  />
        </label>< br/>
        <label>
          <p>Password</p>
          <input type="password" onChange={e => setUser((x)=>({ ...x, password:e.target.value,}))}  />
        </label>< br/>
        <div>
          <button type="submit">Submit</button>
        </div>
      </form>
    </div>
    </div>
  )
}

export {Register}
</code>```

I've followed Ben suggestion and looked at networking tab in devtools and found this error:

```<code>Access to fetch at 'http://localhost:5000/members/add' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
</code>```

答:
Fetch is throwing an unhandled exception. You should add the following to log more information about what might be causing the error.

await fetch('http://localhost:5000/members/add', {
  method: 'POST',
  headers:{
    'Content-Type':'application/json;',
  },
  body: JSON.stringify({
    userName: user.userName,
    email: user.email,
     password: user.password,
     profilePicture: user.profilePicture,
  })
})
.then(data => data.json())
.catch(error => console.error(error));
```

Without more information, it's hard to discern why the fetch request is failing. My suspicion is that you might not have the proper CORS in place. This would explain why it might be working from Postman but not from a browser.

Note: You can also use the networking tab in your browser dev tools to investigate any requests you make.

Body:
I am learning on how to set up the authenticaton on my web-app. I have finished my back end encryption and connection to my database and currently I'm building my register component in the front end.
I working with MERN stack, and **I have tested all my routes with Postman, and worked successfully. ** The new users were posted to my database.

Do you know what triggers this error in my login form and what I can I do to sort it out?

Thanks in advance.

[

Register.js in client side.

import React, {useState} from 'react'

// The form passes tis value to a the state, which will  then be posted when clicking Submit in the form which triggers registerUser()

 function Register() {
   const[user, setUser] = useState({
     userName:"",
     email:"",
     password:"",
     profilePicture:"",
   });

  async function registerUser(event) {
    /* prevent the default behaviour caused by the event itself.
     Keep it from attempting to refresh the browser as the browser
    tries to submit the form to some back end server that doesn't exist */

    event.preventDefault()
       await fetch('http://localhost:5000/members/add', {
        method: 'POST',
        headers:{
          'Content-Type':'application/json;',
        },
        body: JSON.stringify({
          userName: user.userName,
          email: user.email,
          password: user.password,
          profilePicture: user.profilePicture,
        })
      }).then(data => data.json())
   }

  return(

Register

Welcome to our app, please register.

      <form onSubmit={e=> registerUser(e)}>

Username

          <input type="text" onChange={e => setUser((x)=>({ ...x, userName:e.target.value,}))} />

Profile Picture

          <input type="text" onChange={e => setUser((x)=>({ ...x, profilePicture:e.target.value,}))} />

Email

          <input type="email" onChange={e => setUser((x)=>({ ...x, email:e.target.value,}))}  />

Password

          <input type="password" onChange={e => setUser((x)=>({ ...x, password:e.target.value,}))}  />

          <button type="submit">Submit</button>

      </form>

  )
}

export {Register}

I've followed Ben suggestion and looked at networking tab in devtools and found this error:

Access to fetch at 'http://localhost:5000/members/add' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

Body:
Fetch is throwing an unhandled exception. You should add the following to log more information about what might be causing the error.

await fetch('http://localhost:5000/members/add', {
  method: 'POST',
  headers:{
    'Content-Type':'application/json;',
  },
  body: JSON.stringify({
    userName: user.userName,
    email: user.email,
     password: user.password,
     profilePicture: user.profilePicture,
  })
})
.then(data => data.json())
.catch(error => console.error(error));

Without more information, it's hard to discern why the fetch request is failing. My suspicion is that you might not have the proper CORS in place. This would explain why it might be working from Postman but not from a browser.

Note: You can also use the networking tab in your browser dev tools to investigate any requests you make.


问:
Graph API cannot filter Azure AD B2B users by the phone number used to sign in
I'm unable to find users in Azure AD B2C by their phone number used to sign in using the Microsoft Graph API. According to the documentation, I should be able to query users by their identities as long as I provide issuer and issuerAssignedId in the filter, but I always receive an empty result set.

I've tried:

Querying by an email address identity instead. This succeeds.

Signing in for the first time with the phone number, in case there's some sort of initialization that needs to happen. The user is still not returned.

Querying by the user attribute mobilePhone. Querying by mobilePhone requires setting ConsistencyLevel=eventual, and ConsistencyLevel=eventual is not supported in Azure AD B2C.

Below is a request that successfully creates a test user, followed by requests trying to find that user by the email address or by the phone number.

The variable {{B2C_TENANT}} is the full tenant domain: example.onmicrosoft.com.

Create user

First, I create the user and give it two sign in identities: One with an email address, one with a phone number.

Request:

```<code>POST /v1.0/users HTTP/1.1
Host: graph.microsoft.com
Content-Type: application/json

{
    "accountEnabled": true,
    "displayName": "Stephen",
    "passwordPolicies": "DisablePasswordExpiration",
    "passwordProfile": {
        "password": "asdkljfdklsj2340982304#$#$",
        "forceChangePasswordNextSignIn": false
    },
    "identities": [
        {
          "signInType": "emailAddress",
          "issuer": "{{B2C_TENANT}}",
          "issuerAssignedId": "stephen@example.com"
        },
        {
            "signInType": "phoneNumber",
            "issuer": "{{B2C_TENANT}}",
            "issuerAssignedId": "+13105551234"
        }
    ]
}
</code>```

Find user by phone

This request always returns an empty result set, as though no user exists with the given phone number.

Request:

```<code>GET /v1.0/users/?$filter=identities/any(id:id/issuer eq '{{B2C_TENANT}}' and id/issuerAssignedId eq '+13105551234') HTTP/1.1
Host: graph.microsoft.com
</code>```

Response:

```<code>{
  "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users",
  "value": []
}
</code>```

Find user by email

This request returns the user. If I select the identities, I can see it contains the phone number sign in I'm trying to query in the previous request.

Request:

```<code>GET /v1.0/users/?$filter=identities/any(ident:ident/issuer eq '{{B2C_TENANT}}' and ident/issuerAssignedId eq 'stephen@example.com')&$select=id,userPrincipalName,displayName,identities HTTP/1.1
Host: graph.microsoft.com
</code>```

Response:

```<code>{
  "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users(id,userPrincipalName,displayName,identities)",
  "value": [
    {
      "id": "2de83c94-e734-470b-8ca2-c3279c364164",
      "userPrincipalName": "2de83c94-e734-470b-8ca2-c3279c364164@{{B2C_TENANT}}",
      "displayName": "Stephen",
      "identities": [
        {
          "signInType": "phoneNumber",
          "issuer": "{{B2C_TENANT}}",
          "issuerAssignedId": "+13105551234"
        },
        {
          "signInType": "emailAddress",
          "issuer": "{{B2C_TENANT}}",
          "issuerAssignedId": "stephen@example.com"
        },
        {
          "signInType": "userPrincipalName",
          "issuer": "{{B2C_TENANT}}",
          "issuerAssignedId": "2de83c94-e734-470b-8ca2-c3279c364164@{{B2C_TENANT}}"
        }
      ]
    }
  ]
}
</code>```

答: URL encode the phone number. %2B13105551234, then it works.

Body:
I'm unable to find users in Azure AD B2C by their phone number used to sign in using the Microsoft Graph API. According to the documentation, I should be able to query users by their identities as long as I provide issuer and issuerAssignedId in the filter, but I always receive an empty result set.

I've tried:

Querying by an email address identity instead. This succeeds.

Signing in for the first time with the phone number, in case there's some sort of initialization that needs to happen. The user is still not returned.

Querying by the user attribute mobilePhone. Querying by mobilePhone requires setting ConsistencyLevel=eventual, and ConsistencyLevel=eventual is not supported in Azure AD B2C.

Below is a request that successfully creates a test user, followed by requests trying to find that user by the email address or by the phone number.

The variable {{B2C_TENANT}} is the full tenant domain: example.onmicrosoft.com.

Create user

First, I create the user and give it two sign in identities: One with an email address, one with a phone number.

Request:

POST /v1.0/users HTTP/1.1
Host: graph.microsoft.com
Content-Type: application/json

{
    "accountEnabled": true,
    "displayName": "Stephen",
    "passwordPolicies": "DisablePasswordExpiration",
    "passwordProfile": {
        "password": "asdkljfdklsj2340982304#$#$",
        "forceChangePasswordNextSignIn": false
    },
    "identities": [
        {
          "signInType": "emailAddress",
          "issuer": "{{B2C_TENANT}}",
          "issuerAssignedId": "stephen@example.com"
        },
        {
            "signInType": "phoneNumber",
            "issuer": "{{B2C_TENANT}}",
            "issuerAssignedId": "+13105551234"
        }
    ]
}

Find user by phone

This request always returns an empty result set, as though no user exists with the given phone number.

Request:

GET /v1.0/users/?$filter=identities/any(id:id/issuer eq '{{B2C_TENANT}}' and id/issuerAssignedId eq '+13105551234') HTTP/1.1
Host: graph.microsoft.com

Response:

{
  "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users",
  "value": []
}

Find user by email

This request returns the user. If I select the identities, I can see it contains the phone number sign in I'm trying to query in the previous request.

Request:

GET /v1.0/users/?$filter=identities/any(ident:ident/issuer eq '{{B2C_TENANT}}' and ident/issuerAssignedId eq 'stephen@example.com')&$select=id,userPrincipalName,displayName,identities HTTP/1.1
Host: graph.microsoft.com

Response:

{
  "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users(id,userPrincipalName,displayName,identities)",
  "value": [
    {
      "id": "2de83c94-e734-470b-8ca2-c3279c364164",
      "userPrincipalName": "2de83c94-e734-470b-8ca2-c3279c364164@{{B2C_TENANT}}",
      "displayName": "Stephen",
      "identities": [
        {
          "signInType": "phoneNumber",
          "issuer": "{{B2C_TENANT}}",
          "issuerAssignedId": "+13105551234"
        },
        {
          "signInType": "emailAddress",
          "issuer": "{{B2C_TENANT}}",
          "issuerAssignedId": "stephen@example.com"
        },
        {
          "signInType": "userPrincipalName",
          "issuer": "{{B2C_TENANT}}",
          "issuerAssignedId": "2de83c94-e734-470b-8ca2-c3279c364164@{{B2C_TENANT}}"
        }
      ]
    }
  ]
}


问:
NGS Analysis: How can I extract the different variants in two VCF files
I am currently working on my thesis and I am trying to analyze the results of NGS sequencing Illumina. I am not really familiar with bioinformatics and in this part of my project, I am trying two compare two vcf files corresponding to the results of healthy tissue and tumor tissue. I want to compare these vcf files and remove their similarities. More specifically I want to remove the information of the healthy tissue from the tumor one. Have you any suggestions on which tool I should use or any way that I can do my analysis? If you can help me I would be more than thankful. Thank you in advance!</p>

答: I understand your problem. First thing I would recommend is to use Unix software  (I don't know which OS you're running) called VCFtools. It's pretty simple to use. But if You want to do all the processing with, for example python, you can use the pandas library for python which helps to process data in column format or PyVCF library, which is a parser for VCF files. I can help you more if you can provide some example data you're processing.


问:
What is Sqlite used for?
I don't know how authoritative this is but I found this:

http://www.sqlite.org/cvstrac/wiki?p=PerformanceConsiderations

and it doesn't seem good to have a lot of connections to sqlite.  This seems to be bad for the web and most applications that have more than a few users.  I'm having a hard time thinking of what sqlite would be used for when you don't need that many connections.  Every program I can think of needs users, lots of them sometimes, so what would I use a database for that doesn't allow that many connections?  I thought about prototypes but why would I use that when I can just connect to a larger database?  Embedded apps maybe?

Thank you.

EDIT:  Thanks everyone.  I look at the page recommended below but an confused about something:

Under appropriate uses for sqlite it has:

Situations Where SQLite Works Well

•Websites

SQLite usually will work great as the database engine for low to medium traffic websites (which is to say, 99.9% of all websites). The amount of web traffic that SQLite can handle depends, of course, on how heavily the website uses its database. Generally speaking, any site that gets fewer than 100K hits/day should work fine with SQLite. The 100K hits/day figure is a conservative estimate, not a hard upper bound. SQLite has been demonstrated to work with 10 times that amount of traffic.

Situations Where Another RDBMS May Work Better

•Client/Server Applications

If you have many client programs accessing a common database over a network, you should consider using a client/server database engine instead of SQLite. SQLite will work over a network filesystem, but because of the latency associated with most network filesystems, performance will not be great. Also, the file locking logic of many network filesystems implementation contains bugs (on both Unix and Windows). If file locking does not work like it should, it might be possible for two or more client programs to modify the same part of the same database at the same time, resulting in database corruption. Because this problem results from bugs in the underlying filesystem implementation, there is nothing SQLite can do to prevent it.

A good rule of thumb is that you should avoid using SQLite in situations where the same database will be accessed simultaneously from many computers over a network filesystem.

The Question:

I'm going to show my ignorance here but what is the difference between these two?

答:
It's good for situations where you don't have access to a "real" database and still want the power of a relational db. For example, Firefox stores a bunch of information about your settings/history/etc in an SQLite database. You can't expect everyone that runs firefox to have MySQL or postgre installed on their machine.

It's also perfectly capable of running relatively-low traffic, read-heavy websites. The performance of it is overall very good, it's more than the large majority of websites need for their traffic levels.

OwnerDisplayName: johnny

ContentLicense: CC BY-SA 2.5

Title: What is Sqlite used for?

LastEditorDisplayName: johnny

OwnerDisplayName: Chad Birch


问:
Get key events in CheckedListBox control when a listbox item is selected
I'm using a CheckedListBox as the base for a custom DataGridView cell classes edit mode.  I want to close the edit when the user presses the escape key.  If the user doesn't have anything selected overriding OnKeyDown works perfectly.  The problem is that if they do OnKeyDown (and OnKeyPressed) aren't fired by the CheckedListBox; instead the row item deselects itself and eats the event.  This means that if the user makes a selection by clicking on any item in the list it takes two presses of escape to close the edit.  One to unselect the row they clicked on, and a second to cancel edit mode.</p>

答:
Try to override the IsInputKey on your custom DataGridView itself and return false if it's [Esc], thus the grid ignores Esc.

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.isinputkey.aspx

You could maybe enhave this behavior by only ignoring the inputKey if there's nothing in 'edit mode' or similar.

ContentLicense: CC BY-SA 3.0


问:
Is QEMU's `savevm` transactional/atomic?
I've looked into QEMU documentation but found no answers.

I'm using QEMU's savevm command in monitor to save the vm snapshot. For simplicity i use the same tag (it's hightly unlikely to save a new snapshot and then remove existing snapshot due to lack of QEMU admin utils on the device). Is savevm transactional/atomic? Can it happen that no new snapshot is saved, but the existing one (to be overwritten) is corrupted or broken?

How can i understand savevm call was not successful (if it's the case)?

答:
Simply, savevm if you didn't give it a name or id, it will create a new one,
you can check it by this command

```<code>(qemu) info snapshots
</code>```

but if you want to overwrite it, just put an old name or id,

```<code>(qemu) savevm `old_snapshot_name`
</code>```

the attached link talked about that in more detail
here

Body:
Simply, savevm if you didn't give it a name or id, it will create a new one,
you can check it by this command

(qemu) info snapshots

but if you want to overwrite it, just put an old name or id,

(qemu) savevm `old_snapshot_name`

the attached link talked about that in more detail
here


问:
How to loop multiple objects in  in Vue.js?
I have an Array with multiple Objects, now I want to loop each object as a
 in a
. I have done that.

However, these objects may contain multiple objects. Then I want to display all objects within 1 object in 1 .

So this is the code what I have currently:

      {{ propertyValue }}

```
<pre class="lang-js prettyprint-override"><code>const tableData = [
  {
    tableRow: {
      name: 'test',
    },
    tableRow1: {
      test: 'testComponent',
    },
  },
  {
    tableRow: {
      name: 'test 1',
    },
  },
  {
    tableRow: {
      name: 'test 2',
    },
  },
];
</code>```

This should also happen for the other td's when there are multiple properties in the 2nd object.

How can I do this?

答:
Option 1: Calculate rowComponent per iteration

This can be done with a function that calculates the rowComponent for a particular column:

const getRowComponent = ({ rowComponent }, index) =>
  // Only proceed if rowComponent exists
  rowComponent &&

  // Get the object values of rowComponent as an array
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values
  Object.values(rowComponent)

  // Get array element at specified index (undefined if not found)
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at
  .at(index)
```
<p>The function would be used in the template per item of <code>tableData</code>, using the <code>rowData</code> index (named <code>propertyIndex</code> in this case):</p>
<pre class="lang-html prettyprint-override"><code><tr v-for="(data, index) in tableData" :key="index">
  <td v-for="(propertyValue, property, propertyIndex) in data.rowData" :key="property" class="table-body-data">
    <div class="table-body-data-item">
      <span>{{ propertyValue }}</span>

      <span>{{ getRowComponent(data, propertyIndex) }}</span>
    </div>
  </td>
</tr>
</code>```

demo 1

However, if performance is to be considered (e.g., there are many rows and columns), this solution would be inefficient because:

The function is called whenever this component is rendered, which can be multiple times.

The function calls Object.values() on the same object for each column, thus repeating work that was done on the previous column.

If there are only a few columns, this hit probably wouldn't matter much.

Option 2: Compute collated data, and render that

A more performant solution is to use a computed property that collates the corresponding rowData and rowComponent, returning an array that better facilitates accessing the paired data than the tableData object:

// https://stackoverflow.com/a/22015930/6277151
const zip = (a, b) => Array.from(Array(Math.max(b.length, a.length)), (_, i) => [a[i], b[i]])
const zipValues = (a, b) => zip(Object.values(a ?? {}), Object.values(b ?? {}))

// Computed table is an array of rows.
// Each row is an array of columns.
// Each column is an array of cell text.
const computedTableData = computed(() => tableData.map(item => zipValues(item.rowData, item.rowComponent)))
```
<p>Then use the computed array in the template instead of <code>tableData</code>:</p>
<pre class="lang-html prettyprint-override"><code><tr v-for="(row, rowIndex) in computedTableData" :key="rowIndex">
  <td v-for="(col, colIndex) in row" :key="colIndex" class="table-body-data">
    <div class="table-body-data-item">
      <span v-for="(cellText, cellTextIndex) in col" :key="cellTextIndex">{{ cellText }}</span>
    </div>
  </td>
</tr>
</code>```

demo 2

Title: How to loop multiple objects in <td> in Vue.js?

Body:
I have an Array with multiple Objects, now I want to loop each object as a
 in a
. I have done that.

However, these objects may contain multiple objects. Then I want to display all objects within 1 object in 1 .

So this is the code what I have currently:

      {{ propertyValue }}

const tableData = [
  {
    tableRow: {
      name: 'test',
    },
    tableRow1: {
      test: 'testComponent',
    },
  },
  {
    tableRow: {
      name: 'test 1',
    },
  },
  {
    tableRow: {
      name: 'test 2',
    },
  },
];

This should also happen for the other td's when there are multiple properties in the 2nd object.

How can I do this?

Body:
Option 1: Calculate rowComponent per iteration

This can be done with a function that calculates the rowComponent for a particular column:

const getRowComponent = ({ rowComponent }, index) =>
  // Only proceed if rowComponent exists
  rowComponent &&

  // Get the object values of rowComponent as an array
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values
  Object.values(rowComponent)

  // Get array element at specified index (undefined if not found)
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at
  .at(index)

The function would be used in the template per item of tableData, using the rowData index (named propertyIndex in this case):

<tr v-for="(data, index) in tableData" :key="index">
  <td v-for="(propertyValue, property, propertyIndex) in data.rowData" :key="property" class="table-body-data">
    <div class="table-body-data-item">
      <span>{{ propertyValue }}</span>

      <span>{{ getRowComponent(data, propertyIndex) }}</span>
    </div>
  </td>
</tr>

demo 1

However, if performance is to be considered (e.g., there are many rows and columns), this solution would be inefficient because:

The function is called whenever this component is rendered, which can be multiple times.

The function calls Object.values() on the same object for each column, thus repeating work that was done on the previous column.

If there are only a few columns, this hit probably wouldn't matter much.

Option 2: Compute collated data, and render that

A more performant solution is to use a computed property that collates the corresponding rowData and rowComponent, returning an array that better facilitates accessing the paired data than the tableData object:

// https://stackoverflow.com/a/22015930/6277151
const zip = (a, b) => Array.from(Array(Math.max(b.length, a.length)), (_, i) => [a[i], b[i]])
const zipValues = (a, b) => zip(Object.values(a ?? {}), Object.values(b ?? {}))

// Computed table is an array of rows.
// Each row is an array of columns.
// Each column is an array of cell text.
const computedTableData = computed(() => tableData.map(item => zipValues(item.rowData, item.rowComponent)))

Then use the computed array in the template instead of tableData:

<tr v-for="(row, rowIndex) in computedTableData" :key="rowIndex">
  <td v-for="(col, colIndex) in row" :key="colIndex" class="table-body-data">
    <div class="table-body-data-item">
      <span v-for="(cellText, cellTextIndex) in col" :key="cellTextIndex">{{ cellText }}</span>
    </div>
  </td>
</tr>

demo 2


问:
Why isn't SwiftUI "Toggle.onChange" firing?
I have a toggle UI element in a List, and I need to execute code when the toggle state changes. As I understand it, that's accomplished by using a binding on the toggle, and then adding a ".onChange:of:" on the binding variable.

Done:

```<code>//

import Foundation
import SwiftUI

struct User : Hashable, Identifiable {

    var isToggled = false

    var id: String
    var firstName: String?
    var lastName: String?
    var loggedIn: Bool = false
    var loggedInSince: String?
    var isActive: Bool?
    var isAdmin: Bool?

}

struct ListRow: View {
 @EnvironmentObject var userListModel: UserListModel

 @Binding var user: User

 var body: some View {
     Toggle(isOn: $user.loggedIn) {
         VStack {
           Text("\(user.firstName!) \(user.lastName!)")
             if user.loggedIn {
                 Text("Logged in since \(user.loggedInSince!)")
                     .font(Font.system(size: 10))
             }
             else {
                 Text("Logged out since \(user.loggedInSince!)")
                     .font(Font.system(size: 10))
             }
         }
     }
     .disabled(self.cantLogInOut())
     .onChange(of: user.loggedIn) { value in  // THIS ISN'T WORKING, IT'S NOT GETTING CALLED
         // action...
         print(value)
         userListModel.changeLogStatus(user: user)
     }
 }
</code>```

So, the code in the onChange ("print", "userListModel.changeLogStatus") is never called.

I'm getting this in the console:

```<code>2022-02-12 22:56:39.860044-0500 TimeCard[10104:4072116] invalid mode 'kCFRunLoopCommonModes' provided to CFRunLoopRunSpecific - break on _CFRunLoopError_RunCalledWithInvalidMode to debug. This message will only appear once per execution.
</code>```

I have no idea what that means, googling it isn't helpful, and when I put a Symbolic breakpoint on that error, nothing useful is shown in the debugger (it shows a stack trace that is two assembly code segments out of main.)

答:
Here is some code that you can use to "...execute code when the toggle state changes."
Since you are using userListModel.changeLogStatus(user: user) to record the change in loggedIn,
there is no need to have a @Binding var user: User use @State var user: User instead.

```<code>class UserListModel: ObservableObject {
    @Published var users = [User(isToggled: false, id: "1", firstName: "firstName-1", lastName: "lastName-1", loggedIn: false, loggedInSince: "yesterday", isActive: false, isAdmin: false),
                            User(isToggled: false, id: "2", firstName: "firstName-2", lastName: "lastName-2", loggedIn: false, loggedInSince: "yesterday", isActive: false, isAdmin: false),
                            User(isToggled: false, id: "3", firstName: "firstName-3", lastName: "lastName-3", loggedIn: false, loggedInSince: "yesterday", isActive: false, isAdmin: false)
    ]

    func changeLogStatus(user: User) {
        if let ndx = users.firstIndex(of: user) {
            users[ndx].loggedIn = user.loggedIn
        }
    }
}

struct User: Hashable, Identifiable {
    var isToggled = false
    var id: String
    var firstName: String?
    var lastName: String?
    var loggedIn: Bool = false
    var loggedInSince: String?
    var isActive: Bool?
    var isAdmin: Bool?
}

struct ListRow: View {
    @EnvironmentObject var userListModel: UserListModel

    @State var user: User  // <-- use @State

    var body: some View {
        Toggle(isOn: $user.loggedIn) {
            VStack {
                Text("\(user.firstName!) \(user.lastName!)")
                if user.loggedIn {
                    Text("Logged in since \(user.loggedInSince!)").font(Font.system(size: 10))
                }
                else {
                    Text("Logged in since \(user.loggedInSince!)").font(Font.system(size: 10))
                }
            }
        }
    //    .disabled(self.cantLogInOut())
        .onChange(of: user.loggedIn) { value in  // <-- THIS IS WORKING
            print("in onChange value: \(value)")
            userListModel.changeLogStatus(user: user)
        }
    }
}

    struct ContentView: View {
        @StateObject var model = UserListModel()

        var body: some View {
            List(model.users) { user in
                ListRow(user: user)
            }.environmentObject(model)
        }
    }

</code>```

You can also do the opposite, using only a binding, without the EnvironmentObject UserListModel, as in this code example:

```<code>struct ListRow: View {
    @Binding var user: User  // <-- use @Binding, no need for userListModel here

    var body: some View {
        Toggle(isOn: $user.loggedIn) {
            VStack {
                Text("\(user.firstName!) \(user.lastName!)")
                if user.loggedIn {
                    Text("Logged in since \(user.loggedInSince!)").font(Font.system(size: 10))
                }
                else {
                    Text("Logged in since \(user.loggedInSince!)").font(Font.system(size: 10))
                }
            }
        }
        //.disabled(self.cantLogInOut())
        .onChange(of: user.loggedIn) { value in  // <-- THIS IS WORKING
            print("in onChange value: \(value)")
        }
    }
}

struct ContentView: View {
    @StateObject var model = UserListModel()

    var body: some View {
        List($model.users) { $user in   // <-- note the $
            ListRow(user: $user)
        }
    }
}

</code>```

Body:
I have a toggle UI element in a List, and I need to execute code when the toggle state changes. As I understand it, that's accomplished by using a binding on the toggle, and then adding a ".onChange:of:" on the binding variable.

Done:

//

import Foundation
import SwiftUI

struct User : Hashable, Identifiable {

    var isToggled = false

    var id: String
    var firstName: String?
    var lastName: String?
    var loggedIn: Bool = false
    var loggedInSince: String?
    var isActive: Bool?
    var isAdmin: Bool?

}

struct ListRow: View {
 @EnvironmentObject var userListModel: UserListModel

 @Binding var user: User

 var body: some View {
     Toggle(isOn: $user.loggedIn) {
         VStack {
           Text("\(user.firstName!) \(user.lastName!)")
             if user.loggedIn {
                 Text("Logged in since \(user.loggedInSince!)")
                     .font(Font.system(size: 10))
             }
             else {
                 Text("Logged out since \(user.loggedInSince!)")
                     .font(Font.system(size: 10))
             }
         }
     }
     .disabled(self.cantLogInOut())
     .onChange(of: user.loggedIn) { value in  // THIS ISN'T WORKING, IT'S NOT GETTING CALLED
         // action...
         print(value)
         userListModel.changeLogStatus(user: user)
     }
 }

So, the code in the onChange ("print", "userListModel.changeLogStatus") is never called.

I'm getting this in the console:

2022-02-12 22:56:39.860044-0500 TimeCard[10104:4072116] invalid mode 'kCFRunLoopCommonModes' provided to CFRunLoopRunSpecific - break on _CFRunLoopError_RunCalledWithInvalidMode to debug. This message will only appear once per execution.

I have no idea what that means, googling it isn't helpful, and when I put a Symbolic breakpoint on that error, nothing useful is shown in the debugger (it shows a stack trace that is two assembly code segments out of main.)

Body:
Here is some code that you can use to "...execute code when the toggle state changes."
Since you are using userListModel.changeLogStatus(user: user) to record the change in loggedIn,
there is no need to have a @Binding var user: User use @State var user: User instead.

class UserListModel: ObservableObject {
    @Published var users = [User(isToggled: false, id: "1", firstName: "firstName-1", lastName: "lastName-1", loggedIn: false, loggedInSince: "yesterday", isActive: false, isAdmin: false),
                            User(isToggled: false, id: "2", firstName: "firstName-2", lastName: "lastName-2", loggedIn: false, loggedInSince: "yesterday", isActive: false, isAdmin: false),
                            User(isToggled: false, id: "3", firstName: "firstName-3", lastName: "lastName-3", loggedIn: false, loggedInSince: "yesterday", isActive: false, isAdmin: false)
    ]

    func changeLogStatus(user: User) {
        if let ndx = users.firstIndex(of: user) {
            users[ndx].loggedIn = user.loggedIn
        }
    }
}

struct User: Hashable, Identifiable {
    var isToggled = false
    var id: String
    var firstName: String?
    var lastName: String?
    var loggedIn: Bool = false
    var loggedInSince: String?
    var isActive: Bool?
    var isAdmin: Bool?
}

struct ListRow: View {
    @EnvironmentObject var userListModel: UserListModel

    @State var user: User  // <-- use @State

    var body: some View {
        Toggle(isOn: $user.loggedIn) {
            VStack {
                Text("\(user.firstName!) \(user.lastName!)")
                if user.loggedIn {
                    Text("Logged in since \(user.loggedInSince!)").font(Font.system(size: 10))
                }
                else {
                    Text("Logged in since \(user.loggedInSince!)").font(Font.system(size: 10))
                }
            }
        }
    //    .disabled(self.cantLogInOut())
        .onChange(of: user.loggedIn) { value in  // <-- THIS IS WORKING
            print("in onChange value: \(value)")
            userListModel.changeLogStatus(user: user)
        }
    }
}

    struct ContentView: View {
        @StateObject var model = UserListModel()

        var body: some View {
            List(model.users) { user in
                ListRow(user: user)
            }.environmentObject(model)
        }
    }

You can also do the opposite, using only a binding, without the EnvironmentObject UserListModel, as in this code example:

struct ListRow: View {
    @Binding var user: User  // <-- use @Binding, no need for userListModel here

    var body: some View {
        Toggle(isOn: $user.loggedIn) {
            VStack {
                Text("\(user.firstName!) \(user.lastName!)")
                if user.loggedIn {
                    Text("Logged in since \(user.loggedInSince!)").font(Font.system(size: 10))
                }
                else {
                    Text("Logged in since \(user.loggedInSince!)").font(Font.system(size: 10))
                }
            }
        }
        //.disabled(self.cantLogInOut())
        .onChange(of: user.loggedIn) { value in  // <-- THIS IS WORKING
            print("in onChange value: \(value)")
        }
    }
}

struct ContentView: View {
    @StateObject var model = UserListModel()

    var body: some View {
        List($model.users) { $user in   // <-- note the $
            ListRow(user: $user)
        }
    }
}


问:
Profiling a VBScript ASP website?
I recently started working on an E-Commerce site that is written in VBscript/Classic ASP. Coming from a PHP background... this is... less than pleasant.

The largest issue I have right now is that there is a ton of extra an unnecessary code. I am looking for a way to get a stack trace... see what functions get called on a particular page... how long the calls take... things like that.

Another thing that has to be slowing things down is the obscene and unnecessary ammount of Dims at the top of all the documents. There has to be a bunch of those that are legacy and not being used. Getting rid of extra Dims should free up memory and make things faster... I hope.

I have a copy of Visual Studio 2010 on my workstation... but I have no idea how to import the site into that... or if I can even accomplish what I'm looking for with VS2010.

Any suggestions as to how I can profile ASP/VBscript is greatly appreciated.

答:
How to profile a classic ASP web site?

I suggest you learn what the Dim statements do BEFORE you declare them useless and the cause of your slowdowns: http://www.htmlgoodies.com/primers/asp/article.php/3477891/ASP-Primer-Some-Basic-VBScript.htm

Title: Profiling a VBScript ASP website?


问:
My 'for' loop isn't updating my page counter properly. It's returning empty lists for certain results
I'm trying to update page_counter for every URL that doesn't return an empty JSON response.

```<code>headers = {"Accept": "application/.v3+json", "Authorization": "Bearer {api_key}"}

api_url = "https://api.taxes.info.net/taxes/%s/rate?page=%s"

page_counter = 1

     list =[
      {"state": "Ohio"},
      {"state": "Georgia"},
      {"state": "California"},
      {"state": "Texas"}
              ]

list_of_results = []

for i in list:
    state_name= i.get("state")
    url= api_url % (state_name, page_counter) #appends the key value of the state_name

print(url) returns >>>>> https://api.taxes.info.net/taxes/Ohio/rate?page=1, https://api.taxes.info.net/taxes/California/rate?page=1

    response = requests.get(url, headers=api_headers_somewhere)
    if response.json() != None:
        page_counter = page_counter + 1
    else:
        list_of_results.extend([item for item in response.json()])
</code>```

答:
The problem was that you didn't reset the page_counter, so for the next state you provided the API didn't have a page that high and as a result didn't return a JSON. You should use a while loop inside the for loop like so:

```<code>import requests
# changed the api_url to a function that returns an f string
def api_url(name, counter):
    return f"https://api.taxes.info.net/taxes/{name}/rate?page={counter}"

page_counter = 1

list_ =[
{"state": "Ohio"},
{"state": "Georgia"},
{"state": "California"},
{"state": "Texas"}
        ]
list_of_results = []

for state in list_:
    state_name = state.get("state")

    pages = True

    while pages:
        url= api_url(state_name, page_counter)
        response = requests.get(url, headers="api_headers_somewhere")
        if response.json() != None:
            page_counter += 1

        else:
            pages = False
            page_counter = 1
            list_of_results.extend([item for item in response.json()])
</code>```

A small note: page_counter += 1 is the same as page_counter = page_counter + 1.

Don't forget to change the headers to the correct headers.

Body:
I'm trying to update page_counter for every URL that doesn't return an empty JSON response.

headers = {"Accept": "application/.v3+json", "Authorization": "Bearer {api_key}"}

api_url = "https://api.taxes.info.net/taxes/%s/rate?page=%s"

page_counter = 1

     list =[
      {"state": "Ohio"},
      {"state": "Georgia"},
      {"state": "California"},
      {"state": "Texas"}
              ]

list_of_results = []

for i in list:
    state_name= i.get("state")
    url= api_url % (state_name, page_counter) #appends the key value of the state_name

print(url) returns >>>>> https://api.taxes.info.net/taxes/Ohio/rate?page=1, https://api.taxes.info.net/taxes/California/rate?page=1

    response = requests.get(url, headers=api_headers_somewhere)
    if response.json() != None:
        page_counter = page_counter + 1
    else:
        list_of_results.extend([item for item in response.json()])

Body:
The problem was that you didn't reset the page_counter, so for the next state you provided the API didn't have a page that high and as a result didn't return a JSON. You should use a while loop inside the for loop like so:

import requests
# changed the api_url to a function that returns an f string
def api_url(name, counter):
    return f"https://api.taxes.info.net/taxes/{name}/rate?page={counter}"

page_counter = 1

list_ =[
{"state": "Ohio"},
{"state": "Georgia"},
{"state": "California"},
{"state": "Texas"}
        ]
list_of_results = []

for state in list_:
    state_name = state.get("state")

    pages = True

    while pages:
        url= api_url(state_name, page_counter)
        response = requests.get(url, headers="api_headers_somewhere")
        if response.json() != None:
            page_counter += 1

        else:
            pages = False
            page_counter = 1
            list_of_results.extend([item for item in response.json()])

A small note: page_counter += 1 is the same as page_counter = page_counter + 1.

Don't forget to change the headers to the correct headers.


问:
Why replace in this code approves float numbers as numeric . I have tried floats without replace and I am getting message that it is not a number
```<code>#user inputs a number
number = input("Enter number: ")
# 1) changes dot and creates a new string,2) verifies is it a number
if(not number.replace(".","").isnumeric()):
    print("Sorry number is not numeric")
</code>```

Generally replace changes old value with a new one.

答:
isnumeric returns True if and only if every character of the string is a numeric character as defined by Unicode. Periods are not numeric, but many characters that contain or represent numbers, such as ½ or 六, are considered numeric.

First, you probably want isdigit instead, because a lot of the numeric characters in Unicode aren't valid in float numbers. isdigit only returns True if every character is one of the ASCII digits 0-9.

Second, to validate if the input is a float, it's "Better to Ask Forgiveness than Permission": try converting it as a float directly, and see if that fails:

try:
    float(number)
except ValueError:
    print("Sorry number is not a float")
```

Body:
#user inputs a number
number = input("Enter number: ")
# 1) changes dot and creates a new string,2) verifies is it a number
if(not number.replace(".","").isnumeric()):
    print("Sorry number is not numeric")

Generally replace changes old value with a new one.


问:
Biopython(SeqIO) 'FileNotFoundError'
I am new to BioPython and am trying to use several modules.
However, as you can see, in the process of using files such as Genbank or FASTA, such an error appears in the next module.
Can I ask how to solve it, and what procedure should I go through?

Error picture

The Genbank file was also saved in the computer, but the file is not recognized.

答:
You have to make sure, that your file is in the same directory as your notebook file. If you don't want to move the file near your notebook file, then you have to give a full path to your GenBank file, for example:

Bad

```<code>from Bio import SeqIO

record = SeqIO.parse("file.gb", "genbank")
</code>```

Good

```<code>from Bio import SeqIO
record = SeqIO.parse(r"path/to/your/file", "genbank")
</code>```

Title: Biopython(SeqIO) 'FileNotFoundError'

Body:
You have to make sure, that your file is in the same directory as your notebook file. If you don't want to move the file near your notebook file, then you have to give a full path to your GenBank file, for example:

Bad

from Bio import SeqIO

record = SeqIO.parse("file.gb", "genbank")

Good

from Bio import SeqIO
record = SeqIO.parse(r"path/to/your/file", "genbank")


问:
Help Rounding division
I need the end result to be a whole number.  If the division is a whole number fine but if it ends up with a decimal, I need to round up (midpoint).

Example if the division is 85.5, round up and result should be 86
If the division is 85.4, it would naturally round down ...basic rounding rules
If it's a whole number 85, then we're all good but should I store the result regardless of these 3 situations as type double?

```<code>double totalFoundPercent = Math.Round(
        (double) (totalNumbersDeleted / (totalNumbers - totalNumbersApproved)),
                  MidpointRounding.AwayFromZero);
</code>```

This is giving me an error of:

The call is ambiguous between the following methods or properties:
  'System.Math.Round(double, System.MidpointRounding)'  and
  'System.Math.Round(decimal, System.MidpointRounding)'

So I am not sure if this should be stored as a type double in the end or not plus the problem with the error.

答:
Once you have rounded a number, you have the choice of storing it as a integer or long as appropriate. You could choose to store it as a floating point type such as float or double but as you know it has no fractional part it would probably be clearer to a reader to see it represented as an integral type.

One thing to bear in mind is that floating point numbers are able to imprecisely store very large numbers which may not fit into a regular int or even long type. The biggest long is 9,223,372,036,854,775,807 whereas the biggest double is 1.7976931348623157 × 10³⁰⁸.

The error, however is confusing as it should patently be calling the double overload: there is no implicit conversion between double and decimal and your cast makes the type very clear. Are you sure you are getting this error with the exact code you have in your question?

Title: Help Rounding division

Body:
I need the end result to be a whole number.  If the division is a whole number fine but if it ends up with a decimal, I need to round up (midpoint).

Example if the division is 85.5, round up and result should be 86
If the division is 85.4, it would naturally round down ...basic rounding rules
If it's a whole number 85, then we're all good but should I store the result regardless of these 3 situations as type double?

double totalFoundPercent = Math.Round(
        (double) (totalNumbersDeleted / (totalNumbers - totalNumbersApproved)),
                  MidpointRounding.AwayFromZero);

This is giving me an error of:

The call is ambiguous between the following methods or properties:
  'System.Math.Round(double, System.MidpointRounding)'  and
  'System.Math.Round(decimal, System.MidpointRounding)'

So I am not sure if this should be stored as a type double in the end or not plus the problem with the error.


问:
Comparing elements at different indices in array Swift
In swift, I want to compare two different indexes in the same array. Right now, My code is something like:

```<code>var myArray:[String] = ["1" , "1", "2"]

for i in myArray{
     if(myArray[i] == myArray[i + 1]){
     // do something
     }
}
</code>```

From this, I get an error:

```<code>Cannot convert value of type 'String' to expected argument type 'Int'
</code>```

How do I go about fixing this?

答:
For-each construction (for i in array) does not provide you with an index, it takes elements from a sequence.

You may want to use ranges like this to aquire indices:
for i in 0 ..< array.count

Body:
In swift, I want to compare two different indexes in the same array. Right now, My code is something like:

var myArray:[String] = ["1" , "1", "2"]

for i in myArray{
     if(myArray[i] == myArray[i + 1]){
     // do something
     }
}

From this, I get an error:

Cannot convert value of type 'String' to expected argument type 'Int'

How do I go about fixing this?


问:
Grid Layout with ImageButton width and height
I am trying to create a Grid Layout with 2 Columns and 3 Rows. I will use ImageButtons for the grid, so that there's 6 images on the screen, each with the same size. When I add the background to the ImageButton, the button fills the whole screen. Should I add Width and Height properties to fix this? Can anyone help me?</p>
```<code><GridLayout
    android:id="@+id/team_grid"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:columnCount="2"
    android:rowCount="3"
    >

    <ImageButton
        android:id="@+id/alexandre"
        android:layout_rowWeight="1"
        android:layout_columnWeight="1"
        android:layout_gravity="fill"
        android:background=""
        android:textSize="18sp"
        android:src="@drawable/alexandre"/>

    <ImageButton
        android:id="@+id/barbara"
        android:layout_rowWeight="1"
        android:layout_columnWeight="1"
        android:layout_gravity="fill"
        android:background="#ffffff"
        android:textSize="18sp"
        android:src="@drawable/barbara"/>

    <ImageButton
        android:id="@+id/pedro"
        android:layout_rowWeight="1"
        android:layout_columnWeight="1"
        android:layout_gravity="fill"
        android:background="#ffffff"
        android:textSize="18sp"
        android:src="@drawable/goncalo"/>

    <ImageButton
        android:id="@+id/ImageButton4"
        android:layout_rowWeight="1"
        android:layout_columnWeight="1"
        android:layout_gravity="fill"
        android:background="#ffffff"
        android:textSize="18sp"
        android:src="@drawable/pedro">

    <ImageButton
        android:id="@+id/ImageButton5"
        android:layout_rowWeight="1"
        android:layout_columnWeight="1"
        android:layout_gravity="fill"
        android:background="#ffffff"
        android:textSize="18sp"
        android:src="@drawable/rafael"/>

    <ImageButton
        android:id="@+id/ImageButton6"
        android:layout_rowWeight="1"
        android:layout_columnWeight="1"
        android:layout_gravity="fill"
        android:background="#ffffff"
        android:textSize="18sp"
        android:src="@drawable/ricardo"/>

</GridLayout>
</code>```

答:
So, Your question is a bit confusing because in your XML you have set the background of each ImageButton to white color which seems to have no effect but if you try setting different color for each one then it will set a different color accordingly. And, you can't have an empty value for background like in your first ImageButton. And, try to add some padding and margin for the ImageButton.I tried your code and it work's fine. Here's what I did.</p>
```<code><GridLayout android:id="@+id/team_grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnCount="2"
android:rowCount="3"
xmlns:android="http://schemas.android.com/apk/res/android">

<ImageButton
    android:id="@+id/alexandre"
    android:layout_rowWeight="1"
    android:layout_columnWeight="1"
    android:layout_gravity="fill"
    android:textSize="18sp"
    android:background="@color/black"
    android:padding="5dp"
    android:layout_margin="5dp"
    android:src="@drawable/ic_launcher_background"/>

<ImageButton
    android:id="@+id/barbara"
    android:layout_rowWeight="1"
    android:layout_columnWeight="1"
    android:layout_gravity="fill"
    android:background="@android:color/holo_blue_bright"
    android:textSize="18sp"
    android:layout_margin="5dp"
    android:src="@drawable/ic_launcher_foreground"/>

<ImageButton
    android:id="@+id/pedro"
    android:layout_rowWeight="1"
    android:layout_columnWeight="1"
    android:layout_gravity="fill"
    android:background="@color/black"
    android:textSize="18sp"
    android:padding="5dp"
    android:layout_margin="5dp"
    android:src="@drawable/ic_launcher_background"/>

<ImageButton
    android:id="@+id/ImageButton4"
    android:layout_rowWeight="1"
    android:layout_columnWeight="1"
    android:layout_gravity="fill"
    android:background="@color/black"
    android:textSize="18sp"
    android:padding="5dp"
    android:layout_margin="5dp"
    android:src="@drawable/ic_launcher_foreground"/>

<ImageButton
    android:id="@+id/ImageButton5"
    android:layout_rowWeight="1"
    android:layout_columnWeight="1"
    android:layout_gravity="fill"
    android:background="@android:color/holo_blue_dark"
    android:textSize="18sp"
    android:layout_margin="5dp"
    android:padding="5dp"
    android:src="@drawable/ic_launcher_background"/>

<ImageButton
    android:id="@+id/ImageButton6"
    android:layout_rowWeight="1"
    android:layout_columnWeight="1"
    android:layout_gravity="fill"
    android:background="@android:color/holo_orange_dark"
    android:textSize="18sp"
    android:layout_margin="5dp"
    android:padding="5dp"
    android:src="@drawable/ic_launcher_foreground"/>
</code>```

Body:
I am trying to create a Grid Layout with 2 Columns and 3 Rows. I will use ImageButtons for the grid, so that there's 6 images on the screen, each with the same size. When I add the background to the ImageButton, the button fills the whole screen. Should I add Width and Height properties to fix this? Can anyone help me?

<GridLayout
    android:id="@+id/team_grid"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:columnCount="2"
    android:rowCount="3"
    >

    <ImageButton
        android:id="@+id/alexandre"
        android:layout_rowWeight="1"
        android:layout_columnWeight="1"
        android:layout_gravity="fill"
        android:background=""
        android:textSize="18sp"
        android:src="@drawable/alexandre"/>

    <ImageButton
        android:id="@+id/barbara"
        android:layout_rowWeight="1"
        android:layout_columnWeight="1"
        android:layout_gravity="fill"
        android:background="#ffffff"
        android:textSize="18sp"
        android:src="@drawable/barbara"/>

    <ImageButton
        android:id="@+id/pedro"
        android:layout_rowWeight="1"
        android:layout_columnWeight="1"
        android:layout_gravity="fill"
        android:background="#ffffff"
        android:textSize="18sp"
        android:src="@drawable/goncalo"/>

    <ImageButton
        android:id="@+id/ImageButton4"
        android:layout_rowWeight="1"
        android:layout_columnWeight="1"
        android:layout_gravity="fill"
        android:background="#ffffff"
        android:textSize="18sp"
        android:src="@drawable/pedro">

    <ImageButton
        android:id="@+id/ImageButton5"
        android:layout_rowWeight="1"
        android:layout_columnWeight="1"
        android:layout_gravity="fill"
        android:background="#ffffff"
        android:textSize="18sp"
        android:src="@drawable/rafael"/>

    <ImageButton
        android:id="@+id/ImageButton6"
        android:layout_rowWeight="1"
        android:layout_columnWeight="1"
        android:layout_gravity="fill"
        android:background="#ffffff"
        android:textSize="18sp"
        android:src="@drawable/ricardo"/>

</GridLayout>

Body:
So, Your question is a bit confusing because in your XML you have set the background of each ImageButton to white color which seems to have no effect but if you try setting different color for each one then it will set a different color accordingly. And, you can't have an empty value for background like in your first ImageButton. And, try to add some padding and margin for the ImageButton.I tried your code and it work's fine. Here's what I did.

<GridLayout android:id="@+id/team_grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnCount="2"
android:rowCount="3"
xmlns:android="http://schemas.android.com/apk/res/android">

<ImageButton
    android:id="@+id/alexandre"
    android:layout_rowWeight="1"
    android:layout_columnWeight="1"
    android:layout_gravity="fill"
    android:textSize="18sp"
    android:background="@color/black"
    android:padding="5dp"
    android:layout_margin="5dp"
    android:src="@drawable/ic_launcher_background"/>

<ImageButton
    android:id="@+id/barbara"
    android:layout_rowWeight="1"
    android:layout_columnWeight="1"
    android:layout_gravity="fill"
    android:background="@android:color/holo_blue_bright"
    android:textSize="18sp"
    android:layout_margin="5dp"
    android:src="@drawable/ic_launcher_foreground"/>

<ImageButton
    android:id="@+id/pedro"
    android:layout_rowWeight="1"
    android:layout_columnWeight="1"
    android:layout_gravity="fill"
    android:background="@color/black"
    android:textSize="18sp"
    android:padding="5dp"
    android:layout_margin="5dp"
    android:src="@drawable/ic_launcher_background"/>

<ImageButton
    android:id="@+id/ImageButton4"
    android:layout_rowWeight="1"
    android:layout_columnWeight="1"
    android:layout_gravity="fill"
    android:background="@color/black"
    android:textSize="18sp"
    android:padding="5dp"
    android:layout_margin="5dp"
    android:src="@drawable/ic_launcher_foreground"/>

<ImageButton
    android:id="@+id/ImageButton5"
    android:layout_rowWeight="1"
    android:layout_columnWeight="1"
    android:layout_gravity="fill"
    android:background="@android:color/holo_blue_dark"
    android:textSize="18sp"
    android:layout_margin="5dp"
    android:padding="5dp"
    android:src="@drawable/ic_launcher_background"/>

<ImageButton
    android:id="@+id/ImageButton6"
    android:layout_rowWeight="1"
    android:layout_columnWeight="1"
    android:layout_gravity="fill"
    android:background="@android:color/holo_orange_dark"
    android:textSize="18sp"
    android:layout_margin="5dp"
    android:padding="5dp"
    android:src="@drawable/ic_launcher_foreground"/>


问:
How to check email input from HTML button in Javascript
The outcome I want:

Click the button (div class button)

Check what is inputted (div class email)

If it isn't an email, return an error that it isn't an email.

```<code><div class="Email">
<input type="text" name="" class="em" placeholder="Email Address">
</div>
<div class="button" > <h2 class="re"> Request Access </h2> </div>
</div>
</code>```

I don't know where to start from JavaScript code. Any tips will help.

答:
Use regex to validate things like emails, passwords, usernames, etc. It's really powerful and can do a ton.

Solution:

<form class="email">
    <input type="email" class="emailInput" placeholder="Email Address" />
    <button type="submit">Request Access</button>

Please enter a valid email

</form>

```

Body:
The outcome I want:

Click the button (div class button)

Check what is inputted (div class email)

If it isn't an email, return an error that it isn't an email.

<input type="text" name="" class="em" placeholder="Email Address">

 Request Access

I don't know where to start from JavaScript code. Any tips will help.

Body:
Use regex to validate things like emails, passwords, usernames, etc. It's really powerful and can do a ton.

Solution:

<form class="email">
    <input type="email" class="emailInput" placeholder="Email Address" />
    <button type="submit">Request Access</button>
    <p id="error" style="color: red; display: none">Please enter a valid email</p>
</form>

<script>
    const email = document.querySelector('.emailInput');
    const submit = document.querySelector('button');
    const error = document.querySelector('#error');

    const showError = () => {
        error.style.display = 'block';
    };

    submit.addEventListener('click', (e) => {
        e.preventDefault();
        if (!email.value.match(/[^@ \t\r\n]+@[^@ \t\r\n]+\.[^@ \t\r\n]+/)) {
            return showError();
        }

        console.log('success');
    });
</script>


问:
Is there an `assert.deepEqual` that uses _non-strict_ equality for JavaScript?
I have reason to test eg. [ { valueOf: ()=>0 } ] to [ 0 ] and want that test to succeed.

Node assert, and Chai's various interfaces, all seem to automatically use strict equality when doing deep equality tests.

Is there an assert.deepEqual that will not do an assert.deepStrictEqual somewhere? A deep analog of assert.equal instead of assert.strictEqual ?

答:
All right, developing insight: it can't be done generally.

deepEqual will compare "all own and inherited enumerable object properties", and it will ( I am assuming here ) recursively descend on object properties until it encounters primitive values.

It has no reason to stop after the first level ( the array ), when encountering the second level ( the object ). The fact that my data actually has the encoding at the Object level is specific to my use case, and can not be assumed for the general case.

When arriving at primitive values for properties, then equality can generally usefully be non-strict.

The fact that an Object has a valueOf property ( which may or may not even be enumerable ) does not mean it should be treated as a primitive instead of an Object. Lots of things have a valueOf property.

The difference between deepEqual and equal is that equal knows it should be comparing two primitives ( or references ), and deepEqual can never know.

I was assuming too much, and asking the wrong question. Sorry SO.