问:
multiplication of polynomial in C using list
I'm using lists to implement the multiplication of polynomials.
My code is:

```<code>typedef struct node *node_ptr;
typedef struct node
{
    unsigned int power;
    int coeff;
    node_ptr next;
}POLY;
typedef node_ptr polynomial;

void mult_polynomial(polynomial poly1, polynomial poly2, polynomial poly_mult)
{
    assert(!is_null(poly1) && !is_null(poly2) && is_null(poly_mult));
    node_ptr p1 = poly1->next;
    node_ptr p2;
    node_ptr p3;
    node_ptr tmp, cell;

    while (p1) {
        p2 = poly2->next;
        while (p2) {
            p3 = poly_mult;
            cell = p3->next;
            tmp = (node_ptr)malloc(sizeof(struct node));
            tmp->power = p1->power + p2->power;
            tmp->coeff = p1->coeff * p2->coeff;
            tmp->next = NULL;
            if (!cell)
                p3->next = tmp;
            else {
                if (cell->power == tmp->power) {
                    cell->coeff += tmp->coeff;
                    free(tmp);
                } else if (cell->power < tmp->power) {
                    p3->next = tmp;
                    tmp->next = cell;
                } else if (cell->power > tmp->power) {
                    while (cell->power > tmp->power) {
                        if(!cell->next || cell->next->power < tmp->power) {
                            cell->next = tmp;
                            break;
                        } else if (cell->next->power == tmp->power) {
                            cell->next->coeff += tmp->coeff;
                            break;
                        }
                        p3 = cell;
                        cell = p3->next;
                    }
                }
            }
            p2 = p2->next;
        }
        p1 = p1->next;
    }
}
</code>```

But it seems too redundant; how to simplify it?

答:
Here's my take on a solution.  It is basically a complete rewrite — though the structure used is only renamed but structurally equivalent to what you had.

The function add_term() turns out to be crucial — it is a variant of part of what you had in mult_polynomial(), but it also lends itself to use in add_polynomial() and sub_polynomial() — one factor which indicates that it is a useful abstraction.  Note that mult_polynomial() itself is very simple and compact as a result — and neither add_polynomial() nor sub_polynomial() is any more complex.

I'm not completely happy with the code in add_term() (there are too many special cases), but I believe it does its job reasonably well.   You can end up with a polynomial with many terms that have 0 as the coefficient; the code does not remove such terms, though it could (should) be upgraded to do so.  The printing code accordingly has to skip such terms — and has a special case to deal with all terms zero (it prints 0, of course).

Also, the design of mult_polynomial() in the question is inadequate.  If you have void mult_polynomial(polynomial *p1, polynomial *p2, polynomial *p3), you can't get the new data in p3 out of the function.  The options are to use polynomial **p3 or to return the new polynomial — this code returns the new value.

And, as already mentioned in the comments, it is generally best not to used typedef for data pointers (function pointers are a different matter).  You can find out more at Is it a good idea to typedef pointers.  I ended up with one structure for polynomials, which is the same as the structure for a term in a polynomial.  (The test code uses a pair of structures, a term and a termlist, to describe polynomials for testing purposes.  They make life easier.  There's a modest amount of test code.  The add_polynomial() and sub_polynomial() functions were completed inside 10 minutes, including fixing up the printing for 0 polynomials, which is a testament to the usefulness of the add_term() function.

The print_polynomial() function is important and useful.  It also has to deal with some fiddly special cases (negative coefficients, first coefficient negative, zero coefficients, power of one, and power of zero).  It should arguably be generalized to allow the variable name to be specified; it is hard-coded as x.  There might be some simpler functions trying to escape — one possibility is a print_term() function that could be used elsewhere as well as being called in print_polynomial().  There'd be tricky communication to handle the fiddly special cases, of course.

An FYI: I define all functions (other than main()) as static unless there's a second source file that references them and a header file that declares them.  Clearly, some of these functions would become publicly accessible if the code was to be reused and would then be made extern (non-static) and declared in a header.  The details of the type would not be in the header; the typedef struct polynomial polynomial; would be there, but that's all that would be needed.  The definition would be hidden in the implementation file.  This would be an opaque type.  Some functions such as add_term() and make_term() would remain as static functions.

The code uses C99 designated initializers and compound literals.  It could be written using C89/C90 code, but it would be harder and/or messier.  Not necessarily very much harder, but…

Without further ado, here's the code (it's quite long):

```<code>/* SO 4313-7847 */
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include "emalloc.h"

typedef struct polynomial polynomial;

struct polynomial
{
    unsigned int power;
    int          coeff;
    polynomial  *next;
};

static void print_polynomial(const char *tag, const polynomial *poly);

static polynomial *make_term(unsigned int power, int coeff, polynomial *next)
{
    polynomial *new_term = MALLOC(sizeof(*new_term));
    new_term->power = power;
    new_term->coeff = coeff;
    new_term->next  = next;
    return new_term;
}

static polynomial *add_term(polynomial *poly, unsigned int power, int coeff)
{
    if (coeff == 0)
        return poly;
    if (poly == NULL)
        return make_term(power, coeff, NULL);

    /* Find where this term goes */
    polynomial *term = poly;
    polynomial *prev = NULL;
    while (term != NULL && term->power > power)
    {
        prev = term;
        term = term->next;
    }

    if (term != NULL && term->power == power)
    {
        term->coeff += coeff;
        /* Eliminate zero terms here */
    }
    else
    {
        assert(term == NULL || term->power < power);
        polynomial *new_term = make_term(power, coeff, term);
        if (prev == NULL)
            poly = new_term;
        else
            prev->next = new_term;
    }
    return poly;
}

static polynomial *mult_polynomial(polynomial *poly1, polynomial *poly2)
{
    assert(poly1 != NULL && poly2 != NULL);
    polynomial *result = NULL;

    for (polynomial *p1 = poly1; p1 != NULL; p1 = p1->next)
    {
        for (polynomial *p2 = poly2; p2 != NULL; p2 = p2->next)
            result = add_term(result, p1->power + p2->power, p1->coeff * p2->coeff);
    }
    return result;
}

static polynomial *add_polynomial(polynomial *poly1, polynomial *poly2)
{
    assert(poly1 != NULL && poly2 != NULL);
    polynomial *result = NULL;

    for (polynomial *p1 = poly1; p1 != NULL; p1 = p1->next)
        result = add_term(result, p1->power, p1->coeff);
    for (polynomial *p2 = poly2; p2 != NULL; p2 = p2->next)
        result = add_term(result, p2->power, p2->coeff);
    return result;
}

static polynomial *sub_polynomial(polynomial *poly1, polynomial *poly2)
{
    assert(poly1 != NULL && poly2 != NULL);
    polynomial *result = NULL;

    for (polynomial *p1 = poly1; p1 != NULL; p1 = p1->next)
        result = add_term(result, p1->power, p1->coeff);
    for (polynomial *p2 = poly2; p2 != NULL; p2 = p2->next)
        result = add_term(result, p2->power, -p2->coeff);
    return result;
}

static void print_polynomial(const char *tag, const polynomial *poly)
{
    int printed = 0;
    printf("%s:", tag);
    char sign = ' ';
    while (poly != NULL)
    {
        int coeff = poly->coeff;
        if (coeff != 0)
        {
            if (sign != ' ' && coeff < 0)
            {
                sign = '-';
                coeff = -coeff;
            }
            if (poly->power == 0)
                printf(" %c %d", sign, coeff);
            else if (poly->power == 1)
                printf(" %c %dx", sign, coeff);
            else
                printf(" %c %dx^%u", sign, coeff, poly->power);
            printed++;
        }
        poly = poly->next;
        sign = '+';
    }
    if (printed == 0)
        printf("   0");
    putchar('\n');
    fflush(stdout);
}

static void free_polynomial(polynomial *poly)
{
    while (poly != NULL)
    {
        polynomial *next = poly->next;
        free(poly);
        poly = next;
    }
}

typedef struct term
{
    unsigned int power;
    int coeff;
} term;

typedef struct termlist
{
    int n_terms;
    term *terms;
} termlist;

static polynomial *make_polynomial(termlist *terms)
{
    polynomial *poly = 0;
    for (int i = 0; i < terms->n_terms; i++)
    {
        printf("Term: %dx^%u\n", terms->terms[i].coeff, terms->terms[i].power);
        fflush(stdout);
        poly = add_term(poly, terms->terms[i].power, terms->terms[i].coeff);
    }
    return poly;
}

int main(void)
{
    termlist p1[] =
    {
        { .n_terms = 4, .terms = (term[]){ { 3, 2 }, { 2,  1 }, { 1,  4 }, { 0, -9 } } },
        { .n_terms = 3, .terms = (term[]){ { 2, 3 }, { 1, -4 }, { 0,  8 } } },
        { .n_terms = 3, .terms = (term[]){ { 1, 5 }, { 0,  3 }, { 2, -4 } } },
        { .n_terms = 2, .terms = (term[]){ { 4, 5 }, { 0, -5 } } },
        { .n_terms = 4, .terms = (term[]){ { 3, 2 }, { 2,  1 }, { 1,  4 }, { 2, -9 } } },
    };
    enum { NUM_POLYS = sizeof(p1) / sizeof(p1[0]) };
    polynomial *poly[NUM_POLYS] = { 0 };

    for (int i = 0; i < NUM_POLYS; i++)
    {
        poly[i] = make_polynomial(&p1[i]);
        print_polynomial("Building", poly[i]);
    }

    printf("Checking:\n");
    for (int i = 0; i < NUM_POLYS; i++)
        print_polynomial("Next", poly[i]);
    putchar('\n');

    printf("Multiplying polynomials:\n");
    for (int i = 0; i < NUM_POLYS; i++)
    {
        for (int j = 0; j < NUM_POLYS; j++)
        {
            print_polynomial("Term 1", poly[i]);
            print_polynomial("Term 2", poly[j]);
            polynomial *prod = mult_polynomial(poly[i], poly[j]);
            print_polynomial("Product", prod);
            free_polynomial(prod);
        }
        putchar('\n');
    }

    printf("Adding polynomials:\n");
    for (int i = 0; i < NUM_POLYS; i++)
    {
        for (int j = 0; j < NUM_POLYS; j++)
        {
            print_polynomial("Term 1", poly[i]);
            print_polynomial("Term 2", poly[j]);
            polynomial *sum = add_polynomial(poly[i], poly[j]);
            print_polynomial("Sum", sum);
            free_polynomial(sum);
        }
        putchar('\n');
    }

    printf("Subtracting polynomials:\n");
    for (int i = 0; i < NUM_POLYS; i++)
    {
        for (int j = 0; j < NUM_POLYS; j++)
        {
            print_polynomial("Term 1", poly[i]);
            print_polynomial("Term 2", poly[j]);
            polynomial *diff = sub_polynomial(poly[i], poly[j]);
            print_polynomial("Difference", diff);
            free_polynomial(diff);
        }
        putchar('\n');
    }

    for (int i = 0; i < NUM_POLYS; i++)
        free_polynomial(poly[i]);

    return 0;
}
</code>```

And the output, broken into three sections so you can see the start of the multiplication, addition and subtraction sections of the tests:

```<code>Term: 2x^3
Term: 1x^2
Term: 4x^1
Term: -9x^0
Building:   2x^3 + 1x^2 + 4x - 9
Term: 3x^2
Term: -4x^1
Term: 8x^0
Building:   3x^2 - 4x + 8
Term: 5x^1
Term: 3x^0
Term: -4x^2
Building:   -4x^2 + 5x + 3
Term: 5x^4
Term: -5x^0
Building:   5x^4 - 5
Term: 2x^3
Term: 1x^2
Term: 4x^1
Term: -9x^2
Building:   2x^3 - 8x^2 + 4x
Checking:
Next:   2x^3 + 1x^2 + 4x - 9
Next:   3x^2 - 4x + 8
Next:   -4x^2 + 5x + 3
Next:   5x^4 - 5
Next:   2x^3 - 8x^2 + 4x
</code>```

Multiplication:

```<code>Multiplying polynomials:
Term 1:   2x^3 + 1x^2 + 4x - 9
Term 2:   2x^3 + 1x^2 + 4x - 9
Product:   4x^6 + 4x^5 + 17x^4 - 28x^3 - 2x^2 - 72x + 81
Term 1:   2x^3 + 1x^2 + 4x - 9
Term 2:   3x^2 - 4x + 8
Product:   6x^5 - 5x^4 + 24x^3 - 35x^2 + 68x - 72
Term 1:   2x^3 + 1x^2 + 4x - 9
Term 2:   -4x^2 + 5x + 3
Product:   -8x^5 + 6x^4 - 5x^3 + 59x^2 - 33x - 27
Term 1:   2x^3 + 1x^2 + 4x - 9
Term 2:   5x^4 - 5
Product:   10x^7 + 5x^6 + 20x^5 - 45x^4 - 10x^3 - 5x^2 - 20x + 45
Term 1:   2x^3 + 1x^2 + 4x - 9
Term 2:   2x^3 - 8x^2 + 4x
Product:   4x^6 - 14x^5 + 8x^4 - 46x^3 + 88x^2 - 36x

Term 1:   3x^2 - 4x + 8
Term 2:   2x^3 + 1x^2 + 4x - 9
Product:   6x^5 - 5x^4 + 24x^3 - 35x^2 + 68x - 72
Term 1:   3x^2 - 4x + 8
Term 2:   3x^2 - 4x + 8
Product:   9x^4 - 24x^3 + 64x^2 - 64x + 64
Term 1:   3x^2 - 4x + 8
Term 2:   -4x^2 + 5x + 3
Product:   -12x^4 + 31x^3 - 43x^2 + 28x + 24
Term 1:   3x^2 - 4x + 8
Term 2:   5x^4 - 5
Product:   15x^6 - 20x^5 + 40x^4 - 15x^2 + 20x - 40
Term 1:   3x^2 - 4x + 8
Term 2:   2x^3 - 8x^2 + 4x
Product:   6x^5 - 32x^4 + 60x^3 - 80x^2 + 32x

Term 1:   -4x^2 + 5x + 3
Term 2:   2x^3 + 1x^2 + 4x - 9
Product:   -8x^5 + 6x^4 - 5x^3 + 59x^2 - 33x - 27
Term 1:   -4x^2 + 5x + 3
Term 2:   3x^2 - 4x + 8
Product:   -12x^4 + 31x^3 - 43x^2 + 28x + 24
Term 1:   -4x^2 + 5x + 3
Term 2:   -4x^2 + 5x + 3
Product:   16x^4 - 40x^3 + 1x^2 + 30x + 9
Term 1:   -4x^2 + 5x + 3
Term 2:   5x^4 - 5
Product:   -20x^6 + 25x^5 + 15x^4 + 20x^2 - 25x - 15
Term 1:   -4x^2 + 5x + 3
Term 2:   2x^3 - 8x^2 + 4x
Product:   -8x^5 + 42x^4 - 50x^3 - 4x^2 + 12x

Term 1:   5x^4 - 5
Term 2:   2x^3 + 1x^2 + 4x - 9
Product:   10x^7 + 5x^6 + 20x^5 - 45x^4 - 10x^3 - 5x^2 - 20x + 45
Term 1:   5x^4 - 5
Term 2:   3x^2 - 4x + 8
Product:   15x^6 - 20x^5 + 40x^4 - 15x^2 + 20x - 40
Term 1:   5x^4 - 5
Term 2:   -4x^2 + 5x + 3
Product:   -20x^6 + 25x^5 + 15x^4 + 20x^2 - 25x - 15
Term 1:   5x^4 - 5
Term 2:   5x^4 - 5
Product:   25x^8 - 50x^4 + 25
Term 1:   5x^4 - 5
Term 2:   2x^3 - 8x^2 + 4x
Product:   10x^7 - 40x^6 + 20x^5 - 10x^3 + 40x^2 - 20x

Term 1:   2x^3 - 8x^2 + 4x
Term 2:   2x^3 + 1x^2 + 4x - 9
Product:   4x^6 - 14x^5 + 8x^4 - 46x^3 + 88x^2 - 36x
Term 1:   2x^3 - 8x^2 + 4x
Term 2:   3x^2 - 4x + 8
Product:   6x^5 - 32x^4 + 60x^3 - 80x^2 + 32x
Term 1:   2x^3 - 8x^2 + 4x
Term 2:   -4x^2 + 5x + 3
Product:   -8x^5 + 42x^4 - 50x^3 - 4x^2 + 12x
Term 1:   2x^3 - 8x^2 + 4x
Term 2:   5x^4 - 5
Product:   10x^7 - 40x^6 + 20x^5 - 10x^3 + 40x^2 - 20x
Term 1:   2x^3 - 8x^2 + 4x
Term 2:   2x^3 - 8x^2 + 4x
Product:   4x^6 - 32x^5 + 80x^4 - 64x^3 + 16x^2
</code>```

Addition:

```<code>Adding polynomials:
Term 1:   2x^3 + 1x^2 + 4x - 9
Term 2:   2x^3 + 1x^2 + 4x - 9
Sum:   4x^3 + 2x^2 + 8x - 18
Term 1:   2x^3 + 1x^2 + 4x - 9
Term 2:   3x^2 - 4x + 8
Sum:   2x^3 + 4x^2 - 1
Term 1:   2x^3 + 1x^2 + 4x - 9
Term 2:   -4x^2 + 5x + 3
Sum:   2x^3 - 3x^2 + 9x - 6
Term 1:   2x^3 + 1x^2 + 4x - 9
Term 2:   5x^4 - 5
Sum:   5x^4 + 2x^3 + 1x^2 + 4x - 14
Term 1:   2x^3 + 1x^2 + 4x - 9
Term 2:   2x^3 - 8x^2 + 4x
Sum:   4x^3 - 7x^2 + 8x - 9

Term 1:   3x^2 - 4x + 8
Term 2:   2x^3 + 1x^2 + 4x - 9
Sum:   2x^3 + 4x^2 - 1
Term 1:   3x^2 - 4x + 8
Term 2:   3x^2 - 4x + 8
Sum:   6x^2 - 8x + 16
Term 1:   3x^2 - 4x + 8
Term 2:   -4x^2 + 5x + 3
Sum:   -1x^2 + 1x + 11
Term 1:   3x^2 - 4x + 8
Term 2:   5x^4 - 5
Sum:   5x^4 + 3x^2 - 4x + 3
Term 1:   3x^2 - 4x + 8
Term 2:   2x^3 - 8x^2 + 4x
Sum:   2x^3 - 5x^2 + 8

Term 1:   -4x^2 + 5x + 3
Term 2:   2x^3 + 1x^2 + 4x - 9
Sum:   2x^3 - 3x^2 + 9x - 6
Term 1:   -4x^2 + 5x + 3
Term 2:   3x^2 - 4x + 8
Sum:   -1x^2 + 1x + 11
Term 1:   -4x^2 + 5x + 3
Term 2:   -4x^2 + 5x + 3
Sum:   -8x^2 + 10x + 6
Term 1:   -4x^2 + 5x + 3
Term 2:   5x^4 - 5
Sum:   5x^4 - 4x^2 + 5x - 2
Term 1:   -4x^2 + 5x + 3
Term 2:   2x^3 - 8x^2 + 4x
Sum:   2x^3 - 12x^2 + 9x + 3

Term 1:   5x^4 - 5
Term 2:   2x^3 + 1x^2 + 4x - 9
Sum:   5x^4 + 2x^3 + 1x^2 + 4x - 14
Term 1:   5x^4 - 5
Term 2:   3x^2 - 4x + 8
Sum:   5x^4 + 3x^2 - 4x + 3
Term 1:   5x^4 - 5
Term 2:   -4x^2 + 5x + 3
Sum:   5x^4 - 4x^2 + 5x - 2
Term 1:   5x^4 - 5
Term 2:   5x^4 - 5
Sum:   10x^4 - 10
Term 1:   5x^4 - 5
Term 2:   2x^3 - 8x^2 + 4x
Sum:   5x^4 + 2x^3 - 8x^2 + 4x - 5

Term 1:   2x^3 - 8x^2 + 4x
Term 2:   2x^3 + 1x^2 + 4x - 9
Sum:   4x^3 - 7x^2 + 8x - 9
Term 1:   2x^3 - 8x^2 + 4x
Term 2:   3x^2 - 4x + 8
Sum:   2x^3 - 5x^2 + 8
Term 1:   2x^3 - 8x^2 + 4x
Term 2:   -4x^2 + 5x + 3
Sum:   2x^3 - 12x^2 + 9x + 3
Term 1:   2x^3 - 8x^2 + 4x
Term 2:   5x^4 - 5
Sum:   5x^4 + 2x^3 - 8x^2 + 4x - 5
Term 1:   2x^3 - 8x^2 + 4x
Term 2:   2x^3 - 8x^2 + 4x
Sum:   4x^3 - 16x^2 + 8x
</code>```

Subtraction:

```<code>Subtracting polynomials:
Term 1:   2x^3 + 1x^2 + 4x - 9
Term 2:   2x^3 + 1x^2 + 4x - 9
Difference:   0
Term 1:   2x^3 + 1x^2 + 4x - 9
Term 2:   3x^2 - 4x + 8
Difference:   2x^3 - 2x^2 + 8x - 17
Term 1:   2x^3 + 1x^2 + 4x - 9
Term 2:   -4x^2 + 5x + 3
Difference:   2x^3 + 5x^2 - 1x - 12
Term 1:   2x^3 + 1x^2 + 4x - 9
Term 2:   5x^4 - 5
Difference:   -5x^4 + 2x^3 + 1x^2 + 4x - 4
Term 1:   2x^3 + 1x^2 + 4x - 9
Term 2:   2x^3 - 8x^2 + 4x
Difference: + 9x^2 - 9

Term 1:   3x^2 - 4x + 8
Term 2:   2x^3 + 1x^2 + 4x - 9
Difference:   -2x^3 + 2x^2 - 8x + 17
Term 1:   3x^2 - 4x + 8
Term 2:   3x^2 - 4x + 8
Difference:   0
Term 1:   3x^2 - 4x + 8
Term 2:   -4x^2 + 5x + 3
Difference:   7x^2 - 9x + 5
Term 1:   3x^2 - 4x + 8
Term 2:   5x^4 - 5
Difference:   -5x^4 + 3x^2 - 4x + 13
Term 1:   3x^2 - 4x + 8
Term 2:   2x^3 - 8x^2 + 4x
Difference:   -2x^3 + 11x^2 - 8x + 8

Term 1:   -4x^2 + 5x + 3
Term 2:   2x^3 + 1x^2 + 4x - 9
Difference:   -2x^3 - 5x^2 + 1x + 12
Term 1:   -4x^2 + 5x + 3
Term 2:   3x^2 - 4x + 8
Difference:   -7x^2 + 9x - 5
Term 1:   -4x^2 + 5x + 3
Term 2:   -4x^2 + 5x + 3
Difference:   0
Term 1:   -4x^2 + 5x + 3
Term 2:   5x^4 - 5
Difference:   -5x^4 - 4x^2 + 5x + 8
Term 1:   -4x^2 + 5x + 3
Term 2:   2x^3 - 8x^2 + 4x
Difference:   -2x^3 + 4x^2 + 1x + 3

Term 1:   5x^4 - 5
Term 2:   2x^3 + 1x^2 + 4x - 9
Difference:   5x^4 - 2x^3 - 1x^2 - 4x + 4
Term 1:   5x^4 - 5
Term 2:   3x^2 - 4x + 8
Difference:   5x^4 - 3x^2 + 4x - 13
Term 1:   5x^4 - 5
Term 2:   -4x^2 + 5x + 3
Difference:   5x^4 + 4x^2 - 5x - 8
Term 1:   5x^4 - 5
Term 2:   5x^4 - 5
Difference:   0
Term 1:   5x^4 - 5
Term 2:   2x^3 - 8x^2 + 4x
Difference:   5x^4 - 2x^3 + 8x^2 - 4x - 5

Term 1:   2x^3 - 8x^2 + 4x
Term 2:   2x^3 + 1x^2 + 4x - 9
Difference: - 9x^2 + 9
Term 1:   2x^3 - 8x^2 + 4x
Term 2:   3x^2 - 4x + 8
Difference:   2x^3 - 11x^2 + 8x - 8
Term 1:   2x^3 - 8x^2 + 4x
Term 2:   -4x^2 + 5x + 3
Difference:   2x^3 - 4x^2 - 1x - 3
Term 1:   2x^3 - 8x^2 + 4x
Term 2:   5x^4 - 5
Difference:   -5x^4 + 2x^3 - 8x^2 + 4x + 5
Term 1:   2x^3 - 8x^2 + 4x
Term 2:   2x^3 - 8x^2 + 4x
Difference:   0
</code>```

Body:
I'm using lists to implement the multiplication of polynomials.
My code is:

typedef struct node *node_ptr;
typedef struct node
{
    unsigned int power;
    int coeff;
    node_ptr next;
}POLY;
typedef node_ptr polynomial;

void mult_polynomial(polynomial poly1, polynomial poly2, polynomial poly_mult)
{
    assert(!is_null(poly1) && !is_null(poly2) && is_null(poly_mult));
    node_ptr p1 = poly1->next;
    node_ptr p2;
    node_ptr p3;
    node_ptr tmp, cell;

    while (p1) {
        p2 = poly2->next;
        while (p2) {
            p3 = poly_mult;
            cell = p3->next;
            tmp = (node_ptr)malloc(sizeof(struct node));
            tmp->power = p1->power + p2->power;
            tmp->coeff = p1->coeff * p2->coeff;
            tmp->next = NULL;
            if (!cell)
                p3->next = tmp;
            else {
                if (cell->power == tmp->power) {
                    cell->coeff += tmp->coeff;
                    free(tmp);
                } else if (cell->power < tmp->power) {
                    p3->next = tmp;
                    tmp->next = cell;
                } else if (cell->power > tmp->power) {
                    while (cell->power > tmp->power) {
                        if(!cell->next || cell->next->power < tmp->power) {
                            cell->next = tmp;
                            break;
                        } else if (cell->next->power == tmp->power) {
                            cell->next->coeff += tmp->coeff;
                            break;
                        }
                        p3 = cell;
                        cell = p3->next;
                    }
                }
            }
            p2 = p2->next;
        }
        p1 = p1->next;
    }
}

But it seems too redundant; how to simplify it?

Body:
Here's my take on a solution.  It is basically a complete rewrite — though the structure used is only renamed but structurally equivalent to what you had.

The function add_term() turns out to be crucial — it is a variant of part of what you had in mult_polynomial(), but it also lends itself to use in add_polynomial() and sub_polynomial() — one factor which indicates that it is a useful abstraction.  Note that mult_polynomial() itself is very simple and compact as a result — and neither add_polynomial() nor sub_polynomial() is any more complex.

I'm not completely happy with the code in add_term() (there are too many special cases), but I believe it does its job reasonably well.   You can end up with a polynomial with many terms that have 0 as the coefficient; the code does not remove such terms, though it could (should) be upgraded to do so.  The printing code accordingly has to skip such terms — and has a special case to deal with all terms zero (it prints 0, of course).

Also, the design of mult_polynomial() in the question is inadequate.  If you have void mult_polynomial(polynomial *p1, polynomial *p2, polynomial *p3), you can't get the new data in p3 out of the function.  The options are to use polynomial **p3 or to return the new polynomial — this code returns the new value.

And, as already mentioned in the comments, it is generally best not to used typedef for data pointers (function pointers are a different matter).  You can find out more at Is it a good idea to typedef pointers.  I ended up with one structure for polynomials, which is the same as the structure for a term in a polynomial.  (The test code uses a pair of structures, a term and a termlist, to describe polynomials for testing purposes.  They make life easier.  There's a modest amount of test code.  The add_polynomial() and sub_polynomial() functions were completed inside 10 minutes, including fixing up the printing for 0 polynomials, which is a testament to the usefulness of the add_term() function.

The print_polynomial() function is important and useful.  It also has to deal with some fiddly special cases (negative coefficients, first coefficient negative, zero coefficients, power of one, and power of zero).  It should arguably be generalized to allow the variable name to be specified; it is hard-coded as x.  There might be some simpler functions trying to escape — one possibility is a print_term() function that could be used elsewhere as well as being called in print_polynomial().  There'd be tricky communication to handle the fiddly special cases, of course.

An FYI: I define all functions (other than main()) as static unless there's a second source file that references them and a header file that declares them.  Clearly, some of these functions would become publicly accessible if the code was to be reused and would then be made extern (non-static) and declared in a header.  The details of the type would not be in the header; the typedef struct polynomial polynomial; would be there, but that's all that would be needed.  The definition would be hidden in the implementation file.  This would be an opaque type.  Some functions such as add_term() and make_term() would remain as static functions.

The code uses C99 designated initializers and compound literals.  It could be written using C89/C90 code, but it would be harder and/or messier.  Not necessarily very much harder, but…

Without further ado, here's the code (it's quite long):

/* SO 4313-7847 */
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include "emalloc.h"

typedef struct polynomial polynomial;

struct polynomial
{
    unsigned int power;
    int          coeff;
    polynomial  *next;
};

static void print_polynomial(const char *tag, const polynomial *poly);

static polynomial *make_term(unsigned int power, int coeff, polynomial *next)
{
    polynomial *new_term = MALLOC(sizeof(*new_term));
    new_term->power = power;
    new_term->coeff = coeff;
    new_term->next  = next;
    return new_term;
}

static polynomial *add_term(polynomial *poly, unsigned int power, int coeff)
{
    if (coeff == 0)
        return poly;
    if (poly == NULL)
        return make_term(power, coeff, NULL);

    /* Find where this term goes */
    polynomial *term = poly;
    polynomial *prev = NULL;
    while (term != NULL && term->power > power)
    {
        prev = term;
        term = term->next;
    }

    if (term != NULL && term->power == power)
    {
        term->coeff += coeff;
        /* Eliminate zero terms here */
    }
    else
    {
        assert(term == NULL || term->power < power);
        polynomial *new_term = make_term(power, coeff, term);
        if (prev == NULL)
            poly = new_term;
        else
            prev->next = new_term;
    }
    return poly;
}

static polynomial *mult_polynomial(polynomial *poly1, polynomial *poly2)
{
    assert(poly1 != NULL && poly2 != NULL);
    polynomial *result = NULL;

    for (polynomial *p1 = poly1; p1 != NULL; p1 = p1->next)
    {
        for (polynomial *p2 = poly2; p2 != NULL; p2 = p2->next)
            result = add_term(result, p1->power + p2->power, p1->coeff * p2->coeff);
    }
    return result;
}

static polynomial *add_polynomial(polynomial *poly1, polynomial *poly2)
{
    assert(poly1 != NULL && poly2 != NULL);
    polynomial *result = NULL;

    for (polynomial *p1 = poly1; p1 != NULL; p1 = p1->next)
        result = add_term(result, p1->power, p1->coeff);
    for (polynomial *p2 = poly2; p2 != NULL; p2 = p2->next)
        result = add_term(result, p2->power, p2->coeff);
    return result;
}

static polynomial *sub_polynomial(polynomial *poly1, polynomial *poly2)
{
    assert(poly1 != NULL && poly2 != NULL);
    polynomial *result = NULL;

    for (polynomial *p1 = poly1; p1 != NULL; p1 = p1->next)
        result = add_term(result, p1->power, p1->coeff);
    for (polynomial *p2 = poly2; p2 != NULL; p2 = p2->next)
        result = add_term(result, p2->power, -p2->coeff);
    return result;
}

static void print_polynomial(const char *tag, const polynomial *poly)
{
    int printed = 0;
    printf("%s:", tag);
    char sign = ' ';
    while (poly != NULL)
    {
        int coeff = poly->coeff;
        if (coeff != 0)
        {
            if (sign != ' ' && coeff < 0)
            {
                sign = '-';
                coeff = -coeff;
            }
            if (poly->power == 0)
                printf(" %c %d", sign, coeff);
            else if (poly->power == 1)
                printf(" %c %dx", sign, coeff);
            else
                printf(" %c %dx^%u", sign, coeff, poly->power);
            printed++;
        }
        poly = poly->next;
        sign = '+';
    }
    if (printed == 0)
        printf("   0");
    putchar('\n');
    fflush(stdout);
}

static void free_polynomial(polynomial *poly)
{
    while (poly != NULL)
    {
        polynomial *next = poly->next;
        free(poly);
        poly = next;
    }
}

typedef struct term
{
    unsigned int power;
    int coeff;
} term;

typedef struct termlist
{
    int n_terms;
    term *terms;
} termlist;

static polynomial *make_polynomial(termlist *terms)
{
    polynomial *poly = 0;
    for (int i = 0; i < terms->n_terms; i++)
    {
        printf("Term: %dx^%u\n", terms->terms[i].coeff, terms->terms[i].power);
        fflush(stdout);
        poly = add_term(poly, terms->terms[i].power, terms->terms[i].coeff);
    }
    return poly;
}

int main(void)
{
    termlist p1[] =
    {
        { .n_terms = 4, .terms = (term[]){ { 3, 2 }, { 2,  1 }, { 1,  4 }, { 0, -9 } } },
        { .n_terms = 3, .terms = (term[]){ { 2, 3 }, { 1, -4 }, { 0,  8 } } },
        { .n_terms = 3, .terms = (term[]){ { 1, 5 }, { 0,  3 }, { 2, -4 } } },
        { .n_terms = 2, .terms = (term[]){ { 4, 5 }, { 0, -5 } } },
        { .n_terms = 4, .terms = (term[]){ { 3, 2 }, { 2,  1 }, { 1,  4 }, { 2, -9 } } },
    };
    enum { NUM_POLYS = sizeof(p1) / sizeof(p1[0]) };
    polynomial *poly[NUM_POLYS] = { 0 };

    for (int i = 0; i < NUM_POLYS; i++)
    {
        poly[i] = make_polynomial(&p1[i]);
        print_polynomial("Building", poly[i]);
    }

    printf("Checking:\n");
    for (int i = 0; i < NUM_POLYS; i++)
        print_polynomial("Next", poly[i]);
    putchar('\n');

    printf("Multiplying polynomials:\n");
    for (int i = 0; i < NUM_POLYS; i++)
    {
        for (int j = 0; j < NUM_POLYS; j++)
        {
            print_polynomial("Term 1", poly[i]);
            print_polynomial("Term 2", poly[j]);
            polynomial *prod = mult_polynomial(poly[i], poly[j]);
            print_polynomial("Product", prod);
            free_polynomial(prod);
        }
        putchar('\n');
    }

    printf("Adding polynomials:\n");
    for (int i = 0; i < NUM_POLYS; i++)
    {
        for (int j = 0; j < NUM_POLYS; j++)
        {
            print_polynomial("Term 1", poly[i]);
            print_polynomial("Term 2", poly[j]);
            polynomial *sum = add_polynomial(poly[i], poly[j]);
            print_polynomial("Sum", sum);
            free_polynomial(sum);
        }
        putchar('\n');
    }

    printf("Subtracting polynomials:\n");
    for (int i = 0; i < NUM_POLYS; i++)
    {
        for (int j = 0; j < NUM_POLYS; j++)
        {
            print_polynomial("Term 1", poly[i]);
            print_polynomial("Term 2", poly[j]);
            polynomial *diff = sub_polynomial(poly[i], poly[j]);
            print_polynomial("Difference", diff);
            free_polynomial(diff);
        }
        putchar('\n');
    }

    for (int i = 0; i < NUM_POLYS; i++)
        free_polynomial(poly[i]);

    return 0;
}

And the output, broken into three sections so you can see the start of the multiplication, addition and subtraction sections of the tests:

Term: 2x^3
Term: 1x^2
Term: 4x^1
Term: -9x^0
Building:   2x^3 + 1x^2 + 4x - 9
Term: 3x^2
Term: -4x^1
Term: 8x^0
Building:   3x^2 - 4x + 8
Term: 5x^1
Term: 3x^0
Term: -4x^2
Building:   -4x^2 + 5x + 3
Term: 5x^4
Term: -5x^0
Building:   5x^4 - 5
Term: 2x^3
Term: 1x^2
Term: 4x^1
Term: -9x^2
Building:   2x^3 - 8x^2 + 4x
Checking:
Next:   2x^3 + 1x^2 + 4x - 9
Next:   3x^2 - 4x + 8
Next:   -4x^2 + 5x + 3
Next:   5x^4 - 5
Next:   2x^3 - 8x^2 + 4x

Multiplication:

Multiplying polynomials:
Term 1:   2x^3 + 1x^2 + 4x - 9
Term 2:   2x^3 + 1x^2 + 4x - 9
Product:   4x^6 + 4x^5 + 17x^4 - 28x^3 - 2x^2 - 72x + 81
Term 1:   2x^3 + 1x^2 + 4x - 9
Term 2:   3x^2 - 4x + 8
Product:   6x^5 - 5x^4 + 24x^3 - 35x^2 + 68x - 72
Term 1:   2x^3 + 1x^2 + 4x - 9
Term 2:   -4x^2 + 5x + 3
Product:   -8x^5 + 6x^4 - 5x^3 + 59x^2 - 33x - 27
Term 1:   2x^3 + 1x^2 + 4x - 9
Term 2:   5x^4 - 5
Product:   10x^7 + 5x^6 + 20x^5 - 45x^4 - 10x^3 - 5x^2 - 20x + 45
Term 1:   2x^3 + 1x^2 + 4x - 9
Term 2:   2x^3 - 8x^2 + 4x
Product:   4x^6 - 14x^5 + 8x^4 - 46x^3 + 88x^2 - 36x

Term 1:   3x^2 - 4x + 8
Term 2:   2x^3 + 1x^2 + 4x - 9
Product:   6x^5 - 5x^4 + 24x^3 - 35x^2 + 68x - 72
Term 1:   3x^2 - 4x + 8
Term 2:   3x^2 - 4x + 8
Product:   9x^4 - 24x^3 + 64x^2 - 64x + 64
Term 1:   3x^2 - 4x + 8
Term 2:   -4x^2 + 5x + 3
Product:   -12x^4 + 31x^3 - 43x^2 + 28x + 24
Term 1:   3x^2 - 4x + 8
Term 2:   5x^4 - 5
Product:   15x^6 - 20x^5 + 40x^4 - 15x^2 + 20x - 40
Term 1:   3x^2 - 4x + 8
Term 2:   2x^3 - 8x^2 + 4x
Product:   6x^5 - 32x^4 + 60x^3 - 80x^2 + 32x

Term 1:   -4x^2 + 5x + 3
Term 2:   2x^3 + 1x^2 + 4x - 9
Product:   -8x^5 + 6x^4 - 5x^3 + 59x^2 - 33x - 27
Term 1:   -4x^2 + 5x + 3
Term 2:   3x^2 - 4x + 8
Product:   -12x^4 + 31x^3 - 43x^2 + 28x + 24
Term 1:   -4x^2 + 5x + 3
Term 2:   -4x^2 + 5x + 3
Product:   16x^4 - 40x^3 + 1x^2 + 30x + 9
Term 1:   -4x^2 + 5x + 3
Term 2:   5x^4 - 5
Product:   -20x^6 + 25x^5 + 15x^4 + 20x^2 - 25x - 15
Term 1:   -4x^2 + 5x + 3
Term 2:   2x^3 - 8x^2 + 4x
Product:   -8x^5 + 42x^4 - 50x^3 - 4x^2 + 12x

Term 1:   5x^4 - 5
Term 2:   2x^3 + 1x^2 + 4x - 9
Product:   10x^7 + 5x^6 + 20x^5 - 45x^4 - 10x^3 - 5x^2 - 20x + 45
Term 1:   5x^4 - 5
Term 2:   3x^2 - 4x + 8
Product:   15x^6 - 20x^5 + 40x^4 - 15x^2 + 20x - 40
Term 1:   5x^4 - 5
Term 2:   -4x^2 + 5x + 3
Product:   -20x^6 + 25x^5 + 15x^4 + 20x^2 - 25x - 15
Term 1:   5x^4 - 5
Term 2:   5x^4 - 5
Product:   25x^8 - 50x^4 + 25
Term 1:   5x^4 - 5
Term 2:   2x^3 - 8x^2 + 4x
Product:   10x^7 - 40x^6 + 20x^5 - 10x^3 + 40x^2 - 20x

Term 1:   2x^3 - 8x^2 + 4x
Term 2:   2x^3 + 1x^2 + 4x - 9
Product:   4x^6 - 14x^5 + 8x^4 - 46x^3 + 88x^2 - 36x
Term 1:   2x^3 - 8x^2 + 4x
Term 2:   3x^2 - 4x + 8
Product:   6x^5 - 32x^4 + 60x^3 - 80x^2 + 32x
Term 1:   2x^3 - 8x^2 + 4x
Term 2:   -4x^2 + 5x + 3
Product:   -8x^5 + 42x^4 - 50x^3 - 4x^2 + 12x
Term 1:   2x^3 - 8x^2 + 4x
Term 2:   5x^4 - 5
Product:   10x^7 - 40x^6 + 20x^5 - 10x^3 + 40x^2 - 20x
Term 1:   2x^3 - 8x^2 + 4x
Term 2:   2x^3 - 8x^2 + 4x
Product:   4x^6 - 32x^5 + 80x^4 - 64x^3 + 16x^2

Addition:

Adding polynomials:
Term 1:   2x^3 + 1x^2 + 4x - 9
Term 2:   2x^3 + 1x^2 + 4x - 9
Sum:   4x^3 + 2x^2 + 8x - 18
Term 1:   2x^3 + 1x^2 + 4x - 9
Term 2:   3x^2 - 4x + 8
Sum:   2x^3 + 4x^2 - 1
Term 1:   2x^3 + 1x^2 + 4x - 9
Term 2:   -4x^2 + 5x + 3
Sum:   2x^3 - 3x^2 + 9x - 6
Term 1:   2x^3 + 1x^2 + 4x - 9
Term 2:   5x^4 - 5
Sum:   5x^4 + 2x^3 + 1x^2 + 4x - 14
Term 1:   2x^3 + 1x^2 + 4x - 9
Term 2:   2x^3 - 8x^2 + 4x
Sum:   4x^3 - 7x^2 + 8x - 9

Term 1:   3x^2 - 4x + 8
Term 2:   2x^3 + 1x^2 + 4x - 9
Sum:   2x^3 + 4x^2 - 1
Term 1:   3x^2 - 4x + 8
Term 2:   3x^2 - 4x + 8
Sum:   6x^2 - 8x + 16
Term 1:   3x^2 - 4x + 8
Term 2:   -4x^2 + 5x + 3
Sum:   -1x^2 + 1x + 11
Term 1:   3x^2 - 4x + 8
Term 2:   5x^4 - 5
Sum:   5x^4 + 3x^2 - 4x + 3
Term 1:   3x^2 - 4x + 8
Term 2:   2x^3 - 8x^2 + 4x
Sum:   2x^3 - 5x^2 + 8

Term 1:   -4x^2 + 5x + 3
Term 2:   2x^3 + 1x^2 + 4x - 9
Sum:   2x^3 - 3x^2 + 9x - 6
Term 1:   -4x^2 + 5x + 3
Term 2:   3x^2 - 4x + 8
Sum:   -1x^2 + 1x + 11
Term 1:   -4x^2 + 5x + 3
Term 2:   -4x^2 + 5x + 3
Sum:   -8x^2 + 10x + 6
Term 1:   -4x^2 + 5x + 3
Term 2:   5x^4 - 5
Sum:   5x^4 - 4x^2 + 5x - 2
Term 1:   -4x^2 + 5x + 3
Term 2:   2x^3 - 8x^2 + 4x
Sum:   2x^3 - 12x^2 + 9x + 3

Term 1:   5x^4 - 5
Term 2:   2x^3 + 1x^2 + 4x - 9
Sum:   5x^4 + 2x^3 + 1x^2 + 4x - 14
Term 1:   5x^4 - 5
Term 2:   3x^2 - 4x + 8
Sum:   5x^4 + 3x^2 - 4x + 3
Term 1:   5x^4 - 5
Term 2:   -4x^2 + 5x + 3
Sum:   5x^4 - 4x^2 + 5x - 2
Term 1:   5x^4 - 5
Term 2:   5x^4 - 5
Sum:   10x^4 - 10
Term 1:   5x^4 - 5
Term 2:   2x^3 - 8x^2 + 4x
Sum:   5x^4 + 2x^3 - 8x^2 + 4x - 5

Term 1:   2x^3 - 8x^2 + 4x
Term 2:   2x^3 + 1x^2 + 4x - 9
Sum:   4x^3 - 7x^2 + 8x - 9
Term 1:   2x^3 - 8x^2 + 4x
Term 2:   3x^2 - 4x + 8
Sum:   2x^3 - 5x^2 + 8
Term 1:   2x^3 - 8x^2 + 4x
Term 2:   -4x^2 + 5x + 3
Sum:   2x^3 - 12x^2 + 9x + 3
Term 1:   2x^3 - 8x^2 + 4x
Term 2:   5x^4 - 5
Sum:   5x^4 + 2x^3 - 8x^2 + 4x - 5
Term 1:   2x^3 - 8x^2 + 4x
Term 2:   2x^3 - 8x^2 + 4x
Sum:   4x^3 - 16x^2 + 8x

Subtraction:

Subtracting polynomials:
Term 1:   2x^3 + 1x^2 + 4x - 9
Term 2:   2x^3 + 1x^2 + 4x - 9
Difference:   0
Term 1:   2x^3 + 1x^2 + 4x - 9
Term 2:   3x^2 - 4x + 8
Difference:   2x^3 - 2x^2 + 8x - 17
Term 1:   2x^3 + 1x^2 + 4x - 9
Term 2:   -4x^2 + 5x + 3
Difference:   2x^3 + 5x^2 - 1x - 12
Term 1:   2x^3 + 1x^2 + 4x - 9
Term 2:   5x^4 - 5
Difference:   -5x^4 + 2x^3 + 1x^2 + 4x - 4
Term 1:   2x^3 + 1x^2 + 4x - 9
Term 2:   2x^3 - 8x^2 + 4x
Difference: + 9x^2 - 9

Term 1:   3x^2 - 4x + 8
Term 2:   2x^3 + 1x^2 + 4x - 9
Difference:   -2x^3 + 2x^2 - 8x + 17
Term 1:   3x^2 - 4x + 8
Term 2:   3x^2 - 4x + 8
Difference:   0
Term 1:   3x^2 - 4x + 8
Term 2:   -4x^2 + 5x + 3
Difference:   7x^2 - 9x + 5
Term 1:   3x^2 - 4x + 8
Term 2:   5x^4 - 5
Difference:   -5x^4 + 3x^2 - 4x + 13
Term 1:   3x^2 - 4x + 8
Term 2:   2x^3 - 8x^2 + 4x
Difference:   -2x^3 + 11x^2 - 8x + 8

Term 1:   -4x^2 + 5x + 3
Term 2:   2x^3 + 1x^2 + 4x - 9
Difference:   -2x^3 - 5x^2 + 1x + 12
Term 1:   -4x^2 + 5x + 3
Term 2:   3x^2 - 4x + 8
Difference:   -7x^2 + 9x - 5
Term 1:   -4x^2 + 5x + 3
Term 2:   -4x^2 + 5x + 3
Difference:   0
Term 1:   -4x^2 + 5x + 3
Term 2:   5x^4 - 5
Difference:   -5x^4 - 4x^2 + 5x + 8
Term 1:   -4x^2 + 5x + 3
Term 2:   2x^3 - 8x^2 + 4x
Difference:   -2x^3 + 4x^2 + 1x + 3

Term 1:   5x^4 - 5
Term 2:   2x^3 + 1x^2 + 4x - 9
Difference:   5x^4 - 2x^3 - 1x^2 - 4x + 4
Term 1:   5x^4 - 5
Term 2:   3x^2 - 4x + 8
Difference:   5x^4 - 3x^2 + 4x - 13
Term 1:   5x^4 - 5
Term 2:   -4x^2 + 5x + 3
Difference:   5x^4 + 4x^2 - 5x - 8
Term 1:   5x^4 - 5
Term 2:   5x^4 - 5
Difference:   0
Term 1:   5x^4 - 5
Term 2:   2x^3 - 8x^2 + 4x
Difference:   5x^4 - 2x^3 + 8x^2 - 4x - 5

Term 1:   2x^3 - 8x^2 + 4x
Term 2:   2x^3 + 1x^2 + 4x - 9
Difference: - 9x^2 + 9
Term 1:   2x^3 - 8x^2 + 4x
Term 2:   3x^2 - 4x + 8
Difference:   2x^3 - 11x^2 + 8x - 8
Term 1:   2x^3 - 8x^2 + 4x
Term 2:   -4x^2 + 5x + 3
Difference:   2x^3 - 4x^2 - 1x - 3
Term 1:   2x^3 - 8x^2 + 4x
Term 2:   5x^4 - 5
Difference:   -5x^4 + 2x^3 - 8x^2 + 4x + 5
Term 1:   2x^3 - 8x^2 + 4x
Term 2:   2x^3 - 8x^2 + 4x
Difference:   0


来源: stackexchange

问:
Python 2.7. Save text file's name as date with linux command
I am using subprocess() to do linux shell commands in python and what i wanna do is read a file, get the needed info and save it in a text file named by current date. Reading and all works fine, but I don't know how to save file by naming it with current date. I tried making a variable with subprocess, but that was not successful.</p>

```<code>def gauti():
        imti=tekstas.get("1.0", "end-1c")
        subprocess.call("data=$(date +"%d_%m_%Y")", shell=True)
        subprocess.call("grep -i '{imti}' /var/log/syslog > $data.txt".format(imti=imti), shell=True)
</code>```

答:
This code will never work:

```<code>subprocess.call("data=$(date +"%d_%m_%Y")", shell=True)
subprocess.call("grep -i '{imti}' /var/log/syslog > $data.txt".format(imti=imti), shell=True)
</code>```

Because a new shell is created every time, so your $data variable is not passed from the first command to the second.  You can just do this:

```<code>subprocess.check_call("grep -i '{}' /var/log/syslog > $(date +%d_%m_%Y.txt)".format(imti), shell=True)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using subprocess() to do linux shell commands in python and what i wanna do is read a file, get the needed info and save it in a text file named by current date. Reading and all works fine, but I don't know how to save file by naming it with current date. I tried making a variable with subprocess, but that was not successful.

def gauti():
        imti=tekstas.get("1.0", "end-1c")
        subprocess.call("data=$(date +"%d_%m_%Y")", shell=True)
        subprocess.call("grep -i '{imti}' /var/log/syslog > $data.txt".format(imti=imti), shell=True)

Body:
This code will never work:

subprocess.call("data=$(date +"%d_%m_%Y")", shell=True)
subprocess.call("grep -i '{imti}' /var/log/syslog > $data.txt".format(imti=imti), shell=True)

Because a new shell is created every time, so your $data variable is not passed from the first command to the second.  You can just do this:

subprocess.check_call("grep -i '{}' /var/log/syslog > $(date +%d_%m_%Y.txt)".format(imti), shell=True)


问:
Issue with the format in anytime package
```<code>library("anytime")
</code>```

This works well:

```<code>anytime("08/24/2014 01:28:00")
anytime("2014/08/24 01:28:00")

[1] "2014-08-24 00:28:00 NZST"
</code>```

This doesn't:

```<code>anytime("24/08/2014 01:28:00")
anytime("2014/24/08 01:28:00")

[1] NA
</code>```

What is the reason for this and what would be the options (using anytime package ONLY)?

答:
We can add the formats with addFormats in anytime if that formats are not in the default list of formats by using

```<code>getFormats()
#[1] "%Y-%m-%d %H:%M:%S%f"    "%Y/%m/%d %H:%M:%S%f"    "%Y%m%d %H%M%S%f"
#[4] "%Y%m%d %H:%M:%S%f"      "%m/%d/%Y %H:%M:%S%f"    "%m-%d-%Y %H:%M:%S%f"
#[7] "%Y-%b-%d %H:%M:%S%f"    "%Y/%b/%d %H:%M:%S%f"    "%Y%b%d %H%M%S%F"
#[10] "%Y%b%d %H:%M:%S%F"      "%b/%d/%Y %H:%M:%S%f"    "%b-%d-%Y %H:%M:%S%f"
#[13] "%d.%b.%Y %H:%M:%S%f"    "%Y-%B-%d %H:%M:%S%f"    "%Y/%B/%d %H:%M:%S%f"
#[16] "%Y%B%d %H%M%S%f"        "%Y%B%d %H:%M:%S%f"      "%B/%d/%Y %H:%M:%S%f"
#[19] "%B-%d-%Y %H:%M:%S%f"    "%d.%B.%Y %H:%M:%S%f"    "%a %b %d %H:%M:%S%F %Y"
#[22] "%Y-%m-%d"               "%Y%m%d"                 "%m/%d/%Y"
#[25] "%m-%d-%Y"               "%Y-%b-%d"               "%Y%b%d"
#[28] "%b/%d/%Y"               "%b-%d-%Y"               "%Y-%B-%d"
#[31] "%Y%B%d"                 "%B/%d/%Y"               "%B-%d-%Y"
</code>```

If we check the format that gives NA, it is not in the getFormats list

```<code>c("%d/%m/%Y %H:%M:%S", "%Y/%d/%m %H:%M:%S") %in% getFormats()
#[1] FALSE FALSE
</code>```

So, we can add the formats with addFormats and apply the anytime

```<code>anytime::addFormats(c("%d/%m/%Y %H:%M:%S", "%Y/%d/%m %H:%M:%S"))
anytime("24/08/2014 01:28:00")
#[1] "2014-08-24 01:28:00 IST"
anytime("2014/24/08 01:28:00")
#[1] "2014-08-24 01:28:00 IST"
</code>```

Update

In the latest version of anytime, there are 41 formats in getFormats()

```<code>length(getFormats())
#[1] 41
</code>```

But, the format specified in the OP's post is still not included and would have to follow the addFormats route

Body:
library("anytime")

This works well:

anytime("08/24/2014 01:28:00")
anytime("2014/08/24 01:28:00")

[1] "2014-08-24 00:28:00 NZST"

This doesn't:

anytime("24/08/2014 01:28:00")
anytime("2014/24/08 01:28:00")

[1] NA

What is the reason for this and what would be the options (using anytime package ONLY)?

Body:
We can add the formats with addFormats in anytime if that formats are not in the default list of formats by using

getFormats()
#[1] "%Y-%m-%d %H:%M:%S%f"    "%Y/%m/%d %H:%M:%S%f"    "%Y%m%d %H%M%S%f"
#[4] "%Y%m%d %H:%M:%S%f"      "%m/%d/%Y %H:%M:%S%f"    "%m-%d-%Y %H:%M:%S%f"
#[7] "%Y-%b-%d %H:%M:%S%f"    "%Y/%b/%d %H:%M:%S%f"    "%Y%b%d %H%M%S%F"
#[10] "%Y%b%d %H:%M:%S%F"      "%b/%d/%Y %H:%M:%S%f"    "%b-%d-%Y %H:%M:%S%f"
#[13] "%d.%b.%Y %H:%M:%S%f"    "%Y-%B-%d %H:%M:%S%f"    "%Y/%B/%d %H:%M:%S%f"
#[16] "%Y%B%d %H%M%S%f"        "%Y%B%d %H:%M:%S%f"      "%B/%d/%Y %H:%M:%S%f"
#[19] "%B-%d-%Y %H:%M:%S%f"    "%d.%B.%Y %H:%M:%S%f"    "%a %b %d %H:%M:%S%F %Y"
#[22] "%Y-%m-%d"               "%Y%m%d"                 "%m/%d/%Y"
#[25] "%m-%d-%Y"               "%Y-%b-%d"               "%Y%b%d"
#[28] "%b/%d/%Y"               "%b-%d-%Y"               "%Y-%B-%d"
#[31] "%Y%B%d"                 "%B/%d/%Y"               "%B-%d-%Y"

If we check the format that gives NA, it is not in the getFormats list

c("%d/%m/%Y %H:%M:%S", "%Y/%d/%m %H:%M:%S") %in% getFormats()
#[1] FALSE FALSE

So, we can add the formats with addFormats and apply the anytime

anytime::addFormats(c("%d/%m/%Y %H:%M:%S", "%Y/%d/%m %H:%M:%S"))
anytime("24/08/2014 01:28:00")
#[1] "2014-08-24 01:28:00 IST"
anytime("2014/24/08 01:28:00")
#[1] "2014-08-24 01:28:00 IST"

Update

In the latest version of anytime, there are 41 formats in getFormats()

length(getFormats())
#[1] 41

But, the format specified in the OP's post is still not included and would have to follow the addFormats route


问:
how can i load some content from another html file my main html?
I want to add specific content from another HTML page into my main HTML. I am trying using .load by jquery it is work but run just in firefox, I want some method that works in other browsers like chrome.
I have two HTML I want to insert div with id=2 from second html into first HTML to div with id=ok? could you please help me?
main HTML:

```<code><html>
<head>
    <title></title>
</head>
<body>
<div id="ok"></div>
</body>
</html>
</code>```

second html:

```<code><html>
<head>
    <title></title>
</head>
<body>
<div id="1">one</div>
<div id="2">two</div>
<div id="3">three</div>

</body>
</html>
</code>```

答:
You are looking for what is called AJAX. this can be achieve with pure JS or in my opinion more easily with JQuery.

AJAX Introduction

Body:
I want to add specific content from another HTML page into my main HTML. I am trying using .load by jquery it is work but run just in firefox, I want some method that works in other browsers like chrome.
I have two HTML I want to insert div with id=2 from second html into first HTML to div with id=ok? could you please help me?
main HTML:

    <title></title>

second html:

    <title></title>

one

two

three


问:
iOS launch screen not displaying
I'm trying to get the launch images to work on ios (splash screen) but it doesn't seem to be displaying. The app does start but is white initially then goes to the first screen.

I only have an ios simulator not an ios device. Just stating that in case the simulator doesn't show the launch screen however the android emulator does show the android splash screen so I imagine the ios simulator probably does too.

This is the error I see while the app is building:

CompileXIB volcalc_m/Base.lproj/LaunchScreen.xib
      cd /Users/Ben/proj/volcalc_m/ios
      export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/De
  veloper/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/Users/Ben/Library/Developer/X
  amarin/android-sdk-macosx/platform-tools:/Users/Ben/Library/Developer/Xamarin/android-sdk-macosx/
  tools:/Users/Ben/.yarn/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/Ben/Library/Develo
  per/Xamarin/android-sdk-macosx/tools:/Users/Ben/Library/Developer/Xamarin/android-sdk-macosx/plat
  form-tools"
      export XCODE_DEVELOPER_USR_PATH=/Applications/Xcode.app/Contents/Developer/usr/bin/..
      /Applications/Xcode.app/Contents/Developer/usr/bin/ibtool --errors --warnings --notices --mod ule volcalc_m --output-partial-info-plist /Users/Ben/proj/volcalc_m/ios/build/Build/Intermediates
  /volcalc_m.build/Debug-iphonesimulator/volcalc_m.build/LaunchScreen-PartialInfo.plist
  --auto-acti vate-custom-fonts --target-device iphone --minimum-deployment-target 8.0 --output-format human-re adable-text --compile /Users/Ben/proj/volcalc_m/ios/build/Build/Products/Debug-iphonesimulator/vo
  lcalc_m.app/Base.lproj/LaunchScreen.nib
  /Users/Ben/proj/volcalc_m/ios/volcalc_m/Base.lproj/Launch Screen.xib

/* com.apple.ibtool.errors */

/Users/Ben/proj/volcalc_m/ios/volcalc_m/Base.lproj/LaunchScreen.xib:
  error: Interface Builder cou ld not open the document
  LaunchScreen.xib" because it does not exist.

I did indeed delete the Base.lproj folder which container LaunchScreen.xib. I thought that would be best so that it doesn't look for that. However it seems to be looking for that. How can I stop it from doing so?

I have dragged the correct size images into an xcode launch image set:

And in my "general" settings in the project in xcode I have specified the launch image set:

I do however see these weird but probably irrelevant warnings:

Any ideas what I've done wrong? Happy to provide more information on request. Cheers

答:
This occures because your property list file is misconfigured. Go to your Info.plist and add this key:

Launch image ---(String)  value -- LaunchImage1

Title: iOS launch screen not displaying


问:
Cannot write values to HKEY_LOCAL_MACHINE
I want to make application run at startup by writing registry

```<code>Dim regKey As RegistryKey
regKey = Registry.LocalMachine.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", True)
regKey.SetValue("exitit", "exitit.exe")
</code>```

but this code is not working without any errors or exceptions.

Note: This code works for other locations except HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run

答:
I had troubles wit this command in the past as well, couldnt resolve it but i worked arround it with regedit commands:

```<code>Process.Start("cmd", "/c reg ADD HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run /v exitit /t REG_SZ  /d exitit.exe /f")
</code>```

this should work for you, if u intented to assign a value containing spaces you have to type it with Chr(34) (as the " "). Example:

```<code>Process.Start("cmd", "/c reg ADD HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run /v exitit /t REG_SZ  /d " & Chr(34) & "exit it.exe" & Chr(34) & " /f")
</code>```

Body:
I want to make application run at startup by writing registry

Dim regKey As RegistryKey
regKey = Registry.LocalMachine.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", True)
regKey.SetValue("exitit", "exitit.exe")

but this code is not working without any errors or exceptions.

Note: This code works for other locations except HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run

Body:
I had troubles wit this command in the past as well, couldnt resolve it but i worked arround it with regedit commands:

Process.Start("cmd", "/c reg ADD HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run /v exitit /t REG_SZ  /d exitit.exe /f")

this should work for you, if u intented to assign a value containing spaces you have to type it with Chr(34) (as the " "). Example:

Process.Start("cmd", "/c reg ADD HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run /v exitit /t REG_SZ  /d " & Chr(34) & "exit it.exe" & Chr(34) & " /f")


问:
Java Printing a Binary Tree using Level-Order in a Specific Format
Okay, I have read through all the other related questions and cannot find one that helps with java.  I get the general idea from deciphering what i can in other languages; but i am yet to figure it out.

Problem: I would like to level sort (which i have working using recursion) and print it out in the general shape of a tree.

So say i have this:

```<code>    1
   / \
  2   3
 /   / \
4   5   6
</code>```

My code prints out the level order like this:

```<code>1 2 3 4 5 6
</code>```

I want to print it out like this:

```<code>1
2 3
4 5 6
</code>```

Now before you give me a moral speech about doing my work... I have already finished my AP Comp Sci project and got curious about this when my teacher mentioned the Breadth First Search thing.

I don't know if it will help, but here is my code so far:

```<code>/**
  * Calls the levelOrder helper method and prints out in levelOrder.
  */
 public void levelOrder()
 {
  q = new QueueList();
  treeHeight = height();
  levelOrder(myRoot, q, myLevel);
 }

 /**
  * Helper method that uses recursion to print out the tree in
  * levelOrder
  */
 private void levelOrder(TreeNode root, QueueList q, int curLev)
 {
  System.out.print(curLev);
  if(root == null)
  {
   return;
  }

  if(q.isEmpty())
  {
   System.out.println(root.getValue());
  }
  else
  {
   System.out.print((String)q.dequeue()+", ");
  }

  if(root.getLeft() != null)
  {
   q.enqueue(root.getLeft().getValue());
   System.out.println();
  }
  if(root.getRight() != null)
  {
   q.enqueue(root.getRight().getValue());
   System.out.println();
   curLev++;
  }

  levelOrder(root.getLeft(),q, curLev);
  levelOrder(root.getRight(),q, curLev);
 }
</code>```

From what i can figure out, i will need to use the total height of the tree, and use a level counter... Only problem is my level counter keeps counting when my levelOrder uses recursion to go back through the tree.

Sorry if this is to much, but some tips would be nice. :)

答:
Python implementation</p>

```<code># Function to  print level order traversal of tree
def printLevelOrder(root):
    h = height(root)
    for i in range(1, h+1):
        printGivenLevel(root, i)

# Print nodes at a given level
def printGivenLevel(root , level):
    if root is None:
        return
    if level == 1:
        print "%d" %(root.data),
    elif level > 1 :
        printGivenLevel(root.left , level-1)
        printGivenLevel(root.right , level-1)

""" Compute the height of a tree--the number of nodes
    along the longest path from the root node down to
    the farthest leaf node
"""
def height(node):
    if node is None:
        return 0
    else :
        # Compute the height of each subtree
        lheight = height(node.left)
        rheight = height(node.right)

        #Use the larger one
        if lheight > rheight :
            return lheight+1
        else:
            return rheight+1
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Okay, I have read through all the other related questions and cannot find one that helps with java.  I get the general idea from deciphering what i can in other languages; but i am yet to figure it out.

Problem: I would like to level sort (which i have working using recursion) and print it out in the general shape of a tree.

So say i have this:

    1
   / \
  2   3
 /   / \
4   5   6

My code prints out the level order like this:

1 2 3 4 5 6

I want to print it out like this:

1
2 3
4 5 6

Now before you give me a moral speech about doing my work... I have already finished my AP Comp Sci project and got curious about this when my teacher mentioned the Breadth First Search thing.

I don't know if it will help, but here is my code so far:

/**
  * Calls the levelOrder helper method and prints out in levelOrder.
  */
 public void levelOrder()
 {
  q = new QueueList();
  treeHeight = height();
  levelOrder(myRoot, q, myLevel);
 }

 /**
  * Helper method that uses recursion to print out the tree in
  * levelOrder
  */
 private void levelOrder(TreeNode root, QueueList q, int curLev)
 {
  System.out.print(curLev);
  if(root == null)
  {
   return;
  }

  if(q.isEmpty())
  {
   System.out.println(root.getValue());
  }
  else
  {
   System.out.print((String)q.dequeue()+", ");
  }

  if(root.getLeft() != null)
  {
   q.enqueue(root.getLeft().getValue());
   System.out.println();
  }
  if(root.getRight() != null)
  {
   q.enqueue(root.getRight().getValue());
   System.out.println();
   curLev++;
  }

  levelOrder(root.getLeft(),q, curLev);
  levelOrder(root.getRight(),q, curLev);
 }

From what i can figure out, i will need to use the total height of the tree, and use a level counter... Only problem is my level counter keeps counting when my levelOrder uses recursion to go back through the tree.

Sorry if this is to much, but some tips would be nice. :)

Body:
Python implementation

# Function to  print level order traversal of tree
def printLevelOrder(root):
    h = height(root)
    for i in range(1, h+1):
        printGivenLevel(root, i)

# Print nodes at a given level
def printGivenLevel(root , level):
    if root is None:
        return
    if level == 1:
        print "%d" %(root.data),
    elif level > 1 :
        printGivenLevel(root.left , level-1)
        printGivenLevel(root.right , level-1)

""" Compute the height of a tree--the number of nodes
    along the longest path from the root node down to
    the farthest leaf node
"""
def height(node):
    if node is None:
        return 0
    else :
        # Compute the height of each subtree
        lheight = height(node.left)
        rheight = height(node.right)

        #Use the larger one
        if lheight > rheight :
            return lheight+1
        else:
            return rheight+1


问:
How to create a conversion of Fahrenheit to Celsius in java
The code should output a table for Fahrenheit and Celsius:

```<code>public static void main(String[] args) {
    System.out.println("Fahrenheit\tCelsius");
    System.out.println("=======================");
     for(int temp = -45; temp <= 120; temp += 5) //for(int i = 0; i <= 100; i+= 10)
        {
            System.out.printf("%5d       |", temp);
            double sum = (temp + (9.0/5.0)) * 32;
            System.out.printf("%5d", (int) sum );
            System.out.println();
        }
}
</code>```

答:
How to create a conversion of Fahrenheit to Celsius in java

The most important step IMHO is to understand the problem before ever thinking about coding.

Wikipedia is a good start and searching for Celsius it give us:

[°C] = ([°F] − 32) ×  5⁄9

In Java that would be something like:

```<code>celsius = (fahrenheit -32.0) * 5.0 / 9.0;
</code>```

I think it is best to do that in a separate method so it is easier to test it:

```<code>public static double fahrenheitToCelsius(double fahrenheit) {
    double celsius = (fahrenheit - 32.0) * 5.0 / 9.0;
    return celsius;
}
</code>```

Note 1: it is worth testing this method before going on - two significant temperatures are:

32°F  ==  0°C  (melting point of ice)

212°F  ==  100°C  (boiling point of water)

so just do something quick & dirty like:

```<code>System.out.println("32 == " + fahrenheitToCelsius(32));
System.out.println("212 == " + fahrenheitToCelsius(212));
</code>```

much better, maybe a bit to heavy in that simple case, is to use some framework like JUnit.

Note 2: for creating the table do as posted in the question, but only one printf to take advantage of having the format together at one place (obviously after calling above method):

```<code>System.out.printf("%5.0f | %5.1f\n", fahrenheit, celsius);
</code>```

Note 3: caution with 5/9 - in Java that is interpreted as integer division and would result in zero!

(above code is just a sample and was not tested or debugged

Body:
The code should output a table for Fahrenheit and Celsius:

public static void main(String[] args) {
    System.out.println("Fahrenheit\tCelsius");
    System.out.println("=======================");
     for(int temp = -45; temp <= 120; temp += 5) //for(int i = 0; i <= 100; i+= 10)
        {
            System.out.printf("%5d       |", temp);
            double sum = (temp + (9.0/5.0)) * 32;
            System.out.printf("%5d", (int) sum );
            System.out.println();
        }
}

Body:
How to create a conversion of Fahrenheit to Celsius in java

The most important step IMHO is to understand the problem before ever thinking about coding.

Wikipedia is a good start and searching for Celsius it give us:

[°C] = ([°F] − 32) ×  5⁄9

In Java that would be something like:

celsius = (fahrenheit -32.0) * 5.0 / 9.0;

I think it is best to do that in a separate method so it is easier to test it:

public static double fahrenheitToCelsius(double fahrenheit) {
    double celsius = (fahrenheit - 32.0) * 5.0 / 9.0;
    return celsius;
}

Note 1: it is worth testing this method before going on - two significant temperatures are:

32°F  ==  0°C  (melting point of ice)

212°F  ==  100°C  (boiling point of water)

so just do something quick & dirty like:

System.out.println("32 == " + fahrenheitToCelsius(32));
System.out.println("212 == " + fahrenheitToCelsius(212));

much better, maybe a bit to heavy in that simple case, is to use some framework like JUnit.

Note 2: for creating the table do as posted in the question, but only one printf to take advantage of having the format together at one place (obviously after calling above method):

System.out.printf("%5.0f | %5.1f\n", fahrenheit, celsius);

Note 3: caution with 5/9 - in Java that is interpreted as integer division and would result in zero!

(above code is just a sample and was not tested or debugged


问:
cycling star-field animation
I made this star-field animation in javascript. I'm just not sure the best way to make it cycle the same animation from the other side. I like to get the stars to scroll across from one side of the canvas to the other.

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
stars = [];
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, 500, 500);

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function getSpeed(depth) {
  switch (depth / 2) {
    case 0:
      return 6;
    case 1:
      return 5;
    case 2:
      return 4;
    case 3:
      return 3;
    case 4:
      return 2;
    case 5:
      return 1;
  }
}
var i;
for (i = 0; i < 2000; i++) {
  var star = {
    x: 0,
    y: 0,
    z: 0,
    v: 0
  };
  star.x = getRandomInt(0, 500);
  star.y = getRandomInt(0, 500);
  star.z = getRandomInt(0, 5) * 2;
  star.v = getSpeed(star.z);
  stars.push(star);
}

function animation() {
  //clears background
  ctx.fillStyle = "#000000";
  ctx.fillRect(0, 0, 500, 500);

  // populates space with stars
  for (i = 0; i < 2000; i++) {
    ctx.fillStyle = "rgb(" + (256 / stars[i].z) + "," + (256 / stars[i].z) + "," + (256 / stars[i].z) + ")";
    ctx.fillRect(stars[i].x, stars[i].y, 2, 2);
    stars[i].x += stars[i].v;
  }

  setTimeout(animation, 33);
}
animation();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="myCanvas"></canvas></code>```

答:
Just reset the x value when it drops below zero.

```<code>if (star.x < 0) star.x = canvasWidth;
</code>```

I've made a few other changes, compare.

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function StarField(ctx, numStars, width, height) {
  var stars = new Array(numStars).fill(null).map(getStar);

  function getStar() {
    var z = getRandomInt(0, 5),
      c = (256 / z).toString(16);
    return {
      x: getRandomInt(0, width),
      y: getRandomInt(0, height),
      z: z * 2,
      v: 6 - z,
      c: "#" + c + c + c
    };
  }

  this.animate = function () {
    var i, s;

    ctx.fillStyle = "#000000";
    ctx.fillRect(0, 0, width, height);

    for (i = 0; i < numStars; i++) {
      s = stars[i];
      ctx.fillStyle = s.c;
      ctx.fillRect(s.x, s.y, 2, 2);
      s.x -= s.v;
      if (s.x < 0) s.x = width;
    }
    setTimeout(this.animate.bind(this), 32);
  };
}

var canvas = document.getElementById("myCanvas");
var s = new StarField(canvas.getContext("2d"), 2000, 500, 500);
s.animate();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="myCanvas"></canvas></code>```

Title: cycling star-field animation

Body:
I made this star-field animation in javascript. I'm just not sure the best way to make it cycle the same animation from the other side. I like to get the stars to scroll across from one side of the canvas to the other.

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
stars = [];
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, 500, 500);

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function getSpeed(depth) {
  switch (depth / 2) {
    case 0:
      return 6;
    case 1:
      return 5;
    case 2:
      return 4;
    case 3:
      return 3;
    case 4:
      return 2;
    case 5:
      return 1;
  }
}
var i;
for (i = 0; i < 2000; i++) {
  var star = {
    x: 0,
    y: 0,
    z: 0,
    v: 0
  };
  star.x = getRandomInt(0, 500);
  star.y = getRandomInt(0, 500);
  star.z = getRandomInt(0, 5) * 2;
  star.v = getSpeed(star.z);
  stars.push(star);
}

function animation() {
  //clears background
  ctx.fillStyle = "#000000";
  ctx.fillRect(0, 0, 500, 500);

  // populates space with stars
  for (i = 0; i < 2000; i++) {
    ctx.fillStyle = "rgb(" + (256 / stars[i].z) + "," + (256 / stars[i].z) + "," + (256 / stars[i].z) + ")";
    ctx.fillRect(stars[i].x, stars[i].y, 2, 2);
    stars[i].x += stars[i].v;
  }

  setTimeout(animation, 33);
}
animation();

<canvas id="myCanvas"></canvas>

Body:
Just reset the x value when it drops below zero.

if (star.x < 0) star.x = canvasWidth;

I've made a few other changes, compare.

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function StarField(ctx, numStars, width, height) {
  var stars = new Array(numStars).fill(null).map(getStar);

  function getStar() {
    var z = getRandomInt(0, 5),
      c = (256 / z).toString(16);
    return {
      x: getRandomInt(0, width),
      y: getRandomInt(0, height),
      z: z * 2,
      v: 6 - z,
      c: "#" + c + c + c
    };
  }

  this.animate = function () {
    var i, s;

    ctx.fillStyle = "#000000";
    ctx.fillRect(0, 0, width, height);

    for (i = 0; i < numStars; i++) {
      s = stars[i];
      ctx.fillStyle = s.c;
      ctx.fillRect(s.x, s.y, 2, 2);
      s.x -= s.v;
      if (s.x < 0) s.x = width;
    }
    setTimeout(this.animate.bind(this), 32);
  };
}

var canvas = document.getElementById("myCanvas");
var s = new StarField(canvas.getContext("2d"), 2000, 500, 500);
s.animate();

<canvas id="myCanvas"></canvas>


问:
Retrieving single value from Firebase child in Android
I am creating an application in which I store a value named carid in Firebase. Here's my JSON:

```<code>user{  "carid" : 1,
  "emailID" : "please@gmail.com",
  "imgurl" : "xyz",
  "mobileNumber" : "8308717177",
  "pass" : "sai3"
}
</code>```

I want to get only carid in Android app.
Appreciate any help. Thanks!

答:
Are you using the database in firebase?

If yes,
you better read the Documentation here:
Read and Write Data on Android

```<code>private DatabaseReference mDatabase;

mDatabase = FirebaseDatabase.getInstance().getReference();

ValueEventListener postListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        int carid = dataSnapshot.child("user").child("carid").getValue(Integer.class);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        // Getting Post failed, log a message
    }
};
mPostReference.addValueEventListener(postListener);
</code>```

P.S.

You can use addValueEventListener (active) or addListenerForSingleValueEvent (once).
And I am taking the snapshot of the hold database.
If you only need the data of carid,
you can get only the value of carid by this:

```<code>Databasereference ref_carid = mDatabase.child("user").child("carid");
</code>```

Body:
I am creating an application in which I store a value named carid in Firebase. Here's my JSON:

user{  "carid" : 1,
  "emailID" : "please@gmail.com",
  "imgurl" : "xyz",
  "mobileNumber" : "8308717177",
  "pass" : "sai3"
}

I want to get only carid in Android app.
Appreciate any help. Thanks!

Body:
Are you using the database in firebase?

If yes,
you better read the Documentation here:
Read and Write Data on Android

private DatabaseReference mDatabase;

mDatabase = FirebaseDatabase.getInstance().getReference();

ValueEventListener postListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        int carid = dataSnapshot.child("user").child("carid").getValue(Integer.class);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        // Getting Post failed, log a message
    }
};
mPostReference.addValueEventListener(postListener);

P.S.

You can use addValueEventListener (active) or addListenerForSingleValueEvent (once).
And I am taking the snapshot of the hold database.
If you only need the data of carid,
you can get only the value of carid by this:

Databasereference ref_carid = mDatabase.child("user").child("carid");


问:
Add toolbar in certain fragment
I have a main activity:

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</code>```

This activity just has a framelayout and uses this layout to add, replace, and delete fragments.

I have 2 fragments:

LoginFragment  (constraintLayout)

```<code><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#4CF">

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Go to Register"
    android:layout_marginLeft="8dp"
    app:layout_constraintLeft_toLeftOf="parent"
    android:layout_marginRight="8dp"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    android:layout_marginBottom="8dp"
    app:layout_constraintVertical_bias="0.500" />
</code>```

RegisterFragment  (constraintLayout)

```<code><android.support.v7.widget.Toolbar
    android:id="@+id/my_toolbar"
    android:layout_width="0dp"
    android:layout_height="56dp"
    android:background="?attr/colorPrimary"
    android:elevation="4dp"
    android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    tools:layout_editor_absoluteY="1dp"
    android:layout_marginLeft="8dp"
    app:layout_constraintLeft_toLeftOf="parent"
    android:layout_marginRight="8dp"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp" />

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Welcome to the Register fragment"
    tools:layout_editor_absoluteY="205dp"
    tools:layout_editor_absoluteX="62dp" />
</code>```

The login fragment shows up first. This should have no actionbar. There is a button in this fragment which will replace this login fragment with the register fragment. In this fragment I want the actionbar to show up so that it can have the back arrow in the actionbar to go back to the login view. I have no idea though where to place the toolbar widget in the code? I have tried to set it in the register fragment, but it kept displaying oddly.

答:
just make Layout

toolbar.xml

```<code><android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorAccent"
    android:elevation="3dp"
    android:minHeight="?attr/actionBarSize"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
</code>```

wherever u need toolbar just include the Layout like

```<code><include layout="@layout/toolbar.xml">
</code>```

Title: Add toolbar in certain fragment

Body:
I have a main activity:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

This activity just has a framelayout and uses this layout to add, replace, and delete fragments.

I have 2 fragments:

LoginFragment  (constraintLayout)

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#4CF">

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Go to Register"
    android:layout_marginLeft="8dp"
    app:layout_constraintLeft_toLeftOf="parent"
    android:layout_marginRight="8dp"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    android:layout_marginBottom="8dp"
    app:layout_constraintVertical_bias="0.500" />

RegisterFragment  (constraintLayout)

<android.support.v7.widget.Toolbar
    android:id="@+id/my_toolbar"
    android:layout_width="0dp"
    android:layout_height="56dp"
    android:background="?attr/colorPrimary"
    android:elevation="4dp"
    android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    tools:layout_editor_absoluteY="1dp"
    android:layout_marginLeft="8dp"
    app:layout_constraintLeft_toLeftOf="parent"
    android:layout_marginRight="8dp"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp" />

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Welcome to the Register fragment"
    tools:layout_editor_absoluteY="205dp"
    tools:layout_editor_absoluteX="62dp" />

The login fragment shows up first. This should have no actionbar. There is a button in this fragment which will replace this login fragment with the register fragment. In this fragment I want the actionbar to show up so that it can have the back arrow in the actionbar to go back to the login view. I have no idea though where to place the toolbar widget in the code? I have tried to set it in the register fragment, but it kept displaying oddly.

Body:
just make Layout

toolbar.xml

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorAccent"
    android:elevation="3dp"
    android:minHeight="?attr/actionBarSize"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

wherever u need toolbar just include the Layout like

<include layout="@layout/toolbar.xml">


问:
onreadystatechange in a loop, readystate changes too late
I issue in a loop a total of eight xmlhttprequests to a Google map server and process the json objects the server returns to retrieve the zip codes. The code works fine if the xmlhttprequests are synchronous. Since I'm supposed to use asynchronous requests, I'm trying to convert the code to asynchronous. It doesn't work.

I use two alerts to monitor myZip. When the code is run, the second alert, right above the return, runs eight times and shows myZip as null or undefined and that is what is returned. Then the first alert runs eight times and gives the desired zip code, too late, unfortunately. It seems to me the readystate doesn't change until too late.

How should I modify the code so it will return the zip code, not null? Any help will be greatly appreciated.

```<code>var url = "http://maps.googleapis.com/maps/api/geocode/json?address="+address+city+state+"&sensor=false";

req.open("GET", url,true);

var myZip;

req.onreadystatechange = function()
{
        if(req.readyState == 4 && req.status == 200) {
        (function(data){
            var myObj = eval( '(' + data + ')' );
            if(myObj.status=="OK"){
                  for(i=0; i <myObj.results[0].address_components.length; i++){
                  if(myObj.results[0].address_components[i].types=="postal_code"){
                  myZip=myObj.results[0].address_components[i].long_name;
                  alert('zip is '+myZip);
                  }
               }
            }
            else
            {
            alert("Error: returned status code "+req.status+" "+req.statusText);
            }
        })(req.responseText);
    }
}
req.send();
alert(myZip);
return myZip;
</code>```

答:
I guess you use the same object(req) a couple of times and will be overwritten on each loop.

So use separate objects for every requests or start a new request if the last one is finished.

How exactly you can do this  I cannot say without knowing what req is.

Body:
I issue in a loop a total of eight xmlhttprequests to a Google map server and process the json objects the server returns to retrieve the zip codes. The code works fine if the xmlhttprequests are synchronous. Since I'm supposed to use asynchronous requests, I'm trying to convert the code to asynchronous. It doesn't work.

I use two alerts to monitor myZip. When the code is run, the second alert, right above the return, runs eight times and shows myZip as null or undefined and that is what is returned. Then the first alert runs eight times and gives the desired zip code, too late, unfortunately. It seems to me the readystate doesn't change until too late.

How should I modify the code so it will return the zip code, not null? Any help will be greatly appreciated.

var url = "http://maps.googleapis.com/maps/api/geocode/json?address="+address+city+state+"&sensor=false";

req.open("GET", url,true);

var myZip;

req.onreadystatechange = function()
{
        if(req.readyState == 4 && req.status == 200) {
        (function(data){
            var myObj = eval( '(' + data + ')' );
            if(myObj.status=="OK"){
                  for(i=0; i <myObj.results[0].address_components.length; i++){
                  if(myObj.results[0].address_components[i].types=="postal_code"){
                  myZip=myObj.results[0].address_components[i].long_name;
                  alert('zip is '+myZip);
                  }
               }
            }
            else
            {
            alert("Error: returned status code "+req.status+" "+req.statusText);
            }
        })(req.responseText);
    }
}
req.send();
alert(myZip);
return myZip;


问:
How would you print out the data in a binary tree, level by level, starting at the top?
This is an interview question

I think of a solution.
It uses queue.

```<code>public Void BFS()
{
   Queue q = new Queue();
   q.Enqueue(root);
   Console.WriteLine(root.Value);

   while (q.count > 0)
   {
      Node n = q.DeQueue();
      if (n.left !=null)
       {
          Console.Writeln(n.left);
          q.EnQueue(n.left);
        }
       if (n.right !=null)
       {
          Console.Writeln(n.right);
          q.EnQueue(n.right);
        }
    }
}
</code>```

Can anything think of better solution than this, which doesn't  use Queue?

答:
Of course you don't need to use queue. This is in python.</p>

```<code># Function to  print level order traversal of tree
def printLevelOrder(root):
    h = height(root)
    for i in range(1, h+1):
        printGivenLevel(root, i)

# Print nodes at a given level
def printGivenLevel(root , level):
    if root is None:
        return
    if level == 1:
        print "%d" %(root.data),
    elif level > 1 :
        printGivenLevel(root.left , level-1)
        printGivenLevel(root.right , level-1)

""" Compute the height of a tree--the number of nodes
    along the longest path from the root node down to
    the farthest leaf node
"""
def height(node):
    if node is None:
        return 0
    else :
        # Compute the height of each subtree
        lheight = height(node.left)
        rheight = height(node.right)
        return max(lheight, reight)
</code>```

Body:
This is an interview question

I think of a solution.
It uses queue.

public Void BFS()
{
   Queue q = new Queue();
   q.Enqueue(root);
   Console.WriteLine(root.Value);

   while (q.count > 0)
   {
      Node n = q.DeQueue();
      if (n.left !=null)
       {
          Console.Writeln(n.left);
          q.EnQueue(n.left);
        }
       if (n.right !=null)
       {
          Console.Writeln(n.right);
          q.EnQueue(n.right);
        }
    }
}

Can anything think of better solution than this, which doesn't  use Queue?

Body:
Of course you don't need to use queue. This is in python.

# Function to  print level order traversal of tree
def printLevelOrder(root):
    h = height(root)
    for i in range(1, h+1):
        printGivenLevel(root, i)

# Print nodes at a given level
def printGivenLevel(root , level):
    if root is None:
        return
    if level == 1:
        print "%d" %(root.data),
    elif level > 1 :
        printGivenLevel(root.left , level-1)
        printGivenLevel(root.right , level-1)

""" Compute the height of a tree--the number of nodes
    along the longest path from the root node down to
    the farthest leaf node
"""
def height(node):
    if node is None:
        return 0
    else :
        # Compute the height of each subtree
        lheight = height(node.left)
        rheight = height(node.right)
        return max(lheight, reight)


问:
Caesar decrypt weird value?
I just learn about cryptography few week ago. I want to develop my tool to encrypt and decrypt Caesar cipher. But when I decrypt, it alway return weird value. Example: if I encrypt "my first tool crypto", it not return right decrypt "zl svefg gbby pelcgb", but "m_ fiXYZ ZUUl cX_VZU" with rotate 13 or another rotate I chose.</p>

```<code>string array1 = "zl svefg gbby pelcgb";
        int t2 = 0;
        foreach (char c in array1)
        {
            if ((int)c == 32 || ((int)c >= 48 && (int)c <= 57))
                t2 = c;
            else
                t2 = ((((int)c - 97) - 13) % 26) + 97;
            Console.Write((char)t2);
        }
</code>```

答:
The problem is that when you do subtraction you get negative values. The modulo operator will then give wrong results. You need to always add to the value.

The proper way to do it is:

```<code>t2 = ((((int)c - 97) - 13 + 26) % 26) + 97;
</code>```

This will make sure the values are always positive and the modulo works as you expect.

Title: Caesar decrypt weird value?

Body:
I just learn about cryptography few week ago. I want to develop my tool to encrypt and decrypt Caesar cipher. But when I decrypt, it alway return weird value. Example: if I encrypt "my first tool crypto", it not return right decrypt "zl svefg gbby pelcgb", but "m_ fiXYZ ZUUl cX_VZU" with rotate 13 or another rotate I chose.

string array1 = "zl svefg gbby pelcgb";
        int t2 = 0;
        foreach (char c in array1)
        {
            if ((int)c == 32 || ((int)c >= 48 && (int)c <= 57))
                t2 = c;
            else
                t2 = ((((int)c - 97) - 13) % 26) + 97;
            Console.Write((char)t2);
        }

Body:
The problem is that when you do subtraction you get negative values. The modulo operator will then give wrong results. You need to always add to the value.

The proper way to do it is:

t2 = ((((int)c - 97) - 13 + 26) % 26) + 97;

This will make sure the values are always positive and the modulo works as you expect.


问:
Compare the column values and update another column in Oracle
I have a scenario where we have first two entries for each test. Meaning for each test we have two entries, now I want to compare the test ranks and update the LoginID column in my table.

Sample data:

```<code>RANK | TestID | LoginID
-----+--------+---------
234     14       null
235     14       null
330     15       null
331     15       null
223     18       null
222     18       null
500     20       null
501     20       null
</code>```

In the above table, I have two entries for each testId, now I need to compare the RANK column of the corresponding TESTID rows, and update the LoginId column with 1 and 2.

Finally I am looking for output like follows:

```<code>RANK | TestID | LoginID
-----+--------+---------
234     14       1
235     14       2
330     15       1
331     15       2
223     18       2
222     18       1
500     20       1
501     20       2
</code>```

Can anyone suggest which is better way to achieve this? I tried with min() and max(), with Case (When /then) concept, but the query is not returning the expected results.

答:
Try this: </p>

```<code>UPDATE
 yourTable T,
 (
    SELECT
         TestID
        ,MIN( RANK) AS firstRank
        ,MAX( RANK) AS secondRank
    FROM
        yourTable
    GROUP BY
        TestID
) A
SET  RANK  =
    CASE WHEN RANK = A.firstRank  THEN  1
         WHEN RANK = A.secondRank THEN  2
         END
</code>```

Body:
I have a scenario where we have first two entries for each test. Meaning for each test we have two entries, now I want to compare the test ranks and update the LoginID column in my table.

Sample data:

RANK | TestID | LoginID
-----+--------+---------
234     14       null
235     14       null
330     15       null
331     15       null
223     18       null
222     18       null
500     20       null
501     20       null

In the above table, I have two entries for each testId, now I need to compare the RANK column of the corresponding TESTID rows, and update the LoginId column with 1 and 2.

Finally I am looking for output like follows:

RANK | TestID | LoginID
-----+--------+---------
234     14       1
235     14       2
330     15       1
331     15       2
223     18       2
222     18       1
500     20       1
501     20       2

Can anyone suggest which is better way to achieve this? I tried with min() and max(), with Case (When /then) concept, but the query is not returning the expected results.

Body:
Try this:

UPDATE
 yourTable T,
 (
    SELECT
         TestID
        ,MIN( RANK) AS firstRank
        ,MAX( RANK) AS secondRank
    FROM
        yourTable
    GROUP BY
        TestID
) A
SET  RANK  =
    CASE WHEN RANK = A.firstRank  THEN  1
         WHEN RANK = A.secondRank THEN  2
         END


问:
How to edit mail appearance in PHP?
I wonder how that can change the appearance of e-mail that comes to me via PHP?

This is a PHP code:

```<code><?php
$Ime = $_POST["Ime"];
$Prezime = $_POST["Prezime"];
$NaslovOglasa = $_POST["NaslovOglasa"];
$Email = $_POST["Email"];
$SadrzajOglasa = $_POST["SadrzajOglasa"];
$Kontakt = $_POST["Kontakt"];

if (isset($_POST['Istaknut_Oglas'])) {
$IstaknutOglas = "Da";
} else {
$IstaknutOglas = "Ne";
}

if (isset($_POST['Standardni_Paket'])) {
$StandardniPaket = "Da";
} else {
$StandardniPaket = "Ne";
}

$Za = "bratunac.info@gmail.com";
$Od  = "Od: " . $Email . "\r\n";
$Info .= "|NOVI OGLAS|" . "\r\n";
$Info .= "Ime: " . $Ime . "\r\n";
$Info .= "Prezime: " . $Prezime . "\r\n";
$Info .= "Naslov oglasa: " . $NaslovOglasa . "\r\n";
$Info .= "Sadrzaj oglasa: " . $SadrzajOglasa . "\r\n";
$Info .= "Kontakt informacije: " . $Kontakt . "\r\n";
$Info .= "Istaknut oglas: " . $IstaknutOglas . "\r\n";
$Info .= "Standardni paket: " . $StandardniPaket . "\r\n";
$Info .= "" . "\r\n";

if(isset($_FILES['file_array'])){
$name_array = $_FILES['file_array']['name'];
$tmp_name_array = $_FILES['file_array']['tmp_name'];
$type_array = $_FILES['file_array']['type'];
$size_array = $_FILES['file_array']['size'];
$error_array = $_FILES['file_array']['error'];
for($i = 1; $i < count($tmp_name_array); $i++){
    if(move_uploaded_file($tmp_name_array[$i], "adsuploads/".$name_array[$i])){
        $Info .= "Fotografija ".$i.": ".$name_array[$i]. "\r\n";
    }
}
mail($Za, $Od, $Info);
header("Location: http://bratunacinfo.000webhostapp.com/pages/postavi_oglas-3");
}
?>
</code>```

I wonder if this can be done via php me or I need some framework

答:
You can send your email as an HTML email. For example:

```<code><?php
    $to = "someone@somedoamin.com";
    $subject = "Some email title";
    $content = "
    <html>
        <head>
            <title>HTML email</title>
        </head>
        <body>
            <p>This email contains HTML Tags!</p>
            <table>
                <tr>
                    <th>Firstname</th>
                    <th>Lastname</th>
                </tr>
                <tr>
                    <td>John</td>
                    <td>Doe</td>
                </tr>
            </table>
        </body>
    </html>
    ";

    $headers = "MIME-Version: 1.0\r\nContent-type:text/html;charset=UTF-8\r\n";
    mail($to, $subject, $content, $headers);
?>
</code>```

For more information you can visit this.

Title: How to edit mail appearance in PHP?

Body:
I wonder how that can change the appearance of e-mail that comes to me via PHP?

This is a PHP code:

<?php
$Ime = $_POST["Ime"];
$Prezime = $_POST["Prezime"];
$NaslovOglasa = $_POST["NaslovOglasa"];
$Email = $_POST["Email"];
$SadrzajOglasa = $_POST["SadrzajOglasa"];
$Kontakt = $_POST["Kontakt"];

if (isset($_POST['Istaknut_Oglas'])) {
$IstaknutOglas = "Da";
} else {
$IstaknutOglas = "Ne";
}

if (isset($_POST['Standardni_Paket'])) {
$StandardniPaket = "Da";
} else {
$StandardniPaket = "Ne";
}

$Za = "bratunac.info@gmail.com";
$Od  = "Od: " . $Email . "\r\n";
$Info .= "|NOVI OGLAS|" . "\r\n";
$Info .= "Ime: " . $Ime . "\r\n";
$Info .= "Prezime: " . $Prezime . "\r\n";
$Info .= "Naslov oglasa: " . $NaslovOglasa . "\r\n";
$Info .= "Sadrzaj oglasa: " . $SadrzajOglasa . "\r\n";
$Info .= "Kontakt informacije: " . $Kontakt . "\r\n";
$Info .= "Istaknut oglas: " . $IstaknutOglas . "\r\n";
$Info .= "Standardni paket: " . $StandardniPaket . "\r\n";
$Info .= "" . "\r\n";

if(isset($_FILES['file_array'])){
$name_array = $_FILES['file_array']['name'];
$tmp_name_array = $_FILES['file_array']['tmp_name'];
$type_array = $_FILES['file_array']['type'];
$size_array = $_FILES['file_array']['size'];
$error_array = $_FILES['file_array']['error'];
for($i = 1; $i < count($tmp_name_array); $i++){
    if(move_uploaded_file($tmp_name_array[$i], "adsuploads/".$name_array[$i])){
        $Info .= "Fotografija ".$i.": ".$name_array[$i]. "\r\n";
    }
}
mail($Za, $Od, $Info);
header("Location: http://bratunacinfo.000webhostapp.com/pages/postavi_oglas-3");
}
?>

I wonder if this can be done via php me or I need some framework

Body:
You can send your email as an HTML email. For example:

<?php
    $to = "someone@somedoamin.com";
    $subject = "Some email title";
    $content = "
    <html>
        <head>
            <title>HTML email</title>
        </head>
        <body>
            <p>This email contains HTML Tags!</p>
            <table>
                <tr>
                    <th>Firstname</th>
                    <th>Lastname</th>
                </tr>
                <tr>
                    <td>John</td>
                    <td>Doe</td>
                </tr>
            </table>
        </body>
    </html>
    ";

    $headers = "MIME-Version: 1.0\r\nContent-type:text/html;charset=UTF-8\r\n";
    mail($to, $subject, $content, $headers);
?>

For more information you can visit this.


问:
store procedures in parameter php error
I have two store procedures, nearly identical, the only difference being that the second one has a in param.

The sp without the param works fine generates a empty table. I have tested the store procedure on my localhost server, so there is nothing wrong with store procedure as such.

I have also corrected some code where I was mixing procedural and oop coding in mysqli. Thanks to "gmc" I rectified that.
This is my code:

```<code>    //sp

//This store proc without in params is working
echo "<h4>Författartabellen hämtad från databasen med en store procedure</h4>";
  $result_sp = mysqli_query($conn, "CALL jokes");

  //loop the result set
 echo "<table><tr><th>Joke</th><th>AuthorName</th></tr>";
    // output data of each row
    while($row = mysqli_fetch_assoc($result_sp)) {
        echo "<tr><td>".$row["joketext"]."</td><td>".$row["name"]."</td></tr>";
    }
    echo "</table>";

// This store proc with in param is not working, returns a empty table
//run the store proc
echo "<h4>Författartabellen hämtad från databasen med en store procedure</h4>";
  $result_sp_in = mysqli_query($conn, 'CALL jokes_author("Joan Smith")');

  //loop the result set
 echo "<table><tr><th>Joke</th><th>AuthorName</th></tr>";
    // output data of each row
    while($row = mysqli_fetch_array($result_sp_in)) {
        echo "<tr><td>".$row["joketext"]."</td><td>".$row["name"]."</td></tr>";
    }
    echo "</table>";
</code>```

Thanks

答:
Update: try this:

```<code>$result_sp_in = mysqli_query($mysqli, 'CALL jokes_author("Joan Smith", @joketext, @name)');
$select = mysqli_query($mysqli, 'SELECT @joketext, @name');
while($row = mysqli_fetch_array($select)) {
    echo "<tr><td>".$row["joketext"]."</td><td>".$row["name"]."</td></tr>";
}
echo "</table>";
</code>```

Title: store procedures in parameter php error

Body:
I have two store procedures, nearly identical, the only difference being that the second one has a in param.

The sp without the param works fine generates a empty table. I have tested the store procedure on my localhost server, so there is nothing wrong with store procedure as such.

I have also corrected some code where I was mixing procedural and oop coding in mysqli. Thanks to "gmc" I rectified that.
This is my code:

    //sp

//This store proc without in params is working
echo "
Författartabellen hämtad från databasen med en store procedure
";
  $result_sp = mysqli_query($conn, "CALL jokes");

  //loop the result set
 echo "

Joke	AuthorName
";
    // output data of each row
    while($row = mysqli_fetch_assoc($result_sp)) {
        echo "
".$row["joketext"]."	".$row["name"]."
";
    }
    echo "
";

// This store proc with in param is not working, returns a empty table
//run the store proc
echo "
Författartabellen hämtad från databasen med en store procedure
";
  $result_sp_in = mysqli_query($conn, 'CALL jokes_author("Joan Smith")');

  //loop the result set
 echo "

Joke	AuthorName
";
    // output data of each row
    while($row = mysqli_fetch_array($result_sp_in)) {
        echo "
".$row["joketext"]."	".$row["name"]."
";
    }
    echo "
";

Thanks

Body:
Update: try this:

$result_sp_in = mysqli_query($mysqli, 'CALL jokes_author("Joan Smith", @joketext, @name)');
$select = mysqli_query($mysqli, 'SELECT @joketext, @name');
while($row = mysqli_fetch_array($select)) {
    echo "<tr><td>".$row["joketext"]."</td><td>".$row["name"]."</td></tr>";
}
echo "</table>";


问:
Cannot add into an already initialized array
```<code>document.getElementById('form').addEventListener('submit', saveItem);
function saveItem(e){
var items= document.getElementById('items').value;
var date= document.getElementById('date').value;
var price= document.getElementById('price').value;
var expense= {
    items: items,
    date: date,
    price: price
}

if(localStorage.getItem('bill')==null){
var bill=[];
 bill.push(expense);
 localStorage.setItem('bill', JSON.stringify(expense));

} else{

var bill = JSON.parse(localStorage.getItem('bill'));

bill.push(expense);
localStorage.setItem('bill', JSON.stringify(expense));
console.log(bill);

}
e.preventDefault();
}
</code>```

there is no error if

```<code>if(localStorage.getItem('bill')==null)
</code>```

but there comes error at else as

```<code> Uncaught TypeError: Cannot read property 'push' of undefined
  at HTMLFormElement.saveItem
</code>```

the data is stored when the local storage is empty but cannot add data if it is not.

答: Can you please check what is the result of JSON.parse(localStorage.getItem('bill'));? Is its a valid array?

Body:
document.getElementById('form').addEventListener('submit', saveItem);
function saveItem(e){
var items= document.getElementById('items').value;
var date= document.getElementById('date').value;
var price= document.getElementById('price').value;
var expense= {
    items: items,
    date: date,
    price: price
}

if(localStorage.getItem('bill')==null){
var bill=[];
 bill.push(expense);
 localStorage.setItem('bill', JSON.stringify(expense));

} else{

var bill = JSON.parse(localStorage.getItem('bill'));

bill.push(expense);
localStorage.setItem('bill', JSON.stringify(expense));
console.log(bill);

}
e.preventDefault();
}

there is no error if

if(localStorage.getItem('bill')==null)

but there comes error at else as

 Uncaught TypeError: Cannot read property 'push' of undefined
  at HTMLFormElement.saveItem

the data is stored when the local storage is empty but cannot add data if it is not.