问:
Replace text in HTMLBody of an email template
I have been using the below code for years to generate communications. I am adapting it to new requirements.

The code grabs data from Sharepoint/MS Teams to filter then copy into a new tab. The code calls an email template that contains placeholders in multiple tables which includes a banner. By using strings it replaces the value of cells with the placeholder.

The data has bullet points and is in paragraphs. However when the email is generated, it has the data in one block as one continuous line.

I tried inserting line breaks but without success.

My latest iteration is to use a replace function, after the loop through the string arrays.

.HTMLBody = replace(.htmlBody, ";", "
")
```
<p>I put ";" at the end of a line when I want to go the next line.</p>
<p>However, whilst the <code><BR></code> does add the line break, it changes the font to Times New Roman and puts in a lot HTML garbage when the email is generated. I suspect is it is from the <code>"<BR>"</code>.</p>
<p>The odd thing is when I add a <code>debug.print</code> onto <code>.htmlbody</code> it shows the font and line breaks are correct, with or without the second replace function.</p>
<p>I also tried to change <code>"<BR>"</code> with <code>CHR(10)</code> and <code>vbnewline</code> and other permutations.</p>
<p>I have not included the code that declares the outlook objects and the location of the email template as that works.</p>
<pre class="lang-vb prettyprint-override"><code>
Sub ImportSPData() 'Source the Sharepoint data

    Dim objMyList As ListObject
    Dim objWksheet As Worksheet
    Const strSPServer As String = "https://xxxx.xxxxx.xxx.com/teams/xxxx/_vti_bin" 'Sharepoint Url
    Const LISTNAME As String = "{1574AC55-E21A-41D2-9EEC-891CFEC69BF6}" 'Sharepoint list code - where the data is inputted
    Const VIEWNAME As String = "{34D4B58A-D4C6-4190-9248-896D062543C6}" 'Sharepoint View code - The specific view of the list

    Set objWksheet = Worksheets("ImportData") 'Where the data is exported to
    objWksheet.Select

    If ActiveSheet.AutoFilterMode Then
        ActiveSheet.Range("A1").AutoFilter
    End If

    objWksheet.Cells.Select
    Selection.ClearContents
    Range("A1").Select
    Set objMyList = objWksheet.ListObjects.Add(xlSrcExternal, Array(strSPServer, LISTNAME, VIEWNAME), False, , Range("A1")) 'where the above export lands
    Range("A1").Select
    ActiveSheet.ListObjects(1).Unlist
    If Not ActiveSheet.AutoFilterMode Then
        ActiveSheet.Range("A1").AutoFilter
    End If

    Call applyAutoFilter 'sets up the stage. However when the "Import Data" tab is viewed, the line breaks and bullet points are missing.

End Sub

Sub Replace()
    'Populate replacement strings from sharepoint. .Range("xx") corresponds to the column containing new text.
    Dim repNumberText As String: repNumberText = dataSheet.Range("f2").Value
    Dim repTitleText As String: repTitleText = dataSheet.Range("I2").Value
    Dim repSummaryText As String: repSummaryText = dataSheet.Range("B2").Value
    Dim repImpactText As String: repImpactText = dataSheet.Range("C2").Value
    Dim repUnderwayText As String: repUnderwayText = dataSheet.Range("D2").Value
    Dim repCompletedText As String: repCompletedText = dataSheet.Range("E2").Value
    Dim repUpdateText As String: repUpdateText = dataSheet.Range("G2").Value

    repSummaryText = "<p>" & repSummaryText & "</p>"
    repCompletedText = "<p>" & repCompletedText & "</p>"

    Dim replaceStrings() As Variant
    Dim replaceWithStrings() As Variant
    'Replacement Array, replaceStrings are the text placeholders in the email templates, replacewithstrings are the variables assigned above.
    replaceStrings = Array("NumberText", "TitleText", "SummaryText", "ImpactText", "UnderwayText", "CompletedText", "UpdateText")
    replaceWithStrings = Array(repNumberText, repTitleText, repSummaryText, repImpactText, repUnderwayText, repCompletedText, repUpdateText)
    Dim currentItem As String
    Dim currentReplaceItem As String
    Dim i As Integer
    i = UBound(replaceStrings)
    Dim j As Integer
    j = 0

    With msgFile
        Today = Format(Now(), "DDDD DD MMM yyyy")
        'Dim HtmlBody As String

        'Loop through arrays and replace text
        Do Until j = i + 1
            .HtmlBody = Replace(.HtmlBody, replaceStrings(j), replaceWithStrings(j))
            j = j + 1
        Loop

        'Replace subject texts.\
        ' .Subject = "Communications"
        ' .Subject = Today
        .Subject = Replace(.Subject, "NumberText", repNumberText)
        .Subject = Replace(.Subject, "TitleText", repTitleText) & " " & "-" & " " & Today

        .Display
</code>```

答:
It is not clear when and where all these customizations are made. Also it is not clear where the original item comes form. Anyway, keep in mind that you need to prepare a well-formed HTML document to be able to set up the HTMLBody property correctly. Even if Outlook handles cases where only some tags are provided, it is better to deal with a fully-formed HTML document.

The Outlook object model supports three main ways of customizing the message body:

The Body property returns or sets a string representing the clear-text body of the Outlook item.

The HTMLBody property of the MailItem class returns or sets a string representing the HTML body of the specified item. Setting the HTMLBody property will always update the Body property immediately. For example:

```<code>     Sub CreateHTMLMail()
       'Creates a new e-mail item and modifies its properties.
       Dim objMail As Outlook.MailItem
       'Create e-mail item
       Set objMail = Application.CreateItem(olMailItem)
       With objMail
        'Set body format to HTML
        .BodyFormat = olFormatHTML
        .HTMLBody = "<HTML><BODY>Enter the message <a href="http://google.com">text</a> here. </BODY></HTML>"
        .Display
       End With
     End Sub
</code>```

The Word object model can be used for dealing with message bodies. See Chapter 17: Working with Item Bodies for more information.

Note, the MailItem.BodyFormat property allows you to programmatically change the editor that is used for the body of an item.

Body:
I have been using the below code for years to generate communications. I am adapting it to new requirements.

The code grabs data from Sharepoint/MS Teams to filter then copy into a new tab. The code calls an email template that contains placeholders in multiple tables which includes a banner. By using strings it replaces the value of cells with the placeholder.

The data has bullet points and is in paragraphs. However when the email is generated, it has the data in one block as one continuous line.

I tried inserting line breaks but without success.

My latest iteration is to use a replace function, after the loop through the string arrays.

.HTMLBody = replace(.htmlBody, ";", "
")

I put ";" at the end of a line when I want to go the next line.

However, whilst the
 does add the line break, it changes the font to Times New Roman and puts in a lot HTML garbage when the email is generated. I suspect is it is from the "
".

The odd thing is when I add a debug.print onto .htmlbody it shows the font and line breaks are correct, with or without the second replace function.

I also tried to change "
" with CHR(10) and vbnewline and other permutations.

I have not included the code that declares the outlook objects and the location of the email template as that works.

Sub ImportSPData() 'Source the Sharepoint data

    Dim objMyList As ListObject
    Dim objWksheet As Worksheet
    Const strSPServer As String = "https://xxxx.xxxxx.xxx.com/teams/xxxx/_vti_bin" 'Sharepoint Url
    Const LISTNAME As String = "{1574AC55-E21A-41D2-9EEC-891CFEC69BF6}" 'Sharepoint list code - where the data is inputted
    Const VIEWNAME As String = "{34D4B58A-D4C6-4190-9248-896D062543C6}" 'Sharepoint View code - The specific view of the list

    Set objWksheet = Worksheets("ImportData") 'Where the data is exported to
    objWksheet.Select

    If ActiveSheet.AutoFilterMode Then
        ActiveSheet.Range("A1").AutoFilter
    End If

    objWksheet.Cells.Select
    Selection.ClearContents
    Range("A1").Select
    Set objMyList = objWksheet.ListObjects.Add(xlSrcExternal, Array(strSPServer, LISTNAME, VIEWNAME), False, , Range("A1")) 'where the above export lands
    Range("A1").Select
    ActiveSheet.ListObjects(1).Unlist
    If Not ActiveSheet.AutoFilterMode Then
        ActiveSheet.Range("A1").AutoFilter
    End If

    Call applyAutoFilter 'sets up the stage. However when the "Import Data" tab is viewed, the line breaks and bullet points are missing.

End Sub

Sub Replace()
    'Populate replacement strings from sharepoint. .Range("xx") corresponds to the column containing new text.
    Dim repNumberText As String: repNumberText = dataSheet.Range("f2").Value
    Dim repTitleText As String: repTitleText = dataSheet.Range("I2").Value
    Dim repSummaryText As String: repSummaryText = dataSheet.Range("B2").Value
    Dim repImpactText As String: repImpactText = dataSheet.Range("C2").Value
    Dim repUnderwayText As String: repUnderwayText = dataSheet.Range("D2").Value
    Dim repCompletedText As String: repCompletedText = dataSheet.Range("E2").Value
    Dim repUpdateText As String: repUpdateText = dataSheet.Range("G2").Value

    repSummaryText = "
" & repSummaryText & "
"
    repCompletedText = "
" & repCompletedText & "
"

    Dim replaceStrings() As Variant
    Dim replaceWithStrings() As Variant
    'Replacement Array, replaceStrings are the text placeholders in the email templates, replacewithstrings are the variables assigned above.
    replaceStrings = Array("NumberText", "TitleText", "SummaryText", "ImpactText", "UnderwayText", "CompletedText", "UpdateText")
    replaceWithStrings = Array(repNumberText, repTitleText, repSummaryText, repImpactText, repUnderwayText, repCompletedText, repUpdateText)
    Dim currentItem As String
    Dim currentReplaceItem As String
    Dim i As Integer
    i = UBound(replaceStrings)
    Dim j As Integer
    j = 0

    With msgFile
        Today = Format(Now(), "DDDD DD MMM yyyy")
        'Dim HtmlBody As String

        'Loop through arrays and replace text
        Do Until j = i + 1
            .HtmlBody = Replace(.HtmlBody, replaceStrings(j), replaceWithStrings(j))
            j = j + 1
        Loop

        'Replace subject texts.\
        ' .Subject = "Communications"
        ' .Subject = Today
        .Subject = Replace(.Subject, "NumberText", repNumberText)
        .Subject = Replace(.Subject, "TitleText", repTitleText) & " " & "-" & " " & Today

        .Display

Body:
It is not clear when and where all these customizations are made. Also it is not clear where the original item comes form. Anyway, keep in mind that you need to prepare a well-formed HTML document to be able to set up the HTMLBody property correctly. Even if Outlook handles cases where only some tags are provided, it is better to deal with a fully-formed HTML document.

The Outlook object model supports three main ways of customizing the message body:

The Body property returns or sets a string representing the clear-text body of the Outlook item.

The HTMLBody property of the MailItem class returns or sets a string representing the HTML body of the specified item. Setting the HTMLBody property will always update the Body property immediately. For example:

     Sub CreateHTMLMail()
       'Creates a new e-mail item and modifies its properties.
       Dim objMail As Outlook.MailItem
       'Create e-mail item
       Set objMail = Application.CreateItem(olMailItem)
       With objMail
        'Set body format to HTML
        .BodyFormat = olFormatHTML
        .HTMLBody = "<HTML><BODY>Enter the message <a href="http://google.com">text</a> here. </BODY></HTML>"
        .Display
       End With
     End Sub

The Word object model can be used for dealing with message bodies. See Chapter 17: Working with Item Bodies for more information.

Note, the MailItem.BodyFormat property allows you to programmatically change the editor that is used for the body of an item.


来源: stackexchange

问:
Why is my calculator not responding to my if statements?
Newbie programmer here. I'm finished with this project I was working on, and all of my if and else statements function properly, but only when they are placed at the very top of the code I'm writing.

For example, I started writing this code from if(number == 1) and worked my way down, but I eventually had to cut and paste them at the top, because when I entered a value that wasn't 1 (the first if statement, and thus the top statement that functions), the calculator failed to print anything at all when inputting a value for anything else except the top one. Because 4 is at the top, it works fine, but 1-3 don't work, and if I was to put 1 at the top then 2-4 would not print anything.

Here is a screeshot of the if statements on the bottom that do not print, and also have no debugging signs:

I'm sure it's a small issue that I managed to turn big.

```<code>#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    int number;
    float area1, area2, area3, area4;
    int R1;
    int trib;
    int trih;
    int top;
    int bott;
    int traph;
    int majxis;
    int minxis;
    const float PI= 3.14159;
    cout<< "I'm starting my program ";
    cout<<"\n1.Circle";
    cout<<"\n2.triangle";
    cout<<"\n3.trapezoid";
    cout<<"\n4.ellipse ";
    cout<<"\nEnter the corresponding number of your choice(1-4):";
    cin>> number;
    if(number <= 0)
    {
        cout<<"Integer is invalid, try again ";
        cin>> number;
    }
    if(number == 4)
    {
        cout<<"\nWhat is the length of the semi-major axis of the ellipse? ";
    }
     cin>> majxis;
     if(majxis <=0)
     {
         cout<<"Invalid value for the semi-major axis, try again: ";
     }
     else
     {
         cout<<"What is the length for the semi-minor axis of the ellipse? ";
     }
     cin>> minxis;
     area4= PI*minxis*majxis;
     if(minxis <=0)
     {
         cout<<"Invalid value for the semi-minor axis, try again: ";
     }
     else
     {
         cout<<"The area of an ellipse with a semi-major axis of " << majxis<< "and a semi-minor axis of " << minxis << "is " << area4;
     }
    if(number == 3)
    {
        cout<<"\nWhat is the length of the top of the trapezoid? ";
    }
     cin>> top;

     if(top <=0 )
     {
         cout<<"\n Invalid value for top length of trapezoid, try again";
     }
     else
     {
         cout<<"\nWhat is the length of the bottom of the trapezoid? ";
     }
     cin>> bott;
     if (bott <= 0)
     {
         cout<<"Invalid value for bottom length of trapezoid, try again: ";
     }
     else
     {
         cout<<"What is the height of the trapezoid? ";
     }
     cin>>traph;
     area3 = (top+bott)*0.5+traph;
     if (traph <= 0)
     {
         cout<<"Invalid value for height of trapezoid";
     }
     else
     {
         cout<<"The area of a trapezoid with a bottom of " << bott << "and a top of " << top << "is " << area3;
     }
    if(number == 2)
    {
        cout<<"\nWhat is the length of the base of the triangle?";
    }
    cin>> trib;
    if(trib<=0)
    {
        cout<<"\nInvalid Base of triangle, try again:";
    }
    else
    {
        cout<<"\nWhat is the height of the triangle? ";
    }
    cin>> trih;
    area2 = (0.5*trib)*trih;
    if(trih<=0)
    {
        cout<<"\nInvalid height of triangle, try again:";
    }
    else
    {
        cout<<"\nThe area of a trangle with a base of " << trib << "and a height of "<< trih <<" is " << area2;
    }
    if(number == 1)
    {
        cout<<"\nWhat is the radius of the circle?";
    }
    cin>> R1;
    area1 = PI*(R1 *R1);
    if( R1 <=0)
    {cout<<"\nRadius must be greater than 0, try again";
        cin>> R1;
    }
    else
    {
        cout<< "\nThe area of a circle with a radius of " << R1 << " is" << area1;
    }
}
</code>```

答:
It indeed is a small issue. Here is the correct program:

```<code>#include <iostream>
#include <iomanip>

int main()
{
    int number;
    float area1, area2, area3, area4;
    int R1;
    int trib;
    int trih;
    int top;
    int bott;
    int traph;
    int majxis;
    int minxis;
    const float PI = 3.14159;

    std::cout << "I'm starting my program ";
    std::cout << "\n1.Circle";
    std::cout << "\n2.triangle";
    std::cout << "\n3.trapezoid";
    std::cout << "\n4.ellipse ";
    std::cout << "\nEnter the corresponding number of your choice(1-4):";
    std::cin >> number;

    if (number <= 0)
    {
        std::cout << "Integer is invalid, try again ";
        std::cin >> number;
    }
    else if (number == 1)
    {
        std::cout << "\nWhat is the radius of the circle?";

        std::cin >> R1;
        area1 = PI * (R1 * R1);
        if (R1 <= 0)
        {
            std::cout << "\nRadius must be greater than 0, try again";
            std::cin >> R1;
        }
        else
        {
            std::cout << "\nThe area of a circle with a radius of " << R1 << " is" << area1;
        }
    }
    else if (number == 2)
    {
        std::cout << "\nWhat is the length of the base of the triangle?";

        std::cin >> trib;
        if (trib <= 0)
        {
            std::cout << "\nInvalid Base of triangle, try again:";
        }
        else
        {
            std::cout << "\nWhat is the height of the triangle? ";
        }
        std::cin >> trih;
        area2 = (0.5 * trib) * trih;
        if (trih <= 0)
        {
            std::cout << "\nInvalid height of triangle, try again:";
        }
        else
        {
            std::cout << "\nThe area of a trangle with a base of " << trib << "and a height of " << trih << " is " << area2;
        }
    }
    else if (number == 3)
    {
        std::cout << "\nWhat is the length of the top of the trapezoid? ";

        std::cin >> top;

        if (top <= 0)
        {
            std::cout << "\n Invalid value for top length of trapezoid, try again";
        }
        else
        {
            std::cout << "\nWhat is the length of the bottom of the trapezoid? ";
        }
        std::cin >> bott;
        if (bott <= 0)
        {
            std::cout << "Invalid value for bottom length of trapezoid, try again: ";
        }
        else
        {
            std::cout << "What is the height of the trapezoid? ";
        }
        std::cin >> traph;
        area3 = (top + bott) * 0.5 + traph;
        if (traph <= 0)
        {
            std::cout << "Invalid value for height of trapezoid";
        }
        else
        {
            std::cout << "The area of a trapezoid with a bottom of " << bott << "and a top of " << top << "is " << area3;
        }
    }
    else if (number == 4)
    {
        std::cout << "\nWhat is the length of the semi-major axis of the ellipse? ";

        std::cin >> majxis;
        if (majxis <= 0)
        {
            std::cout << "Invalid value for the semi-major axis, try again: ";
        }
        else
        {
            std::cout << "What is the length for the semi-minor axis of the ellipse? ";
        }
        std::cin >> minxis;
        area4 = PI * minxis * majxis;
        if (minxis <= 0)
        {
            std::cout << "Invalid value for the semi-minor axis, try again: ";
        }
        else
        {
            std::cout << "The area of an ellipse with a semi-major axis of " << majxis << "and a semi-minor axis of " << minxis << "is " << area4;
        }
    }
}
</code>```

Explanation: Let's take an example of the area of eclipse (number == 4). In your code, you have made the following if condition:

```<code>if(number == 4)
{
    cout<<"\nWhat is the length of the semi-major axis of the ellipse? ";
}
</code>```

This means if number == 4 then print - "\nWhat is the length of the semi-major axis of the ellipse? " but all of the code after it is outside the if condition's {} brackets, and thus is not considered as a part of the if statement. It will be called anyways even if number != 4. Now, in my code, I've done this:

```<code>else if (number == 4)
{
    std::cout << "\nWhat is the length of the semi-major axis of the ellipse? ";

    std::cin >> majxis;
    if (majxis <= 0)
    {
        std::cout << "Invalid value for the semi-major axis, try again: ";
    }
    else
    {
        std::cout << "What is the length for the semi-minor axis of the ellipse? ";
    }
    std::cin >> minxis;
    area4 = PI * minxis * majxis;
    if (minxis <= 0)
    {
        std::cout << "Invalid value for the semi-minor axis, try again: ";
    }
    else
    {
        std::cout << "The area of an ellipse with a semi-major axis of " << majxis << "and a semi-minor axis of " << minxis << "is " << area4;
    }
}
</code>```

Here, all of the code related to the area of the eclipse is all part of the if (number == 4) statement because it is present between the brackets {} of the if (number == 4) statement.

Apply this to all 4 cases and you get the correct program.

Also, it would be better to refactor your code as such:

```<code>#include <iostream>
#include <iomanip>

const float PI = 3.14159;

void areaof_circle()
{
    float area;
    int R1;

    std::cout << "\nWhat is the radius of the circle?";

    std::cin >> R1;
    area = PI * (R1 * R1);
    if (R1 <= 0)
    {
        std::cout << "\nRadius must be greater than 0, try again";
        std::cin >> R1;
    }
    else
    {
        std::cout << "\nThe area of a circle with a radius of " << R1 << " is" << area;
    }
}

void areaof_triangle()
{
    float area;
    int trib, trih;
    std::cout << "\nWhat is the length of the base of the triangle?";

    std::cin >> trib;
    if (trib <= 0)
    {
        std::cout << "\nInvalid Base of triangle, try again:";
    }
    else
    {
        std::cout << "\nWhat is the height of the triangle? ";
    }
    std::cin >> trih;
    area = (0.5 * trib) * trih;
    if (trih <= 0)
    {
        std::cout << "\nInvalid height of triangle, try again:";
    }
    else
    {
        std::cout << "\nThe area of a trangle with a base of " << trib << "and a height of " << trih << " is " << area;
    }
}

void areaof_trapezoid()
{
    float area;
    int top, bott, traph;

    std::cout << "\nWhat is the length of the top of the trapezoid? ";

    std::cin >> top;

    if (top <= 0)
    {
        std::cout << "\n Invalid value for top length of trapezoid, try again";
    }
    else
    {
        std::cout << "\nWhat is the length of the bottom of the trapezoid? ";
    }
    std::cin >> bott;
    if (bott <= 0)
    {
        std::cout << "Invalid value for bottom length of trapezoid, try again: ";
    }
    else
    {
        std::cout << "What is the height of the trapezoid? ";
    }
    std::cin >> traph;
    area = (top + bott) * 0.5 + traph;
    if (traph <= 0)
    {
        std::cout << "Invalid value for height of trapezoid";
    }
    else
    {
        std::cout << "The area of a trapezoid with a bottom of " << bott << "and a top of " << top << "is " << area;
    }
}

void areaof_ellipse()
{
    float area;
    int majxis, minxis;

    std::cout << "\nWhat is the length of the semi-major axis of the ellipse? ";

    std::cin >> majxis;
    if (majxis <= 0)
    {
        std::cout << "Invalid value for the semi-major axis, try again: ";
    }
    else
    {
        std::cout << "What is the length for the semi-minor axis of the ellipse? ";
    }
    std::cin >> minxis;
    area = PI * minxis * majxis;
    if (minxis <= 0)
    {
        std::cout << "Invalid value for the semi-minor axis, try again: ";
    }
    else
    {
        std::cout << "The area of an ellipse with a semi-major axis of " << majxis << "and a semi-minor axis of " << minxis << "is " << area;
    }
}

int main()
{
    int number;
    const float PI = 3.14159;

    std::cout << "I'm starting my program ";
    std::cout << "\n1.Circle";
    std::cout << "\n2.triangle";
    std::cout << "\n3.trapezoid";
    std::cout << "\n4.ellipse ";
    std::cout << "\nEnter the corresponding number of your choice(1-4):";
    std::cin >> number;

    if (number <= 0)
    {
        std::cout << "Integer is invalid, try again ";
        std::cin >> number;
    }
    else if (number == 1)
    {
        areaof_circle();
    }
    else if (number == 2)
    {
        areaof_triangle();
    }
    else if (number == 3)
    {
        areaof_trapezoid();
    }
    else if (number == 4)
    {
        areaof_ellipse();
    }
}
</code>```

Also, don't use the following in your programs:

```<code>using namespace std;
</code>```

...as it's considered as bad practice. Use std:: every time instead.

ContentLicense: CC BY-SA 4.0

Body:
Newbie programmer here. I'm finished with this project I was working on, and all of my if and else statements function properly, but only when they are placed at the very top of the code I'm writing.

For example, I started writing this code from if(number == 1) and worked my way down, but I eventually had to cut and paste them at the top, because when I entered a value that wasn't 1 (the first if statement, and thus the top statement that functions), the calculator failed to print anything at all when inputting a value for anything else except the top one. Because 4 is at the top, it works fine, but 1-3 don't work, and if I was to put 1 at the top then 2-4 would not print anything.

Here is a screeshot of the if statements on the bottom that do not print, and also have no debugging signs:

I'm sure it's a small issue that I managed to turn big.

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    int number;
    float area1, area2, area3, area4;
    int R1;
    int trib;
    int trih;
    int top;
    int bott;
    int traph;
    int majxis;
    int minxis;
    const float PI= 3.14159;
    cout<< "I'm starting my program ";
    cout<<"\n1.Circle";
    cout<<"\n2.triangle";
    cout<<"\n3.trapezoid";
    cout<<"\n4.ellipse ";
    cout<<"\nEnter the corresponding number of your choice(1-4):";
    cin>> number;
    if(number <= 0)
    {
        cout<<"Integer is invalid, try again ";
        cin>> number;
    }
    if(number == 4)
    {
        cout<<"\nWhat is the length of the semi-major axis of the ellipse? ";
    }
     cin>> majxis;
     if(majxis <=0)
     {
         cout<<"Invalid value for the semi-major axis, try again: ";
     }
     else
     {
         cout<<"What is the length for the semi-minor axis of the ellipse? ";
     }
     cin>> minxis;
     area4= PI*minxis*majxis;
     if(minxis <=0)
     {
         cout<<"Invalid value for the semi-minor axis, try again: ";
     }
     else
     {
         cout<<"The area of an ellipse with a semi-major axis of " << majxis<< "and a semi-minor axis of " << minxis << "is " << area4;
     }
    if(number == 3)
    {
        cout<<"\nWhat is the length of the top of the trapezoid? ";
    }
     cin>> top;

     if(top <=0 )
     {
         cout<<"\n Invalid value for top length of trapezoid, try again";
     }
     else
     {
         cout<<"\nWhat is the length of the bottom of the trapezoid? ";
     }
     cin>> bott;
     if (bott <= 0)
     {
         cout<<"Invalid value for bottom length of trapezoid, try again: ";
     }
     else
     {
         cout<<"What is the height of the trapezoid? ";
     }
     cin>>traph;
     area3 = (top+bott)*0.5+traph;
     if (traph <= 0)
     {
         cout<<"Invalid value for height of trapezoid";
     }
     else
     {
         cout<<"The area of a trapezoid with a bottom of " << bott << "and a top of " << top << "is " << area3;
     }
    if(number == 2)
    {
        cout<<"\nWhat is the length of the base of the triangle?";
    }
    cin>> trib;
    if(trib<=0)
    {
        cout<<"\nInvalid Base of triangle, try again:";
    }
    else
    {
        cout<<"\nWhat is the height of the triangle? ";
    }
    cin>> trih;
    area2 = (0.5*trib)*trih;
    if(trih<=0)
    {
        cout<<"\nInvalid height of triangle, try again:";
    }
    else
    {
        cout<<"\nThe area of a trangle with a base of " << trib << "and a height of "<< trih <<" is " << area2;
    }
    if(number == 1)
    {
        cout<<"\nWhat is the radius of the circle?";
    }
    cin>> R1;
    area1 = PI*(R1 *R1);
    if( R1 <=0)
    {cout<<"\nRadius must be greater than 0, try again";
        cin>> R1;
    }
    else
    {
        cout<< "\nThe area of a circle with a radius of " << R1 << " is" << area1;
    }
}

Body:
It indeed is a small issue. Here is the correct program:

#include <iostream>
#include <iomanip>

int main()
{
    int number;
    float area1, area2, area3, area4;
    int R1;
    int trib;
    int trih;
    int top;
    int bott;
    int traph;
    int majxis;
    int minxis;
    const float PI = 3.14159;

    std::cout << "I'm starting my program ";
    std::cout << "\n1.Circle";
    std::cout << "\n2.triangle";
    std::cout << "\n3.trapezoid";
    std::cout << "\n4.ellipse ";
    std::cout << "\nEnter the corresponding number of your choice(1-4):";
    std::cin >> number;

    if (number <= 0)
    {
        std::cout << "Integer is invalid, try again ";
        std::cin >> number;
    }
    else if (number == 1)
    {
        std::cout << "\nWhat is the radius of the circle?";

        std::cin >> R1;
        area1 = PI * (R1 * R1);
        if (R1 <= 0)
        {
            std::cout << "\nRadius must be greater than 0, try again";
            std::cin >> R1;
        }
        else
        {
            std::cout << "\nThe area of a circle with a radius of " << R1 << " is" << area1;
        }
    }
    else if (number == 2)
    {
        std::cout << "\nWhat is the length of the base of the triangle?";

        std::cin >> trib;
        if (trib <= 0)
        {
            std::cout << "\nInvalid Base of triangle, try again:";
        }
        else
        {
            std::cout << "\nWhat is the height of the triangle? ";
        }
        std::cin >> trih;
        area2 = (0.5 * trib) * trih;
        if (trih <= 0)
        {
            std::cout << "\nInvalid height of triangle, try again:";
        }
        else
        {
            std::cout << "\nThe area of a trangle with a base of " << trib << "and a height of " << trih << " is " << area2;
        }
    }
    else if (number == 3)
    {
        std::cout << "\nWhat is the length of the top of the trapezoid? ";

        std::cin >> top;

        if (top <= 0)
        {
            std::cout << "\n Invalid value for top length of trapezoid, try again";
        }
        else
        {
            std::cout << "\nWhat is the length of the bottom of the trapezoid? ";
        }
        std::cin >> bott;
        if (bott <= 0)
        {
            std::cout << "Invalid value for bottom length of trapezoid, try again: ";
        }
        else
        {
            std::cout << "What is the height of the trapezoid? ";
        }
        std::cin >> traph;
        area3 = (top + bott) * 0.5 + traph;
        if (traph <= 0)
        {
            std::cout << "Invalid value for height of trapezoid";
        }
        else
        {
            std::cout << "The area of a trapezoid with a bottom of " << bott << "and a top of " << top << "is " << area3;
        }
    }
    else if (number == 4)
    {
        std::cout << "\nWhat is the length of the semi-major axis of the ellipse? ";

        std::cin >> majxis;
        if (majxis <= 0)
        {
            std::cout << "Invalid value for the semi-major axis, try again: ";
        }
        else
        {
            std::cout << "What is the length for the semi-minor axis of the ellipse? ";
        }
        std::cin >> minxis;
        area4 = PI * minxis * majxis;
        if (minxis <= 0)
        {
            std::cout << "Invalid value for the semi-minor axis, try again: ";
        }
        else
        {
            std::cout << "The area of an ellipse with a semi-major axis of " << majxis << "and a semi-minor axis of " << minxis << "is " << area4;
        }
    }
}

Explanation: Let's take an example of the area of eclipse (number == 4). In your code, you have made the following if condition:

if(number == 4)
{
    cout<<"\nWhat is the length of the semi-major axis of the ellipse? ";
}

This means if number == 4 then print - "\nWhat is the length of the semi-major axis of the ellipse? " but all of the code after it is outside the if condition's {} brackets, and thus is not considered as a part of the if statement. It will be called anyways even if number != 4. Now, in my code, I've done this:

else if (number == 4)
{
    std::cout << "\nWhat is the length of the semi-major axis of the ellipse? ";

    std::cin >> majxis;
    if (majxis <= 0)
    {
        std::cout << "Invalid value for the semi-major axis, try again: ";
    }
    else
    {
        std::cout << "What is the length for the semi-minor axis of the ellipse? ";
    }
    std::cin >> minxis;
    area4 = PI * minxis * majxis;
    if (minxis <= 0)
    {
        std::cout << "Invalid value for the semi-minor axis, try again: ";
    }
    else
    {
        std::cout << "The area of an ellipse with a semi-major axis of " << majxis << "and a semi-minor axis of " << minxis << "is " << area4;
    }
}

Here, all of the code related to the area of the eclipse is all part of the if (number == 4) statement because it is present between the brackets {} of the if (number == 4) statement.

Apply this to all 4 cases and you get the correct program.

Also, it would be better to refactor your code as such:

#include <iostream>
#include <iomanip>

const float PI = 3.14159;

void areaof_circle()
{
    float area;
    int R1;

    std::cout << "\nWhat is the radius of the circle?";

    std::cin >> R1;
    area = PI * (R1 * R1);
    if (R1 <= 0)
    {
        std::cout << "\nRadius must be greater than 0, try again";
        std::cin >> R1;
    }
    else
    {
        std::cout << "\nThe area of a circle with a radius of " << R1 << " is" << area;
    }
}

void areaof_triangle()
{
    float area;
    int trib, trih;
    std::cout << "\nWhat is the length of the base of the triangle?";

    std::cin >> trib;
    if (trib <= 0)
    {
        std::cout << "\nInvalid Base of triangle, try again:";
    }
    else
    {
        std::cout << "\nWhat is the height of the triangle? ";
    }
    std::cin >> trih;
    area = (0.5 * trib) * trih;
    if (trih <= 0)
    {
        std::cout << "\nInvalid height of triangle, try again:";
    }
    else
    {
        std::cout << "\nThe area of a trangle with a base of " << trib << "and a height of " << trih << " is " << area;
    }
}

void areaof_trapezoid()
{
    float area;
    int top, bott, traph;

    std::cout << "\nWhat is the length of the top of the trapezoid? ";

    std::cin >> top;

    if (top <= 0)
    {
        std::cout << "\n Invalid value for top length of trapezoid, try again";
    }
    else
    {
        std::cout << "\nWhat is the length of the bottom of the trapezoid? ";
    }
    std::cin >> bott;
    if (bott <= 0)
    {
        std::cout << "Invalid value for bottom length of trapezoid, try again: ";
    }
    else
    {
        std::cout << "What is the height of the trapezoid? ";
    }
    std::cin >> traph;
    area = (top + bott) * 0.5 + traph;
    if (traph <= 0)
    {
        std::cout << "Invalid value for height of trapezoid";
    }
    else
    {
        std::cout << "The area of a trapezoid with a bottom of " << bott << "and a top of " << top << "is " << area;
    }
}

void areaof_ellipse()
{
    float area;
    int majxis, minxis;

    std::cout << "\nWhat is the length of the semi-major axis of the ellipse? ";

    std::cin >> majxis;
    if (majxis <= 0)
    {
        std::cout << "Invalid value for the semi-major axis, try again: ";
    }
    else
    {
        std::cout << "What is the length for the semi-minor axis of the ellipse? ";
    }
    std::cin >> minxis;
    area = PI * minxis * majxis;
    if (minxis <= 0)
    {
        std::cout << "Invalid value for the semi-minor axis, try again: ";
    }
    else
    {
        std::cout << "The area of an ellipse with a semi-major axis of " << majxis << "and a semi-minor axis of " << minxis << "is " << area;
    }
}

int main()
{
    int number;
    const float PI = 3.14159;

    std::cout << "I'm starting my program ";
    std::cout << "\n1.Circle";
    std::cout << "\n2.triangle";
    std::cout << "\n3.trapezoid";
    std::cout << "\n4.ellipse ";
    std::cout << "\nEnter the corresponding number of your choice(1-4):";
    std::cin >> number;

    if (number <= 0)
    {
        std::cout << "Integer is invalid, try again ";
        std::cin >> number;
    }
    else if (number == 1)
    {
        areaof_circle();
    }
    else if (number == 2)
    {
        areaof_triangle();
    }
    else if (number == 3)
    {
        areaof_trapezoid();
    }
    else if (number == 4)
    {
        areaof_ellipse();
    }
}

Also, don't use the following in your programs:

using namespace std;

...as it's considered as bad practice. Use std:: every time instead.


问:
bash or zsh: how to pass multiple inputs to interactive piped parameters?
I have 3 different files that I want to compare

words_freq
words_freq_deduped
words_freq_alpha

For each file, I run a command like so, which I iterate on constantly to compare the results.

For example, I would do this:

```<code>$ cat words_freq | grep -v '[soe]'
$ cat words_freq_deduped | grep -v '[soe]'
$ cat words_freq_alpha | grep -v '[soe]'
</code>```

and then review the results, and then do it again, with an additional filter

```<code>$ cat words_freq | grep -v '[soe]' | grep a | grep r | head -n20
a

$ cat words_freq_deduped | grep -v '[soe]' | grep a | grep r | head -n20
b

$ cat words_freq_alpha | grep -v '[soe]' | grep a | grep r | head -n20
c
</code>```

This continues on until I've analyzed my data.

I would like to write a script that could take the piped portions, and pass it to each of these files, as I iterate on the grep/head portions of the command.

e.g. The following would dump the results of running the 3 commands above AND also compare the 3 results, and dump additional calculations on them

```<code>$ myScript | grep -v '[soe]' | grep a | grep r | head -n20
the letters were in all 3 runs, and it took 5 seconds
a
b
c
</code>```

How can I do this using bash/python or zsh for the myScript part?

EDIT: After asking the question, it occurred to me that I could use eval to do it, like so, which I've added as an answer as well

The following approach allows me to process multiple files by using eval, which I know is frowned upon - any other suggestions are greatly appreciated!

```<code>$ myScript "grep -v '[soe]' | grep a | grep r | head -n20"
</code>```

myScript

```<code>#!/usr/bin/env bash
function doIt(){
  FILE=$1
  CMD="cat $1 | $2"
  echo processing file "$FILE"
  eval "$CMD"
  echo
}

doIt words_freq "$@"
doIt words_freq_deduped "$@"
doIt words_freq_alpha "$@"
</code>```

Body:
I have 3 different files that I want to compare

words_freq
words_freq_deduped
words_freq_alpha

For each file, I run a command like so, which I iterate on constantly to compare the results.

For example, I would do this:

$ cat words_freq | grep -v '[soe]'
$ cat words_freq_deduped | grep -v '[soe]'
$ cat words_freq_alpha | grep -v '[soe]'

and then review the results, and then do it again, with an additional filter

$ cat words_freq | grep -v '[soe]' | grep a | grep r | head -n20
a

$ cat words_freq_deduped | grep -v '[soe]' | grep a | grep r | head -n20
b

$ cat words_freq_alpha | grep -v '[soe]' | grep a | grep r | head -n20
c

This continues on until I've analyzed my data.

I would like to write a script that could take the piped portions, and pass it to each of these files, as I iterate on the grep/head portions of the command.

e.g. The following would dump the results of running the 3 commands above AND also compare the 3 results, and dump additional calculations on them

$ myScript | grep -v '[soe]' | grep a | grep r | head -n20
the letters were in all 3 runs, and it took 5 seconds
a
b
c

How can I do this using bash/python or zsh for the myScript part?

EDIT: After asking the question, it occurred to me that I could use eval to do it, like so, which I've added as an answer as well

The following approach allows me to process multiple files by using eval, which I know is frowned upon - any other suggestions are greatly appreciated!

$ myScript "grep -v '[soe]' | grep a | grep r | head -n20"

myScript

#!/usr/bin/env bash
function doIt(){
  FILE=$1
  CMD="cat $1 | $2"
  echo processing file "$FILE"
  eval "$CMD"
  echo
}

doIt words_freq "$@"
doIt words_freq_deduped "$@"
doIt words_freq_alpha "$@"


问:
Why is DHT11 Sensor not giving correct readings on Arduino Mega?
This is the outcome I am getting

#include <SimpleDHT.h>

// for DHT11,

//      VCC: 5V or 3V

//      GND: GND

//      DATA: 2

int pinDHT11 = 2;

SimpleDHT11

dht11(pinDHT11);

void setup() {

Serial.begin(9600);

}

void loop() {

// start working...

Serial.println("=================================");

Serial.println("Sample DHT11...");

// read without samples.

byte temperature = 0;

byte humidity = 0;

int err = SimpleDHTErrSuccess;

if ((err = dht11.read(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {

```<code>Serial.print("Read DHT11 failed, err="); Serial.print(SimpleDHTErrCode(err));

Serial.print(","); Serial.println(SimpleDHTErrDuration(err)); delay(1000);

return;
</code>```

}

Serial.print("Sample OK: ");

Serial.print((int)temperature); Serial.print(" *C, ");

Serial.print((int)humidity); Serial.println(" H");

// DHT11 sampling rate is 1HZ.

delay(1500);

}

答: The reason the DHT11 would not work was because the sesnors were actualy faulty. There was nothing wrong with our code or wirings. We figured this out by trying a third DHT11 sensor which was brand new and just out of the packet. This time it worked and gave us accurate realistic readings.</p>

Body:
This is the outcome I am getting

#include <SimpleDHT.h>

// for DHT11,

//      VCC: 5V or 3V

//      GND: GND

//      DATA: 2

int pinDHT11 = 2;

SimpleDHT11

dht11(pinDHT11);

void setup() {

Serial.begin(9600);

}

void loop() {

// start working...

Serial.println("=================================");

Serial.println("Sample DHT11...");

// read without samples.

byte temperature = 0;

byte humidity = 0;

int err = SimpleDHTErrSuccess;

if ((err = dht11.read(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {

Serial.print("Read DHT11 failed, err="); Serial.print(SimpleDHTErrCode(err));

Serial.print(","); Serial.println(SimpleDHTErrDuration(err)); delay(1000);

return;

}

Serial.print("Sample OK: ");

Serial.print((int)temperature); Serial.print(" *C, ");

Serial.print((int)humidity); Serial.println(" H");

// DHT11 sampling rate is 1HZ.

delay(1500);

}


问:
How to split an element on R?
Well, I'm working on a data frame that has a column where some elements have two or more words. I'm trying to use this column as a vector to make a pie chart, and I need the words on these elements to be split into single ones to be counted as individuals for the chart.

That's the vector in question:

```<code>science$area
 [1] "Matematica"                          "Filosofia"
 [3] "Arqueologia"                         "Astronomia"
 [5] "Biologia, Paleontologia"             "Biologia"
 [7] "Psicologia"                          "Astronomia"
 [9] "Fisica"                              "Biologia, Paleontologia"
[11] "Astronomia"                          "Biologia"
[13] "Biologia, Fisica, Matematica, Saude" "Fisica"
[15] "Paleontologia"                       "Saude"
[17] "Biologia, Saude"                     "Biologia, Saude"
[19] "Saude"                               NA
[21] "Biologia"                            "Fisica"
[23] "Psicologia"                          "Biologia"
[25] "Fisica"                              "Biologia"
[27] NA                                    "Historia"
[29] "Experiencias"                        "Astronomia"
[31] "Geografia"                           "Matematica"
[33] "Astronomia"                          "Filosofia, Literatura"
[35] "Biologia"                            "Psicologia"
[37] "Biologia, Saude"                     "Saude"
[39] "Fisica"                              "Experiencias, Fisica"
[41] "Biologia, Saude"                     "Biologia"
[43] "Computacao"                          "Biologia"
[45] "Fisica"                              "Fisica"
[47] "Filosofia, Historia, Literatura"     NA
[49] "Literatura"                          "Astronomia"
[51] "Geografia, Meio Ambiente"            "Geografia"
[53] "Biologia, Paleontologia"             "Computacao"
[55] "Fisica, Literatura"                  "Filosofia"
[57] "Geografia, Meio Ambiente"            "Fisica"
[59] "Biologia"                            "Geografia, Historia"
</code>```

When I summarize it, this returns:

```<code>> summary(factor(science$area))
                    Arqueologia                          Astronomia
                              1                                   6
                       Biologia Biologia, Fisica, Matematica, Saude
                              9                                   1
        Biologia, Paleontologia                     Biologia, Saude
                              3                                   4
                     Computacao                        Experiencias
                              2                                   1
           Experiencias, Fisica                           Filosofia
                              1                                   2
Filosofia, Historia, Literatura               Filosofia, Literatura
                              1                                   1
                         Fisica                  Fisica, Literatura
                              8                                   1
                      Geografia                 Geografia, Historia
                              2                                   1
       Geografia, Meio Ambiente                            Historia
                              2                                   1
                     Literatura                          Matematica
                              1                                   2
                  Paleontologia                          Psicologia
                              1                                   3
                          Saude                                NA's
                              3                                   3
</code>```

So, as you can see, "Biologia, Paleontologia" is being treated as a level for example, and I need it to count to both "Biologia" and "Paleontologia" instead. How can I do this?? I've already tried, unsuccessfully, to write these elements using c() and using "" amongst them, and also tried to use the split(), but it just split without considering the words...

答:
In base R, we can use strsplit to split the strings at every occurrence of ", ", then unlist the result into one vector. Note though that this vector will be longer than your original data frame, so can't be stored as a column within it.

table(unlist(strsplit(science$area, ", ")))
#>
#>   Arqueologia    Astronomia      Biologia    Computacao  Experiencias
#>             1             6            17             2             2
#>     Filosofia        Fisica     Geografia      Historia    Literatura
#>             4            11             5             3             4
#>    Matematica Meio Ambiente Paleontologia    Psicologia         Saude
#>             3             2             4             3             8
```

Created on 2022-02-12 by the reprex package (v2.0.1)

Title: How to split an element on R?

Body:
Well, I'm working on a data frame that has a column where some elements have two or more words. I'm trying to use this column as a vector to make a pie chart, and I need the words on these elements to be split into single ones to be counted as individuals for the chart.

That's the vector in question:

science$area
 [1] "Matematica"                          "Filosofia"
 [3] "Arqueologia"                         "Astronomia"
 [5] "Biologia, Paleontologia"             "Biologia"
 [7] "Psicologia"                          "Astronomia"
 [9] "Fisica"                              "Biologia, Paleontologia"
[11] "Astronomia"                          "Biologia"
[13] "Biologia, Fisica, Matematica, Saude" "Fisica"
[15] "Paleontologia"                       "Saude"
[17] "Biologia, Saude"                     "Biologia, Saude"
[19] "Saude"                               NA
[21] "Biologia"                            "Fisica"
[23] "Psicologia"                          "Biologia"
[25] "Fisica"                              "Biologia"
[27] NA                                    "Historia"
[29] "Experiencias"                        "Astronomia"
[31] "Geografia"                           "Matematica"
[33] "Astronomia"                          "Filosofia, Literatura"
[35] "Biologia"                            "Psicologia"
[37] "Biologia, Saude"                     "Saude"
[39] "Fisica"                              "Experiencias, Fisica"
[41] "Biologia, Saude"                     "Biologia"
[43] "Computacao"                          "Biologia"
[45] "Fisica"                              "Fisica"
[47] "Filosofia, Historia, Literatura"     NA
[49] "Literatura"                          "Astronomia"
[51] "Geografia, Meio Ambiente"            "Geografia"
[53] "Biologia, Paleontologia"             "Computacao"
[55] "Fisica, Literatura"                  "Filosofia"
[57] "Geografia, Meio Ambiente"            "Fisica"
[59] "Biologia"                            "Geografia, Historia"

When I summarize it, this returns:

> summary(factor(science$area))
                    Arqueologia                          Astronomia
                              1                                   6
                       Biologia Biologia, Fisica, Matematica, Saude
                              9                                   1
        Biologia, Paleontologia                     Biologia, Saude
                              3                                   4
                     Computacao                        Experiencias
                              2                                   1
           Experiencias, Fisica                           Filosofia
                              1                                   2
Filosofia, Historia, Literatura               Filosofia, Literatura
                              1                                   1
                         Fisica                  Fisica, Literatura
                              8                                   1
                      Geografia                 Geografia, Historia
                              2                                   1
       Geografia, Meio Ambiente                            Historia
                              2                                   1
                     Literatura                          Matematica
                              1                                   2
                  Paleontologia                          Psicologia
                              1                                   3
                          Saude                                NA's
                              3                                   3

So, as you can see, "Biologia, Paleontologia" is being treated as a level for example, and I need it to count to both "Biologia" and "Paleontologia" instead. How can I do this?? I've already tried, unsuccessfully, to write these elements using c() and using "" amongst them, and also tried to use the split(), but it just split without considering the words...

Body:
In base R, we can use strsplit to split the strings at every occurrence of ", ", then unlist the result into one vector. Note though that this vector will be longer than your original data frame, so can't be stored as a column within it.

table(unlist(strsplit(science$area, ", ")))
#>
#>   Arqueologia    Astronomia      Biologia    Computacao  Experiencias
#>             1             6            17             2             2
#>     Filosofia        Fisica     Geografia      Historia    Literatura
#>             4            11             5             3             4
#>    Matematica Meio Ambiente Paleontologia    Psicologia         Saude
#>             3             2             4             3             8

Created on 2022-02-12 by the reprex package (v2.0.1)


问:
How can I send image using SignalR?
I built an application with angular 10 as frontend and .net core 5 as backend, through this application people can chat and send images to each other in realtime. I could implement chatting functionality using signalR but I don't have any idea how to do that to send images, please give me a strong reference to help me do that</p>

答:
One solution would be sending the files as a base64 string using signalR.

You could use the javascript FileReader class to convert the files to their base64 equivilent on the client side. E.G.

```<code>const toBase64 = (file) => new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
});

async function Main() {
   const file = document.querySelector('#myfile').files[0];
   console.log(await toBase64(file));
}

Main();
</code>```

You could then create a class server side for the uploaded files like:

```<code>public class SignalRFileUpload {
    public string FileName { get; set; }
    public string ContentType { get; set; }
    public string FileContent { get; set; }
}
</code>```

You could then send the file/s using signalR as you would any other data.

Then you could either store them as strings on the server or perhaps convert them to byte[] using:

```<code>Convert.FromBase64String(FileContent);
</code>```

This solution should be fine with smaller images under a couple MB or so. Any bigger than that and I am sure it would become problematic. I have never tried before so I cant be certain.

Title: How can I send image using SignalR?

Body:
One solution would be sending the files as a base64 string using signalR.

You could use the javascript FileReader class to convert the files to their base64 equivilent on the client side. E.G.

const toBase64 = (file) => new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
});

async function Main() {
   const file = document.querySelector('#myfile').files[0];
   console.log(await toBase64(file));
}

Main();

You could then create a class server side for the uploaded files like:

public class SignalRFileUpload {
    public string FileName { get; set; }
    public string ContentType { get; set; }
    public string FileContent { get; set; }
}

You could then send the file/s using signalR as you would any other data.

Then you could either store them as strings on the server or perhaps convert them to byte[] using:

Convert.FromBase64String(FileContent);

This solution should be fine with smaller images under a couple MB or so. Any bigger than that and I am sure it would become problematic. I have never tried before so I cant be certain.


问:
Auto-format credit card number input as user types
I want to create an input using JavaScript that automatically formats it in the correct Credit Card format.

What I Want?

The input should format input in groups of 4. e.g. If I typed in 1234567890123456, it should format it to 1234 5678 9012 3456

The max length should be 16 digits. So if I typed in 1234567890123456789 it should format it to "1234 5678 9012 3456"

formatting should occur as you type. So if I typed "123456" it should format it to "1234 56"

Invalid characters should be ignored. So if I typed in 564adsd299  474 it should format it to "5642 9947 4"

The input should also respect traditional behaviour of the textbox. (The | here resembles the cursor e.g.

If I typed in 8 when the input is:

1234 5|67 it should turn to 1234 58|67

1234|, it should turn to 1234 8

1234| 567 it should turn to 1234 8567

1234| 5679 it should turn to 1234 8567 9

If I delete the previous character when the input is:

1234 5|67 it should turn to 1234 |67

1234 |567 it should turn to 1234| 567

1234| 567 it should turn to 123|5 67

More test cases is likely to follow.

Example

Basically it should behave exactly like the "Enter card details" used in Google Play Store. To find this page: Open Play Store on an Android device > Click Account > Payment methods > Add credit or debit card. This screen can also be found here: https://play.google.com/store/account

What I have so far?

This is what I have so far:

var txtCardNumber = document.querySelector("#txtCardNumber");
txtCardNumber.addEventListener("input", onChangeTxtCardNumber);

function onChangeTxtCardNumber(e) {
    var cardNumber = txtCardNumber.value;

   // Do not allow users to write invalid characters
    var formattedCardNumber = cardNumber.replace(/[^\d]/g, "");
    formattedCardNumber = formattedCardNumber.substring(0, 16);

    // Split the card number is groups of 4
    var cardNumberSections = formattedCardNumber.match(/\d{1,4}/g);
    if (cardNumberSections !== null) {
        formattedCardNumber = cardNumberSections.join(' ');
    }

    console.log("'"+ cardNumber + "' to '" + formattedCardNumber + "'");

    // If the formmattedCardNumber is different to what is shown, change the value
    if (cardNumber !== formattedCardNumber) {
        txtCardNumber.value = formattedCardNumber;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="txtCardNumber"/></code>```

The above formats the credit number perfectly, but the issues begin when I want to edit.

However, the above does not satisfy test cases 5 onward, as the cursor just jumps to the end.

How can I achieve this behaviour. I know it's possible as Google has done it already.

(Please no use PayPal answers)

Edit: Note that I am looking for native JavaScript solutions, however feel free to suggest plugins as comments. The exception is libraries with little to no dependencies so it's possible to just copy the source code.

I've also removed jQuery on the above code to encourage native JS solutions.

答:
This should work:</p>
```<code>var format = [9, 2, 3,5,5,5,5,5,5,5,4, 5, 5, 5, 54, 4, 4, 4, 4, 4, 4, 4,
  4, 4].map((data, index) => {

  if ((index + 1) % 4 == 0) {
    data = data + " "
  }

  return data
})

format= format.join("")
console.log("format", format)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to create an input using JavaScript that automatically formats it in the correct Credit Card format.

What I Want?

The input should format input in groups of 4. e.g. If I typed in 1234567890123456, it should format it to 1234 5678 9012 3456

The max length should be 16 digits. So if I typed in 1234567890123456789 it should format it to "1234 5678 9012 3456"

formatting should occur as you type. So if I typed "123456" it should format it to "1234 56"

Invalid characters should be ignored. So if I typed in 564adsd299  474 it should format it to "5642 9947 4"

The input should also respect traditional behaviour of the textbox. (The | here resembles the cursor e.g.

If I typed in 8 when the input is:

1234 5|67 it should turn to 1234 58|67

1234|, it should turn to 1234 8

1234| 567 it should turn to 1234 8567

1234| 5679 it should turn to 1234 8567 9

If I delete the previous character when the input is:

1234 5|67 it should turn to 1234 |67

1234 |567 it should turn to 1234| 567

1234| 567 it should turn to 123|5 67

More test cases is likely to follow.

Example

Basically it should behave exactly like the "Enter card details" used in Google Play Store. To find this page: Open Play Store on an Android device > Click Account > Payment methods > Add credit or debit card. This screen can also be found here: https://play.google.com/store/account

What I have so far?

This is what I have so far:

var txtCardNumber = document.querySelector("#txtCardNumber");
txtCardNumber.addEventListener("input", onChangeTxtCardNumber);

function onChangeTxtCardNumber(e) {
    var cardNumber = txtCardNumber.value;

   // Do not allow users to write invalid characters
    var formattedCardNumber = cardNumber.replace(/[^\d]/g, "");
    formattedCardNumber = formattedCardNumber.substring(0, 16);

    // Split the card number is groups of 4
    var cardNumberSections = formattedCardNumber.match(/\d{1,4}/g);
    if (cardNumberSections !== null) {
        formattedCardNumber = cardNumberSections.join(' ');
    }

    console.log("'"+ cardNumber + "' to '" + formattedCardNumber + "'");

    // If the formmattedCardNumber is different to what is shown, change the value
    if (cardNumber !== formattedCardNumber) {
        txtCardNumber.value = formattedCardNumber;
    }
}

<input id="txtCardNumber"/>

The above formats the credit number perfectly, but the issues begin when I want to edit.

However, the above does not satisfy test cases 5 onward, as the cursor just jumps to the end.

How can I achieve this behaviour. I know it's possible as Google has done it already.

(Please no use PayPal answers)

Edit: Note that I am looking for native JavaScript solutions, however feel free to suggest plugins as comments. The exception is libraries with little to no dependencies so it's possible to just copy the source code.

I've also removed jQuery on the above code to encourage native JS solutions.

Body:
This should work:

var format = [9, 2, 3,5,5,5,5,5,5,5,4, 5, 5, 5, 54, 4, 4, 4, 4, 4, 4, 4,
  4, 4].map((data, index) => {

  if ((index + 1) % 4 == 0) {
    data = data + " "
  }

  return data
})

format= format.join("")
console.log("format", format)


问:
Is there a rule or setting when Narrator ignore aria-label on element while aria-label's value same as element 's content?
When I set aria-label's value same as button's content, the screen-reader cannot readout aria-label.

 <button aria-label="Close">Close</button>

But when I change aria-label's value different from button's content, the screen-reader readout the aria-label.

 <button aria-label="Close X">Close</button>

Is there a rule or setting when Narrator ignore aria-label on element while aria-label's value same as element 's content?

Thanks for your help.

答:
You are talking about the accessible name.  An element can only have one accessible name and it's announced by the screen reader when you navigate to that element, along with it's role and value or state, as per WCAG 4.1.2.  (It can also have an accessible description.)

The accessible name is calculated using a precedence order defined in "Accessible Name and Description Computation 1.1".  It's essentially a big "if then else" statement and when one of the conditions are true, the rest are ignored.  The order of precedence (which is a little oversimplified here but you can see the details in the aforementioned link), is:

aria-labelledby

aria-label

 element

from content

from tooltip

In your example, you have two sources of the accessible name, #2 and #4.  The aria-label (#2, "Close X") will be found first so the content (#4, "Close") will be ignored.

Body:
You are talking about the accessible name.  An element can only have one accessible name and it's announced by the screen reader when you navigate to that element, along with it's role and value or state, as per WCAG 4.1.2.  (It can also have an accessible description.)

The accessible name is calculated using a precedence order defined in "Accessible Name and Description Computation 1.1".  It's essentially a big "if then else" statement and when one of the conditions are true, the rest are ignored.  The order of precedence (which is a little oversimplified here but you can see the details in the aforementioned link), is:

aria-labelledby

aria-label

<label> element

from content

from tooltip

In your example, you have two sources of the accessible name, #2 and #4.  The aria-label (#2, "Close X") will be found first so the content (#4, "Close") will be ignored.


问:
Module compiled with Swift 5.5.1 cannot be imported by the Swift 5.5.2 compiler RazorPay
I'm working on a Flutter app, when trying to build the iOS version on xCode it's showing me this error

```<code>Module compiled with Swift 5.5.1 cannot be imported by the Swift 5.5.2 compiler
</code>```

I updated my Pods folder, deleted profile.lock, deleted Derived Data folder, Cleaned my Build folder .. and still got same error

I even changed the Runner -> Target -> Build Settings -> Build Libraries for Distribution to YES, and still doesn't work

I remember i faced this issue before and fixed it, but really forgot what i did :/

What shall i do please?

答:
I fixed it by adding this code into my Podfile</p>
```<code>post_install do |installer|
  installer.pods_project.targets.each do |target|
    flutter_additional_ios_build_settings(target)
  end
  installer.pods_project.build_configurations.each do |config|
    config.build_settings["EXCLUDED_ARCHS[sdk=iphonesimulator*]"] = "arm64"
  end
end
</code>```

Body:
I'm working on a Flutter app, when trying to build the iOS version on xCode it's showing me this error

Module compiled with Swift 5.5.1 cannot be imported by the Swift 5.5.2 compiler

I updated my Pods folder, deleted profile.lock, deleted Derived Data folder, Cleaned my Build folder .. and still got same error

I even changed the Runner -> Target -> Build Settings -> Build Libraries for Distribution to YES, and still doesn't work

I remember i faced this issue before and fixed it, but really forgot what i did :/

What shall i do please?

Body:
I fixed it by adding this code into my Podfile

post_install do |installer|
  installer.pods_project.targets.each do |target|
    flutter_additional_ios_build_settings(target)
  end
  installer.pods_project.build_configurations.each do |config|
    config.build_settings["EXCLUDED_ARCHS[sdk=iphonesimulator*]"] = "arm64"
  end
end


问:
Issue with Fabs() and Abs()
My program checks to see if the max price is bigger than the price you spent. If the max price is bigger than the price you spent it turns the absolute value of two floats; but when I use fabs(), returns "Wow, you overspent on that first cupcake...you owe $0.00. Bye!".
I also tried abs(), but that didn't work.

Here is my code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

int main(int argc, char**argv)
{
    float maxPrice;
    char flavor[20];
    char flavor2[20];
    float price;
    double price2;
    char anotherCupcake[20];
    double newPrice;
    newPrice=maxPrice-price;

   // int idxToDel = 2;
    //memove(&word[idxToDel], &word[idxToDel + 1], strlen(word) - idxToDel);

    printf("Please enter starting budget: ");
    scanf("%f", &maxPrice);
    printf("Enter the flavor of cupcake 1: ");
    scanf("%s", &flavor);
    printf("Enter the price of %s cupcake: $", flavor);
    scanf("%f", &price);

    //determining if you have enough money for a second cupcake
    if(price == maxPrice)
    {
        printf("\nOops! No more money left to spend on anymore cupcakes...enjoy the %s one! Bye!", flavor);
    }
    else if(price > maxPrice)
    {

        printf("\nWow, you overspent on that first cupcake...you owe $%.2lf. Bye!", fabs(newPrice)*1.0);
    }
    else
    {
        printf("Ok, looks like you you have $.2lf left to spend on cupcakes...  Would you like to get another one?", maxPrice - price);
        scanf("%s", &anotherCupcake);
        if(anotherCupcake == "yes")
        {
           printf("Enter the flavor of cupcake 2: ");
           scanf("%s", &flavor2);
           printf("Enter the price of cupcake 2 $: ");
           scanf("%f", &price2);
           printf("Done! Enjoy your %s and %s cupcakes! Bye!", flavor, flavor2);

        }
        else
        {
            printf("Ok then...Enjoy that one %s cupcake! Bye!", flavor);
        }
    }
    return 0;
}
</code>```

答:
You have to calculate newPrice with current values of
maxPrice-price, not at the beginning when neither maxPrice nor
price are initialized. Like that:

```<code>      newPrice = maxPrice - price;
      printf("\nWow, you overspent on that first cupcake...you owe $%.2lf. Bye!\n", fabs(newPrice)*1.0);
</code>```

It'll work like that:

```<code>$ ./main
Please enter starting budget: 10
Enter the flavor of cupcake 1: 1
Enter the price of 1 cupcake: $18

Wow, you overspent on that first cupcake...you owe $8.00. Bye!
</code>```

As a sidenote, you didn't specify what compiler you're using but the minimum set of flags you should use with gcc/clang is -Wall -Wextra -pedantic and fix all warnings.

Title: Issue with Fabs() and Abs()

Body:
My program checks to see if the max price is bigger than the price you spent. If the max price is bigger than the price you spent it turns the absolute value of two floats; but when I use fabs(), returns "Wow, you overspent on that first cupcake...you owe $0.00. Bye!".
I also tried abs(), but that didn't work.

Here is my code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

int main(int argc, char**argv)
{
    float maxPrice;
    char flavor[20];
    char flavor2[20];
    float price;
    double price2;
    char anotherCupcake[20];
    double newPrice;
    newPrice=maxPrice-price;

   // int idxToDel = 2;
    //memove(&word[idxToDel], &word[idxToDel + 1], strlen(word) - idxToDel);

    printf("Please enter starting budget: ");
    scanf("%f", &maxPrice);
    printf("Enter the flavor of cupcake 1: ");
    scanf("%s", &flavor);
    printf("Enter the price of %s cupcake: $", flavor);
    scanf("%f", &price);

    //determining if you have enough money for a second cupcake
    if(price == maxPrice)
    {
        printf("\nOops! No more money left to spend on anymore cupcakes...enjoy the %s one! Bye!", flavor);
    }
    else if(price > maxPrice)
    {

        printf("\nWow, you overspent on that first cupcake...you owe $%.2lf. Bye!", fabs(newPrice)*1.0);
    }
    else
    {
        printf("Ok, looks like you you have $.2lf left to spend on cupcakes...  Would you like to get another one?", maxPrice - price);
        scanf("%s", &anotherCupcake);
        if(anotherCupcake == "yes")
        {
           printf("Enter the flavor of cupcake 2: ");
           scanf("%s", &flavor2);
           printf("Enter the price of cupcake 2 $: ");
           scanf("%f", &price2);
           printf("Done! Enjoy your %s and %s cupcakes! Bye!", flavor, flavor2);

        }
        else
        {
            printf("Ok then...Enjoy that one %s cupcake! Bye!", flavor);
        }
    }
    return 0;
}

Body:
You have to calculate newPrice with current values of
maxPrice-price, not at the beginning when neither maxPrice nor
price are initialized. Like that:

      newPrice = maxPrice - price;
      printf("\nWow, you overspent on that first cupcake...you owe $%.2lf. Bye!\n", fabs(newPrice)*1.0);

It'll work like that:

$ ./main
Please enter starting budget: 10
Enter the flavor of cupcake 1: 1
Enter the price of 1 cupcake: $18

Wow, you overspent on that first cupcake...you owe $8.00. Bye!

As a sidenote, you didn't specify what compiler you're using but the minimum set of flags you should use with gcc/clang is -Wall -Wextra -pedantic and fix all warnings.


问:
How to Update C# Console App without causing a flicker
I'm trying to write a simple console based game engine in C# for fun. Right now what I'm trying to do is establish a simple game loop where the "game" waits for user input, updates then renders then clears the screen then repeats.

This is my code so far:

```<code>
int x = 0;

bool quit = false;
Task.Run(async () =>
{
    try // Catch any issues
    {
        while (!quit)
        {
            Console.WriteLine("render");
            Console.WriteLine("Position of implicit object: {0}", x);
            await Task.Delay(100);
            Console.Clear();
        }
    }
    catch (Exception e) { Console.WriteLine(e); }
});

while (!quit)
{
    ConsoleKeyInfo keyInfo = Console.ReadKey(false);
    ConsoleKey key = keyInfo.Key;

    switch (key)
    {
        case ConsoleKey.D:
            x++;
            Console.WriteLine("A-key pressed");
            break;
        case ConsoleKey.A:
            x--;
            Console.WriteLine("D-key pressed");
            break;

        case ConsoleKey.Escape:
            quit = true;
            break;
    }
}
</code>```

But the issue is, there's a constant flicker when the console is updating. I heard  Console.SetCursorPosition(0, 0); might work but when I try that, it seems that the updating stops when the user clicks the screen.

Is there another way to do it? Even if it involves changing the method of the game loop itself.

Thank you!

答: Please use this as a fix Console.SetCursorPosition(0, 0), add this before Console.WriteLine("render"). To fix the click issue as you have mentioned. You have to uncheck Quick Edit mode on console window. Right click on console window -> properties in edit section uncheck Quick Edit. Screenshot attached.

Body:
I'm trying to write a simple console based game engine in C# for fun. Right now what I'm trying to do is establish a simple game loop where the "game" waits for user input, updates then renders then clears the screen then repeats.

This is my code so far:

int x = 0;

bool quit = false;
Task.Run(async () =>
{
    try // Catch any issues
    {
        while (!quit)
        {
            Console.WriteLine("render");
            Console.WriteLine("Position of implicit object: {0}", x);
            await Task.Delay(100);
            Console.Clear();
        }
    }
    catch (Exception e) { Console.WriteLine(e); }
});

while (!quit)
{
    ConsoleKeyInfo keyInfo = Console.ReadKey(false);
    ConsoleKey key = keyInfo.Key;

    switch (key)
    {
        case ConsoleKey.D:
            x++;
            Console.WriteLine("A-key pressed");
            break;
        case ConsoleKey.A:
            x--;
            Console.WriteLine("D-key pressed");
            break;

        case ConsoleKey.Escape:
            quit = true;
            break;
    }
}

But the issue is, there's a constant flicker when the console is updating. I heard  Console.SetCursorPosition(0, 0); might work but when I try that, it seems that the updating stops when the user clicks the screen.

Is there another way to do it? Even if it involves changing the method of the game loop itself.

Thank you!


问:
Ordered Lists Inside ShieldUI Accordion
Is it possible to include an ordered list inside a ShieldUI accordion?  Including one seems to break my accordion; I'm hoping there is some sort of flag or work around to get ordered lists working.

Delivery Instructions

Vehicle Delivery to Media / Client

Accordion 1

Header

One

Two

Delivery to Airport

Accordion 2

```

答:
Try putting it in a DIV, like this:

```<code>  <div class='accordion-container'>
    <h2>Delivery Instructions</h2>
    <ul id='accordion'>
        <li>
            <h2>Vehicle Delivery to Media / Client</h2>
            <p>Accordion 1</p>
            <li>
                <h2>Header</h2>
                <div>
                    <ol>
                        <li>One</li>
                        <li>Two</li>
                    </ol>
                </div>
            </li>
        </li>
        <li>
            <h2>Delivery to Airport</h2>
            <p>Accordion 2</p>
        </li>
    </ul>
  </div>
</code>```

Title: Ordered Lists Inside ShieldUI Accordion

Body:
Try putting it in a DIV, like this:

  <div class='accordion-container'>
    <h2>Delivery Instructions</h2>
    <ul id='accordion'>
        <li>
            <h2>Vehicle Delivery to Media / Client</h2>
            <p>Accordion 1</p>
            <li>
                <h2>Header</h2>
                <div>
                    <ol>
                        <li>One</li>
                        <li>Two</li>
                    </ol>
                </div>
            </li>
        </li>
        <li>
            <h2>Delivery to Airport</h2>
            <p>Accordion 2</p>
        </li>
    </ul>
  </div>


问:
Dictionary key name from combination of string and variable value
Basically, I am trying to append values from a list as key-value pairs to a new dictionary. I want the key names in a specific format and order.

```<code>#!/usr/bin/env python3
ipv4_list = ["192.168.1.2", "192.168.1.3", "192.168.1.4"]
ipv4_dic = {}
ipv4_len = len(ipv4_list)
i = 1

for val in range(len(ipv4_list)):
    ipv4_dic[i] = ipv4_list[val]
    i+=1

print(ipv4_dic)
</code>```

Current output:

```<code>{1: '192.168.1.2', 2: '192.168.1.3', 3: '192.168.1.4'}
</code>```

The above is good but I want to change key names to something like IP1, IP2, etc.

How do I make that in the line ipv4_dic[i] = ipv4_list[key]

I tried something like ipv4_dic["IP"+i] but does not work.

```<code>    ipv4_dic["IP"+i] = ipv4_list[val]
TypeError: can only concatenate str (not "int") to str
</code>```

The expected dictionary output as follows:

```<code>{IP1: '192.168.1.2', IP2: '192.168.1.3', IP3: '192.168.1.4'}
</code>```

答:
I almost didn’t post this because Georgio almost had what I would have written:  use a dictionary comprehension based on a for loop.  Andd tell you about the str and int concatenation.

The only thing missing was using enumerate to get the list indices.  Full of goodness, is enumerate. It returns the elements from an iterable as a list of pairs (tuples):  first item is the zero-based index, second is what the for loop (well actually the iterable at that index) would normally return.

Then those pairs get assigned to i,v via tuple unpacking.

```<code>di = { f"IP{i+1}":v for i,v in enumerate( [" 192.168.1.2", "192.168.1.3", "192.168.1.4"])}
print(di)
</code>```

See https://docs.python.org/3/library/functions.html#enumerate

Body:
Basically, I am trying to append values from a list as key-value pairs to a new dictionary. I want the key names in a specific format and order.

#!/usr/bin/env python3
ipv4_list = ["192.168.1.2", "192.168.1.3", "192.168.1.4"]
ipv4_dic = {}
ipv4_len = len(ipv4_list)
i = 1

for val in range(len(ipv4_list)):
    ipv4_dic[i] = ipv4_list[val]
    i+=1

print(ipv4_dic)

Current output:

{1: '192.168.1.2', 2: '192.168.1.3', 3: '192.168.1.4'}

The above is good but I want to change key names to something like IP1, IP2, etc.

How do I make that in the line ipv4_dic[i] = ipv4_list[key]

I tried something like ipv4_dic["IP"+i] but does not work.

    ipv4_dic["IP"+i] = ipv4_list[val]
TypeError: can only concatenate str (not "int") to str

The expected dictionary output as follows:

{IP1: '192.168.1.2', IP2: '192.168.1.3', IP3: '192.168.1.4'}

Body:
I almost didn’t post this because Georgio almost had what I would have written:  use a dictionary comprehension based on a for loop.  Andd tell you about the str and int concatenation.

The only thing missing was using enumerate to get the list indices.  Full of goodness, is enumerate. It returns the elements from an iterable as a list of pairs (tuples):  first item is the zero-based index, second is what the for loop (well actually the iterable at that index) would normally return.

Then those pairs get assigned to i,v via tuple unpacking.

di = { f"IP{i+1}":v for i,v in enumerate( [" 192.168.1.2", "192.168.1.3", "192.168.1.4"])}
print(di)

See https://docs.python.org/3/library/functions.html#enumerate


问:
Print out value of stack pointer
How can I print out the current value at the stack pointer in C in Linux (Debian and Ubuntu)?

I tried google but found no results.

答:
You can use setjmp. The exact details are implementation dependent, look in the header file.

```<code>#include <setjmp.h>
jmp_buf jmp;
setjmp(jmp);
printf("%08x\n", jmp[0].j_esp);
</code>```

This is also handy when executing unknown code. You can check the sp before and after and do a longjmp to clean up.

Title: Print out value of stack pointer

Body:
You can use setjmp. The exact details are implementation dependent, look in the header file.

#include <setjmp.h>
jmp_buf jmp;
setjmp(jmp);
printf("%08x\n", jmp[0].j_esp);

This is also handy when executing unknown code. You can check the sp before and after and do a longjmp to clean up.


问:
How can I multiply the integer arguments in the numpy array?
I am creating a program that has a function that takes in four integer arguments which are put into a Numpy array. The function is supposed to print the type of array: <class 'numpy.ndarray'> (which it does) and then print the multiplication of the four items in the array(that's the part I am having trouble with). Any hits on what to do? I am a beginner. Thank you</p>
```<code>enter code hereimport numpy as np
import sys
def array(x1, x2, x3, x4):

    x1 = int(x1)
    x2 = int(x2)
    x3 = int(x3)
    x4 = int(x4)

class Numpy():
    pass

np.arange(4)
array_1 = np.arange(4)
print(type(array_1))
array_1 = np.multiply(x1,x2,x3,x4)

x1 = sys.argv[1]
x2 = sys.argv[2]
x3 = sys.argv[3]
x4 = sys.argv[4]

array_1 = array(x1, x2, x3, x4)
print(array_1)
</code>```

答:
You can use numpy's reduce function to apply a reducing function to your array

```<code>>>> import numpy as np
>>> values = np.arange(1, 5)
>>> values
[1 2 3 4]
>>> np.multiply.reduce(values)
24
>>> np.add.reduce(values)
10
</code>```

Body:
I am creating a program that has a function that takes in four integer arguments which are put into a Numpy array. The function is supposed to print the type of array: <class 'numpy.ndarray'> (which it does) and then print the multiplication of the four items in the array(that's the part I am having trouble with). Any hits on what to do? I am a beginner. Thank you

enter code hereimport numpy as np
import sys
def array(x1, x2, x3, x4):

    x1 = int(x1)
    x2 = int(x2)
    x3 = int(x3)
    x4 = int(x4)

class Numpy():
    pass

np.arange(4)
array_1 = np.arange(4)
print(type(array_1))
array_1 = np.multiply(x1,x2,x3,x4)

x1 = sys.argv[1]
x2 = sys.argv[2]
x3 = sys.argv[3]
x4 = sys.argv[4]

array_1 = array(x1, x2, x3, x4)
print(array_1)

Body:
You can use numpy's reduce function to apply a reducing function to your array

>>> import numpy as np
>>> values = np.arange(1, 5)
>>> values
[1 2 3 4]
>>> np.multiply.reduce(values)
24
>>> np.add.reduce(values)
10


问:
python string concatenation split over two lines

for don in open('list.txt', 'r'):
    myURL=don
    myURL=myURL.replace("rep.php","")
    print(myURL+"test.php")
```
<p>It's printing</p>
```http://www.blabla.com
blablabla.html
```

答:
When you iterate over a file handle, you get one line at a time with any trailing newline characters.  So, the line is probably 'http://www.blabla.com\n'.  That's why, when you append 'blabla.html', the result is split over two lines.

An easy fix is to do

print(myURL.rstrip() + 'blabla.html')
```
<p>On a side note, it's good practice to manage resources like file handles with context blocks so that the file handle is explicitly closed (and not left to the garbage collector):</p>
<pre class="lang-py prettyprint-override"><code>with open('list.txt', 'r') as f:
    for don in f:
        ...
</code>```

Body:
for don in open('list.txt', 'r'):
    myURL=don
    myURL=myURL.replace("rep.php","")
    print(myURL+"test.php")

It's printing

http://www.blabla.com
blablabla.html

Body:
When you iterate over a file handle, you get one line at a time with any trailing newline characters.  So, the line is probably 'http://www.blabla.com\n'.  That's why, when you append 'blabla.html', the result is split over two lines.

An easy fix is to do

print(myURL.rstrip() + 'blabla.html')

On a side note, it's good practice to manage resources like file handles with context blocks so that the file handle is explicitly closed (and not left to the garbage collector):

with open('list.txt', 'r') as f:
    for don in f:
        ...


问:
Mailu : when I run docker-compose, I got this error
I made a fresh install of mailu and when I run docker-compose up -d I have the following message :

```<code>Starting mailu_resolver_1 ... error

ERROR: for mailu_resolver_1  Cannot start service resolver: OCI runtime create failed: container_linux.go:380: starting container process caused: process_linux.go:545: container init caused: rootfs_linux.go:76: mounting "proc" to rootfs at "/proc" caused: mount through procfd: permission denied: unknown

ERROR: for resolver  Cannot start service resolver: OCI runtime create failed: container_linux.go:380: starting container process caused: process_linux.go:545: container init caused: rootfs_linux.go:76: mounting "proc" to rootfs at "/proc" caused: mount through procfd: permission denied: unknown
ERROR: Encountered errors while bringing up the project.
</code>```

Do you know the cause of the issue ?

Thanks for your help.

Best regards,

答: Docker daemon has permissions problems. Check out: https://github.com/sindresorhus/guides/blob/main/docker-without-sudo.md</p>

Body:
I made a fresh install of mailu and when I run docker-compose up -d I have the following message :

Starting mailu_resolver_1 ... error

ERROR: for mailu_resolver_1  Cannot start service resolver: OCI runtime create failed: container_linux.go:380: starting container process caused: process_linux.go:545: container init caused: rootfs_linux.go:76: mounting "proc" to rootfs at "/proc" caused: mount through procfd: permission denied: unknown

ERROR: for resolver  Cannot start service resolver: OCI runtime create failed: container_linux.go:380: starting container process caused: process_linux.go:545: container init caused: rootfs_linux.go:76: mounting "proc" to rootfs at "/proc" caused: mount through procfd: permission denied: unknown
ERROR: Encountered errors while bringing up the project.

Do you know the cause of the issue ?

Thanks for your help.

Best regards,


答:
Using strsplit() and unlist() I was able to solve my problem.

Like this:

```<code>areas=unlist(strsplit(science$area,","))
pie(summary(factor(areas)))
</code>```

Title: How to split an element on R?

Body:
Well, I'm working on a data frame that has a column where some elements have two or more words. I'm trying to use this column as a vector to make a pie chart, and I need the words on these elements to be split into single ones to be counted as individuals for the chart.

That's the vector in question:

science$area
 [1] "Matematica"                          "Filosofia"
 [3] "Arqueologia"                         "Astronomia"
 [5] "Biologia, Paleontologia"             "Biologia"
 [7] "Psicologia"                          "Astronomia"
 [9] "Fisica"                              "Biologia, Paleontologia"
[11] "Astronomia"                          "Biologia"
[13] "Biologia, Fisica, Matematica, Saude" "Fisica"
[15] "Paleontologia"                       "Saude"
[17] "Biologia, Saude"                     "Biologia, Saude"
[19] "Saude"                               NA
[21] "Biologia"                            "Fisica"
[23] "Psicologia"                          "Biologia"
[25] "Fisica"                              "Biologia"
[27] NA                                    "Historia"
[29] "Experiencias"                        "Astronomia"
[31] "Geografia"                           "Matematica"
[33] "Astronomia"                          "Filosofia, Literatura"
[35] "Biologia"                            "Psicologia"
[37] "Biologia, Saude"                     "Saude"
[39] "Fisica"                              "Experiencias, Fisica"
[41] "Biologia, Saude"                     "Biologia"
[43] "Computacao"                          "Biologia"
[45] "Fisica"                              "Fisica"
[47] "Filosofia, Historia, Literatura"     NA
[49] "Literatura"                          "Astronomia"
[51] "Geografia, Meio Ambiente"            "Geografia"
[53] "Biologia, Paleontologia"             "Computacao"
[55] "Fisica, Literatura"                  "Filosofia"
[57] "Geografia, Meio Ambiente"            "Fisica"
[59] "Biologia"                            "Geografia, Historia"

When I summarize it, this returns:

> summary(factor(science$area))
                    Arqueologia                          Astronomia
                              1                                   6
                       Biologia Biologia, Fisica, Matematica, Saude
                              9                                   1
        Biologia, Paleontologia                     Biologia, Saude
                              3                                   4
                     Computacao                        Experiencias
                              2                                   1
           Experiencias, Fisica                           Filosofia
                              1                                   2
Filosofia, Historia, Literatura               Filosofia, Literatura
                              1                                   1
                         Fisica                  Fisica, Literatura
                              8                                   1
                      Geografia                 Geografia, Historia
                              2                                   1
       Geografia, Meio Ambiente                            Historia
                              2                                   1
                     Literatura                          Matematica
                              1                                   2
                  Paleontologia                          Psicologia
                              1                                   3
                          Saude                                NA's
                              3                                   3

So, as you can see, "Biologia, Paleontologia" is being treated as a level for example, and I need it to count to both "Biologia" and "Paleontologia" instead. How can I do this?? I've already tried, unsuccessfully, to write these elements using c() and using "" amongst them, and also tried to use the split(), but it just split without considering the words...

Body:
Using strsplit() and unlist() I was able to solve my problem.

Like this:

areas=unlist(strsplit(science$area,","))
pie(summary(factor(areas)))