问:
Continuation to my last question : Having trouble in calculating roots of a quartic equation in C#
This thread is a continuation of my last asked question.

My friends and I are trying to make a multi-functional calculator that can automatically calculate
the roots of quadratic, cubic, and even quartic equations.
However, we have run into some problems, previously on cubic equations, now on quartic equations.

Unlike the last thread, we will provide images including the answers calculated by our program and the answers calculated by WolframAlpha instead of putting them into text here.

The quartic equation will be denoted as in

ax^4 + bx^3 + cx^2 + dx + e

Our method of finding the roots of a quartic equation. (Found on another thread from another website)

a=1 b=2 c=-41 d=-42 e=360

a=1 b=-0.25 c=-0.85 d=1.45 e=-4.35

a=1 b=2 c=3 d=4 e=5

As seen in the images, the discriminant calculated by the program is always correct. However, the roots of the equation can sometimes cause errors (NaN), and the nature of roots can also cause errors as well but so as often as the roots do.

With all the information provided above, we wish to know the answers to the following questions :

What exactly is causing these errors and problems,

What amendment should I make to my code so that the program can function properly and as intended,

Whether our method of finding the roots of a quartic equation is correct, or is it even possible to find the roots of all quartic equations by a general formula,

Last but not least, is there a way to improve, or condense the code lines in our program but still function as we intended it to.

As aforementioned in the previous thread, we have just started learning C#.

For your convenience, we have put notes to some code lines.

Codes (C#) :

```<code>using System;
using System.Numerics;

namespace ComplexNumbers
{
    public class ComplexNo
    {
        public static void Main()
        {
            // prompting for coefficients and constant
            Console.WriteLine("Quartic Equation Calculator :");
            Console.Write("Insert first coefficient : ");
            double a = Convert.ToDouble(Console.ReadLine());
            Console.Write("Insert second coefficient : ");
            double b = Convert.ToDouble(Console.ReadLine());
            Console.Write("Insert third coefficient : ");
            double c = Convert.ToDouble(Console.ReadLine());
            Console.Write("Insert fourth coefficient : ");
            double d = Convert.ToDouble(Console.ReadLine());
            Console.Write("Insert constant : ");
            double e = Convert.ToDouble(Console.ReadLine());
            // discriminant
            double discriminant = 256 * Math.Pow(a, 3) * Math.Pow(e, 3) - (192 * Math.Pow(a, 2) * b * d * Math.Pow(e, 2)) -
                (128 * Math.Pow(a, 2) * Math.Pow(c, 2) * Math.Pow(e, 2)) + (144 * Math.Pow(a, 2) * c * Math.Pow(d, 2) * e) -
                (27 * Math.Pow(a, 2) * Math.Pow(d, 4)) + (144 * a * Math.Pow(b, 2) * c * Math.Pow(e, 2)) -
                (6 * a * Math.Pow(b, 2) * Math.Pow(d, 2) * e) - (80 * a * b * Math.Pow(c, 2) * d * e) +
                (18 * a * b * c * Math.Pow(d, 3)) + (16 * a * Math.Pow(c, 4) * e) - (4 * a * Math.Pow(c, 3) * Math.Pow(d, 2)) -
                (27 * Math.Pow(b, 4) * Math.Pow(e, 2)) + (18 * Math.Pow(b, 3) * c * d * e) -
                (4 * Math.Pow(b, 3) * Math.Pow(d, 3)) - (4 * Math.Pow(b, 2) * Math.Pow(c, 3) * e) +
                (Math.Pow(b, 2) * Math.Pow(c, 2) * Math.Pow(d, 2));

            // different parts of the roots presented in p1-p6
            double p1 = (2 * Math.Pow(c, 3)) - (9 * b * c * d) + (27 * a * Math.Pow(d, 2)) + (27 * Math.Pow(b, 2) * e) -
                (72 * a * c * e);
            double p2 = p1 + Math.Sqrt(-4.0 * Math.Pow(Math.Pow(c, 2) - (3 * b * d) + (12 * a * e), 3) + Math.Pow(p1, 2));
            double p3 = ((Math.Pow(c, 2) - (3 * b * d) + (12 * a * e)) / (3 * a * Math.Cbrt(p2 / 2))) + (Math.Cbrt(p2 / 2) / (3 * a));
            double p4 = Math.Sqrt((Math.Pow(b, 2) / (4 * Math.Pow(a, 2))) - (2 * c / (3 * a)) + p3);
            double p5 = (Math.Pow(b, 2) / (2 * Math.Pow(a, 2))) - (4 * c / (3 * a)) - p3;
            double p6 = ((-(Math.Pow(b, 3) / Math.Pow(a, 3))) + (4 * b * c / Math.Pow(a, 2)) - (8 * d / a)) / (4 * p4);
            // calculating roots with p1-p6
            Complex x1 = (-(b / (4 * a))) - (p4 / 2) - (Math.Sqrt(p5 - p6) / 2);
            Complex x2 = (-(b / (4 * a))) - (p4 / 2) + (Math.Sqrt(p5 - p6) / 2);
            Complex x3 = (-(b / (4 * a))) + (p4 / 2) - (Math.Sqrt(p5 - p6) / 2);
            Complex x4 = (-(b / (4 * a))) + (p4 / 2) + (Math.Sqrt(p5 - p6) / 2);

            // polynomials used for testing the nature of roots
            double P = (8 * a * c) - (3 * Math.Pow(b, 2));
            double R = Math.Pow(b, 3) + (8 * d * Math.Pow(a, 2)) - (4 * a * b * c);
            double deltazero = Math.Pow(c, 2) - (3 * b * d) + (12 * a * e);
            double D = (64 * Math.Pow(a, 3) * e) - (16 * Math.Pow(a, 2) * Math.Pow(c, 2)) +
                (16 * a * Math.Pow(b, 2) * c) - (16 * Math.Pow(a, 2) * b * d) - (3 * Math.Pow(b, 4));

            // results
            Console.WriteLine(" ");
            Console.WriteLine("Solve for " + a + "x^4 " + " + " + b + "x^3 " + " + " + c + "x^2 " + " + " + d + "x " + " + " + e + " :");
            Console.WriteLine(" ");
            Console.WriteLine("Results :");
            Console.WriteLine("First Root :");
            string x1rp = Convert.ToString(Math.Round(x1.Real, 5)); // rounding up both real and unreal parts
            string x1ip = Convert.ToString(Math.Round(x1.Imaginary, 5));
            if (x1.Imaginary == 0)
            {
                Console.WriteLine(x1rp);
            }
            else if (x1.Imaginary < 0) // testing if unreal part is negative
            {
                Console.WriteLine(x1rp + " - " + Math.Round(Complex.Abs(x1.Imaginary)) + "i");
            }
            else
            {
                Console.WriteLine(x1rp + " + " + x1ip + "i");
            }
            string x2rp = Convert.ToString(Math.Round(x2.Real, 5)); // rounding up both real and unreal parts
            string x2ip = Convert.ToString(Math.Round(x2.Imaginary, 5));
            if (x2.Imaginary == 0)
            {
                Console.WriteLine(x2rp);
            }
            else if (x2.Imaginary < 0) // testing if unreal part is negative
            {
                Console.WriteLine(x2rp + " - " + Math.Round(Complex.Abs(x2.Imaginary)) + "i");
            }
            else
            {
                Console.WriteLine(x2rp + " + " + x2ip + "i");
            }
            string x3rp = Convert.ToString(Math.Round(x3.Real, 5)); // rounding up both real and unreal parts
            string x3ip = Convert.ToString(Math.Round(x3.Imaginary, 5));
            if (x3.Imaginary == 0)
            {
                Console.WriteLine(x3rp);
            }
            else if (x3.Imaginary < 0) // testing if unreal part is negative
            {
                Console.WriteLine(x3rp + " - " + Math.Round(Complex.Abs(x3.Imaginary)) + "i");
            }
            else
            {
                Console.WriteLine(x3rp + " + " + x3ip + "i");
            }
            string x4rp = Convert.ToString(Math.Round(x4.Real, 5)); // rounding up both real and unreal parts
            string x4ip = Convert.ToString(Math.Round(x4.Imaginary, 5));
            if (x4.Imaginary == 0)
            {
                Console.WriteLine(x4rp);
            }
            else if (x4.Imaginary < 0) // testing if unreal part is negative
            {
                Console.WriteLine(x4rp + " - " + Math.Round(Complex.Abs(x4.Imaginary)) + "i");
            }
            else
            {
                Console.WriteLine(x4rp + " + " + x4ip + "i");
            }

            // discriminant tests
            if (discriminant == 0) // if delta = 0
            {
                if (P < 0 && D < 0 && deltazero != 0)
                {
                    string result4 = "The equation yields a pair of double roots and two real simple roots.";
                    Console.WriteLine(result4);
                }
                else if (D > 0 || (P > 0 && (D != 0 || R != 0)))
                {
                    string result5 = "The equation yields a pair of double roots and two complex conjugate roots.";
                    Console.WriteLine(result5);
                }
                else if (deltazero == 0 && D != 0)
                {
                    string result6 = "The equation yields a triple root and a simple root.";
                    Console.WriteLine(result6);
                }
                else if (D == 0)
                {
                    if (P < 0)
                    {
                        string result7 = "The equation yields two pairs of real double roots.";
                        Console.WriteLine(result7);
                    }
                    else if (P > 0 && R == 0)
                    {
                        string result8 = "The equation yields two pairs of double complex conjugate roots.";
                        Console.WriteLine(result8);
                    }
                    else if (deltazero == 0)
                    {
                        string result9pt2 = Convert.ToString(-(b / (4 * a)));
                        string result9 = "All of the roots of this equation are equal to -b/4a";
                        Console.WriteLine(result9 + "(" + result9pt2 + ")");
                    }
                    else
                    {
                        Console.WriteLine("ERROR");
                    }
                }
                else
                {
                    Console.WriteLine("ERROR");
                }
            }
            else if (discriminant > 0) // if delta > 0
            {
                if (P < 0 && D < 0)
                {
                    string result2 = "The equation yields four distinct real roots.";
                    Console.WriteLine(result2);
                }
                else if (P > 0 && D > 0)
                {
                    string result3 = "The equation yields two pairs of unreal complex conjugate roots.";
                    Console.WriteLine(result3);
                }
                else
                {
                    Console.WriteLine("ERROR");
                }
            }
            else if (discriminant < 0) // if delta < 0
            {
                string result1 = "The equation yields two distinct real roots and two complex conjugate non-real roots.";
                Console.WriteLine(result1);
            }

            // discriminant of equation
            Console.WriteLine(" ");
            Console.WriteLine("Discriminant :");
            Console.WriteLine(discriminant);

            Console.ReadLine();
        }
    }
}
</code>```

==========================================================

Edit #1 :

I tried another method to solve the roots.

However, the imaginary part is still wrong for the last 2 roots.

If anyone is able to spot my mistake, I would be grateful.

```<code>// different parts of the roots presented in p1-p6
            double p = ((8 * a * c) - (3 * Math.Pow(b, 2))) / (8 * Math.Pow(a, 2));
            double q = (Math.Pow(b, 3) - (4 * a * b * c) + (8 * Math.Pow(a, 2) * d)) / (8 * Math.Pow(a, 3));
            double D0 = Math.Pow(c, 2) - (3 * b * d) + (12 * a * e);
            double D1 = (2 * Math.Pow(c, 3)) - (9 * b * c * d) + (27 * Math.Pow(b, 2) * e) + (27 * a * Math.Pow(d, 2)) - (72 * a * c * e);
            Complex Q = Complex.Pow((D1 + Complex.Sqrt(Complex.Pow(D1, 2) - (4 * Complex.Pow(D0, 3)))) / 2.0, 1.0 / 3.0);
            Complex S = 1.0 / 2.0 * Complex.Sqrt((-2.0 / 3.0 * p) + (1.0 / (3 * a) * (Q + (D0 / Q))));
            // calculating roots with p1-p6
            Complex x1 = (-(b / 4 * a)) - S + (1.0 / 2.0 * Complex.Sqrt((-4.0 * Complex.Pow(S, 2)) - (2 * p) + (q / S)));
            Complex x2 = (-(b / 4 * a)) - S - (1.0 / 2.0 * Complex.Sqrt((-4.0 * Complex.Pow(S, 2)) - (2 * p) + (q / S)));
            Complex x3 = (-(b / 4 * a)) + S + (1.0 / 2.0 * Complex.Sqrt((-4.0 * Complex.Pow(S, 2)) - (2 * p) + (q / S)));
            Complex x4 = (-(b / 4 * a)) + S - (1.0 / 2.0 * Complex.Sqrt((-4.0 * Complex.Pow(S, 2)) - (2 * p) + (q / S)));
</code>```

==========================================================

Edit #2

Problem solved.

The program is now able to solve quartic equations. The cause of the problems mentioned above is actually the minor typos I made in the code lines.

答:
I got an algorithm from here that works. It seems simpler than yours.

```<code>            double D0 = c * c - 3 * b * d + 12 * a * e;
            double D1 = 2 * c * c * c - 9 * b * c * d + 27 * b * b * e + 27 * a * d * d - 72 * a * c * e;
            double p = (8 * a * c - 3 * b * b) / (8 * a * a);
            double q = (b * b * b - 4 * a * b * c + 8 * a * a * d) / (8 * a * a * a);
            Complex Q = Complex.Pow((D1 + Complex.Sqrt(D1 * D1 - 4 * D0 * D0 * D0)) / 2, 1.0 / 3.0);
            Complex S = Complex.Sqrt(-2 * p / 3 + (Q + D0 / Q) / (3 * a)) / 2;
            Complex u = Complex.Sqrt(-4 * S * S - 2 * p + q / S) / 2;
            Complex v = Complex.Sqrt(-4 * S * S - 2 * p - q / S) / 2;
            Complex x1 = -b / (4 * a) - S + u;
            Complex x2 = -b / (4 * a) - S - u;
            Complex x3 = -b / (4 * a) + S + v;
            Complex x4 = -b / (4 * a) + S - v;
</code>```

Also, according to this page, you can use this instead of the very long discriminant formula just to get its sign:

```<code>            double discriminantSign = c * c - 3 * b * d + 12 * a * e;
</code>```

I also noticed 4 typos, you forgot to mention the 5 decimal when you apply the Math.Round function, so your results are rounded to an integer.

EDIT: If you still have issues in you imaginary part, it's because you didn't correct the typos:

```<code>     Console.WriteLine(x1rp + " - " + Math.Round(Complex.Abs(x1.Imaginary)) + "i");
</code>```

Into:

```<code>     Console.WriteLine(x1rp + " - " + Math.Round(Complex.Abs(x1.Imaginary), 5) + "i");
</code>```

You take 5 decimals everywhere except in 4 lines as above. So it's rounding the integer. Replace them all.

Body:
This thread is a continuation of my last asked question.

My friends and I are trying to make a multi-functional calculator that can automatically calculate
the roots of quadratic, cubic, and even quartic equations.
However, we have run into some problems, previously on cubic equations, now on quartic equations.

Unlike the last thread, we will provide images including the answers calculated by our program and the answers calculated by WolframAlpha instead of putting them into text here.

The quartic equation will be denoted as in

ax^4 + bx^3 + cx^2 + dx + e

Our method of finding the roots of a quartic equation. (Found on another thread from another website)

a=1 b=2 c=-41 d=-42 e=360

a=1 b=-0.25 c=-0.85 d=1.45 e=-4.35

a=1 b=2 c=3 d=4 e=5

As seen in the images, the discriminant calculated by the program is always correct. However, the roots of the equation can sometimes cause errors (NaN), and the nature of roots can also cause errors as well but so as often as the roots do.

With all the information provided above, we wish to know the answers to the following questions :

What exactly is causing these errors and problems,

What amendment should I make to my code so that the program can function properly and as intended,

Whether our method of finding the roots of a quartic equation is correct, or is it even possible to find the roots of all quartic equations by a general formula,

Last but not least, is there a way to improve, or condense the code lines in our program but still function as we intended it to.

As aforementioned in the previous thread, we have just started learning C#.

For your convenience, we have put notes to some code lines.

Codes (C#) :

using System;
using System.Numerics;

namespace ComplexNumbers
{
    public class ComplexNo
    {
        public static void Main()
        {
            // prompting for coefficients and constant
            Console.WriteLine("Quartic Equation Calculator :");
            Console.Write("Insert first coefficient : ");
            double a = Convert.ToDouble(Console.ReadLine());
            Console.Write("Insert second coefficient : ");
            double b = Convert.ToDouble(Console.ReadLine());
            Console.Write("Insert third coefficient : ");
            double c = Convert.ToDouble(Console.ReadLine());
            Console.Write("Insert fourth coefficient : ");
            double d = Convert.ToDouble(Console.ReadLine());
            Console.Write("Insert constant : ");
            double e = Convert.ToDouble(Console.ReadLine());
            // discriminant
            double discriminant = 256 * Math.Pow(a, 3) * Math.Pow(e, 3) - (192 * Math.Pow(a, 2) * b * d * Math.Pow(e, 2)) -
                (128 * Math.Pow(a, 2) * Math.Pow(c, 2) * Math.Pow(e, 2)) + (144 * Math.Pow(a, 2) * c * Math.Pow(d, 2) * e) -
                (27 * Math.Pow(a, 2) * Math.Pow(d, 4)) + (144 * a * Math.Pow(b, 2) * c * Math.Pow(e, 2)) -
                (6 * a * Math.Pow(b, 2) * Math.Pow(d, 2) * e) - (80 * a * b * Math.Pow(c, 2) * d * e) +
                (18 * a * b * c * Math.Pow(d, 3)) + (16 * a * Math.Pow(c, 4) * e) - (4 * a * Math.Pow(c, 3) * Math.Pow(d, 2)) -
                (27 * Math.Pow(b, 4) * Math.Pow(e, 2)) + (18 * Math.Pow(b, 3) * c * d * e) -
                (4 * Math.Pow(b, 3) * Math.Pow(d, 3)) - (4 * Math.Pow(b, 2) * Math.Pow(c, 3) * e) +
                (Math.Pow(b, 2) * Math.Pow(c, 2) * Math.Pow(d, 2));

            // different parts of the roots presented in p1-p6
            double p1 = (2 * Math.Pow(c, 3)) - (9 * b * c * d) + (27 * a * Math.Pow(d, 2)) + (27 * Math.Pow(b, 2) * e) -
                (72 * a * c * e);
            double p2 = p1 + Math.Sqrt(-4.0 * Math.Pow(Math.Pow(c, 2) - (3 * b * d) + (12 * a * e), 3) + Math.Pow(p1, 2));
            double p3 = ((Math.Pow(c, 2) - (3 * b * d) + (12 * a * e)) / (3 * a * Math.Cbrt(p2 / 2))) + (Math.Cbrt(p2 / 2) / (3 * a));
            double p4 = Math.Sqrt((Math.Pow(b, 2) / (4 * Math.Pow(a, 2))) - (2 * c / (3 * a)) + p3);
            double p5 = (Math.Pow(b, 2) / (2 * Math.Pow(a, 2))) - (4 * c / (3 * a)) - p3;
            double p6 = ((-(Math.Pow(b, 3) / Math.Pow(a, 3))) + (4 * b * c / Math.Pow(a, 2)) - (8 * d / a)) / (4 * p4);
            // calculating roots with p1-p6
            Complex x1 = (-(b / (4 * a))) - (p4 / 2) - (Math.Sqrt(p5 - p6) / 2);
            Complex x2 = (-(b / (4 * a))) - (p4 / 2) + (Math.Sqrt(p5 - p6) / 2);
            Complex x3 = (-(b / (4 * a))) + (p4 / 2) - (Math.Sqrt(p5 - p6) / 2);
            Complex x4 = (-(b / (4 * a))) + (p4 / 2) + (Math.Sqrt(p5 - p6) / 2);

            // polynomials used for testing the nature of roots
            double P = (8 * a * c) - (3 * Math.Pow(b, 2));
            double R = Math.Pow(b, 3) + (8 * d * Math.Pow(a, 2)) - (4 * a * b * c);
            double deltazero = Math.Pow(c, 2) - (3 * b * d) + (12 * a * e);
            double D = (64 * Math.Pow(a, 3) * e) - (16 * Math.Pow(a, 2) * Math.Pow(c, 2)) +
                (16 * a * Math.Pow(b, 2) * c) - (16 * Math.Pow(a, 2) * b * d) - (3 * Math.Pow(b, 4));

            // results
            Console.WriteLine(" ");
            Console.WriteLine("Solve for " + a + "x^4 " + " + " + b + "x^3 " + " + " + c + "x^2 " + " + " + d + "x " + " + " + e + " :");
            Console.WriteLine(" ");
            Console.WriteLine("Results :");
            Console.WriteLine("First Root :");
            string x1rp = Convert.ToString(Math.Round(x1.Real, 5)); // rounding up both real and unreal parts
            string x1ip = Convert.ToString(Math.Round(x1.Imaginary, 5));
            if (x1.Imaginary == 0)
            {
                Console.WriteLine(x1rp);
            }
            else if (x1.Imaginary < 0) // testing if unreal part is negative
            {
                Console.WriteLine(x1rp + " - " + Math.Round(Complex.Abs(x1.Imaginary)) + "i");
            }
            else
            {
                Console.WriteLine(x1rp + " + " + x1ip + "i");
            }
            string x2rp = Convert.ToString(Math.Round(x2.Real, 5)); // rounding up both real and unreal parts
            string x2ip = Convert.ToString(Math.Round(x2.Imaginary, 5));
            if (x2.Imaginary == 0)
            {
                Console.WriteLine(x2rp);
            }
            else if (x2.Imaginary < 0) // testing if unreal part is negative
            {
                Console.WriteLine(x2rp + " - " + Math.Round(Complex.Abs(x2.Imaginary)) + "i");
            }
            else
            {
                Console.WriteLine(x2rp + " + " + x2ip + "i");
            }
            string x3rp = Convert.ToString(Math.Round(x3.Real, 5)); // rounding up both real and unreal parts
            string x3ip = Convert.ToString(Math.Round(x3.Imaginary, 5));
            if (x3.Imaginary == 0)
            {
                Console.WriteLine(x3rp);
            }
            else if (x3.Imaginary < 0) // testing if unreal part is negative
            {
                Console.WriteLine(x3rp + " - " + Math.Round(Complex.Abs(x3.Imaginary)) + "i");
            }
            else
            {
                Console.WriteLine(x3rp + " + " + x3ip + "i");
            }
            string x4rp = Convert.ToString(Math.Round(x4.Real, 5)); // rounding up both real and unreal parts
            string x4ip = Convert.ToString(Math.Round(x4.Imaginary, 5));
            if (x4.Imaginary == 0)
            {
                Console.WriteLine(x4rp);
            }
            else if (x4.Imaginary < 0) // testing if unreal part is negative
            {
                Console.WriteLine(x4rp + " - " + Math.Round(Complex.Abs(x4.Imaginary)) + "i");
            }
            else
            {
                Console.WriteLine(x4rp + " + " + x4ip + "i");
            }

            // discriminant tests
            if (discriminant == 0) // if delta = 0
            {
                if (P < 0 && D < 0 && deltazero != 0)
                {
                    string result4 = "The equation yields a pair of double roots and two real simple roots.";
                    Console.WriteLine(result4);
                }
                else if (D > 0 || (P > 0 && (D != 0 || R != 0)))
                {
                    string result5 = "The equation yields a pair of double roots and two complex conjugate roots.";
                    Console.WriteLine(result5);
                }
                else if (deltazero == 0 && D != 0)
                {
                    string result6 = "The equation yields a triple root and a simple root.";
                    Console.WriteLine(result6);
                }
                else if (D == 0)
                {
                    if (P < 0)
                    {
                        string result7 = "The equation yields two pairs of real double roots.";
                        Console.WriteLine(result7);
                    }
                    else if (P > 0 && R == 0)
                    {
                        string result8 = "The equation yields two pairs of double complex conjugate roots.";
                        Console.WriteLine(result8);
                    }
                    else if (deltazero == 0)
                    {
                        string result9pt2 = Convert.ToString(-(b / (4 * a)));
                        string result9 = "All of the roots of this equation are equal to -b/4a";
                        Console.WriteLine(result9 + "(" + result9pt2 + ")");
                    }
                    else
                    {
                        Console.WriteLine("ERROR");
                    }
                }
                else
                {
                    Console.WriteLine("ERROR");
                }
            }
            else if (discriminant > 0) // if delta > 0
            {
                if (P < 0 && D < 0)
                {
                    string result2 = "The equation yields four distinct real roots.";
                    Console.WriteLine(result2);
                }
                else if (P > 0 && D > 0)
                {
                    string result3 = "The equation yields two pairs of unreal complex conjugate roots.";
                    Console.WriteLine(result3);
                }
                else
                {
                    Console.WriteLine("ERROR");
                }
            }
            else if (discriminant < 0) // if delta < 0
            {
                string result1 = "The equation yields two distinct real roots and two complex conjugate non-real roots.";
                Console.WriteLine(result1);
            }

            // discriminant of equation
            Console.WriteLine(" ");
            Console.WriteLine("Discriminant :");
            Console.WriteLine(discriminant);

            Console.ReadLine();
        }
    }
}

==========================================================

Edit #1 :

I tried another method to solve the roots.

However, the imaginary part is still wrong for the last 2 roots.

If anyone is able to spot my mistake, I would be grateful.

// different parts of the roots presented in p1-p6
            double p = ((8 * a * c) - (3 * Math.Pow(b, 2))) / (8 * Math.Pow(a, 2));
            double q = (Math.Pow(b, 3) - (4 * a * b * c) + (8 * Math.Pow(a, 2) * d)) / (8 * Math.Pow(a, 3));
            double D0 = Math.Pow(c, 2) - (3 * b * d) + (12 * a * e);
            double D1 = (2 * Math.Pow(c, 3)) - (9 * b * c * d) + (27 * Math.Pow(b, 2) * e) + (27 * a * Math.Pow(d, 2)) - (72 * a * c * e);
            Complex Q = Complex.Pow((D1 + Complex.Sqrt(Complex.Pow(D1, 2) - (4 * Complex.Pow(D0, 3)))) / 2.0, 1.0 / 3.0);
            Complex S = 1.0 / 2.0 * Complex.Sqrt((-2.0 / 3.0 * p) + (1.0 / (3 * a) * (Q + (D0 / Q))));
            // calculating roots with p1-p6
            Complex x1 = (-(b / 4 * a)) - S + (1.0 / 2.0 * Complex.Sqrt((-4.0 * Complex.Pow(S, 2)) - (2 * p) + (q / S)));
            Complex x2 = (-(b / 4 * a)) - S - (1.0 / 2.0 * Complex.Sqrt((-4.0 * Complex.Pow(S, 2)) - (2 * p) + (q / S)));
            Complex x3 = (-(b / 4 * a)) + S + (1.0 / 2.0 * Complex.Sqrt((-4.0 * Complex.Pow(S, 2)) - (2 * p) + (q / S)));
            Complex x4 = (-(b / 4 * a)) + S - (1.0 / 2.0 * Complex.Sqrt((-4.0 * Complex.Pow(S, 2)) - (2 * p) + (q / S)));

==========================================================

Edit #2

Problem solved.

The program is now able to solve quartic equations. The cause of the problems mentioned above is actually the minor typos I made in the code lines.

Body:
I got an algorithm from here that works. It seems simpler than yours.

            double D0 = c * c - 3 * b * d + 12 * a * e;
            double D1 = 2 * c * c * c - 9 * b * c * d + 27 * b * b * e + 27 * a * d * d - 72 * a * c * e;
            double p = (8 * a * c - 3 * b * b) / (8 * a * a);
            double q = (b * b * b - 4 * a * b * c + 8 * a * a * d) / (8 * a * a * a);
            Complex Q = Complex.Pow((D1 + Complex.Sqrt(D1 * D1 - 4 * D0 * D0 * D0)) / 2, 1.0 / 3.0);
            Complex S = Complex.Sqrt(-2 * p / 3 + (Q + D0 / Q) / (3 * a)) / 2;
            Complex u = Complex.Sqrt(-4 * S * S - 2 * p + q / S) / 2;
            Complex v = Complex.Sqrt(-4 * S * S - 2 * p - q / S) / 2;
            Complex x1 = -b / (4 * a) - S + u;
            Complex x2 = -b / (4 * a) - S - u;
            Complex x3 = -b / (4 * a) + S + v;
            Complex x4 = -b / (4 * a) + S - v;

Also, according to this page, you can use this instead of the very long discriminant formula just to get its sign:

            double discriminantSign = c * c - 3 * b * d + 12 * a * e;

I also noticed 4 typos, you forgot to mention the 5 decimal when you apply the Math.Round function, so your results are rounded to an integer.

EDIT: If you still have issues in you imaginary part, it's because you didn't correct the typos:

     Console.WriteLine(x1rp + " - " + Math.Round(Complex.Abs(x1.Imaginary)) + "i");

Into:

     Console.WriteLine(x1rp + " - " + Math.Round(Complex.Abs(x1.Imaginary), 5) + "i");

You take 5 decimals everywhere except in 4 lines as above. So it's rounding the integer. Replace them all.


来源: stackexchange

问:
how to write a recursive function that sums the integers in a tree?
Write a recursive function TreeSum(T) to add up all the integers in a tree. My test case is

```<code>TreeSum(set)
</code>```

48

where

```<code>set=[[[[2,1],[3,7]],[1,2]],[[0,6],[[[3,2],[1,1]],[9,10]]]]
</code>```

This is the code I have so far:

```<code>def TreeSum(T):
     if len(T)==0:
       return 0
     else:
       return T[0] + TreeSum(T[1:])
</code>```

I am getting an error from the return line ("can only concatenate list (not "int") to list"). How can I fix this?
Error:

```<code>----> 5    return T[0] + TreeSum(T[1:])
      6
      7 TreeSum(maple)

TypeError: can only concatenate list (not "int") to list
</code>```

答:
@j1-lee had the correct approach, but this is limited in terms of span of the sublists (silently ignoring the items with a position > 1, or failing if one of the first two elements is an integer). You need to apply the recursive function on all sub-elements. One way is to use map

NB. I slightly changed the input to add two more elements to the first sublist

```<code>tree = [[[[2,1],1,[3,7],[1]],[1,2]],[[0,6],[[[3,2],[1,1]],[9,10]]]]

def treesum(x):
    if not isinstance(x, list):
        return x
    return sum(map(treesum, x))
print(treesum(tree))
</code>```

Output: 50

ContentLicense: CC BY-SA 4.0

Body:
Write a recursive function TreeSum(T) to add up all the integers in a tree. My test case is

TreeSum(set)

48

where

set=[[[[2,1],[3,7]],[1,2]],[[0,6],[[[3,2],[1,1]],[9,10]]]]

This is the code I have so far:

def TreeSum(T):
     if len(T)==0:
       return 0
     else:
       return T[0] + TreeSum(T[1:])

I am getting an error from the return line ("can only concatenate list (not "int") to list"). How can I fix this?
Error:

----> 5    return T[0] + TreeSum(T[1:])
      6
      7 TreeSum(maple)

TypeError: can only concatenate list (not "int") to list

Body:
@j1-lee had the correct approach, but this is limited in terms of span of the sublists (silently ignoring the items with a position > 1, or failing if one of the first two elements is an integer). You need to apply the recursive function on all sub-elements. One way is to use map

NB. I slightly changed the input to add two more elements to the first sublist

tree = [[[[2,1],1,[3,7],[1]],[1,2]],[[0,6],[[[3,2],[1,1]],[9,10]]]]

def treesum(x):
    if not isinstance(x, list):
        return x
    return sum(map(treesum, x))
print(treesum(tree))

Output: 50


问:
How do I make an html link look like a button?
I'm using ASP.NET, some of my buttons just do redirects.  I'd rather they were ordinary links, but I don't want my users to notice much difference in the appearance.  I considered images wrapped by anchors, i.e.  tags, but I don't want to have to fire up an image editor every time I change the text on a button.</p>

答:
This gets into the details of the css a bit more too, and gives you some images:

http://www.dynamicdrive.com/style/csslibrary/item/css_square_buttons/

OwnerDisplayName: MatthewMartin

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Greg


问:
How to add a class to the  tag in Yoast SEO breadcrumbs?
I am using Yoast Wordpress plugin and the breadcrumb function that it provides. It works great, but I want to modify the default structure and to add an additional class.

So instead of:

```<code><a href="http://www.example.com" rel="v:url" property="v:title">Home</a>
</code>```

I want to make it:

```<code><a href="http://www.example.com" class="my-class" rel="v:url" property="v:title">Home</a>
</code>```

答:
If you need to add a breadcrumb name specific CSS class to each link, you could use the fallowing:</p>
```<code>/**
     * Helper function which will generate a valid CSS class
     * from a breadcrumb link text name.
     *
     * @param string $string
     *
     * @return void
     */
    function cleanString($string)
    {
        $string = remove_accents($string); // WordPress internal function
        $string = strtolower($string); // convert to lower case
        $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
        $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.

        return preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
    }

    /**
     * Modifies SEO Yeast breadcrumbs links through wpseo_breadcrumb_single_link filter
     *
     * @see https://stackoverflow.com/questions/42178688/how-to-add-a-class-to-the-a-tag-in-yoast-seo-breadcrumbs
     *
     */
    add_filter('wpseo_breadcrumb_single_link', 'ss_breadcrumb_single_link', 10, 2);
    function ss_breadcrumb_single_link($link_output, $link)
    {
        $classText = cleanString($link['text']);
        return str_replace('<a', '<a class="breadcrumbs-' . $classText . '"', $link_output);
    }
</code>```

Title: How to add a class to the <a> tag in Yoast SEO breadcrumbs?

Body:
I am using Yoast Wordpress plugin and the breadcrumb function that it provides. It works great, but I want to modify the default structure and to add an additional class.

So instead of:

Home

I want to make it:

Home

Body:
If you need to add a breadcrumb name specific CSS class to each link, you could use the fallowing:

/**
     * Helper function which will generate a valid CSS class
     * from a breadcrumb link text name.
     *
     * @param string $string
     *
     * @return void
     */
    function cleanString($string)
    {
        $string = remove_accents($string); // WordPress internal function
        $string = strtolower($string); // convert to lower case
        $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
        $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.

        return preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
    }

    /**
     * Modifies SEO Yeast breadcrumbs links through wpseo_breadcrumb_single_link filter
     *
     * @see https://stackoverflow.com/questions/42178688/how-to-add-a-class-to-the-a-tag-in-yoast-seo-breadcrumbs
     *
     */
    add_filter('wpseo_breadcrumb_single_link', 'ss_breadcrumb_single_link', 10, 2);
    function ss_breadcrumb_single_link($link_output, $link)
    {
        $classText = cleanString($link['text']);
        return str_replace('<a', '<a class="breadcrumbs-' . $classText . '"', $link_output);
    }


问:
How can I access MariaDb outside from Helm installation
I have a RKE2 kube installation, 3 nodes, I install MariaDB from BitNami repository:

```<code>- name: mariadb
  repository: https://charts.bitnami.com/bitnami
  version: 10.3.2
</code>```

It boots up correctly in my kube installation, but I need to access it from outside the cluster, let's say with my Navicat client as example.

This is my values.yaml:

```<code>mariadb:
  clusterDomain: a4b-kube.local
  auth:
    rootPassword: "password"
    replicationPassword: "password"
  architecture: replication
  primary:
    service:
      type: LoadBalancer
      loadBalancerIP: mariadb.acme.com
  secondary:
    replicaCount: 2
</code>```

Listing the services I see:

```<code>NAME                         TYPE           CLUSTER-IP     EXTERNAL-IP   PORT(S)          AGE
a4b-test-mariadb-primary     LoadBalancer   10.43.171.45   <pending>     3306:31379/TCP   48m
</code>```

And the external IP never gets updated, I also try specifing an IP instead of dns, in my case was 192.168.113.120 but I got same result. What am I missing?

答: You need an ingress controller to setup the EXTERNAL-IP. But if you have no intention to expose the database to the Internet; and the cluster nodes are network reachable to your client application, you can use NodePort instead of LoadBalancer. You can then connect to your database thru any of the 3 nodes with the node port from the outside of your cluster.

Body:
I have a RKE2 kube installation, 3 nodes, I install MariaDB from BitNami repository:

- name: mariadb
  repository: https://charts.bitnami.com/bitnami
  version: 10.3.2

It boots up correctly in my kube installation, but I need to access it from outside the cluster, let's say with my Navicat client as example.

This is my values.yaml:

mariadb:
  clusterDomain: a4b-kube.local
  auth:
    rootPassword: "password"
    replicationPassword: "password"
  architecture: replication
  primary:
    service:
      type: LoadBalancer
      loadBalancerIP: mariadb.acme.com
  secondary:
    replicaCount: 2

Listing the services I see:

NAME                         TYPE           CLUSTER-IP     EXTERNAL-IP   PORT(S)          AGE
a4b-test-mariadb-primary     LoadBalancer   10.43.171.45   <pending>     3306:31379/TCP   48m

And the external IP never gets updated, I also try specifing an IP instead of dns, in my case was 192.168.113.120 but I got same result. What am I missing?


问:
Can I print tibbles in Rmarkdown / xaringan so they look like the RStudio console
If I print a tibble with the console in the RStudio IDE the NA values appear in red. When I print the table on a xaringan slide the table is black and white and the NA_character_ values display as <NA>. Is there a way to get the output on a xaringan slide to look like the console output (without using a screen shot)?

Here is an example:

```<code>---
title: "x"
output:
  xaringan::moon_reader
---

```{r}
library(tibble)
example <- tribble(
  ~name, ~age,
  "Fran", 2,
  "Bob", NA,
  NA, NA
)
example
```
</code>```

答:
This is available via the fansi package which provides knitr hooks for rendering crayon output into HTML in rmarkdown.  More info in the vignette here.

```<code>```{r setup, echo = FALSE, results='asis'}

options(crayon.enabled = TRUE)

old.hooks <- fansi::set_knit_hooks(knitr::knit_hooks)

```

```{r}

tibble::tribble(
  ~name, ~age,
  "Fran", 2,
  "Bob", NA,
  NA, NA
)

waldo::compare(1:5, 3:7)

```
</code>```

Body:
If I print a tibble with the console in the RStudio IDE the NA values appear in red. When I print the table on a xaringan slide the table is black and white and the NA_character_ values display as <NA>. Is there a way to get the output on a xaringan slide to look like the console output (without using a screen shot)?

Here is an example:

---
title: "x"
output:
  xaringan::moon_reader
---

```{r}
library(tibble)
example <- tribble(
  ~name, ~age,
  "Fran", 2,
  "Bob", NA,
  NA, NA
)
example
```

Body:
This is available via the fansi package which provides knitr hooks for rendering crayon output into HTML in rmarkdown.  More info in the vignette here.

```{r setup, echo = FALSE, results='asis'}

options(crayon.enabled = TRUE)

old.hooks <- fansi::set_knit_hooks(knitr::knit_hooks)

```

```{r}

tibble::tribble(
  ~name, ~age,
  "Fran", 2,
  "Bob", NA,
  NA, NA
)

waldo::compare(1:5, 3:7)

```


问:
How do i avoid UI delay in drag and drop app using RxJS
https://codesandbox.io/s/pedantic-roentgen-s514z?file=/src/index.js

```<code>import "./styles.css";
import { fromEvent } from "rxjs";
import { switchMap, takeUntil } from "rxjs/operators";

let el = document.getElementById("box0");

const mousedown$ = fromEvent(el, "mousedown");
const mousemove$ = fromEvent(document, "mousemove");
const mouseup$ = fromEvent(document, "mouseup");

const drag$ = mousedown$.pipe(
  switchMap(() => mousemove$.pipe(takeUntil(mouseup$)))
);

drag$.subscribe((e) => {
  console.log(e);
  el.style.left = `${e.clientX}px`;
  el.style.top = `${e.clientY}px`;
});
</code>```

Noticing some delay visually in the drag and drop effect in the UI. Is there any feedback on the way i'm using reactive extensions that might be causing this?

答: There is nothing wrong with the way you use Rx on this example. If you want to boost the performance just remove console.log and maybe use CSS translate property for square movement.

Body:
https://codesandbox.io/s/pedantic-roentgen-s514z?file=/src/index.js

import "./styles.css";
import { fromEvent } from "rxjs";
import { switchMap, takeUntil } from "rxjs/operators";

let el = document.getElementById("box0");

const mousedown$ = fromEvent(el, "mousedown");
const mousemove$ = fromEvent(document, "mousemove");
const mouseup$ = fromEvent(document, "mouseup");

const drag$ = mousedown$.pipe(
  switchMap(() => mousemove$.pipe(takeUntil(mouseup$)))
);

drag$.subscribe((e) => {
  console.log(e);
  el.style.left = `${e.clientX}px`;
  el.style.top = `${e.clientY}px`;
});

Noticing some delay visually in the drag and drop effect in the UI. Is there any feedback on the way i'm using reactive extensions that might be causing this?


问:
ssl.cipher_suites/0 is undefined or private, use cipher_suites/2,3 instead (ssl 10.4.1) :ssl.cipher_suites()
```<code>** (UndefinedFunctionError) function :ssl.cipher_suites/0 is undefined or private, use cipher_suites/2,3 instead
    (ssl 10.4.1) :ssl.cipher_suites()
    (hackney 1.15.2) /Users/naveen/NAV/moviematch/deps/hackney/src/hackney_ssl.erl:77: :hackney_ssl.ciphers/0
    (hackney 1.15.2) /Users/naveen/NAV/moviematch/deps/hackney/src/hackney_ssl.erl:69: :hackney_ssl.connect/4
    (hackney 1.15.2) /Users/naveen/NAV/moviematch/deps/hackney/src/hackney_connect.erl:277: :hackney_connect.do_connect/5
    (hackney 1.15.2) /Users/naveen/NAV/moviematch/deps/hackney/src/hackney_connect.erl:47: :hackney_connect.connect/5
    (hackney 1.15.2) /Users/naveen/NAV/moviematch/deps/hackney/src/hackney.erl:333: :hackney.request/5
    (httpoison 1.8.0) lib/httpoison/base.ex:846: HTTPoison.Base.request/6
</code>```

project dependency specified here:
https://github.com/navyad/moviematch/blob/master/mix.exs#L22

Current Elixir version: 1.12 and Erlang/OTP 24
I have upgraded the httpoison from 1.4 to 1.8

Steps

mix deps.get

mix compile

iex -S mix

MovieMatch.Imdb.fetch_imdb_watchlist("ur26610840")

答:
If you're seeing this error (or ones like it), your local Erlang probably doesn't include the :ssl package. An example GitHub issue:

Installation fails, module :ssl is not available · Issue #602 · phoenixframework/phoenix

Installing the :ssl package depends on your system's OS.

Body:
** (UndefinedFunctionError) function :ssl.cipher_suites/0 is undefined or private, use cipher_suites/2,3 instead
    (ssl 10.4.1) :ssl.cipher_suites()
    (hackney 1.15.2) /Users/naveen/NAV/moviematch/deps/hackney/src/hackney_ssl.erl:77: :hackney_ssl.ciphers/0
    (hackney 1.15.2) /Users/naveen/NAV/moviematch/deps/hackney/src/hackney_ssl.erl:69: :hackney_ssl.connect/4
    (hackney 1.15.2) /Users/naveen/NAV/moviematch/deps/hackney/src/hackney_connect.erl:277: :hackney_connect.do_connect/5
    (hackney 1.15.2) /Users/naveen/NAV/moviematch/deps/hackney/src/hackney_connect.erl:47: :hackney_connect.connect/5
    (hackney 1.15.2) /Users/naveen/NAV/moviematch/deps/hackney/src/hackney.erl:333: :hackney.request/5
    (httpoison 1.8.0) lib/httpoison/base.ex:846: HTTPoison.Base.request/6

project dependency specified here:
https://github.com/navyad/moviematch/blob/master/mix.exs#L22

Current Elixir version: 1.12 and Erlang/OTP 24
I have upgraded the httpoison from 1.4 to 1.8

Steps

mix deps.get

mix compile

iex -S mix

MovieMatch.Imdb.fetch_imdb_watchlist("ur26610840")


问:
gRPC slow serialization on large dataset
I know that google states that protobufs don't support large messages (i.e. greater than 1 MB), but I'm trying to stream a dataset using gRPC that's tens of megabytes, and it seems like some people say it's ok, or at least with some splitting...

However, when I try to send an array this way (repeated uint32), it takes like 20 seconds on the same local machine.

```<code>#proto
service PAS {
  // analyze single file
  rpc getPhotonRecords (PhotonRecordsRequest) returns (PhotonRecordsReply) {}
}

message PhotonRecordsRequest {
  string fileName = 1;
}

message PhotonRecordsReply {
  repeated uint32 PhotonRecords = 1;
}
</code>```

where PhotonRecordsReply needs to be ~10 million uint32 in length...

Does anyone have an idea on how to speed this up? Or what technology would be more appropriate?

So I think I've implemented streaming based on comments and answers given, but it still takes the same amount of time:

```<code>#proto
service PAS {
  // analyze single file
  rpc getPhotonRecords (PhotonRecordsRequest) returns (stream PhotonRecordsReply) {}
}
</code>```

class PAS_GRPC(pas_pb2_grpc.PASServicer):

    def getPhotonRecords(self, request: pas_pb2.PhotonRecordsRequest, _context):
        raw_data_bytes = flb_tools.read_data_bytes(request.fileName)
        data = flb_tools.reshape_flb_data(raw_data_bytes)
        index = 0
        chunk_size = 1024
        len_data = len(data)
        while index < len_data:
            # last chunk
            if index + chunk_size > len_data:
                yield pas_pb2.PhotonRecordsReply(PhotonRecords=data[index:])
            # all other chunks
            else:
                yield pas_pb2.PhotonRecordsReply(PhotonRecords=data[index:index + chunk_size])
            index += chunk_size
```

Min repro
Github example

答:
If you changed it over to use streams that should help. It took less than 2 seconds to transfer for me. Note this was without ssl and on localhost. This code I threw together. I did run it and it worked. Not sure what might happen if the file is not a multiple of 4 bytes for example. Also the endian order of bytes read is the default for Java.

I made my 10 meg file like this.

```<code>dd if=/dev/random  of=my_10mb_file bs=1024 count=10240
</code>```

Here's the service definition. Only thing I added here was the stream to the response.

```<code>service PAS {
  // analyze single file
  rpc getPhotonRecords (PhotonRecordsRequest) returns (stream PhotonRecordsReply) {}
}
</code>```

Here's the server implementation.

```<code>public class PhotonsServerImpl extends PASImplBase {

  @Override
  public void getPhotonRecords(PhotonRecordsRequest request, StreamObserver<PhotonRecordsReply> responseObserver) {
    log.info("inside getPhotonRecords");

    // open the file, I suggest using java.nio API for the fastest read times.
    Path file = Paths.get(request.getFileName());
    try (FileChannel fileChannel = FileChannel.open(file, StandardOpenOption.READ)) {

      int blockSize = 1024 * 4;
      ByteBuffer byteBuffer = ByteBuffer.allocate(blockSize);
      boolean done = false;
      while (!done) {
        PhotonRecordsReply.Builder response = PhotonRecordsReply.newBuilder();
        // read 1000 ints from the file.
        byteBuffer.clear();
        int read = fileChannel.read(byteBuffer);
        if (read < blockSize) {
          done = true;
        }
        // write to the response.
        byteBuffer.flip();
        for (int index = 0; index < read / 4; index++) {
          response.addPhotonRecords(byteBuffer.getInt());
        }
        // send the response
        responseObserver.onNext(response.build());
      }
    } catch (Exception e) {
      log.error("", e);
      responseObserver.onError(
          Status.INTERNAL.withDescription(e.getMessage()).asRuntimeException());
    }
    responseObserver.onCompleted();
    log.info("exit getPhotonRecords");

  }
}
</code>```

The client just logs the size of the array received.

```<code>public long getPhotonRecords(ManagedChannel channel) {
  if (log.isInfoEnabled())
    log.info("Enter - getPhotonRecords ");

  PASGrpc.PASBlockingStub photonClient = PASGrpc.newBlockingStub(channel);

  PhotonRecordsRequest request = PhotonRecordsRequest.newBuilder().setFileName("/udata/jdrummond/logs/my_10mb_file").build();

  photonClient.getPhotonRecords(request).forEachRemaining(photonRecordsReply -> {
    log.info("got this many photons: {}", photonRecordsReply.getPhotonRecordsCount());
  });

  return 0;
}
</code>```

Body:
I know that google states that protobufs don't support large messages (i.e. greater than 1 MB), but I'm trying to stream a dataset using gRPC that's tens of megabytes, and it seems like some people say it's ok, or at least with some splitting...

However, when I try to send an array this way (repeated uint32), it takes like 20 seconds on the same local machine.

#proto
service PAS {
  // analyze single file
  rpc getPhotonRecords (PhotonRecordsRequest) returns (PhotonRecordsReply) {}
}

message PhotonRecordsRequest {
  string fileName = 1;
}

message PhotonRecordsReply {
  repeated uint32 PhotonRecords = 1;
}

where PhotonRecordsReply needs to be ~10 million uint32 in length...

Does anyone have an idea on how to speed this up? Or what technology would be more appropriate?

So I think I've implemented streaming based on comments and answers given, but it still takes the same amount of time:

#proto
service PAS {
  // analyze single file
  rpc getPhotonRecords (PhotonRecordsRequest) returns (stream PhotonRecordsReply) {}
}

class PAS_GRPC(pas_pb2_grpc.PASServicer):

    def getPhotonRecords(self, request: pas_pb2.PhotonRecordsRequest, _context):
        raw_data_bytes = flb_tools.read_data_bytes(request.fileName)
        data = flb_tools.reshape_flb_data(raw_data_bytes)
        index = 0
        chunk_size = 1024
        len_data = len(data)
        while index < len_data:
            # last chunk
            if index + chunk_size > len_data:
                yield pas_pb2.PhotonRecordsReply(PhotonRecords=data[index:])
            # all other chunks
            else:
                yield pas_pb2.PhotonRecordsReply(PhotonRecords=data[index:index + chunk_size])
            index += chunk_size

Min repro
Github example

Body:
If you changed it over to use streams that should help. It took less than 2 seconds to transfer for me. Note this was without ssl and on localhost. This code I threw together. I did run it and it worked. Not sure what might happen if the file is not a multiple of 4 bytes for example. Also the endian order of bytes read is the default for Java.

I made my 10 meg file like this.

dd if=/dev/random  of=my_10mb_file bs=1024 count=10240

Here's the service definition. Only thing I added here was the stream to the response.

service PAS {
  // analyze single file
  rpc getPhotonRecords (PhotonRecordsRequest) returns (stream PhotonRecordsReply) {}
}

Here's the server implementation.

public class PhotonsServerImpl extends PASImplBase {

  @Override
  public void getPhotonRecords(PhotonRecordsRequest request, StreamObserver<PhotonRecordsReply> responseObserver) {
    log.info("inside getPhotonRecords");

    // open the file, I suggest using java.nio API for the fastest read times.
    Path file = Paths.get(request.getFileName());
    try (FileChannel fileChannel = FileChannel.open(file, StandardOpenOption.READ)) {

      int blockSize = 1024 * 4;
      ByteBuffer byteBuffer = ByteBuffer.allocate(blockSize);
      boolean done = false;
      while (!done) {
        PhotonRecordsReply.Builder response = PhotonRecordsReply.newBuilder();
        // read 1000 ints from the file.
        byteBuffer.clear();
        int read = fileChannel.read(byteBuffer);
        if (read < blockSize) {
          done = true;
        }
        // write to the response.
        byteBuffer.flip();
        for (int index = 0; index < read / 4; index++) {
          response.addPhotonRecords(byteBuffer.getInt());
        }
        // send the response
        responseObserver.onNext(response.build());
      }
    } catch (Exception e) {
      log.error("", e);
      responseObserver.onError(
          Status.INTERNAL.withDescription(e.getMessage()).asRuntimeException());
    }
    responseObserver.onCompleted();
    log.info("exit getPhotonRecords");

  }
}

The client just logs the size of the array received.

public long getPhotonRecords(ManagedChannel channel) {
  if (log.isInfoEnabled())
    log.info("Enter - getPhotonRecords ");

  PASGrpc.PASBlockingStub photonClient = PASGrpc.newBlockingStub(channel);

  PhotonRecordsRequest request = PhotonRecordsRequest.newBuilder().setFileName("/udata/jdrummond/logs/my_10mb_file").build();

  photonClient.getPhotonRecords(request).forEachRemaining(photonRecordsReply -> {
    log.info("got this many photons: {}", photonRecordsReply.getPhotonRecordsCount());
  });

  return 0;
}


问:
Compiler doesn't recognize precompiled header
my precompiled header is called pch.h. When I specify #include "../pch.h, the compiler doesn't seem to recognize the precompiled header and gives compilation error C2857. It does however recognize just #include "pch.h", but this doesn't work for my files within a folder.

答:
What Hans said works for me. Please check if your path is correct.

If ../ is not used, you can also check the settings below:

1.Properties > C/C++>Add Additional Directories

2.Precomplied Header > /Yc

3.Precomplied Header File > pch.h


问:
How do instructions from a program get sent to different memory levels? Are they pre-loaded when the chips are manufactured for the first time?
I had asked a question earlier on how data gets pushed to registers in the CPU

My question now is, do instructions required for program execution get moved to memory by the compiler the same way data gets pushed?

If the answer to the first question is yes, then what do CPU designers load into the cache/main memory when it comes fresh out of the foundry? Since no program has ever been run before on the chip, are any instructions preloaded into memory at the time of designing and manufacturing of the chip so that it executes a pre-defined set of sequences when it is powered up for the first time?

答:
I think you are trying to over-complicate this.  Your question is of course quite broad and there are different solutions.

Microcontrollers, MCUs, tend to have some form of non volatile storage, today that means flash.  For each brand/family/product there is some way to program that flash using the pins of the part in some way.  The machine code, the program/instructions as well as data can be programmed into this flash.  Then on a normal boot, the processor in the mcu will start executing those instructions and run the application.

Normal processors, or let's say non-mcus, typically do not have on chip non-volatile storage.  There will normally be some form of off chip non-volatile storage be it a flash, an SD card interface, etc.  This storage will contain the machine code, etc, that boots the chip and gets it going.

Some processors have on chip sram and have some interface that one may be able to come in through an interface on the chip to halt the processor, load that memory with instructions and start execution of those instructions.  Some may use this sram in a way that logic on reset/boot will copy instructions from an sd card to this sram, then start the processor executing from that sram.

There is no one way that every processor boots.

Once running an operating system for example, a program from a hard disk can be loaded into ram by the operating system, and then a jump to that code starts it running.

cache is just cache, it is in between the processor and the main memory (usually dram for Linux/Windows/MacOS type systems).  You generally have an MMU, memory management unit, that is configured by software (kernel/operating system) to describe the system and define which parts of the address space are to be cached and in what way (instruction, data, etc).  Then when memory transactions happen from the processor, and go through the mmu, that will mark the transaction as cacheable or not, then the cache, if configured and enabled, will....cache that transaction...You do not fill the cache directly, the cache is basically automatic and based on transactions going by, generally not predictable.

There have been processor chip designs, that for various reasons, have an on chip rom or flash, that is programmed by the chip manufacturer.  This can be used to drive microcode for a CISC design, this can be a factory bootloader for an MCU, or other reasons.

Memory, DRAM, is dynamic D, not only do you have to work for it to retain any information, it is volatile, when the power goes off, or refreshes stop, it loses its information.  You definitely do not preprogram this at some factory.

Same goes for SRAM.

Except for some very rare cases, the logic is designed such that it boots off of some non-volatile storage (these days that is some form of flash device on chip or off).  That non-volatile storage is generally programmed by the PRODUCT vendor (not chip vendor), computer motherboard, TV set top box, cell phone, etc.  That code generally then looks for additional software possibly on another non-volatile storage of some sort (hard disk, SSD, etc).  And then of course that software may be an operating system, that can then run other various applications (web browser, mail program, games, etc).  You often have one solution to get the chip booted, dram initialized, etc, to prepare the system to load and run an operating system off of some media, not uncommon to be different from the boot loader.  Then the operating system loads and runs applications, usually from the same media that held the operating system.

The car is generic.  The user has to insert a key and turn it on and start it.  Then the user has to drive it somewhere.  Multiple steps for the thing to do its job.  The design for the car is such that the driver is not pre-built into the car, but instead a generic interface such that countless different operators can start and drive the car.

Same with a processor/system, reset starts the bootloader, the bootloader loads the operating system, the operating system loads the applications.  The software is stored in one or more forms of non volatile storage and loaded through generic interfaces designed into the hardware (chip or board).

RAM, including layers of caches, are simply volatile storage devices on layers of buses according to some design.  Professor writes formulas on the whiteboard, from their brain, student copies those formulas onto paper, longer term storage.  Professor runs out of white board and starts to erase some of the info to make room for more.   The whiteboard is just a cache between the professor and the students notebook.  There is no reason for the whiteboard to be pre-loaded with a fraction of one lecture when the building is constructed.  It is designed to be used and reused runtime.


问:
Bringing a DIV upwards so it sits behind another DIV
I'm confused here... Here's my site that I'm working on: http://s361608839.websitehome.co.uk/marbleenergy/

The div #main is sitting about 10px below #navigation and I've tried bringing it up 10px by adding:

```<code> #main {
 margin-top: -10px;
 }
</code>```

Had no luck there unfortunately. I'm learning CSS here, what is it I need to do?

Thanks

答: As the other answer more clearly details, you need to make sure that positioning is absolute, in order for any 'px' CSS specification to make sense, if not, it defaults to relative (to nearest parent container) I believe.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm confused here... Here's my site that I'm working on: http://s361608839.websitehome.co.uk/marbleenergy/

The div #main is sitting about 10px below #navigation and I've tried bringing it up 10px by adding:

 #main {
 margin-top: -10px;
 }

Had no luck there unfortunately. I'm learning CSS here, what is it I need to do?

Thanks


答:
You might consider using NodePort

```<code>mariadb:
  clusterDomain: a4b-kube.local
  auth:
    rootPassword: "password"
    replicationPassword: "password"
  architecture: replication
  primary:
    service:
      type: NodePort
      nodePort: 32036
  secondary:
    replicaCount: 2
</code>```

nodePort: 32036 you can choose in range 30000 - 32767 (default)

Then, you can access via nodeIP:nodePort

Title: How can I access MariaDb outside from Helm installation

Body:
You might consider using NodePort

mariadb:
  clusterDomain: a4b-kube.local
  auth:
    rootPassword: "password"
    replicationPassword: "password"
  architecture: replication
  primary:
    service:
      type: NodePort
      nodePort: 32036
  secondary:
    replicaCount: 2

nodePort: 32036 you can choose in range 30000 - 32767 (default)

Then, you can access via nodeIP:nodePort


问:
Why is so much time spent in scripting when rendering list items in React? (performance optimisation)
I've been trying to improve the performance of my React app (Electron to be specific) which uses react-redux and reselect. I have a parent (grid) component which gets some data from the redux store using useSelector, and for each item in the array renders a child component (row in the grid). We also have a filter functionality, so we do some transformation on the array of product data. Something along these lines:

```<code> const data = useDataSelector(
   "all",
   categoryId || EVERYTHING_CATEGORY_ID
 );
 const location = useLocation();
 const [filteredData, setFilteredData] = useState([]);

 useEffect(() => {
    if (query) {
      setFilteredData(
        fuse.search(`${query}`).map((product) => product.item)
      );
    } else {
      setFilteredData(data);
    }
  }, [
    location.search,
  ])

 return (
   <>
     {data.map((productInfo) => (
            <Row key={productInfo.id} {...productInfo} />
          ))}
   </>
 );
</code>```

useDataSelector calls useSelector:

```<code>export const useDataSelector = (statusType: StatusType = "all", categoryId) =>
  useSelector(productSelector(statusType, categoryId));
</code>```

and productSelector is a memoized selector that does some pretty heavy computation:

```<code>const productSelector = (
  statusType: StatusType,
  categoryId: number,
) =>
  createSelector(
    [selectProductData, selectProductStatus],
    (productData, productStatus) =>
    //some pretty heavy computations here
  )
</code>```

Now the issue I am seeing is the fact that rendering the grid component is super slow. I can't really see much when recording performance except for the fact that we're spending a very long time scripting:

I can't see much when looking at the Call Tree or Event Log tabs. It seems like death by a thousand papercuts... Is this normal? It's rather disappointing how janky our scroll is.

(regarding the screenshot above: we've added LazyLoad to reduce load time when we switch the tabs or when the app is loaded). This guy sets up scroll event listener and renders more components when needed.

```<code><li>
  <LazyLoad
        height={60}
        scrollContainer={scrollContainer}
        offset={500}
        overflow
        once
  >
    // actual component rendering
  </LazyLoad>
</li>
</code>```

答:
As explained by @Zachary Haber in the comments, you aren't getting the full benefit of createSelector because you are creating the memoized selector through a function which gets re-executed on every render.

You can actually pass arguments through your input selectors, though it's annoying because you have two arguments (and we don't want to combine them into an object without memoizing that object).

You can move the productSelector function into the useDataSelector hook and wrap it in useMemo such that it is only re-evaluated when statusType or categoryId change.

```<code>import { createSelector } from '@reduxjs/toolkit'; // or from 'reselect'
import { useMemo } from 'react';
import { useSelector } from 'react-redux';

export const useDataSelector = (statusType: StatusType = "all", categoryId: number): Product[] => {
  const productSelector = useMemo(() => {
    return createSelector(
      [selectProductData, selectProductStatus],
      (productData, productStatus): Product[] => {
        return heavyComputation(productData, productStatus, statusType, categoryId);
      }
    )
  },
    [statusType, categoryId]
  );

  return useSelector(productSelector);
}
</code>```

If someone visits a categoryId then goes to another one then comes back to the first, it will re-evaluate with this approach.  Whereas something like re-reselect would keep the previously-computed selectors in its cache.

Also note that if you have multiple components using useDataSelector they will each create their own cached version of the selector.  I am assuming here that the list is the only place which accesses the data and that all child components get their data passed down via props.

Since re-reselect solves these issue, let's see how we can use it.

```<code>import { useSelector } from 'react-redux';
import { createCachedSelector } from 're-reselect';

const productSelector = createCachedSelector(
  // select from redux state
  selectProductData,
  selectProductStatus,
  // pass through arguments
  (state: RootState, statusType: StatusType) => statusType,
  (state: RootState, statusType: StatusType, categoryId: number) => categoryId,
  // combine the results
  (productData, productStatus, statusType, categoryId): Product[] => {
    return heavyComputation(productData, productStatus, statusType, categoryId);
  }
)(
  // create a unique cache key from our arguments
  (state, statusType, categoryId) => `${statusType}__${categoryId}`
)

export const useDataSelector = (statusType: StatusType = "all", categoryId: number): Product[] => {
  return useSelector((state: RootState) => productSelector(state, statusType, categoryId));
}
</code>```

TypeScript Playground

Body:
I've been trying to improve the performance of my React app (Electron to be specific) which uses react-redux and reselect. I have a parent (grid) component which gets some data from the redux store using useSelector, and for each item in the array renders a child component (row in the grid). We also have a filter functionality, so we do some transformation on the array of product data. Something along these lines:

 const data = useDataSelector(
   "all",
   categoryId || EVERYTHING_CATEGORY_ID
 );
 const location = useLocation();
 const [filteredData, setFilteredData] = useState([]);

 useEffect(() => {
    if (query) {
      setFilteredData(
        fuse.search(`${query}`).map((product) => product.item)
      );
    } else {
      setFilteredData(data);
    }
  }, [
    location.search,
  ])

 return (
   <>
     {data.map((productInfo) => (
            <Row key={productInfo.id} {...productInfo} />
          ))}
   </>
 );

useDataSelector calls useSelector:

export const useDataSelector = (statusType: StatusType = "all", categoryId) =>
  useSelector(productSelector(statusType, categoryId));

and productSelector is a memoized selector that does some pretty heavy computation:

const productSelector = (
  statusType: StatusType,
  categoryId: number,
) =>
  createSelector(
    [selectProductData, selectProductStatus],
    (productData, productStatus) =>
    //some pretty heavy computations here
  )

Now the issue I am seeing is the fact that rendering the grid component is super slow. I can't really see much when recording performance except for the fact that we're spending a very long time scripting:

I can't see much when looking at the Call Tree or Event Log tabs. It seems like death by a thousand papercuts... Is this normal? It's rather disappointing how janky our scroll is.

(regarding the screenshot above: we've added LazyLoad to reduce load time when we switch the tabs or when the app is loaded). This guy sets up scroll event listener and renders more components when needed.

  <LazyLoad
        height={60}
        scrollContainer={scrollContainer}
        offset={500}
        overflow
        once
  >
    // actual component rendering
  </LazyLoad>

Body:
As explained by @Zachary Haber in the comments, you aren't getting the full benefit of createSelector because you are creating the memoized selector through a function which gets re-executed on every render.

You can actually pass arguments through your input selectors, though it's annoying because you have two arguments (and we don't want to combine them into an object without memoizing that object).

You can move the productSelector function into the useDataSelector hook and wrap it in useMemo such that it is only re-evaluated when statusType or categoryId change.

import { createSelector } from '@reduxjs/toolkit'; // or from 'reselect'
import { useMemo } from 'react';
import { useSelector } from 'react-redux';

export const useDataSelector = (statusType: StatusType = "all", categoryId: number): Product[] => {
  const productSelector = useMemo(() => {
    return createSelector(
      [selectProductData, selectProductStatus],
      (productData, productStatus): Product[] => {
        return heavyComputation(productData, productStatus, statusType, categoryId);
      }
    )
  },
    [statusType, categoryId]
  );

  return useSelector(productSelector);
}

If someone visits a categoryId then goes to another one then comes back to the first, it will re-evaluate with this approach.  Whereas something like re-reselect would keep the previously-computed selectors in its cache.

Also note that if you have multiple components using useDataSelector they will each create their own cached version of the selector.  I am assuming here that the list is the only place which accesses the data and that all child components get their data passed down via props.

Since re-reselect solves these issue, let's see how we can use it.

import { useSelector } from 'react-redux';
import { createCachedSelector } from 're-reselect';

const productSelector = createCachedSelector(
  // select from redux state
  selectProductData,
  selectProductStatus,
  // pass through arguments
  (state: RootState, statusType: StatusType) => statusType,
  (state: RootState, statusType: StatusType, categoryId: number) => categoryId,
  // combine the results
  (productData, productStatus, statusType, categoryId): Product[] => {
    return heavyComputation(productData, productStatus, statusType, categoryId);
  }
)(
  // create a unique cache key from our arguments
  (state, statusType, categoryId) => `${statusType}__${categoryId}`
)

export const useDataSelector = (statusType: StatusType = "all", categoryId: number): Product[] => {
  return useSelector((state: RootState) => productSelector(state, statusType, categoryId));
}

TypeScript Playground


问:
Python pandas - look up value in different df using 2 columns' values, then calculate difference
I want to add a column to my df to show the difference betweeb the CurrentScore and the base scores corresponding to the same Date, Sector, and Classification.  The base scores are in a separate dataframe called base_score_df with the Dates as its index.  If the base_score_df is missing that day's base scores, I want the result to be null.

The main df:

```<code>import pandas as pd
import numpy as np
df = pd.DataFrame({'Date': '2022-2-1 2022-2-1 2022-2-2 2022-2-2 2022-2-2 2022-2-3 2022-2-3 2022-2-3'.split(),
                   'Name': 'Walmart Google Walmart Microsoft Target Walmart Google Microsoft'.split(),
                   'Sector': 'Retail Tech Retail Tech Retail Retail Tech Tech'.split(),
                   'Classification': '3 4 3 5 5 4 4 4'.split(),
                   'CurrentScore': '200 197 202 188 186 193 202 201'.split()
                   })
print(df)

       Date       Name  Sector Classification CurrentScore
0  2022-2-1    Walmart  Retail              3          200
1  2022-2-1     Google    Tech              4          197
2  2022-2-2    Walmart  Retail              3          202
3  2022-2-2  Microsoft    Tech              5          188
4  2022-2-2     Target  Retail              5          186
5  2022-2-3    Walmart  Retail              4          193
6  2022-2-3     Google    Tech              4          202
7  2022-2-3  Microsoft    Tech              4          201
</code>```

The base_score_df:

```<code>base_score_df=pd.DataFrame({'Date': '2022-2-1 2022-2-3'.split(),
                   'Retail 3': '100 97'.split(),
                   'Retail 4': '102 100'.split(),
                   'Retail 5': '103 101'. split(),
                   'Tech 3': '105 107'.split(),
                   'Tech 4': '110 109'.split(),
                   'Tech 5': '112 113'.split()
                    })
base_score_df.set_index(['Date'], inplace=True)
print(base_score_df)

         Retail 3 Retail 4 Retail 5 Tech 3 Tech 4 Tech 5
Date
2022-2-1      100      102      103    105    110    112
2022-2-3       97      100      101    107    109    113
</code>```

My solution is to (1) concatenate Sector and Classification into a "Sector Classification" column, (2) use a for loop, itertuples, and apply() to look up the base scores row by row to put into a new "Base Score" column in the df, (3) calculate the difference in another column

Code for (2):

```<code>for row in df.iterruples(index=False,name='SP'):
    def base_score_lookup(row):
        scoredate=row['Date'],
        header=row['Sector Classification']
        return base_score_df.loc[scoredate,header]

base_score_df['Base Score']=df.apply(base_score_lookup,axis=1)
</code>```

The problem is, if a date is missing in the base_score_df, the code doesn't run. I just want to use a null value in that case and move on to the next row. And I wonder the code can be written differently for faster speed. Thanks in advance.

答:
Here's what you can do, explanation in the comments:</p>
```<code>import pandas as pd
import numpy as np

df = pd.DataFrame({'Date': '2022-2-1 2022-2-1 2022-2-2 2022-2-2 2022-2-2 2022-2-3 2022-2-3 2022-2-3'.split(),
                   'Name': 'Walmart Google Walmart Microsoft Target Walmart Google Microsoft'.split(),
                   'Sector': 'Retail Tech Retail Tech Retail Retail Tech Tech'.split(),
                   'Classification': '3 4 3 5 5 4 4 4'.split(),
                   'CurrentScore': '200 197 202 188 186 193 202 201'.split()
                   })

base_score_df=pd.DataFrame({'Date': '2022-2-1 2022-2-3'.split(),
                   'Retail 3': '100 97'.split(),
                   'Retail 4': '102 100'.split(),
                   'Retail 5': '103 101'. split(),
                   'Tech 3': '105 107'.split(),
                   'Tech 4': '110 109'.split(),
                   'Tech 5': '112 113'.split()
                    })

# ensure date column is in the same format
df['Date']            = pd.to_datetime(df.Date)
base_score_df['Date'] = pd.to_datetime(base_score_df.Date)

# melt the base score df into a long format
base_score_df = pd.melt(base_score_df,
                        id_vars=['Date'],
                        value_vars=[_ for _ in base_score_df.columns if _ != 'Date'])

base_score_df.columns = ['Date', 'category', 'BaseScore']

# split the category into Sector and Classification
base_score_df['Sector'], base_score_df['Classification'] = zip(*base_score_df.category.str.split(' '))
base_score_df.drop('category', axis=1, inplace=True)

# merge back with original dataframe
df = pd.merge(df,
              base_score_df,
              on=['Date', 'Sector', 'Classification'],
              how='left')

# calculate score difference
df['ScoreDiff'] = df['CurrentScore'].astype(float) - df['BaseScore'].astype(float)

# output
df

Date    Name    Sector  Classification  CurrentScore    BaseScore   ScoreDiff
0   2022-02-01  Walmart Retail  3   200 100 100.0
1   2022-02-01  Google  Tech    4   197 110 87.0
2   2022-02-02  Walmart Retail  3   202 NaN NaN
3   2022-02-02  Microsoft   Tech    5   188 NaN NaN
4   2022-02-02  Target  Retail  5   186 NaN NaN
5   2022-02-03  Walmart Retail  4   193 100 93.0
6   2022-02-03  Google  Tech    4   202 109 93.0
7   2022-02-03  Microsoft   Tech    4   201 109 92.0
</code>```

Body:
I want to add a column to my df to show the difference betweeb the CurrentScore and the base scores corresponding to the same Date, Sector, and Classification.  The base scores are in a separate dataframe called base_score_df with the Dates as its index.  If the base_score_df is missing that day's base scores, I want the result to be null.

The main df:

import pandas as pd
import numpy as np
df = pd.DataFrame({'Date': '2022-2-1 2022-2-1 2022-2-2 2022-2-2 2022-2-2 2022-2-3 2022-2-3 2022-2-3'.split(),
                   'Name': 'Walmart Google Walmart Microsoft Target Walmart Google Microsoft'.split(),
                   'Sector': 'Retail Tech Retail Tech Retail Retail Tech Tech'.split(),
                   'Classification': '3 4 3 5 5 4 4 4'.split(),
                   'CurrentScore': '200 197 202 188 186 193 202 201'.split()
                   })
print(df)

       Date       Name  Sector Classification CurrentScore
0  2022-2-1    Walmart  Retail              3          200
1  2022-2-1     Google    Tech              4          197
2  2022-2-2    Walmart  Retail              3          202
3  2022-2-2  Microsoft    Tech              5          188
4  2022-2-2     Target  Retail              5          186
5  2022-2-3    Walmart  Retail              4          193
6  2022-2-3     Google    Tech              4          202
7  2022-2-3  Microsoft    Tech              4          201

The base_score_df:

base_score_df=pd.DataFrame({'Date': '2022-2-1 2022-2-3'.split(),
                   'Retail 3': '100 97'.split(),
                   'Retail 4': '102 100'.split(),
                   'Retail 5': '103 101'. split(),
                   'Tech 3': '105 107'.split(),
                   'Tech 4': '110 109'.split(),
                   'Tech 5': '112 113'.split()
                    })
base_score_df.set_index(['Date'], inplace=True)
print(base_score_df)

         Retail 3 Retail 4 Retail 5 Tech 3 Tech 4 Tech 5
Date
2022-2-1      100      102      103    105    110    112
2022-2-3       97      100      101    107    109    113

My solution is to (1) concatenate Sector and Classification into a "Sector Classification" column, (2) use a for loop, itertuples, and apply() to look up the base scores row by row to put into a new "Base Score" column in the df, (3) calculate the difference in another column

Code for (2):

for row in df.iterruples(index=False,name='SP'):
    def base_score_lookup(row):
        scoredate=row['Date'],
        header=row['Sector Classification']
        return base_score_df.loc[scoredate,header]

base_score_df['Base Score']=df.apply(base_score_lookup,axis=1)

The problem is, if a date is missing in the base_score_df, the code doesn't run. I just want to use a null value in that case and move on to the next row. And I wonder the code can be written differently for faster speed. Thanks in advance.

Body:
Here's what you can do, explanation in the comments:

import pandas as pd
import numpy as np

df = pd.DataFrame({'Date': '2022-2-1 2022-2-1 2022-2-2 2022-2-2 2022-2-2 2022-2-3 2022-2-3 2022-2-3'.split(),
                   'Name': 'Walmart Google Walmart Microsoft Target Walmart Google Microsoft'.split(),
                   'Sector': 'Retail Tech Retail Tech Retail Retail Tech Tech'.split(),
                   'Classification': '3 4 3 5 5 4 4 4'.split(),
                   'CurrentScore': '200 197 202 188 186 193 202 201'.split()
                   })

base_score_df=pd.DataFrame({'Date': '2022-2-1 2022-2-3'.split(),
                   'Retail 3': '100 97'.split(),
                   'Retail 4': '102 100'.split(),
                   'Retail 5': '103 101'. split(),
                   'Tech 3': '105 107'.split(),
                   'Tech 4': '110 109'.split(),
                   'Tech 5': '112 113'.split()
                    })

# ensure date column is in the same format
df['Date']            = pd.to_datetime(df.Date)
base_score_df['Date'] = pd.to_datetime(base_score_df.Date)

# melt the base score df into a long format
base_score_df = pd.melt(base_score_df,
                        id_vars=['Date'],
                        value_vars=[_ for _ in base_score_df.columns if _ != 'Date'])

base_score_df.columns = ['Date', 'category', 'BaseScore']

# split the category into Sector and Classification
base_score_df['Sector'], base_score_df['Classification'] = zip(*base_score_df.category.str.split(' '))
base_score_df.drop('category', axis=1, inplace=True)

# merge back with original dataframe
df = pd.merge(df,
              base_score_df,
              on=['Date', 'Sector', 'Classification'],
              how='left')

# calculate score difference
df['ScoreDiff'] = df['CurrentScore'].astype(float) - df['BaseScore'].astype(float)

# output
df

Date    Name    Sector  Classification  CurrentScore    BaseScore   ScoreDiff
0   2022-02-01  Walmart Retail  3   200 100 100.0
1   2022-02-01  Google  Tech    4   197 110 87.0
2   2022-02-02  Walmart Retail  3   202 NaN NaN
3   2022-02-02  Microsoft   Tech    5   188 NaN NaN
4   2022-02-02  Target  Retail  5   186 NaN NaN
5   2022-02-03  Walmart Retail  4   193 100 93.0
6   2022-02-03  Google  Tech    4   202 109 93.0
7   2022-02-03  Microsoft   Tech    4   201 109 92.0


问:
words in a list - words in another list
Im new to coding and am looking for some help.

I need to remove words of a small list from a large list.

```<code>clean_book = [word for word in bwords_split if word in words_list]
</code>```

I used the line above where bwords_split is the larger list and words_list is the smaller list and clean_book is the result. I think I'm thinking to arthemetically. Could someone help me?

答: Your solution looks fine.  Just change the second "in" to "not in"</p>

Title: words in a list - words in another list

Body:
Im new to coding and am looking for some help.

I need to remove words of a small list from a large list.

clean_book = [word for word in bwords_split if word in words_list]

I used the line above where bwords_split is the larger list and words_list is the smaller list and clean_book is the result. I think I'm thinking to arthemetically. Could someone help me?


问:
Could not detect language for functions at functions
After firebase deploy in flutter web I get this error:

In this answer person recommends firebase init, but I already have Firebase in the app.
Thanks for any ideas!

答:
I came across this issue with a custom build process and pointing only to my dist folder.

There are three requirements for a successful build:

a firebase.json with functions.source pointing to a directory containing a package.json

The package.json containing a "main":"path-to-index.js" field.

A node engine specified in either the package.json or firebase.json

//firebase.json
{
  "functions": {
    "source": "./some-dir"
  }
}
//some-dir/package.json
{
  "main": "lib/index.js",
  "engines": {
    "node": "16"
  }
}
```


问:
command to compile typescript in react-native?
I went through this tutorial

https://reactnative.dev/docs/typescript

However, I am using npm and the only command to compile typescript I see in that page is "yarn tsc"

I found another blog that said "npm start" does this but when I add this one line to my typescript, it still compiles and should not since I do not declare a variable something, nor a variable called blah ->

something = blah;

What command should I run to compile/type-check?  I am looking for it to fail because of the above line.

答:
I think the TS compilation (transcompilation or transpiling to JS) happens when the JS bundle is generated when you run npm start or when you release your app.

If you just want to check types, syntax and lint you might want to run:

eslint . --ext .js,.jsx,.ts,.tsx

You can also do tsc only, and this will check typescript according to your tsconfig.json file. Please note you need to have typescript installed globally with npm install -g typescript


问:
sibling selector with :before doesn't work in styled-component?
How to use this

```<code>li+li:before {
  padding: 8px;
  color: black;
  content: "/\00a0";
}
</code>```

in styled-component? I tried to convert this https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_breadcrumbs

to styled-component but it's not working.

https://codesandbox.io/s/recursing-pasteur-mkmyh?file=/src/App.js

答:
The content of the content seems to be the culprit. The rest of the code is fine.

Instead of /\00a0 it should be /\\00a0. It seems to be a styled-components specific issue.

Here's a short quote as an explanation, the source has more in depth discussion.

Basically because you write CSS in JS you have to escape twice - once for JS parser and once for CSS one.

Source/GitHub

Full working code:

```<code>import styled from "styled-components";

export default function Namaste() {
  return (
    <UL>
      <li>
        <a href="/#">Home</a>
      </li>
      <li>
        <a href="/#">Pictures</a>
      </li>
      <li>
        <a href="/#">Summer 15</a>
      </li>
      <li>Italy</li>
    </UL>
  );
}

const UL = styled.ul`
  padding: 10px 16px;
  list-style: none;
  background-color: #eee;

  li {
    display: inline;
    font-size: 18px;
    color: red;
  }
  li + li:before {
    padding: 8px;
    color: black;
    content: "/\\00a0";
  }
  li a {
    color: #0275d8;
    text-decoration: none;
  }
`;

</code>```

Body:
How to use this

li+li:before {
  padding: 8px;
  color: black;
  content: "/\00a0";
}

in styled-component? I tried to convert this https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_breadcrumbs

to styled-component but it's not working.

https://codesandbox.io/s/recursing-pasteur-mkmyh?file=/src/App.js

Body:
The content of the content seems to be the culprit. The rest of the code is fine.

Instead of /\00a0 it should be /\\00a0. It seems to be a styled-components specific issue.

Here's a short quote as an explanation, the source has more in depth discussion.

Basically because you write CSS in JS you have to escape twice - once for JS parser and once for CSS one.

Source/GitHub

Full working code:

import styled from "styled-components";

export default function Namaste() {
  return (
    <UL>
      <li>
        <a href="/#">Home</a>
      </li>
      <li>
        <a href="/#">Pictures</a>
      </li>
      <li>
        <a href="/#">Summer 15</a>
      </li>
      <li>Italy</li>
    </UL>
  );
}

const UL = styled.ul`
  padding: 10px 16px;
  list-style: none;
  background-color: #eee;

  li {
    display: inline;
    font-size: 18px;
    color: red;
  }
  li + li:before {
    padding: 8px;
    color: black;
    content: "/\\00a0";
  }
  li a {
    color: #0275d8;
    text-decoration: none;
  }
`;


问:
Search and Add Row on BigQuery
on BigQuery, I am searching for a Query that will allow me to search for a specific value, and add it with a row to my table if it does not exist. Is there a possible way to do this? I currently do know how to search for a value, but if the value does not exist, I'm wondering if there is a Query that will create a new row with the value if it is not there. Any help would be appreciated.. Thanks!</p>

答:
Hope below example will help you!</p>
```<code>merge your_table a
using (
  with check_list as (
  select value
  from unnest([1, 3, 5, 7]) value
  )
  select value from check_list
) b
on a.value = b.value
when not matched then
  insert(value)
  values(value);
</code>```

Title: Search and Add Row on BigQuery

Body:
Hope below example will help you!

merge your_table a
using (
  with check_list as (
  select value
  from unnest([1, 3, 5, 7]) value
  )
  select value from check_list
) b
on a.value = b.value
when not matched then
  insert(value)
  values(value);


问:
paperclip working in development but not working in production?
I'm pretty new to rails and seem to be having an issue with the paperclip gem. I installed the gem and it works well in development (localhost:3000) but when I'm running it on the heroku server, for some reason it does not want to attach files, and the app breaks (error 500 page).

Here is the process i ran... I pushed my file to heroku, heroku ran rake db:migrate (to add paperclip migrations), and then I ran heroku restart (to restart the app with new migrations). This did not seem to help.

Here is the code that I have for paperclip:

user.rb model:

```<code>  has_attached_file :avatar,
                    :styles => {:small => "70x70>"},
                    :url  => "/users/:attachment/:id/:style/:basename.:extension",
                    :path => ":rails_root/public/users/:attachment/:id/:style/:basename.:extension"
  validates_attachment_size :avatar, :less_than => 500.kilobytes
  validates_attachment_content_type :avatar, :content_type => ['image/jpeg', 'image/png']
</code>```

edit_form.html.haml view:

```<code>  = form_for (@user || User.new), :html => { :multipart => true } do |f|
  ...
  .profile_picture.text_field
    = image_tag current_profile.avatar.url(:small)
    %br
    = f.file_field :avatar
</code>```

Again, for some reason it runs great in development, but breaks down in production. Any pointers would be greatly appreciated... I just cant seem to figure this out and it's pretty frustrating. Thank you so much for your time and any help!

答:
In your model.

```<code>has_attached_file :picture,
                   :styles => {:large => "275x450>"},
                   :storage => :s3,
                   :s3_credentials => "#{RAILS_ROOT}/config/s3.yml",
                   :path => "appname/:attachment/:style/:id.:extension"
</code>```

In s3.yml in your config dir:

```<code>    development:
      bucket: bucketname
      access_key_id: key
      secret_access_key: key

    production:
      bucket: bucketname
      access_key_id: key
      secret_access_key: key
</code>```

Then go signup for a bucket at Amazon S3: http://aws.amazon.com/s3/

Body:
I'm pretty new to rails and seem to be having an issue with the paperclip gem. I installed the gem and it works well in development (localhost:3000) but when I'm running it on the heroku server, for some reason it does not want to attach files, and the app breaks (error 500 page).

Here is the process i ran... I pushed my file to heroku, heroku ran rake db:migrate (to add paperclip migrations), and then I ran heroku restart (to restart the app with new migrations). This did not seem to help.

Here is the code that I have for paperclip:

user.rb model:

  has_attached_file :avatar,
                    :styles => {:small => "70x70>"},
                    :url  => "/users/:attachment/:id/:style/:basename.:extension",
                    :path => ":rails_root/public/users/:attachment/:id/:style/:basename.:extension"
  validates_attachment_size :avatar, :less_than => 500.kilobytes
  validates_attachment_content_type :avatar, :content_type => ['image/jpeg', 'image/png']

edit_form.html.haml view:

  = form_for (@user || User.new), :html => { :multipart => true } do |f|
  ...
  .profile_picture.text_field
    = image_tag current_profile.avatar.url(:small)
    %br
    = f.file_field :avatar

Again, for some reason it runs great in development, but breaks down in production. Any pointers would be greatly appreciated... I just cant seem to figure this out and it's pretty frustrating. Thank you so much for your time and any help!

Body:
In your model.

has_attached_file :picture,
                   :styles => {:large => "275x450>"},
                   :storage => :s3,
                   :s3_credentials => "#{RAILS_ROOT}/config/s3.yml",
                   :path => "appname/:attachment/:style/:id.:extension"

In s3.yml in your config dir:

    development:
      bucket: bucketname
      access_key_id: key
      secret_access_key: key

    production:
      bucket: bucketname
      access_key_id: key
      secret_access_key: key

Then go signup for a bucket at Amazon S3: http://aws.amazon.com/s3/