Ideas on how to concentrate/not get lost when listening to a song for transcription/understanding purposes

Question: I am learning to listen analytically to music (listening to try and figure out what is going on) but I tend to get lost in the music quite easily.
For example, when I start counting in my head, at some point I'll lose track (I try to count the beats and sometimes also try and count the bars and phrase lengths). I'm also trying to figure out the chords and rhythms.
I'm probably trying to do too much at once and that is the problem. But I also tend to have distracting thoughts (such as what time it is, what I have to do tomorrow, etc... you know, useless stuff that modern society forces on us).
If there isn't a good answer (since it is probably pretty vague), what is the best thing to work on first? Counting so much that it becomes innate, which would then make learning all the rest of the stuff easier? (since you then know where everything is at)
Also, is counting bars useful? I tend to think that counting them might be a bad idea, because if I get out of sync then I have to start the song over to make sure I don't associate wrong numbers with specifics in a song (e.g., chorus starts at bar 37 but I counted it wrong at 38... Then I think the chorus is at bar 38 and next time I count I get confused because I'm unsure of myself). Or are these mistakes just part of learning?
Comment: The problem with saying that knowing/learning something like that can't hurt is that it *can* hurt if it distracts you from using more relevant skills and wastes the time you could spend doing more fun and educational things. Always having the bar number right on the tip of your tongue is a skill only used by a subset of musicians, and even then, they'd usually be referring to a score in situations where they needed to do that. Honestly, the people I know who focus too much on counting seem to be the ones who end up most frustrated with their music!
Comment: I'm struggling a little to reconcile what you are saying in these comments with what you said in the original question - e.g. *chorus starts at bar 37 but I counted it wrong at 38*. Maybe you were exaggerating there about actually having those kinds of problems? If not, then it does seem to me that a focus on linear counting - rather than having a higher-level view of, and feel for, a song's structure - seems to be already causing you problems.
Comment: When it comes to the 'concentration' part - what's your motivation for wanting to do these particular exercises/transcriptions? I didn't think actual numeric counting of bars was a particularly useful skill for most musicians, but I could be wrong.
Comment: @topomorto There are several reasons: Be better equipped to know where I'm at in the song. e.g., say I have a problem with a bar of music. If I can know exactly what bar number it is then it can't hurt, right? Also, if I'm transcribing, then knowing the bars seem like it can't hurt? The main thing is, if I knew the bar number "magically" it seems like I would be a better musician, no? I tend to lose concentration very easily and knowing where I'm at is a big deal(helps me feel the music and play more confidently). I am getting better counting though but still sometimes lose track...
Comment: @topomorto Well, remember that everyone is different. I feel like I have no problem creating music now. It flows more or less immediately, when I want(I have no creative block in music, for the most part). Not saying it's all good but I don't struggle with that like I used to. My biggest problem is essentially memorization. I find it very difficult to learn songs. It always has been a problem. I have noticed the more I know about where things occur in the song time wise, the better I seem to be able to remember it, I think because I have a lack of solid time feel.
Comment: It seems the more I get "time" under my belt the better things fall in to place for me. I'm not a detail oriented person, at least when it comes to music. I get tripped up on little things and if I don't know why things don't sound right, I get confused and it affects my performance. When I know exactly what to do, I play music, when I don't I make noise.  So, I do not know if it is a good tool to have, and maybe it is a waste of time, but it also might be one more stepping stone that helps me improve.
Comment: Don't take this the wrong way, but basically "Everyone else do X" is not a good reason not to do X. Most "musicians" can't read, do you think that is a good thing or that it will hurt them if they learn simply because most don't do read? (It's sort of circular reasoning) Also, For those that do count bars and are not good musicians does not mean that it's because they count. There are people that don't count and also are not good. Now, if you know precisely why counting bars is bad, such as a physiological reason, then that is different.
Comment: Certainly I don't know you well, so I'm just responding to your words here. If you've found that having an 'indexed linear' structure to a piece in your mind helps you, I'm not going to claim it won't, though I do think it's quite unusual (depending on what kind of music you are studying, maybe?). I guess that for most people it's neither good to slavishly follow what others do, nor to be totally unaware of what common practice is - I wonder if it might be worth taking a step back, think why you're focusing on counting so much, and then ask a question here as to what others do to achieve that.
Comment: *Everyone else do X is not a good reason not to do X* - I think here, I'm agreeing with that! I'm saying that it sounds to me that the way you are focusing *so much* on counting bars is, perhaps, not the usual way to go about memorising a piece.
Comment: @topomorto Well, I don't slavishly count bars in music! ;) I rarely count when I'm listening. I'm mainly going off my own analysis of my own issues and solutions. Obviously it would be nice to work with someone who truly understands the problems and solutions of those starting out... unfortunately I am self taught and also created many bad habits. But what I have noticed is that counting, has much as I have hated it, has helped me tremendously in not only understanding music(hearing things correctly) but in just other areas(sight reading, improvising, composing, transcribing, etc).
Comment: I agree that bar counting is not a solution in and of it self. But I do see it as a skill, and, depending on the cost(time invested), it may or may not be worth it. Since I'm having to count beats anyways, is it really that much more work? (difference between 1 2 3 4 vs n 2 3 4) ... And surely it will become second nature after a point and not cause problems?
Answer: As far as the distracting thoughts, it happens to a lot of people. It happens to me as well. One way that has helped me concentrate is to have some to tell me to. Let's say I am at my lesson with my teacher and he sees that I am getting a bit distracted, he will tell me to focus. This is something that has helped me and now I don't get that much distracted.

what is the best thing to work on first?

Well, for starters you can start counting the beats of the time signature. Then you can start counting bars and see how many bars each section has. For instance, the intro has 12, the main chorus 24 etc. This will be easier rather than saying 'bridge is on bar 342' or something.

is counting bars useful? I tend to think that counting them might be a bad idea

I wouldn't call it a bad idea, but it isn't something I do very often. It is good to be able to count bars, but don't get hang up on it.
And of course all these mistakes, like getting one or two bars wrong and getting distracted and getting mixed up are part of your learning. With practice you'll be able to get it without all these.
Comment: Ok, I'll just keep practicing. It's been working as I'm way better at doing it then I was in the past and I'm not as lost as I used to be. I try to count sections too. But I guess trying to do it all at once and also feel the music was just too much for my brain at first(not being very good anyways). At least practicing correctly(on the right stuff) seems to help. Thanks.
Answer: As Shev. says, counting bars isn't that helpful, or something done a lot (unless you're percussionist in an orchestra...) but a good move is to actually write stuff down as you listen. Once the metre thus time sig. has been established, make some boxes on paper, usually 4 per line works, and put in maybe the word or chord or thing that happens, say, at the start of each line. Maybe a word sung, a cymbal crash, etc. If the timing is 4/4, then count each box - which equates to each bar- so you know when the next 'event' comes. Mark that in, too. Leave a space (paragraph) where the verse and chorus, maybe, are separated. Like most things, the more you do, the better it gets, hopefully.
EDIT: you ask if counting bars is useful. As above, but it will depend an awful lot on what kind of music you're trying to analyse. If it's pop songs, there is little point, as one verse is very similar to another, and also the same with the chorus. Words may differ, but structure and length are pretty constant. If it's a serious classical piece, then it's very different, although knowing that a particular bar is bar 38 will only really be of use when you are playing it with the rest of the orchestra. It would be good for you to mix with other musos, and discuss all this with them. Failing that have a session with a teacher, who will probably reiterate all that's been said here.
Comment: yeah, I'm learning how to do all that stuff... Just never realized I should do it or that people did this sort of analysis of music. I always thought it was just a "feel" thing and I found it very hard to do by feel(since I would tend to feel things my own way and it would cause problems here and there).
Answer: I vote up what Shevliaskovic says counting the  beats that the first that you need to be proficient. Then maybe bar numbers. But for bars to know where something comes in, you have the score or get the score and teach yourself where everything comes in or goes out. That's my experience.
Comment: Well, I don't always have the score. In some cases it is to notate the score or to know a bar that I have trouble with. I lose focus so easily at times that I forget where I'm at in the song. I'm realizing it's just all practice... The more I do it the more these problems go away, of course one should practice things in the correct order. (seems counting is necessary for transcribing... I tried to do it the reverse way and was so painfully slow that I couldn't get anywhere... was also very inaccurate). I'm a relative noob on so many musical fronts that I'm trying to focus on all my weakness.
Comment: I'm in the same boat with you. So you should make your priorities clear. What you could make yourself easier try and do that. There is sooo much to learn. If you get the score it will make it easier for you to remember. So you could relegate you energy to more important things.
Comment: Yeah, I have started to use the scores. They help tremendously. I have found that when I forget stuff or even when I'm just cruising along, I can sometimes visualize the score on some level and it helps me not get in to trouble like I would before I started reading scores. I still have a while to go to actually get good at it, but it's a great skill to have.


Beautiful Soup web scraping with CSS selectors

Question: I'm trying to scrape 11 fields from a standard SEC filing on EDGAR (SEC.gov) and return them to a simple dictionary. When I run the code below, 7 of the fields work fine, but 4 of the fields (named in the code as "Director", "Officer", "Person", and "Ticker") return an empty list value in spite of showing actual text in these fields on the page and I cannot figure out how to resolve. I obtained the CSS selector info for these fields using DevTools in Chrome and viewing the Elements tab while on the page I'm trying to scrape. One thing to note is that these 4 fields have longer CSS selectors than the ones that work correctly (i.e. the "tree" describing the location on the page is longer than the others) so I feel there must be something I'm doing wrong syntax-wise in pointing to these 4 fields.
As a side note I'm new to Python, and early in the process of working on this I learned that with Beautiful Soup the CSS selector references must use "nth-of-type" instead of "nth-child", so I've already made those changes to my code.
I'm at a loss as to why these 4 fields won't return the data shown on the form, while the other 7 work fine. Any help or guidance would be much appreciated!
Note: I'm using Python 3.
import bs4, requests, pprint

def getFormData(form4url):
    res = requests.get(form4url)
    res.raise_for_status()

    soup = bs4.BeautifulSoup(res.text, 'html.parser')

    # scrape the data from each field of the SEC Form 4 document. Each field is identified by its
    # CSS selector from the web page's html (viewed using DevTools -> Elements tab in Chrome)
    person = soup.select('body > table:nth-of-type(2) > tbody > tr:nth-of-type(1) > td:nth-of-type(1) > table:nth-of-type(2) > tbody > tr > td > a')
    ticker = soup.select('body > table:nth-of-type(2) > tbody > tr:nth-of-type(1) > td:nth-of-type(2) > span.FormData')
    director = soup.select('body > table:nth-of-type(2) > tbody > tr:nth-of-type(1) > td:nth-of-type(3) > table > tbody > tr:nth-of-type(1) > td:nth-of-type(1) > span')
    officer = soup.select('body > table:nth-of-type(2) > tbody > tr:nth-of-type(1) > td:nth-of-type(3) > table > tbody > tr:nth-of-type(2) > td:nth-of-type(1)')
    security = soup.select('body > table:nth-of-type(3) > tbody > tr:nth-of-type(1) > td:nth-of-type(1) > span')
    date = soup.select('body > table:nth-of-type(3) > tbody > tr:nth-of-type(1) > td:nth-of-type(2) > span')
    tCode = soup.select('body > table:nth-of-type(3) > tbody > tr:nth-of-type(1) > td:nth-of-type(4)')
    qtyTrans = soup.select('body > table:nth-of-type(3) > tbody > tr:nth-of-type(1) > td:nth-of-type(6) > span.FormData')
    transType = soup.select('body > table:nth-of-type(3) > tbody > tr:nth-of-type(1) > td:nth-of-type(7) > span')
    price = soup.select('body > table:nth-of-type(3) > tbody > tr:nth-of-type(1) > td:nth-of-type(8) > span.FormData')
    qtyAfter = soup.select('body > table:nth-of-type(3) > tbody > tr:nth-of-type(1) > td:nth-of-type(9) > span')

    return {'Person':person,'Ticker':ticker,'Director':director,'Officer':officer, \
            'Security':security,'Date':date, 'Trans Code':tCode, 'Quantity':qtyTrans, \
            'Trans Type':transType,'Price':price,'Qty After':qtyAfter}

# this is the website to scrape
userLink = 'https://www.sec.gov/Archives/edgar/data/1539638/000120919118040737/xslF345X03/doc4.xml'
dataDict = getFormData(userLink)

# following just cleans up values in dict by removing html from scraped fields (lists of
# strings), leaving only the visible text
for key,value in dataDict.items():
    if len(value) > 0:
        dataDict[key] = dataDict[key][0].text.strip()

pprint.pprint(dataDict)

Comment: Any recommendations on a more appropriate forum for me to post this question?
Answer: The correct CSS selectors for Person, Ticker, Director, and Officer are:
person: "table:nth-of-type(2) > tr > td > table"
ticker: "table:nth-of-type(2) > tr > td:nth-of-type(2) > span:nth-of-type(2)"
director: "table:nth-of-type(2) > tr > td:nth-of-type(3) > table > tr > td"
officer: "table:nth-of-type(2) > tr > td:nth-of-type(3) > table > tr:nth-of-type(2) > td"

Here is demo using Node.js, x-ray, and the example link you provided: https://codesandbox.io/s/j489wlyzmw
The demo doesn't return any value for Officer because Officer is not set.


Pushing an array in js doesn't look to work properly

Question: <code> $Flight = array
            (
            '1' => array
                (
                '5' => array
                    (
                    'LFID' => '6684',
                    'DepartureDate' => '2012-10-22T12:30:00',
                    'ArrivalDate' => '2012-10-22T14:00:00',
                    'BaseFareAmtInclTax' => '343.50',
                    'ReturnFlightSegmentDetails' =>
                    array
                        (
                        '87' => array
                            (
                            'LFID' => '6647',
                            'DepartureDate' => '2012-10-24T12:25:00',
                            'FareTypeName' => 'Change',
                            'FareTypeID' => '22',
                            'BaseFareAmtInclTax' => '198',
                        )
                    )
                ),
                '10' => array
                    (
                    'LFID' => '6684',
                    'DepartureDate' => '2012-10-23T12:30:00',
                    'ArrivalDate' => '2012-10-23T14:00:00',
                    'BaseFareAmtInclTax' => '243.50',
                    'ReturnFlightSegmentDetails' =>
                    array
                        (
                        '150' => array
                            (
                            'LFID' => '6647',
                            'DepartureDate' => '2012-10-24T12:25:00',
                            'FareTypeName' => 'Change',
                            'FareTypeID' => '22',
                            'BaseFareAmtInclTax' => '198',
                        ),
                        '153' => Array
                            (
                            'LFID' => '6647',
                            'DepartureDate' => '2012-10-26T12:25:00',
                            'FareTypeName' => 'Change',
                            'FareTypeID' => '22',
                            'BaseFareAmtInclTax' => '198',
                        )
                    )
                )
            ),
        );
</code>
I have this array from my controller which is passed to my twig where I execute the below code to parse it into a js array:
<code>{% for flight in flights%}
                   var $FlightSegment = new Array();
                  $flight.push({
                        key:"{{ flight.key }}",
                        DepartureDate:"{{flight.DepartureDate}}",
                        ArrivalDate:"{{flight.ArrivalDate}}",
                        Amount:"{{flight.BaseFareAmtInclTax}}",

                     });
                     {% for ReturnFlightSegmentDetails in flight.ReturnFlightSegmentDetails %}
                          $FlightSegment.push({
                                LFID :"{{ReturnFlightSegmentDetails.LFID}}",
                                DepartureDate:"{{ReturnFlightSegmentDetails.DepartureDate}}",
                                ArrivalDate:"{{ReturnFlightSegmentDetails.BaseFareAmtInclTax}}",
                                Class:"{{ReturnFlightSegmentDetails.FareTypeName}}",
                           });
                      {% endfor %}
                      console.info($FlightSegment);
                    $flight.push({
                        ReturnFlightSegmentDetails :$FlightSegment,
                    });
                {% endfor %}
</code>
The problem is that $flight.length returns 4 instead of 2, the ReturnFlightSegmentDetails is considered like an object instead to be an attribute for a flight.
Comment: Well you're pushing onto the list separately.
Comment: Also the suggestion to just let twig do this with `json_encode` seemed like a pretty good idea.
Comment: Sorry but i can't see where is m fault :/ i excecute the second push in the global for ! o.O' i ll sort the data so this is why i choosed to parse into in a js array because it will be easier i guess then to have a String with json_encode
Answer: You need to build the "flight" object differently; there's really no need for the "$FlightSegment" variable.
<code>{% for flight in flights%}
    $flight.push({
        key: "{{ flight.key }}",
        DepartureDate: "{{flight.DepartureDate}}",
        ArrivalDate: "{{flight.ArrivalDate}}",
        Amount: "{{flight.BaseFareAmtInclTax}}",
        ReturnFlighSegmentDetails: [
           {% for ReturnFlightSegmentDetails in flight.ReturnFlightSegmentDetails %}
             {
                LFID :"{{ReturnFlightSegmentDetails.LFID}}",
                DepartureDate:"{{ReturnFlightSegmentDetails.DepartureDate}}",
                ArrivalDate:"{{ReturnFlightSegmentDetails.BaseFareAmtInclTax}}",
                Class:"{{ReturnFlightSegmentDetails.FareTypeName}}"
              }
               {% if not loop.last } , {% endif }
           {% endfor %}
        ]
       });
 {% endfor %}
</code>
Comment: You made my day i'm so grateful thanks :) but i don't get this {% if not loop.last } , {% endif } what does it means?
Comment: @fbh it is there to add the necessary comma *between* the objects in that sub-array.  When you're on the last iteration, you don't want a comma because that would be a problem on old versions of IE.  The "loop" variable is a feature of twig `for` loops; it's automatically provided.


Calculate standard deviation when subtracting and dividing means

Question: I have a series of independent uptake rate (u) measurements at different times (2h, 4h, 6h, 24h) (n=3) and want to find the difference between the mean values for each time with standard deviation. Then I want to see that value per hour.
For the means this is easy: (mean u (4h)-mean u(2h))/2 = mean u/h
(then the same for 6h-4h and so on)
I do not know how to make these calculations for the SD, I just know it is more complicated than this.
I would really appreciate some help as this is very important for my research, thank you!
Comment: I think in this case you are assuming mean is changing linearly with time, is your standard deviation also changing linearly with time?
Comment: No, my mean uptake rate is actually highest between 2 and 4h, after that it depends on the treatment, some have steep declines first, others more linear, some rise again. Very variable over all. The SD is not proportional to the mean in any way. Sometimes rather high, sometimes low.
Answer: Assume two measures $(A,B)$, $C$ is constant and that $Cov\left[A,B\right]=0$
$$\sigma_{\frac{A-B}{C}}=\sqrt{\left(\frac{\sigma_A}{C}\right)^{2}+\left(\frac{\sigma_B}{C}\right)^{2}} = \frac{1}{C}\sqrt{\sigma_{A}^{2}+\sigma_{B}^{2}}$$
In your case $(A,B)$ are the consecutive measures. $C$ is the time elapsed between the measures.
If you are interested check the derivation and sources in the Wiki article on Propagation of uncertainty.


Is $(\log n)^{\log \log n}$ polynomial-time?

Question: Is the following running time polynomial?
$$O((\log n)^{\log \log n})$$
How do I compare it with $O(n^k)$, where $k$ is a constant?
Definition: If an Algorithm running time $T(n)$ is polynomial time, then we can find a constant $C,k$, that $T(n)<Cn^k$.
Example: $2^{\sqrt{\log n}} <2^{\log n}<2^{k\log n}=2^{\log n^k}=n^k$, then $O(2^{\sqrt{\log n}})$ is polynomial time.
Comment: I think the definition should be that $T(n) < n^k$ for almost all $n$. Otherwise, $T(1) = 2$ would imply that $T$ is not polynomial. Another equivalent definition to what I said is that there are constants $C$, $k$ such that $T(n) < Cn^k$.
Comment: you are right, T(n)<Cn^k
Answer: $$(\log n) ^ {\log\log n} = e ^ {(\log \log n) ^ 2} = n ^ {\frac{(\log \log n) ^ 2}{\log n}} < n$$
for almost all $n$
Comment: @DiWang: $n=e^{\log n}$, therefore $e=n^\frac{1}{\log n}$.
Comment: I don't understand everything after the second '='
Answer: $\log (\log n^{\log\log n}) = (\log\log n)^2$ and $\log n^k =k\log n$ (where k>0).
On the other hand,
$$\lim_{n\rightarrow \infty} \frac{(\log\log n)^2}{k\log n} = \lim_{x\rightarrow \infty} \frac{\log^2 x}{kx} = 0,$$
using the L'Hospital rule twice. So $O(\log n^{\log\log n})<O(n^k)$, for any $k>0$.


Adding a new node to the end of a linked list in C

Question: I'm trying to add a new node to the end of a linked list in C, but I'm having trouble with my code.
here is what I tried
#include <stdio.h>
#include <stdlib.h>

struct node {
  int data;
  struct node *next;
};

struct node *head = NULL;

void add_node(int data) {
  struct node *new_node = malloc(sizeof(struct node));
  new_node->data = data;
  new_node->next = NULL;

  if (head == NULL) {
    head = new_node;
  } else {
    struct node *current = head;
    while (current->next != NULL) {
      current = current->next;
    }
    current->next = new_node;
  }

  int *x = NULL;
  *x = 5;
}

int main() {
  add_node(5);

  return 0;
}

However, when I try to run this code, I get a segmentation fault. Can someone help me figure out what's going wrong?
I've tried debugging the code by adding print statements, but I'm not sure where the problem is occurring. I've also tried double-checking that I've correctly allocated memory for the new node using malloc.
Comment: This code doesn't 'run'. there is no `main`, and nothing that calls `add_node`. Post a proper [mcve].
Comment: Really??? What's the point of the last two lines that you added in the edit, other than to create a segfault?
Comment: Not quite the same function in the reposted version... What's the business with `*x` doing?
Comment: OT: is the indent only 2 for any special reason. Code is much more readable with an indent of 4.
Comment: It works fine for me adding a couple of nodes (i.e. not reproducible).  Unrelated, I suggest you pass in the head instead of using a global variable.
Comment: sorry! I forgot to copy the whole code from editor.
Answer: In your updated code you deference the pointer x which you previously set to NULL.  Eliminate the junk code, or if you must you make x point at an integer:
int *x = &(int) {0};
*x = 5;

I suggest you eliminate the global variable along these lines:
#include <stdlib.h>

struct node {
    int data;
    struct node *next;
};

void add_node(struct node **head, int data) {
    struct node *new_node = malloc(sizeof(struct node));
    if(!new_node) {
       // handle error
       return;
    }
    new_node->data = data;
    new_node->next = NULL;
    if (!*head) {
        *head = new_node;
        return;
    }
    struct node *current = *head;
    for(;current->next; current = current->next);
    current->next = new_node;
}

int main() {
    struct node *head = NULL;
    add_node(&head, 5);
}

Comment: @Fe2O3 Likewise!


Adding two integers (range can be greater than long long int) in C

Question: I wrote the following code to add two integers greater than long long int but somehow it seems that it is entering in an infinite loop.
I am only moderately acquainted with the language so the code is a bit clumsy. It will be great if someone points out my mistake.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
    char a[127], c[127];
    char b[127], d[127];
    char result[127];
    int i, j, k, l1, l2, sum, carry;
    printf("\n\nenter 1st number\n\n");
    gets(a);
    printf("\n\nenter 2nd number\n\n");
    gets(b);
    l1 = strlen(a);
    l2 = strlen(b);
    //  for(i=0;i<=l1;i++)
    //      printf("%c",a[i]);
    j = l1;
    k = l2;
    /*for(i=l1;i>=0;i--)
    {
    c[j]=a[i];
    j--;
    }
    for(i=l2;i>=0;i--)
    {
    d[j]=b[i];
    j--;
    }*/
    printf("\n%d %d\n", j, k);
    if (l1>l2)
    {
        for (i = l1; i <= l2; i--)
        {
            c[i] = a[j];
            d[i] = b[k];
            j--;
            k--;
        }
        for (i = l2; i <= 0; i--)
        {
            c[i] = a[j];
            d[i] = 0;
            j--;
        }

    }
    //  printf("hello");
    j = l1;
    k = l2;
    if (l1<l2)
    {
        for (i = l2; i <= l1; i--)
        {
            c[i] = a[j];
            d[i] = b[k];
            j--;
            k--;
        }
        for (i = l1; i <= 0; i--)
        {
            c[i] = 0;
            d[i] = b[k];
            k--;
        }
    }
    j = l1;
    k = l2;
    if (l1 = l2)
    {
        for (i = l2; i <= 0; i--)
        {
            c[i] = a[j];
            d[i] = b[k];
            j--;
            k--;
        }
    }
    if (l1>l2)
    {
        for (i = l1; i <= 0; i--)
            printf("%c", c[i]);
    }

    if (l1>l2)
    {
        for (i = l1; i >= 0; i--)
        {
            if (i = l1)
                carry = 0;
            else
                /*if(i=l2)
                carry[i]=0;
                else
                carry[i]=sum[i]*/
                carry = sum / 10;
            sum = ((c[i] - '0') + (d[i] - '0')) + carry;
            //  if(i!=0)
            result[i] = sum % 10 + '0';
            //  else
            //      result[i]=sum[i];
        }
        //  for(i=l1-l2;i<=l1;i++)
        //      result[i]=c[i];
    }
    if (l1<l2)
    {
        for (i = l2; i >= 0; i--)
        {
            if (i = l2)
                carry = 0;
            else
                carry = sum / 10;
            sum = (c[i] - '0') + (d[i] - '0') + carry;
            //if(i!=0)
            result[i] = sum % 10 + '0';
            //  else
            //      result[i]=sum[i];
        }
        //      for(i=l2-l1;i<=l2;i++)
        //          result[i]=d[i];
    }
    if (l1 = l2)
    {
        for (i = l1; i >= 0; i--)
        {
            if (i = l1)
                carry = 0;
            else
                carry = sum / 10;
            sum = (c[i] - '0') + (d[i] - '0') + carry;
            if (i != 0)
                result[i] = sum % 10 + '0';
            else
                result[i] = sum + '0';
        }
    }
    printf("\n\nthe result is\n\n");
    if (l1 >= l2)
    {
        for (i = 0; i <= l1; i++)
            printf("%c", result[i]);
    }
    else
    {
        for (i = 0; i <= l2; i++)
            printf("%c", result[i]);
    }
    printf("\n\n");
    return 0;
}

Comment: I've fixed the indentation (will be visible when someone approves), but please do it properly from now on, it will greatly aid you in debugging your code. And **NEVER** use `gets`; `fgets` is your friend.
Comment: when u have a char array , actually number is not `c[i]` , it is `c[i]-'0'` ..
Answer: First off, you should never use gets because you cannot specify how many characters it should read; it may very well overflow your buffer. Instead, use fgets(buf, sizeof(buf), stdin).
The reason why your code is looping forever is all your ifs are wrong - you're using the assignment operator = instead of the comparison operator ==. = returns the assigned value, i.e. if (var = 0) always returns 0, which means the code inside that if will never be executed. When you fix all your if statements, you'll discover the next problem:


Splitting of an exact sequence

Question:
Let $(R,\mathfrak m)$ be a Noetherian local ring. Suppose that $x \in \mathfrak m \setminus \mathfrak m^2$.  Is it true that
  $$
\frac{\mathfrak m}{x\mathfrak m} \cong \frac{\mathfrak m}{(x)} \oplus \frac{(x)}{x\mathfrak m}?$$

There exists an exact sequence
$$
0 \rightarrow \frac{(x)}{x\mathfrak m} \rightarrow \frac{\mathfrak m}{x\mathfrak m} \rightarrow \frac{\mathfrak m}{(x)} \rightarrow 0$$
and the question becomes: Does this sequence split? If not, what is a counterexample?
Comment: Welcome to math.SE: I have tried to improve the readability of your question by fixing the LaTeX syntax in it.  It is possible that I unintentionally changed the meaning of your question. Please proofread the question to ensure this has not happened.
Comment: @ali1ghanbari: in *part of Theorem 2.2.8 of Bruns-Herzog they prove that *$I/(x)$ is a direct summand of $I/xI$*. maybe it help you.
Comment: @11156 thats can not help me.I dont understand relation between thats proof and my question?in thats proof uses similar notation but not exactly my question.thanks
Comment: At least when $R$ is regular without any modification the proof, which @11156 suggested, shows that your questions has an affirmative answer. Also, I believe the proof can be used to answer your question. One has the inclusion $J \cap (x) \subseteq xI$ when $I = m$.
Answer: In $\mathfrak m/\mathfrak m^2$ we have $\bar x\ne\bar 0$. Since $\mathfrak m/\mathfrak m^2$ is a finite dimensional $R/\mathfrak m$-vector space, there is a basis $\{\bar x,\bar x_1,\dots,\bar x_r\}$ in $\mathfrak m/\mathfrak m^2$. By NAK we have $\mathfrak m=(x,x_1,\dots,x_n)$.
Let $\mathfrak a=x\mathfrak m+(x_1,\dots,x_n)$.
Then $\mathfrak a+(x)=\mathfrak m$.
We also have $\mathfrak a\cap(x)=x\mathfrak m$. Let $y\in \mathfrak a\cap(x)$. Then $y=ax=a_0x+a_1x_1+\cdots+a_nx_n$ with $a_0\in \mathfrak m$, so $ax-(a_1x_1+\cdots+a_nx_n)=a_0x\in \mathfrak m^2$. It follows that $a\in \mathfrak m$ hence $y\in x\mathfrak m$.
We get $\dfrac{\mathfrak m}{x\mathfrak m}=\dfrac{\mathfrak a}{x\mathfrak m}+\dfrac{(x)}{x\mathfrak m}$, and $\dfrac{\mathfrak a}{x\mathfrak m}\cap\dfrac{(x)}{x\mathfrak m}=(0)$. This shows that $\dfrac{(x)}{x\mathfrak m}$ is a direct summand in $\dfrac{\mathfrak m}{x\mathfrak m}$.
Furthermore, $\dfrac{\mathfrak a}{x\mathfrak m}\simeq\dfrac{(x_1,\dots,x_n)}{x\mathfrak m\cap(x_1,\dots,x_n)}$. But $x\mathfrak m\cap(x_1,\dots,x_n)=(x)\cap(x_1,\dots,x_n)$, so $\dfrac{\mathfrak a}{x\mathfrak m}\simeq\dfrac{(x_1,\dots,x_n)}{(x)\cap(x_1,\dots,x_n)}\simeq\dfrac{\mathfrak m}{(x)}$.

Splitting of an exact sequence


Teams in North American leagues that won their first game ever?

Question: What teams, in the four major North American leagues (NHL, NBA, NFL, MLB), won their first ever game?
This includes both expansion franchises (e.g., Minnesota Wild) and relocations (e.g., Atlanta Thrashers -> Winnipeg Jets, Seattle SuperSonics -> Oklahoma City Thunder).
I take it is easier for recent additions or relocations, but it is somewhat harder to determine, for example, if the Ottawa Senators of the NHL won their first ever game, in 1917, the year the original team joined the NHL.
This is what I have figured out so far:
NBA

Vancouver Grizzlies (beat the Portland TrailBlazers 92-80 on Nov 3, 1995)
Toronto Raptors (beat the New Jersey Nets 94-79 on Nov 3, 1995)

NHL

Colorado Avalanche (beat the Detroit Red Wings 3-2 on Oct 6, 1995)
Atlanta Flames (beat the NY Islanders 3-2 on Oct 7, 1972)
Dallas Stars (beat the Detroit Red Wings 6-4 on Oct 5, 1993)

MLB

Montreal Expos (beat the NY Mets 11-10 on Apr 8, 1969)

NFL

Houston Texans (beat the Dallas Cowboys 19-10 on Sep 8, 2002)
Comment: As with other list type questions, this is a bad fit for Stack Exchange's Q&A format.
Comment: The trouble with list type questions is that there isn't going to be one, or even a few, good answers to the question, so they don't fit well into Stack Exchange's Q&A format. The answer you received on this question demonstrates this pretty well: when another 10 people find instances, they add their own answer. Now we've got ten answers, none of which are really any better than the other. A good SE answer should stand alone, without needing reference to other answers, and experience has shown that doesn't happen for list-type questions.
Comment: I don't see how a question like this can be "too broad" or even "off topic". I've added as many details I could.
Answer: If you can count their first appearance being an exhibition game, the Orlando Magic won their first ever appearance against the Detroit Pistons in 1989.


Can we pass a string( "emp id") as path variable to the controller in Spring?

Question: I am writing an controller for one of spring based applications. I was extensively using path variable but I have few scenarios where I have stringswhich has spaces for example "bike racing" and I also have &
Answer: I think for doing that you need to define a regular expression on your request mapping, something like this:
<code>@RequestMapping("/home/{test:[a-zA-Z &+-]*}")
public ModelAndView getTest(@PathVariable("test") String test) {
    ModelAndView model = new ModelAndView();
    model.setViewName("/test/teste");
    model.addObject("label_title", test);

    return model;
}
</code>
And then you will have your strings correctly:

I hope I have helped you!
Comment: Thanks that's helpful.


Making a Portfolio on Visual Studio Code

Question: Hello I am attempting to create a Portfolio using HTML, CSS, and Javascript. My only previous experience is making a basic website with standard text and a light\dark theme button. I am trying to get my Title the be on the left of my navigation bar, and my directories to be on the left side of the navigation bar. Could Someone explain how i would do this.

@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&family=Ubuntu:wght@400;500;700&display=swap');
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    text-decoration: none;
}
/* navbar styling */
.navbar{
    position: fixed;
    width: 100%;
    background: crimson;
    font-family: 'Ubuntu', sans-serif;
}
.navbar .maxwidth{
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.navbar .logo a{
    color: #fff;
    font-size: 35px;
    font-weight: 600;
}
.navbar .menu li{
    list-style: none;
    display: inline-block;
}
.navbar .menu li a{
    color: #fff;
    float: right;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Personal Portfolio</title>
    <link rel="stylesheet" href="style.css">

Portfolio.

Home

About

Services

Skills

Teams

Contact

Comment: Consider starting with something like Bootstrap, so you can see how they do it. Flexbox will be your friend.
Answer: You were doing it pretty much correctly. Your css had a typo. I changed maxwidth to max-width.

@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&family=Ubuntu:wght@400;500;700&display=swap');
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    text-decoration: none;
}
/* navbar styling */
.navbar{
    position: fixed;
    width: 100%;
    background: crimson;
    font-family: 'Ubuntu', sans-serif;
}
.navbar .max-width{
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.navbar .logo a{
    color: #fff;
    font-size: 35px;
    font-weight: 600;
}
.navbar .menu li{
    list-style: none;
    display: inline-block;
}
.navbar .menu li a{
    color: #fff;
    float: right;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Personal Portfolio</title>
    <link rel="stylesheet" href="style.css">

Portfolio.

Home

About

Services

Skills

Teams

Contact


Set  content in C#

Question: I'm currently learning to use MasterPages and ContentPlaceHolders in ASP.NET 3.5 and C# - and right now, I'm desperately trying to edit the contents of an asp:Content-Control through my programming code.
Background is this; As soon as a Button is pressed, I want the asp:Content to be cleared and filled with dynamic generated content through the *.cs-File.
But I can't figure out how to access the asp:Content-Control, neither through its ID or Page.FindControl etc.
So, how can you edit the contents of a asp:Content-Control through your programming code?
Answer: You can access a ContentPlaceholder by using FindControl not on the page object, but on its master page.
<code>System.Web.UI.MasterPage masterPage = this.Master;
ContentPlaceHolder pageContent;

pageContent = (ContentPlaceHolder)masterPage.FindControl("YourContentPlaceholderName");
</code>
I'd agree though that it's better to define a panel or placeholder within this block and access that directly, rather than try to modify the ContentPlaceholder
Comment: I don't want to modify the placeholder, but the content that fills a placeholder.

Placeholder is defined in the MasterPage, but I'm trying to change a Conten-Control in a derived SubPage of that MasterPage.
Comment: When you call Master.FindControl() it will return your page's instance of that placeholder, which will be your Content control.
Answer: You can put an asp:Panel into the ContentPlaceHolder and move the placeholder markup into it. This way you can get to the Panel container and manipulate its content.
Comment: Sounds like a fine workaround for me, I'll sure try this - still, the mystery remains :-/
Answer: Did you forget to add runat="server" to your asp:Content-Control?
Regards,
M.

Set  content in C#


SwipeRefreshLayout swipe down scrollview with progress bar

Question: <code><androidx.swiperefreshlayout.widget.SwipeRefreshLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        /*
        Something......
        */

    </ScrollView>

</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</code>
I want to swipe down my scrollview with progress bar.
Like left one.
How can i do this ?
Answer: I'm pretty sure you can just put the androidx.swiperefreshlayout.widget.SwipeRefreshLayout inside of the ScrollView


Incrementar ViewBag no .cshtml

Question: Preciso incrementar minha ViewBag na minha página .cshtml, para a minha PartialView
no meu Controller eu inicío ela: ViewBag.count = 0
Na minha pagina .cshtml preciso incrementar:
exemplo:
@{
for (int i = 0; i < 10; i++)
{
     ViewBag.count = i;
     Html.Partial("EditorTemplates/Endereco", Model.Enderecos[@i]);
}
}

minha PartialView:

seguinte erro ocorre:
O índice estava fora do intervalo. Ele deve ser não-negativo e menor que o tamanho da coleção

Comment: usa foreach meu querido!
Comment: Acho que teria que colocar o @ antes do FOR... ALGO ASSIM @{ for(int i = 0; i < 10; i++){
    ViewBag.count = i
}
}
Comment: Acho bem melhor  adica do @RBoschini
Comment: @PauloHDSousa vou implementar mais a pergunta, obrigado por responder
Comment: funcionou o que eu falei? @Furlan
Comment: @PauloHDSousa outro erro ocorreu
Comment: Então, acontece que dentro de Model.Enderecos[] a quantidade de elementos é menor do que está sendo passado no I,  Outro ponto... Passa assim -> Model.Enderecos[i]);
Comment: @RBoschini como ficaria usando `foreach` ?
Answer: Lógica de negócio em View é uma péssima prática, sobretudo porque ViewBag é um objeto auxiliar para transportar valores do Controller para a View.
Se você realmente precisa de variáveis em View, use variáveis normais do .NET na sua lógica. Se você precisa passar dados de uma View para uma PartialView, deve fazer por ViewModels, e não pela ViewBag.
Este trecho pode ser perfeitamente escrito da seguinte forma:
@for (var enderecoObjeto in Model.Enderecos.Select((endereco, i) => new {endereco, i}))
{
     @Html.Partial("EditorTemplates/Endereco", enderecoObjeto);
}

A Partial pode ter @model dynamic ou você pode tipar o objeto com o i usando ViewModel.
Comment: Você até pode consertar, mas o código é ruim mesmo na formulação dele. Não tem muito o que fazer.
Comment: Eu fico meio sei la em alterar código alheio, mas obrigado pela informação. @Cigano Morrison Mendez
Comment: Cara, eu posso propor códigos assim para a galera que pergunta? Eu geralmente concerto os erros do código mesmo quando poderia ser feito 100x melhor, eu posso fazer isso então né? @Cigano Morrison Mendez
Answer: Consegui fazendo assim:
no meu controller, iniciei minha viewbag:
ViewBag.count = 0;

na view:
@foreach (var telefone in Model.Telefones)
{
    @Html.Partial("Telefone", telefone)
}

Comment: @RBoschini Pelo incrível que pareça, essa é realmente a resposta para o problema dele.
Comment: Edita sua pergunta com esses dados, nao poste uma resposta.

Incrementar ViewBag no .cshtml


Send HTTP request and receive HTTP response using javascript

Question: I want to send HTTP request like a simple request for "http://google.com/" and then print the HTTP response headers on screen. How can it be done?
I want the base code so that I can use it to send more complex GET and POST requests.
<code><html>
<body>

<script type="text/javascript">
function sendgetreq()
{
    var req = new XMLHttpRequest();
    req.open('GET', "https://www.google.com/search?q=asd", true);
    req.send(null);
    var headers = req.getAllResponseHeaders().toLowerCase();
    //document.write("Headers are:"+headers);
    alert(headers);
}
</script>
<INPUT TYPE=BUTTON OnClick="sendgetreq();" VALUE="Send Request">

</body>
</html>
</code>
This shows me an empty popup box.
Comment: http://stackoverflow.com/questions/220231/accessing-the-web-pages-http-headers-in-javascript
Comment: http://www.w3schools.com/dom/tryit.asp?filename=try_dom_xmlhttprequest_first
Comment: Thanks @Ajeet for the quick reply. I had tried both but they didn't work for me. Check out the code I have posted now.
Comment: The link i posted will get you headers for your own domain only as cross domain restrictions will apply for external domains.
Comment: @Ajeet: But I want to send a GET request to google.com and fetch the response header.
Comment: that is restricted by same origin policy .http://en.wikipedia.org/wiki/Same-origin_policy
Answer: You can't use XMLHttpRequest cross domain unless requested server explicitly allow it and google.com doesn't explicitly allow it.
However you may disable the web security feature of your browser, and then your same code will start working.


Ubuntu Server 21.04 Update Error On apt update

Question: I was trying to install a deb package which refused to run because of dependencies, after failed attempt to install the dependencies or OS updates i uninstalled the deb package. since there were a number of pending updates, i tried running those but the sources urls were reporting NOT Found.
Server: ubuntu 21.04
apt update
Hit:1 https://deb.nodesource.com/node_14.x hirsute InRelease
Hit:2 https://dl.yarnpkg.com/debian stable InRelease
Ign:3 http://us.archive.ubuntu.com/ubuntu hirsute InRelease
Ign:4 http://us.archive.ubuntu.com/ubuntu hirsute-updates InRelease
Ign:5 http://us.archive.ubuntu.com/ubuntu hirsute-backports InRelease
Ign:6 http://us.archive.ubuntu.com/ubuntu hirsute-security InRelease
Err:7 http://us.archive.ubuntu.com/ubuntu hirsute Release
  404  Not Found [IP: 22.214.171.124 80]
Err:8 http://us.archive.ubuntu.com/ubuntu hirsute-updates Release
  404  Not Found [IP: 22.214.171.124 80]
Err:9 http://us.archive.ubuntu.com/ubuntu hirsute-backports Release
  404  Not Found [IP: 18.104.22.168 80]
Err:10 http://us.archive.ubuntu.com/ubuntu hirsute-security Release
  404  Not Found [IP: 22.214.171.124 80]
Reading package lists... Done
E: The repository 'http://us.archive.ubuntu.com/ubuntu hirsute Release' no longer has a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
E: The repository 'http://us.archive.ubuntu.com/ubuntu hirsute-updates Release' no longer has a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
E: The repository 'http://us.archive.ubuntu.com/ubuntu hirsute-backports Release' no longer has a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
E: The repository 'http://us.archive.ubuntu.com/ubuntu hirsute-security Release' no longer has a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.

Any ideas on how to resolve this
Answer: A quick fix for this is to run:
sed -i -e 's/archive.ubuntu.com\|security.ubuntu.com/old-releases.ubuntu.com/g' /etc/apt/sources.list

... before the apt update command.
Comment: Note that there is no `us.old-releases.ubuntu.com`. The `us.` needs to be removed after running sed, or prepended to the sed matches.
Comment: wow, it works! thanks sir!
Answer: Ubuntu 21.04 was non LTS version and was supported up to begin od 2022 year.
The best solution is an upgrade to current LTS version - 22.04.
If it's not possible - change source in /etc/apt/sources.list to https://old-releases.ubuntu.com/ubuntu/ - it's an archive for outdated ubuntu versions.
Answer: Ubuntu 21.04 (Hirsute Hippo) End of Life reached on January 20 2022.


In a grid with a top resizable row, how can I resize the top row without moving the absolute position of the bottom rows?

Question: Problem:
    I have WPF window that is set sizeToContent on height. It has one child (grid) with following row defs:
<Grid.RowDefinitions>
    <RowDefinition Name="QueueHeight" Height="*"/>
    <RowDefinition Height="30"/>
    <RowDefinition Name="PlayedHeight" Height="*"/>
</Grid.RowDefinitions>

Row 2 is a static row that will always be 30 pixels and contains main UI.
Resizing the contents row 3 results in window expanding down and row 2 staying put
Resizing the contents row 1 results in window also expanding down and row 2 moving down as well.
Question: What can I do so that resizing the contents of row 1 results in row 2 staying in the same place (akin to row 3)? Since this has to be done with animations, I can't just use w.Top = w.Top + resize
Attempted solutions:
    Animated w.Top property and move down needed amount. Results in extremely jittery animation that looks like shit.
Edit: Clarified that I was resizing the contents, not the rows themselves.
Comment: Don't change the RowDefiniton height. Leave it constant and change the height of the UI element in row 1 and row 2.
Comment: If you resize the first row, how can the second one stay in place? Does this mean that the content of the first row will be cut off? What will happen to the window and the third row in this case?
Comment: @vesan: I basically want the first row to grow up instead of down when resizing.
Comment: @Anand: That's what I already do.
Answer: Ok, without any pictures or further description I had to make some wild assumptions about what you really want, so this might be all wrong.
However, if you want an element to grow upwards, I assume that there is some space for it to grow. So, I imagine that you have a situation like this:

If that is the case and if you want the growth to be done using an animation, it can be achieved using the following XAML: Note that the element that grows up is not a part of the "bottom" grid, as you had it (because it's quite difficult to have it grow outside of the grid). Instead, it is aligned to the bottom of the "top" grid (here's assuming that you have one, of course), and overlaps the "background" element that is already there.
Well, without further ado, here's the XAML. Hope it helps (Window element omitted).
<Window.Resources>
    <Storyboard x:Key="GrowStoryboard">
        <DoubleAnimation Storyboard.TargetName="TopContent" Storyboard.TargetProperty="Height"
                         To="80" Duration="0:0:1"></DoubleAnimation>
    </Storyboard>
    <Storyboard x:Key="ShrinkStoryboard">
        <DoubleAnimation Storyboard.TargetName="TopContent" Storyboard.TargetProperty="Height"
                         To="25" Duration="0:0:1"></DoubleAnimation>
    </Storyboard>
</Window.Resources>

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="100"></RowDefinition>
        <RowDefinition Height="*"></RowDefinition>
    </Grid.RowDefinitions>

        Top background

        Top Content

    <Grid Grid.Row="1">
        <Grid.RowDefinitions>
            <RowDefinition Height="30"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>

            Menu

            Content

        <Button Grid.Row="1" Margin="10,30" Content="Grow" VerticalAlignment="Top" HorizontalAlignment="Left">
            <Button.Triggers>
                <EventTrigger RoutedEvent="Button.Click">
                    <BeginStoryboard Storyboard="{StaticResource GrowStoryboard}"></BeginStoryboard>
                </EventTrigger>
            </Button.Triggers>
        </Button>
        <Button Grid.Row="1" Margin="10,60" Content="Shrink" VerticalAlignment="Top" HorizontalAlignment="Left">
            <Button.Triggers>
                <EventTrigger RoutedEvent="Button.Click">
                    <BeginStoryboard Storyboard="{StaticResource ShrinkStoryboard}"></BeginStoryboard>
                </EventTrigger>
            </Button.Triggers>
        </Button>
    </Grid>

</Grid>

Comment: I'm so sorry, I really appreciate your help but I just got home and solved my problem by switching to the PopUp class instead of using grids. I do appreciate the time you took to put into this, and I'll definitely save it for future reference.

Thank you!
Answer: I solved this by simply using Popups instead of grids. They solved all of my issues and simplified my code since a lot of the things I was doing with the grids before, was already done in the popup.


PHP export CSV Table from Database

Question: I'm new to PHP and I'm trying to do a small experiment to learn.
I want to create a line of words, that when clicked, will download a csv file from a table I have in my database.
So far, this is what I've come up with (which isn't even near what I want to do. But I was able to make it turn into a hyperlink).
 echo "Click here to visit site";

Assuming I already have a connection to my database, how would I go about connecting "Click here to visit site" to download a csv file, from say, table1 of my database ABC?
I think there will have to be some loop that reads the rows in table1 and writes it into the csv file, right?
Answer: Create a file separate file having the following code and create a hyperlink in your current file like:
echo "<a href='http://<your domain name>/test.php'>Click here to visit site";

<?php
 //test.php
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');

// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');

// output the column headings
fputcsv($output, array('Column 1', 'Column 2', 'Column 3'));

// fetch the data

$rows = mysqli_query($conn, 'SELECT name, email  FROM users limit 10');

// loop over the rows, outputting them
while ($row = mysqli_fetch_assoc($rows)) fputcsv($output, $row);
?>

PHP export CSV Table from Database


Pager disappears when adding "GROUP BY" in the SQL query

Question: Drupal pager disappears when I add GROUP BY to the query.
This code works.
$countSql = "SELECT  COUNT(*) FROM journal ";
$sql = "SELECT  * FROM journal";

$result = pager_query($sql, 1, 0, null, $countSql);
theme_pager(NULL, 10)

This code doesn't show the pager.
$countSql = "SELECT  COUNT(*) FROM journal ";
$sql = "SELECT  * FROM journal GROUP BY id";

$result = pager_query($sql, 1, 0, null, $countSql);
theme_pager(NULL, 10)

What is it wrong with the latter code?
Answer: Your query with the GROUP BY is incorrect, MySQL is lax enough to let you write this kind of queries but it is by no way recommended. When you use a GROUP BY clause you should group all the columns without an aggregate function.
Also if you put a GROUP BY in your query, you should also include it in your count query. Generally a brutal way to make the count query is to put it this way:
$sql = "SELECT  * FROM journal";
$countSql = "SELECT  COUNT(*) FROM ($sql) ";

Try to modify your queries and amend your question with further precisions.
Comment: Thanks for your reply, u r right in sql server i cannot use group by like this but mysql let me do this,also that is not actual query i m going to post my actual query in my own answer
Comment: If you want, you can correct this behaviour by secifying the option [`ONLY_FULL_GROUP_BY`](http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html#sqlmode_only_full_group_by) in MySQL configuration.
Answer: I need distinct journals, and their IDs must be in article table; the article table can have multiple journal IDs, and I need two article columns.
SELECT  j.nid AS journal_nid, j.title AS journal_title, j.id AS journal_id, a.is_epub, a.nid AS article_nid, j.image_file_name
FROM journal j
INNER JOIN article a ON j.id = a.journal_id ". $condition." GROUP BY j.id ORDER BY j.title ASC

I modified my query, and the pager appears.
SELECT  j.id AS journal_id, j.nid AS journal_nid, j.title AS journal_title, j.image_file_name,
(select max(nid) from article where journal_id = j.id) AS article_nid,
(select max(is_epub) from article where journal_id = j.id) is_epub
FROM journal j
WHERE j.id IN (SELECT journal_id FROM article)


Looking for closed-forms of $\int_0^{\pi/4}\ln^2(\sin x)\,dx$ and $\int_0^{\pi/4}\ln^2(\cos x)\,dx$

Question: A few days ago, I posted the following problems
Prove that
\begin{equation}
\int_0^{\pi/2}\ln^2(\cos x)\,dx=\frac{\pi}{2}\ln^2 2+\frac{\pi^3}{24}\\[20pt]
-\int_0^{\pi/2}\ln^3(\cos x)\,dx=\frac{\pi}{2}\ln^3 2+\frac{\pi^3}{8}\ln 2 +\frac{3\pi}{4}\zeta(3)
\end{equation}
and the OP receives some good answers even I then could answer it.

My next question is finding the closed-forms for

\begin{align}
\int_0^{\pi/4}\ln^2(\sin x)\,dx\tag1\\[20pt]
\int_0^{\pi/4}\ln^2(\cos x)\,dx\tag2\\[20pt]
\int_0^1\frac{\ln t~\ln\big(1+t^2\big)}{1+t^2}dt\tag3
\end{align}

I have a strong feeling that the closed-forms exist because we have nice closed-forms for
\begin{equation}
\int_0^{\pi/4}\ln(\sin x)\ dx=-\frac12\left(C+\frac\pi2\ln2\right)\\
\text{and}\\
\int_0^{\pi/4}\ln(\cos x)\ dx=\frac12\left(C-\frac\pi2\ln2\right).
\end{equation}
The complete proofs can be found here.
As shown by Mr. Lucian in his answer below, the three integrals are closely related, so finding the closed-form one of them will also find the other closed-forms. How to find the closed-forms of the integrals? Could anyone here please help me to find the closed-form, only one of them, preferably with elementary ways (high school methods)? If possible, please avoiding contour integration and double summation. Any help would be greatly appreciated. Thank you.
Comment: As I wrote in my answer on this thread, this question is equivalent to [finding the closed form expression for $\text{Li}_3\Big(\frac{1+i}2\Big)$](http://math.stackexchange.com/questions/918680).
Comment: What type of integration is this, I was taught only basic integrals, can you tell me waht topic which they come under so that   I can read about them and learn about them.
Comment: @Aditya Log-Trig integrals
Answer: Following the same approach as in this answer,
$$ \begin{align} &\int_{0}^{\pi/4} \log^{2} (2 \sin x) \ dx = \int_{0}^{\pi/4} \log^{2}(2) \ dx + 2 \log 2 \int_{0}^{\pi/4}\log(\sin x) \ dx + \int_{0}^{\pi /4}\log^{2}(\sin x) \ dx \\ &= \frac{\pi}{4} \log^{2}(2) - \log (2) \left(G + \frac{\pi}{2} \log (2) \right) + \int_{0}^{\pi/4} \log^{2}(\sin x) \ dx \\ &= \int_{0}^{\pi /4} \left(x- \frac{\pi}{2} \right)^{2} \ dx + \text{Re} \int_{0}^{\pi/4} \log^{2}(1-e^{2ix}) \ dx \\ &= \frac{7 \pi^{3}}{192} + \frac{1}{2} \text{Im} \int_{{\color{red}{1}}}^{i} \frac{\log^{2}(1-z)}{z} \ dz \\ &= \frac{7 \pi^{3}}{192} + \frac{1}{2} \text{Im} \left(\log^{2}(1-i) \log(i) + 2 \log(1-i) \text{Li}_{2}(1-i) - 2 \text{Li}_{3}(1-i) \right) \\ &= \frac{7 \pi^{3}}{192} + \frac{1}{2} \left(\frac{\pi}{8} \log^{2}(2) - \frac{\pi^{3}}{32} + \log(2)  \ \text{Im} \ \text{Li}_{2}(1-i) - \frac{\pi}{2} \text{Re} \ \text{Li}_{2}(1-i)- 2 \ \text{Im} \ \text{Li}_{3}(1-i)\right) . \end{align}$$
Therefore,
$$ \begin{align}\int_{0}^{\pi/4} \log^{2}(\sin x) \ dx &= \frac{\pi^{3}}{48} + G \log(2)+ \frac{5 \pi}{16}\log^{2}(2) + \frac{\log(2)}{2} \text{Im} \ \text{Li}_{2}(1-i) - \frac{\pi}{4}    \text{Re} \ \text{Li}_{2}(1-i) \\ &- \text{Im} \ \text{Li}_{3}(1-i) \approx 2.0290341368 . \end{align}$$
The answer could be further simplified using the dilogarithm reflection formula $$\text{Li}_{2}(x) {\color{red}{+}} \text{Li}_{2}(1-x) = \frac{\pi^{2}}{6} - \log(x) \log(1-x) $$
and the fact that $$ \text{Li}_{2}(i) = - \frac{\pi^{2}}{48} + i G.$$
EDIT:
Specifically, $$\text{Li}_{2}(1-i) = \frac{\pi^{2}}{16} - i G - \frac{i \pi}{4} \log(2). $$
So $$\int_{0}^{\pi /4} \log^{2}(\sin x) \ dx = \frac{\pi^{3}}{192} + G\frac{  \log(2)}{2} + \frac{3 \pi}{16} \log^{2}(2) - \text{Im} \  \text{Li}_{3}(1-i).$$
Comment: @DavidH Why did you do that? I consider this answer as a strong candidate winner for my bounty! ᕙ(`皿´)╯
Comment: Ack. Apparently I accidentally downvoted, and now it's locked in. I'll fix this if you edit. :(
Comment: Thank you Mr. Random variable, for now I'll upvote this answer and study it (ô‿ô)
Comment: There were a couple of errors that I fixed.
Comment: I added a bit more detail to the other answer.
Comment: @DavidH I have edited, why it's still locked?
Comment: @DavidH I think I have to be the one to edit it so that you can change your vote. So I edited it and went back to $\text{Re}$ and $\text{Im}$.
Comment: @Anastasiya-Romanova  Thank you.
Comment: @RandomVariable My pleasure. Thanks for helping me. ❤유 Anyway, please take a look my new problem: http://math.stackexchange.com/q/927427/133248
Answer:
$$\int_0^\frac\pi4\Big(\ln\sin x\Big)^2~dx~=~\dfrac{23}{384}\cdot\pi^3~+~\dfrac9{32}\cdot\pi\cdot\ln^22~+~\underbrace{\beta(2)}_\text{Catalan}\cdot\dfrac{\ln2}2~-~\Im\bigg[\text{Li}_3\bigg(\dfrac{1+i}2\bigg)\bigg].$$
$$\int_0^\frac\pi4\Big(\ln\cos x\Big)^2~dx~=~\dfrac{-7}{384}\cdot\pi^3~+~\dfrac7{32}\cdot\pi\cdot\ln^22~-~\underbrace{\beta(2)}_\text{Catalan}\cdot\dfrac{\ln2}2~+~\Im\bigg[\text{Li}_3\bigg(\dfrac{1+i}2\bigg)\bigg].$$

$$S=\int_0^\frac\pi4\Big(\ln\sin x\Big)^2~dx~+~\int_0^\frac\pi4\Big(\ln\cos x\Big)^2~dx=I+J.$$
But, by a simple change of variable, $t=\dfrac\pi2-x,~J$ can be shown to equal $\displaystyle\int_\frac\pi4^\frac\pi2\Big(\ln\sin x\Big)^2~dx$,
in which case $I+J=\displaystyle\int_0^\frac\pi2\Big(\ln\sin x\Big)^2~dx=\dfrac{\pi^3}{24}+\dfrac\pi2\ln^22.~$ So we know their sum! Now all
that's left to do is to find out their difference, $D=I-J.~$ Then we'll have $I=\dfrac{S+D}2$ and
$J=\dfrac{S-D}2$.

$$D=I-J=\int_0^\frac\pi4\Big(\ln\sin x\Big)^2~dx-\int_0^\frac\pi4\Big(\ln\cos x\Big)^2~dx=\int_0^\frac\pi4\Big(\ln^2\sin x-\ln^2\cos x\Big)~dx$$
$$=\int_0^\frac\pi4\Big(\ln\sin x-\ln\cos x\Big)~\Big(\ln\sin x+\ln\cos x\Big)~dx=\int_0^\frac\pi4\ln\frac{\sin x}{\cos x}~\ln\big(\sin x~\cos x\big)~dx=$$
$$=\int_0^\frac\pi4\ln\tan x\cdot\ln\frac{\sin2x}2~dx=\frac12\int_0^\frac\pi2\ln\tan\frac x2\cdot\ln\frac{\sin x}2~dx=\int_0^1\ln t\cdot\ln\frac t{1+t^2}\cdot\frac{dt}{1+t^2}$$
where the last expression was obtained by using the famous Weierstrass substitution, $t=\tan\dfrac x2$
$$=\int_0^1\frac{\ln t\cdot\Big[\ln t-\ln(1+t^2)\Big]}{1+t^2}dt~=~\int_0^1\frac{\ln^2t}{1+t^2}dt~-~\int_0^1\frac{\ln t~\ln\big(1+t^2\big)}{1+t^2}dt~=~\frac{\pi^3}{16}-K,$$
where $~K=2~\Im\bigg[\text{Li}_3\bigg(\dfrac{1+i}2\bigg)\bigg]-\dfrac{\pi^3}{64}-\dfrac\pi{16}\ln^22-\underbrace{\beta(2)}_\text{Catalan}\ln2.~$ It follows then that our two
definite integrals possess a closed form expression if and only if $~\text{Li}_3\bigg(\dfrac{1+i}2\bigg)$ has one as well. As
an aside, $~\Re\bigg[\text{Li}_3\bigg(\dfrac{1+i}2\bigg)\bigg]=\dfrac{\ln^32}{48}-\dfrac5{192}~\pi^2~\ln2+\dfrac{35}{64}~\zeta(3).~$ Also, $~K=\displaystyle\sum_{n=1}^\infty\frac{(-1)^n~H_n}{(2n+1)^2}$.
Comment: @Lucian Do you mind explaining how you compute $\displaystyle K=\sum^\infty_{n=1}\frac{(-1)^n H_n}{(2n+1)^2}$? Thanks.
Comment: @Anastasiya-Romanova 秀 check this link https://math.stackexchange.com/q/3449505
Comment: +1 Mr. Lucian, your method is easy to follow but I have a question, how to evaluate $$\int_0^1\frac{\ln t~\ln\big(1+t^2\big)}{1+t^2}dt$$
Comment: @SuperAbound: I didn't. Mathematica did. Basically, I struggled for hours to find an expression which my CAS could finally evaluate, since all other intermediary results available on this page were impenetrable, and, in the end, I actually did. Then I posted the result. As far as the integral is concerned, I tried the two main approaches: series expansion and the Feynman trick, both of which failed miserably, but your Euler sum gives me hope. $($How on earth did you even come up with it, anyway?$)$ My only idea would be to write $H_n$ as a sum, then switch the order of the two summations.
Comment: @V-Moy: In my opinion, *SuperAbound's* Euler sum seems the way to go. Indeed, many such similar sums have been solved on this site, so I am rather hopeful.
Comment: @SuperAbound: The real part of the complex polylogarithm I posted possesses a closed form, so perhaps its imaginary part does so as well. Either way, I will not be the one to find it, so any help would, at this point, be deeply appreciated.
Comment: @Lucian I actually posted a question regarding this sum afterwards. It seems it has been evaluated elsewhere on another website. http://math.stackexchange.com/questions/918135/sum-sum-infty-n-1-frac-1nh-n2n12?noredirect=1#comment1895358_918135
Answer: By setting $x=\arctan t$ we have:
$$\int_{0}^{\pi/4}\log^2(\cos x)\,dx = \frac{1}{4}\int_{0}^{1}\frac{\log^2(1+t^2)}{1+t^2}.$$
Attack plan: get the Taylor series of $\log^2(1+t^2)$ and integrate it termwise.
Since
$$-\log(1-z)=\sum_{n=1}^{+\infty}\frac{z^n}{n}$$
it follows that
$$[z^n]\log^2(1-z)=\sum_{k=1}^{n-1}\frac{1}{k(n-k)}=2\frac{H_{n-1}}{n},$$
$$\log^2(1+t^2)=\sum_{n=2}^{+\infty}2\frac{H_{n-1}}{n}(-1)^n t^{2n}.\tag{1}$$
If now we set
$$\mathcal{J}_m = \int_{0}^{1}\frac{t^{2m}}{t^2+1}\,dt $$
we have $\mathcal{J}_0=\frac{\pi}{4}$ and $\mathcal{J}_{m+1}+\mathcal{J}_m = \frac{1}{2m+1}$, hence:
$$\mathcal{J}_m = (\mathcal{J}_m+\mathcal{J}_{m-1})-(\mathcal{J}_{m-1}+\mathcal{J}_{m-2})+\ldots\pm(\mathcal{J}_1+\mathcal{J}_0)\mp\mathcal{J}_0,$$
$$\mathcal{J}_m = \sum_{j=0}^{m-1}\frac{(-1)^j}{(2m-2j-1)}+(-1)^m\frac{\pi}{4}=(-1)^m \sum_{j\geq m}\frac{(-1)^j}{2j+1}.\tag{2}$$
From $(1)$ and $(2)$ it follows that:
$$\int_{0}^{\pi/4}\log^2(\cos x)\,dx=\frac{1}{2}\sum_{n=2}^{+\infty}\frac{H_{n-1}}{n}\sum_{r\geq n}\frac{(-1)^r}{2r+1},\tag{3}$$
and summation by parts gives:

$$\int_{0}^{\pi/4}\log^2(\cos x)\,dx=\frac{1}{4}\sum_{n=2}^{+\infty}(H_n^2-H_n^{(2)})\frac{(-1)^n}{2n+1}.\tag{4}$$

UPDATE: the question is now set in an answer to another question. This site (many thanks to @gammatester) is devoted to the evaluation of sums like the one appearing in the RHS of $(4)$. Through Euler-Landen's identity (see the line below $(608)$ in the linked site) it is not too much difficult to see that the RHS of $(4)$ depends on $\operatorname{Li}_3\left(\frac{1+i}{2}\right)$ as stated in the @Lucian's answer.
Comment: +1 for your answer before I sleep Mr. Jack D'Aurizio (ô‿ô)
Comment: another approach:

using the following identity:
$$\displaystyle \frac{\ln^2(1-x)}{1-x}=\sum_{n=1}^{\infty}\left(H_n^2-H_n^{(2)}\right)x^n$$

replacing $x$ with $-x^2$ and integrating both sides from $0$ to $1$ gives:

$$\int_{0}^{1}\frac{\log^2(1+x^2)}{1+x^2}\ dx=\sum_{n=1}^{\infty}(H_n^2-H_n^{(2)})\frac{(-1)^n}{2n+1}$$
Answer: The strategy in this post will be included in another paper.

A solution (in large steps) by Cornel Ioan Valean
In my opinion, this is a very magical & powerful way that manages to circumvent the necessity of using the already famous method proposed by Random Variable which I think most posts on MSE use it for such integrals. It's time for a new way to come in place and join the existing one!
In this post, we magically prove that
$$\int_0^1\frac{\log x\log(1+x^2)}{1+x^2}\textrm{d}x=-\frac{\pi}{16}  \log ^2(2) - \log (2)G-\frac{\pi ^3}{64}+2\Im\biggr \{\operatorname{Li}_3\left(\frac{1+i}{2}\right)\biggr \},$$
by wisely combining a result from the book, (Almost) Impossible Integrals, Sums, and Series, namely the special Fourier series (see eq. 3.284, page 244, and eq. 3.288, page 247),
\begin{equation}
\begin{aligned}
\small \sum_{n=1}^{\infty} (-1)^{n-1}\left(\psi\left(\frac{n+1}{2}\right)-\psi\left(\frac{n}{2}\right)-\frac{1}{n}\right)\sin(2nx)&\small=\sum_{n=1}^{\infty} (-1)^{n-1}\left(\int_0^1 t^{n-1}\frac{1-t}{1+t} \textrm{d}t\right)\sin(2nx)\\
&=-\cot(x)\log(\cos(x)),
\end{aligned}
\end{equation}
where $\displaystyle 0< x<\frac{\pi}{2}$, and the Cornel's integral,
$$\int_0^{\pi/2} x\frac{\log(\cos x)}{\sin x}\textrm{d}x=2\log(2)G-\frac{\pi}{8}\log^2(2)-\frac{5}{32}\pi^3+4\Im\left\{\text{Li}_3\left(\frac{1+i}{2}\right)\right\},$$
already calculated in this post How can you approach $\int_0^{\pi/2} x\frac{\ln(\cos x)}{\sin x}dx$.
Proof: We differentiate both sides of the Fourier series that leads to
$$2 \sum_{n=1}^{\infty} (-1)^{n-1}\left(\int_0^1 t^{n-1}\frac{1-t}{1+t} \textrm{d}t\right)n\cos(2nx)=1+\frac{\log(\cos(x))}{\sin^2(x)},$$
and if we multiply both side by $x \sin(x)$ and integrate from $x=0$ to $x=\pi/2$, we arrive at
$$\int_0^{\pi/2} x\sin(x)\textrm{d}x+\int_0^{\pi/2}x\frac{\log(\cos(x))}{\sin(x)}\textrm{d}x$$
$$=2 \log (2)-1+2 \log (2)\underbrace{\int_0^1 \frac{\log (x)}{1+x^2}\textrm{d}x}_{\displaystyle \text{Trivial}}+\frac{1}{2}\underbrace{\int_0^1 \log (x) \log \left(1-x^2\right)\textrm{d}x}_{\displaystyle \text{Trivial}}$$
$$+\frac{1}{2}\underbrace{\int_0^1\frac{\log (x) \log \left(1-x^2\right)}{x^2}\textrm{d}x}_{\displaystyle \text{Trivial}}-2\underbrace{\int_0^1\frac{ \log (x) \log \left(1-x^4\right)}{1-x^4}\textrm{d}x}_{\displaystyle \text{Beta function in disguise}}$$
$$+2\underbrace{\int_0^1\frac{x^2 \log (x) \log \left(1-x^4\right)}{1-x^4}\textrm{d}x}_{\displaystyle \text{Beta function in disguise}}+2\color{blue}{\int_0
^1 \frac{\log (x) \log(1+x^2)}{1+x^2}\textrm{d}x},$$
from which the desired result follows.
Note the following values of the Beta function forms in disguise:
$$\int_0^1 \frac{\log (x) \log \left(1-x^4\right)}{1-x^4} \textrm{d}x=\frac{1}{16}\int_0^1 \frac{\log(x)\log (1-x)}{ x^{3/4}(1-x) } \textrm{d}x$$
$$=\frac{7 }{4}\zeta (3)+\frac{\pi ^3}{32}-\frac{3}{16}\log (2)\pi ^2-\frac{\pi }{4}G-\frac{3}{2}\log(2)G,$$
and
$$\int_0^1 \frac{x^2\log (x) \log \left(1-x^4\right)}{1-x^4} \textrm{d}x=\frac{1}{16}\int_0^1 \frac{\log(x)\log (1-x)}{x^{1/4}(1-x)} \textrm{d}x$$
$$=\frac{7}{4} \zeta (3)+\frac{3}{2} \log (2)G-\frac{1}{4} \pi G-\frac{3}{16}\log(2)\pi^2-\frac{\pi ^3}{32}.$$
A note: this method can also be adjusted to extract other very difficult integrals, which is possible by further exploiting and developing ideas like the ones in the paper A symmetry-related treatment of two fascinating sums of integrals by C.I. Valean.
End of story
Comment: (+1) hats off to Cornel. His magic never stop.
Answer: we can prove, using the same strategy of Random Variable, the following equality:
$$\int_0^{\pi/4}\ln^2(\cos x)\ dx=\frac7{192}\pi^3+\frac5{16}\pi\ln^22-\frac12\ln2G-\text{Im}\operatorname{Li_3}(1+i)$$
proof :
\begin{align*} \ln(1+e^{2ix}) &=  \ln (e^{-ix}+e^{ix}) + \ln(e^{ix}) \\ &=  \ln(2\cos x) + ix
\end{align*}
squaring both sides and integrating, we get
$$\int_0^{\pi/4}\ln^2(1+e^{2ix})\ dx=\int_0^{\pi/4}(\ln(2\cos x)+ix)^2\ dx$$
equating the real parts on both sides and rearranging the terms, we have:
$$
\int_0^{\pi/4}\ln^2(\cos x)\ dx=\int_0^{\pi/4}(x^2-\ln^22)\ dx-2\ln2\int_0^{\pi/4}\ln(\cos x)\ dx$$
$$+\text{Re}\int_0^{\pi/4}\ln^2(1+e^{2ix})\ dx$$
$$=\frac{\pi^3}{192}-\frac{\pi}{4}\ln^22-2\ln2\left(\frac12G-\frac{\pi}{4}\ln2\right)+\text{Re}\int_0^{\pi/4}\ln^2(1+e^{2ix})\ dx$$
$$=\frac{\pi^3}{192}+\frac{\pi}{4}\ln^22-\ln2G+\text{Re}\int_0^{\pi/4}\ln^2(1+e^{2ix})\ dx \tag{1}$$
Evaluating the last integral:
\begin{align*}
I&=\text{Re}\int_0^{\pi/4}\ln^2(1+e^{2ix})\ dx=\frac12\text{Im}\int_1^i\frac{\ln^2(1+x)}{x}\ dx\\
&=\frac12\text{Im}\left(\ln(-i)\ln^2(1+i)+2\ln(1+i)\operatorname{Li_2}(1+i)-2\operatorname{Li_3}(1+i)\right)\\
&=\frac{\pi^3}{32}+\frac{\pi}{16}\ln^22+\frac12\ln2G-\text{Im}\operatorname{Li_3}(1+i)\tag{2}
\end{align*}
Plugging $(2)$ in $(1)$ we get our result.
note that we used:
$$\ln(-i)=-\frac{\pi}{2}i$$
$$\ln(1+i)=\frac12\ln2+\frac{\pi}{4}i$$
$$\operatorname{Li_2}(1+i)=\frac{\pi^2}{16}+\left(\frac{\pi}{4}\ln2+G\right)i$$
which give us:
$$\ln(-i)\ln^2(1+i)=\frac{\pi^2}{8}\ln2+\left(\frac{\pi^3}{32}-\frac{\pi}{8}\ln^22\right)i$$
$$\ln(1+i)\operatorname{Li_2}(1+i) =-\frac{\pi}{4}G-\frac{\pi^2}{32}\ln2+\left(\frac12\ln2G+\frac{\pi^3}{64}+\frac{\pi}{8}\ln^22\right)i$$
Answer: my approach to problem $(3)$:
\begin{align}
I&=\int_0^1\frac{\ln x\ln(1+x^2)}{1+x^2}\ dx=-2\int_0^{\pi/4}\ln(\tan x)\ln(\cos x)\ dx\\
&=-2\int_0^{\pi/4}\ln(\sin x)\ln(\cos x)\ dx+2\int_0^{\pi/4}\ln^2(\cos x)\ dx\\
&=-\int_0^{\pi/2}\ln(\sin x)\ln(\cos x)\ dx+2\int_0^{\pi/4}\ln^2(\cos x)\ dx\\
&=-\left(\frac{\pi}{2}\ln^22-\frac{\pi^3}{48}\right)+2\left(\frac7{192}\pi^3+\frac5{16}\pi\ln^22-\frac12\ln2~G-\text{Im}\operatorname{Li_3}(1+i)\right)\\
&=\frac3{32}\pi^3+\frac{\pi}8\ln^22-\ln2~G-2\text{Im}\operatorname{Li_3}(1+i)
\end{align}
note that we evaluated the first integral using the derivative of beta function and as follows:
\begin{align}
J&=\int_0^{\pi/2}\ln(\sin x)\ln(\cos x)\ dx=\frac18\frac{\partial^2}{\partial{a}\partial{b}}\beta(a,b)\Bigg\rvert_{a\to1/2,~b\to1/2}\\
&=\frac18\beta(a,b)\left(\left(\psi(a)-\psi(a+b)\right)\left(\psi(b)-\psi(a+b)\right)-\psi^{(1)}(a+b)\right)\Bigg\rvert_{a\to1/2,~b\to1/2}\\
&=\frac18\beta(1/2,1/2)\left((\psi(1/2)-\psi(1))^2-\psi^{(1)}(1)\right)\\
&=\frac{\pi}8\left(4\ln^22-\zeta(2)\right)\\
&=\frac{\pi}2\ln^22-\frac{\pi^3}{48}
\end{align}
Answer: Evaluation of $\int_0^1\frac{\ln(x)\ln(1+x^2)}{1+x^2}dx:$
First note that
$$\int_0^1\frac{\ln(x)\ln(1+x^2)}{1+x^2}dx=\sum_{n=1}^\infty (-1)^n H_n\int_0^1 \ln(x) x^{2n}dx$$
$$=\sum_{n=1}^\infty\frac{(-1)^nH_n}{(2n+1)^2}=\sum_{n=0}^\infty\frac{(-1)^nH_n}{(2n+1)^2}.$$
We have here
$$\int_0^1\frac{x^{2n}}{1+x}dx=\ln(2)+H_n-H_{2n}$$
$$=\ln(2)+H_n-H_{2n+1}+\frac1{2n+1}.$$
Multiply both sides by $\frac{(-1)^n}{(2n+1)^2}$ then $\sum_{n=0}^\infty$ we get
$$\text{G}\ln(2)+\sum_{n=0}^\infty\frac{(-1)^nH_n}{(2n+1)^2}-\sum_{n=0}^\infty\frac{(-1)^nH_{2n+1}}{(2n+1)^2}+\underbrace{\sum_{n=0}^\infty\frac{(-1)^n}{(2n+1)^3}}_{\pi^3/32}$$
$$=\int_0^1\frac{1}{1+x}\left(\sum_{n=0}^\infty\frac{(-1)^nx^{2n}}{(2n+1)^2}\right)dx=\int_0^1\frac{1}{1+x}\left(\Im\frac{\text{Li}_2(ix)}{x}\right)dx$$
$$\int_0^1\frac{1}{1+x}\left(\Im\int_0^1-\frac{i\ln(y)}{1-ixy}dy\right)dx=\int_0^1\frac{1}{1+x}\left(\int_0^1-\frac{\ln(y)}{1+x^2y^2}dy\right)dx$$
$$\overset{xy=t}{=}\int_0^1\int_0^x\frac{\ln(x/t)}{x(1+x)(1+t^2)}dtdx=\int_0^1\frac{1}{1+t^2}\left(\int_t^1\frac{\ln(x/t)}{x(1+x)}dx\right)dt$$
$$=\int_0^1\frac{1}{1+t^2}\left(\text{Li}_2(-t)+\frac12\ln^2(t)+\ln(2)\ln(t)+\frac12\zeta(2)\right)dt$$
$$=\int_0^1\frac{\text{Li}_2(-t)}{1+t^2}dt+\frac{\pi^3}{32}-\text{G}\ln(2)+\frac{\pi^3}{48}$$
Therefore
$$\sum_{n=0}^\infty\frac{(-1)^nH_n}{(2n+1)^2}=\sum_{n=0}^\infty\frac{(-1)^nH_{2n+1}}{(2n+1)^2}+\int_0^1\frac{\text{Li}_2(-t)}{1+t^2}dt-2\text{G}\ln(2)+\frac{\pi^3}{48}\tag1$$
where
$$\sum_{n=0}^\infty\frac{(-1)^nH_{2n+1}}{(2n+1)^2}=\Im\sum_{n=1}^\infty\frac{i^nH_{n}}{n^2}=-\frac{\pi}{16}\ln^2(2)-\frac12\text{G}\ln(2)+\Im\operatorname{Li}_3(1+i)\tag2$$
and
$$\int_0^1\frac{\text{Li}_2(-t)}{1+t^2}dt=\int_0^1\frac{1}{1+t^2}\left(\int_0^1\frac{t\ln(x)}{1+tx}dx\right)dt$$
$$=\int_0^1\ln x\left(\int_0^1\frac{t}{(1+t^2)(1+tx)}dt\right)dx$$
$$=\int_0^1\ln(x)\left(\frac{\pi}{4}\frac{x}{1+x^2}+\frac{\ln(2)}{2}\frac{1}{1+x^2}-\frac{\ln(1+x)}{1+x^2}\right)dx$$
$$=-\frac{\pi^3}{192}-\frac12\text{G}\ln(2)-\int_0^1\frac{\ln(x)\ln(1+x)}{1+x^2}dx$$
Substitute
$$\int_0^1\frac{\ln(x)\ln(1+x)}{1+x^2}dx=3\ \text{Im}\operatorname{Li}_3(1+i)-\frac{5\pi^3}{64}-\frac{3\pi}{16}\ln^2(2)-2\ln(2)\ G,$$
we get
$$\int_0^1\frac{\text{Li}_2(-t)}{1+t^2}dt=-3\ \text{Im}\operatorname{Li}_3(1+i)+\frac{7\pi^3}{96}+\frac{3\pi}{16}\ln^2(2)+\frac32\ln(2)\ G.\tag3$$
Substitute $(2)$ and $(3)$ in $(1)$, we get
$$\sum_{n=0}^\infty\frac{(-1)^nH_n}{(2n+1)^2}:=\int_0^1\frac{\ln(x)\ln(1+x^2)}{1+x^2}dx=\frac{3\pi^3}{32}+\frac{\pi}8\ln^2(2)-\text{G}\ln(2)-2\Im\operatorname{Li_3}(1+i).$$
Comment: (+1) Ingenious work.
Comment: @user97357329 Thank you :)


add billing information in Drupal Commerce Programatically

Question: I am developing api access point for drupal commerce, from that access point user can upload his/her billing information during checkout process. Here is my code, but it can not add user full name in billing information. Any suggestion is greatly appreciated.
Thanks
  function commerce_services_bill_ship_create($data, $flatten_fields) {
    $status; $message;
    $orderId; $uid;

    $orderId =$data["orderId"];
    $uid = $data["uid"];
    $fullname = $data['fullname'];

    $order = commerce_cart_order_load($uid);
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    $order_wrapper->commerce_customer_billing->commerce_customer_address->name_line = $fullname;
    $order_wrapper->commerce_customer_billing->commerce_customer_address->thoroughfare = "No.1, ABC street";

    $order_wrapper->commerce_customer_billing->commerce_customer_address->locality = "New York";
     try{
        // Save the order.
        commerce_order_save ($order);
        $status = 1;
        $message = "order update successfully.";
    }catch(Exception $ex){
        $status = 0;
        $message = "order can't update successfully.";
    }
    $reply= (array('status' => $status,'message' => $message));

    return $reply;
 }

Answer: To add billing information in checkout process first we have to create a profile object and assign it to the order. This code works for me
For adding new profile for billing information
function commerce_services_bill_ship_create($data, $flatten_fields) {
$status; $message;
$orderId; $uid;

$orderId =$data["orderId"];
$fullname = $data['fullname'];
$city = $data["city"];
$address = $data["address"];

//load order that you want to add billing information
$order = commerce_cart_order_load($uid);

// We'll assume that the current user will be the customer of our order
global $user;

$profile = commerce_customer_profile_new('billing', $user->uid);
$profile->commerce_customer_address = array(LANGUAGE_NONE => array(0 => addressfield_default_values()));

//for updating existing profile, uncomment the line below and comment commerce_customer_profile_new()
//$profile = commerce_customer_profile_load($profile_id); //

//add fullname
$profile -> commerce_customer_address['und'][0]['name_line'] = $fullname;

//add address
$profile->commerce_customer_address['und'][0]['thoroughfare'] = $address;

//add city
$profile->commerce_customer_address['und'][0]['locality'] = $city;

// You sould pass the entire $profile object as parameter.
commerce_customer_profile_save($profile);

//assign profile_id to the order
$order->commerce_customer_billing[LANGUAGE_NONE][0]['profile_id'] = $profile->profile_id;

try{
    // Now you can save the order.
    commerce_order_save($order);
    $status = 1;
    $message = "order update successfully.";
}catch(Exception $ex){
    $status = 0;
    $message = "order can't update successfully.";
}

$reply= (array('status' => $status,'message' => $message));

return $reply;
}

Reference site - Programatically Create Order with Customer Profile
, Creating Customer Profiles Programmatically
Comment: You can still use wrappers here, bit this is correct because it replaces the reference value. With a wrapper you just need `$wrapper->commerce_customer_billing = $profile` then save order.
Answer: You are saving the order, which would have the state that it held before you made it into a wrapper. You need to save the $order_wrapper:
$order_wrapper->save();

Comment: You don't need ->save(), objects are always passed by reference, so $order was saved
Comment: I have tried as u said, but no billing information updated or changed. It seem to me I am following the wrong way, I think I have to create user profile and have to assign in order. https://drupalcommerce.org/discussions/2615/programatically-create-order-customer-profile


Will learning to play another instrument help me to become a better guitarist?

Question: I am a programmer and I do this for living. As a programmer, I've noticed how much difference it makes to learn another language - the quality of your work improves greatly, just because you know how things are done in different environments. Looking at the same things from another point of view cam be a bit help.
Does the same apply to music? Will learning the basics of piano, trumpet or violin help me at all? Are there any benefits of being able to play several instruments if my goal is to be better at guitar?
Answer: Learning another instrument will not necessarily make you a better guitarist; since the time spent learning another instrument is time that your spending not building your technical ability on the guitar.
It will however probably make you a better overall musician; since playing/learning a different instrument encourages you to think about your preferred instrument differently; and will probably give you a better idea of how they fit together musically.
There are many guitarists who have got ideas for their own playing by analysing the music of players of other instruments.  Actually learning another instrument is a natural extension of that.
Comment: Just to expand on this: Al Di Meola started as a drummer, ["Drums were my first love, and then guitar."](http://www.jazzreview.com/articledetails.cfm?ID=1082); Listen to his compositions, especially his early stuff with Return to Forever, and you hear how his rhythmic sense was very drummer-like. He's always been a good guitarist but knowing the drummer side of him explains the emphasis on great rhythms in his songs.
Comment: IMHO, sticking with the guitar but playing music from other genres than you're accustomed to might help you become a better guitarist. For example, if you're playing rock and roll most of the time, try playing an entry-level jazz piece or a classical piece. It will challenge your current technique as well as expand your view musically.
Comment: I believe "time spent learning another instrument is time that your spending not building your technical ability on the guitar" is strictly false.

'Time spent on practice' isn't something fixed that needs to be allocated - if we look at how human motivation and pedagogy work, changing to different activity may easily create additional time as a separate hobby, and even revigorate previously lost motivation to spend time on practice and play.
Comment: I started music as a clarinet/Alto sax player and as a guitarist I have a better sense of melody and phrasing than I do for complex rhythms as I'm sure a once drummer would have on guitar.  A drummer, I assume that begins to play guitar would be able to grasp the strumming faster than say scales and phrasing.   Any body have that experience?
Comment: Accepting the answer because you also have mentioned the back-draws: "Learning another instrument will not necessarily make you a better guitarist; since the time spent learning another instrument is time that your spending not building your technical ability on the guitar." Thank you!
Comment: Yeah have similar experience; i started out with the violin in school; picked up the guitar in my mid teens, I was pretty much instantly playing melody and my phrasing was ok.  It took me longer to get to grips with chords and rhythm.
Answer: Learning the piano is the best way to learn about music in general.  Its orderly, logical keyboard layout reinforces music theory concepts that can be otherwise difficult to learn and appreciate.  Plus, the ability to play bass, melody, and chords simultaneously make it a great way to learn how all the different parts of music work together to make a whole sound.  In fact, it's such a good way to learn about music that most music schools require their students to pass a keyboard proficiency test, regardless of the instrument they're primarily studying.  It's not an accident that almost all of the major composers of Western classical music were at least decent keyboardists, and some (Beethoven*, for example) were among the very best pianists in the world.
If you were also a bassist, I'd recommend too that you learn to play the drums at least passably well.  The bass/drums interplay is the foundation of most pop music, and when both instrumentalists understand each other better, it can go a long way to making your lives easier.
As for trumpet, saxophone, and other non C-based instruments, you don't have to learn how to play them, but it would probably be helpful to at least understand that they call the notes by different names than you do: for example, when you ask a trumpet player to play a C, the sound that comes out will actually be a B♭.  Understanding that will clear up a lot of confusion.

*Possibly apocryphal but believable story about Beethoven's piano prowess: He played the piano for the world premiere of his Piano Concerto #1 in C Major (this part is undisputed fact).  When he arrived at the concert, the orchestra had tuned to the oboe, as is SOP, so they were in standard concert pitch.  But the piano, it turns out, was a half-step flat.  Rather than re-tune the orchestra---because, after all, he wrote the piece in C and not B for a reason---he proceeded simply to sit down and play the entire piece in C♯ (!!).
Update: The Beethoven story apparently comes from Carl Czerny, who was a student of Beethoven's at the time and who had been asked by Beethoven to serve as page turner for the performance. To my mind, this lends credence to the story, as astounding as it is.
Comment: The piano is called the "composer's instrument" because it lays out all the intervals and chords where they're right in front of you. I also started with it, added trumpet, then picked up guitar. My piano knowledge came in very handy and helped me visualize a lot of chord and interval things, especially when I was taking music theory. I'm not sure playing other instruments helps with guitar technique. Knowing theory definitely helps with guitar because it helps you know how to build chords and pick the right scales.
Comment: Learning the piano may be the best way to learn about _western_ music. It's pretty hard to play any style that uses quarter tones on a piano. Of course, that is fine for fretted guitars, but why limit yourself?
Comment: As a proficient guitarist and one time Sax player..the piano still scares me to death and have a hard time doing anything but throw my fingers down and try to make a cool sounding chord.  I agree with the reply 100%  I WANT to learn piano so that it will enhance my ability to grasp poly rhythms and chord interplay.
Comment: I'm also from the school of thought that thinks theory on a piano is the right place to start learning theory. And cool Beethoven story.
Comment: Once you get to a certain level on the piano, you start realizing that the guitar is really a piano with a different layout ... and you start experimenting with your chording hand over top of the neck and "keying" the strings instead of coming from below ... hehe.  +1!
Comment: _If you were also a bassist..._ - hard to agree with that. Bass requires dedication and you don't need to **play** drums - you need to **listen** to drummers and how bass players and drummers work together, and when you play, you work with the drummer. Whenever I play bass in a group, I stand right in front of the drummer, a lot of the time with my back to the audience, and I tend to block out to a large extent what other people are playing because it distracts from what I'm trying to do on bass. The drummer is my partner in crime - bass and drums are the heart of it all.
Answer: I think learning other instruments can give you great new perspectives on music and how it's made.
Take the piano for example: a radically different approach to music creation. Very linear. There's only one place to play a C3 on the piano. There can be multiple places to play the same note on the guitar. That may make certain musical expressions and techniques easier on the guitar, which in turn may make expressing your music easier if you understand how to play the piano. I'm actually of the school of thought that thinks theory should be taught at a piano first. It's linear and you can see exactly what notes you're playing quite clearly.
And knowing other instruments can also help you understand their roles in an ensemble. If you can keep a beat on the drums, you'll understand better why the drummer can't make 5 things sound simultaneously (because he's only got 4 limbs to hit things with). You'll understand an instrument's range, it's limitations and you can score better for it if you're writing for an ensemble.
In addition to a deeper understanding of music, I just personally think there's a ton of joy in exploring new instruments. You get to revisit that struggle to get proficient. You get to have those "ah ha!" moments all over again, where you suddenly realize some deep new insight in to your instrument. The journey, in my opinion, is so much a part of the fun.
Comment: @DRL for me it's drums. Co-ordinating four limbs I find very, very hard. But I like the struggle nonetheless.
Comment: This is true, I never thot about being able to play potentially 10 notes at once instead of only 6 till I began to noodle on the keyboard.
Comment: I have found that the more proficient with one instrument; the less of a struggle it is to become proficient in another (I'm excluding wind instruments from this statement, since learning how to blow is whole 'other kettle of fish)
Answer: My 2 cents : if you are a guitarist, and want to dramatically improve your playing, take drum lessons.
It might seem surprising, but after one month you won't play guitar the same way. At all.
The idea is to litterally add another dimension to your playing style.
Piano or another "harmonic" instrument won't make so much different. Additionally, I don't know if you are playing the classical guitar, but piano is definitely a symetrical instrument somehow, which is not necessarily a direction in which you want to go forward when playing such a disymetrical instruemnt as the guitar.
What will drumming lessons bring to you ?
You will become sensitive to rythm. Very sensitive. Much more sensitive than with all the "studies" you may go through and which are purely intended at improving your guitar playing.
You will realize the essential role of dynamics. You can play a whole piece of music with only one snare drum. By varying rythm, notes intensity, and the exact place where you hit them, you create a variety that feeds the piece you are playing. Always the same note.
Good luck !
(P.S. : try to learn on a real drumset, not an electronic one. They have a much lower dynamics amplitude)
EDIT:
Just saw you were a programmer. An analogy would be that you will make a bigger conceptual leap, as a C++ programmer, by diving into LISP, than by learning Java, which is quite similar and won't teach you how to think differently.
Comment: As someone who started on drums, I can wholeheartedly agree with this. I'd also add that it forces you to focus more on the group dynamics when playing in a band. As a drummer, I couldn't stand guitarists who were off in la la land ignoring what the rhythm section was doing. As a guitarist now, I pay more attention to the drums than anything else when performing.
Answer: Learning other instruments will open you up as a musician. Composers in particular need to learn how to write for multiple instruments, for the simple reason that songs will sound different when written for different instruments -- even when written for different musicians! When I started writing songs specifically for my band's flute player, and tailoring songs to our singers' vocal ranges, these pieces were always easier to learn when rehearsing, and were simpler to play live.
This in turn caused me to be more comfortable as a musician. I write a lot of songs on the piano and, even though I'll later transfer them to guitar -- it's much harder to bring an 88-key keyboard on a gig than a guitar -- these songs sound different than the ones I wrote on guitar.
Putting writing to the side, knowing multiple instruments can make a musician more confident in their playing. I sometimes learn a song on piano, later transferring it to guitar to play it live; this will change how I play the piece, perhaps learning a piano part on guitar that I wouldn't have thought to try.
Answer: I learned piano and violin before moving on to guitar.
Some of the guitarists I learn with struggle with improvising harmonies. It feels logical that if one note in the melody harmonises with, say, its fifth, then moving that chord shape up or down the fretboard for the next note will also create a pleasing chord -- yet that doesn't always work.
It's possible to explain why this is without recourse to a piano keyboard -- but it's a lot easier to explain if you can use a keyboard. Likewise there are things that are easier to explain with a guitar than a piano.
I would like to add though, the piano layout is especially biased towards western music; locked as it is to a chromatic scale, and laid out around a major scale.
Answer: Definitely. Cross training to see how the "other guy does it" will make you a better musician. Someone that other musicians will want to play with, because you develop an empathy for the work that others do.
The attack on a trumpet is different than an attack with a sax. Knowing this can affect the way a drummer sets up figures in a piece of music. As a drummer, I try to think of tempo in relation to how hard a part is to play on sax or guitar at that tempo, or if the singer will be able to phrase effectively. It just takes a second, but my bandmates appreciate that, and over time, I wound up with a reputation for having "big ears" That's a killer compliment to a musician.....
Answer: I'd like to reiterate what Skippy Fastol said (drum lessons)  and add that a lot of searing, blisteringly good solo/lead guiltarists I have heard aren't so good on the rhythm side. I don't want to assume this of you, but I've always thought that some drum lessons would help them appreciate the excellent play to be had with dynamics, syncopation, and also what you don't play as well as what you do. That is : When a note stops is as important as when it starts. Learning drums has worked wonders for me in this respect. Somehow I seem to get more than twice as much fun out of music.  The whole is larger than the sum of the parts, and all that.
Learning bass guitar might be an easily accessible turn. Still stringed, you can play the tune immediately as it's tuned the same as a guitar's bottom 4 strings - but what works well on a bass is totally different to what works on a guitar, so you have to re-learn how you're going about it. It's a rhythm instrument, and the notes are almost secondary.
Go for it ! I hope you enjoy it as much as I have :-D
Answer: Have you ever noticed that picking up a guitar you haven't played before encourages you to play differently?  The same thing happens playing different instrument, only more so.  You have less muscle memory to constrain you.  And while that might result in some dissonant rubbish, it can also result in pleasing new phrases.
Answer: Honestly YES YES YES! Essentially like learning a new programming language whether it be C# or python or whatever else, You are building on an already set base of knowledge, take the bass as a fine example, I found after learning to play the bass my skill and knowledge in guitar benefited greatly from this, when you are learning another instrument, just as the other gentleman said, you are becoming a better overall musician but all instruments benefit from each other when you learn them because you are able to combine that mix of knowledge to form one great central of instrument knowledge, from experience though, not all instruments you learn can make you a better guitar player exactly said, You just benefit very nicely from your combined knowledge of all those instruments as well as their role and your role in playing them. It is always good to learn more and as much as you can


Adding price field on Drupal Commerce that affect Order Price

Question: The case is
When user place an order, shipping price must be manually calculated before the final invoice is sent to user.
What I do
I create Price custom field on Order named shippingfee.
Problem is
How to make shippingfee field affect the Order price?
Another thing that I tried is creating custom line item type. I'm thinking that by creating this custom line item type would update the value.But following this tutorial, the custom line item type did not appear when I check on admin/commerce/config/line-items.
Code added to custom module:
/**
 * Implements hook_commerce_line_item_type_info().
 */
function owemji_commerce_line_item_type_info() {
  return array(
    'owemji' => array(
        'name' => t('Shipping Fee'),
        'product' => false,
        'description' => t('Price of shipping.'),
        'base' => 'owemji',
    ),
  );
}

/**
 * Implements hook_enable().
 */
function owemji_enable() {
  commerce_line_item_configure_line_item_fields(array('owemji'));
}

I did try clear cache and disable -> enable the owemji module, but it's still not there.
Comment: FYI: There is a module for custom line item types creation: [Commerce Customizable Products](https://www.drupal.org/project/commerce_custom_product)
Comment: approach with order price is wrong. order price should be calculated with line items. see my answer below about 'commerce_shipping' and 'Commerce Flat Rate' module. It creates shipping line item from the box and takes care about all the calculations. The only thing you need to do is configure rules. See the videos in my answer
Answer: There is a contrib module developed espacially for shipping - Commerce Flat Rate

This module allows you to define any number of flat rate shipping
  services via the user interface in conjunction with Commerce Shipping
  2.x. When you define a new flat rate service, you specify the base rate for it in the add / edit form. You can further modify the base
  rate (enabling things like weight or quantity based shipping) using
  rate calculation rules.
This is functionally equivalent to using product pricing rules to add
  discounts or fees to base product prices before adding them to the
  cart.

There are few old but still actual video casts from rfay about Commerce Shipping. Watch it for a basic understanding:

Introduction to Commerce Shipping
Free Shipping Based on Order
Value or User Role
Shipping Discount for Item in Cart using
Calculation Rules
Answer: I think you can commerce_fees and if you want update you price according to user data you can do it with some custom coding and this module is what you want.
Answer: As @milkovsky said Commerce Flat Rate seems like the way to go.
Or if you want an even simpler solution : just create a Shipping product and manually add it to your order when you know the shipping.


Is it cheating to track val_loss and then measure accuracy on that same val dataset?

Question: So I'm training my neural network, and I've split my dataset into training and validation sets. I'm training the neural network on the training set, but I'm also tracking the validation set loss, and I'm actually using early stopping based on the validation loss to automatically stop training.
But then I'm assessing my classifier's accuracy on the same validation set I used to determine the early stopping point.
Is this a common practice, a totally unacceptable practice, or in sort of a grey area?
Thanks.
Answer: The best practice is to use a distinct partition to measure & report model performance. Chapter 4 of Elements of Statistical Learning covers this issue in detail.