How to altertable if not exist in c#?

Question: I have an API in .NET Core 3.1 which insert some data to my databases, the issue is that i had to add a new column to the column where i'm inserting the data, as then the api is called i'm dynamically connect to the database to which i should do the insert, how could i make an altertable if that column not exist and then insert the new item?
Here is the method where i'm inserting the stuff:
public static IActionResult InsertOrder(string piva, string idNegozio, RiepilogoTakeaway ordine, HttpResponse Response) {
            string connectionString = getConnectionString(piva);
            var query_ordine = @"INSERT INTO `ordini` (`TIPO_OR`, `TAVOLO_OR`, `ORA_OR`, `SENT_OR`, `ID_OR_CFG`, `LOTTERIA_OR`) VALUES (@tipo, @tavolo, NOW(), 0, @id, @lotteria); SELECT LAST_INSERT_ID();";

            using var connection = new MySqlConnection(connectionString);
            using var cmd = new MySqlCommand(query_ordine, connection);
            cmd.Parameters.AddWithValue("@tipo", "STB");
            cmd.Parameters.AddWithValue("@tavolo", 0);
            cmd.Parameters.AddWithValue("@id", idNegozio);
            cmd.Parameters.AddWithValue("@lotteria", ordine.lotteria);
            connection.Open();
            cmd.Prepare();

            string idOrdine = cmd.ExecuteScalar().ToString();

            ...
}

And that's the alter table i should execute:
ALTER TABLE `ordini`
ADD COLUMN `LOTTERIA_OT` VARCHAR(10) NULL AFTER `ID_OR_CFG`;

Which would be the best way to do it?
Comment: Hello there, according to the language i probably miss something but i don't understand why you need to add a column on a C# runtime. Is there no other ways ?
Comment: @BradleyGrainger: Oops, missed the MySQL tag. Thanks for the pointer. Removed the comment.
Comment: @stickybit `AddWithValue` is fine for MySQL: https://mysqlconnector.net/overview/using-addwithvalue/
Answer: Try to deploy the SQL changes before calling it. It's very likely that you'll need higher level of privilege in the database to run the alter or add column, for example, if the SQL user you are using to insert the order doesn't have permissions to change the DB schema.
However, if that is still an option, you will need to execute the SQL schema changeusing  command.ExecuteNonQuery().
Possibly worth creating a new method "PrepareSqlTable" so you can call before your query runs. Bear in mind that will impact your application performance/scalability because now we'll be checking that on every single query.
Another alternative, handle this in the catch by looking into the error message and creating it accordingly (provides more performance benefits than the previous option).

How to altertable if not exist in c#?


What is the integral of $\frac{\arcsin x}{(1-x^2)^{3/2}}$?

Question: I was attempting this integral:
$I = \int \dfrac{\arcsin x}{(1-x^2)^{3/2}} dx$.
But I am getting the wrong answer.
My approach:
Let  $\arcsin x = t \implies  dx = \sqrt{1-x^2} dt$.
So, $I =\frac{t}{\cos^2 t} dt = t × \tan t - \int \tan t dt = \dfrac{\arcsin x × x}{\sqrt {1-x^2}} + \ln (\cos t) + K $.
But apparently, the correct answer includes a negative sign in the first term, that is:
$I = - \dfrac{\arcsin x × x}{\sqrt{1-x^2}}+ \ln (\sqrt{1-x^2}) + K $.
So, I want to know where that minus sign comes from.
Comment: I made a small start in the title. With "copy-paste" you can try the rest?
Comment: Checking the original post, there seems to be a huge mistake in the above editing: the integrand originally was $$\frac{\arcsin x}{(1-x^2)^{3/2}}$$ . As it is now it appears as $$\frac{\arcsin x}{(1-x^2)^{3/\color{red}4}}$$
Comment: @MrReality No, there is none...but you can check this simply differentiating without a sign and with the sign...
Comment: I think something went very wrong during your LaTeX implementation...
Comment: You know.... you can preview your latex before posting. And you really should.
Comment: Sorry for this poor latex implementation. I don't know latex, so I pasted the syntax from other questions and this mess resulted. As you can see I have rectified it now.
Comment: @MrReality What you call "the correct answer" is for the function with the exponent $\;3/2\;$ in the denominator , as was **originally** in your post. As it is now the answer is the mess that appears in the answer below...
Comment: @DonAntonio, corrected that too. So, can you tell me which answer is correct: mine or the one with the minus sign?
Comment: @MrReality Apparently, no minus sign must be there...
Comment: As it stands now I don't think this question is inapt or the formatting is bad and so doesn't deserve this many downvotes. So can people upvote it to get it to "0" at least?
Comment: @MrReality You're correct. Sometimes people in this site get excited and a frenzy of downvotes begins. I already upvoted your question. +1
Comment: >> "*You're correct*" -            @DonAntonio, so you mean there is no negative sign in the first term of the solution, right?
Comment: @DonAntonio, Thanks then.
Answer: Whilst waiting for your LaTeX improvement...
$$\int \frac{\arcsin(x)}{(\sqrt{1-x^2})^{3/2}}\ \text{d}x = $$
$$ =  -\frac{\pi  \left(1-x^2\right)^{3/4} \, _3F_2\left(\frac{3}{4},\frac{3}{4},1;\frac{5}{4},\frac{7}{4};1-x^2\right)}{2 \sqrt{2} \Gamma \left(\frac{5}{4}\right) \Gamma \left(\frac{7}{4}\right)}-2 x \sqrt[4]{1-x^2} \, _2F_1\left(\frac{3}{4},1;\frac{5}{4};1-x^2\right) \sin ^{-1}(x)$$
Where $_aF_b$ are the hypergeometric functions, and $\Gamma(\cdot)$ is the Euler Gamma function.
Comment: I have rectified the poor formatting. Can you answer where the minus sign comes from, now?


Intersection of integer sets

Question: This is probably a trivial question for mathematicians but I am not seeing how to approach the following problem:
Imagine two sets defined by:
set1 = (x: x<stop1 and x = start1, ..., start1+n*step1, ...; n element of set of integers)
set2 = (x: x<stop2 and x = start2, ..., start2+m*step2, ...; m element of set of integers)

Where:

all variables are integers
step != 0

Example of what I mean by this:
for start = 3, stop = 20, step = 5:
set =  [3, 8, 13, 18]

I am looking for:

whether the two sets intersect
what start, stop, step are for the intersection set
Comment: What are $m$ and $n$?
Comment: @ToddWilcox m and n are integer. I added an example of what I mean with this notation to the question.
Comment: @Max I added a Ruby implementation to my answer. Have a look at the excerpt from the log to better understand how it works.
Answer: Mathematical Model:
You could model the sets $S_1$ and $S_2$ like this
\begin{align}
I_1 &= [a_1, b_1) \quad (a_1, b_1 \in \mathbb{N})\\
I_2 &= [a_2, b_2) \quad (a_2, b_2 \in \mathbb{N}) \\
Z_1 &= \{ x = a_1 + n \Delta x_1 \mid n \in \mathbb{Z} \} \quad (\Delta x_1 \in \mathbb{N}) \\
Z_2 &= \{ x = a_2 + m \Delta x_2 \mid m \in \mathbb{Z} \} \quad (\Delta x_2 \in \mathbb{N}) \\
S_1 &= Z_1 \cap I_1 \subseteq I_1 \\
S_2 &= Z_2 \cap I_2 \subseteq I_2
\end{align}
Then for an element of the intersection $S_1 \cap S_2$ we have the condition
$$
a_1 + n \Delta x_1 = a_2 + m \Delta x_2 \iff \\
(\Delta x_1) n - (\Delta x_2) m = a_2 - a_1 \quad (*)
$$
This is a linear Diophantine equation
$$
a x + b y = c \quad (**)
$$
plus the limiting condition
$$
a_1 + n \Delta x_1 \in I_1 \cap I_2
$$
A linear Diophantine equation $(**)$ has either no or infinite many solutions.
It has solutions if $\gcd(a,b) \mid c$.
Applying the Solution of the Diophantine Equation:
Translating this to the case of equation $(*)$ we have the criterion
$$
\gcd(\Delta x_1, \Delta x_2) \mid (a_2 - a_1) \quad (\#)
$$
In the case of solutions, we can find a particular solution by using the extended Euclidean algorithm to find integers $s$, $t$ with the property
$$
s \Delta x_1 + t \Delta x_2 = \gcd(\Delta x_1, \Delta x_2) \quad (\#\#)
$$
Then
$$
(n_0, m_0) =
\left(
\frac{a_2-a_1}{\gcd(\Delta x_1, \Delta x_2)} s,
-\frac{a_2-a_1}{\gcd(\Delta x_1, \Delta x_2)} t
\right)
$$
is a solution of equation $(*)$.
Then all solutions are
$$
(n, m) =
\left(
n_0 + k \frac{\Delta x_2}{\gcd(\Delta x_1, \Delta x_2)},
m_0 + k \frac{\Delta x_1}{\gcd(\Delta x_1, \Delta x_2)},
\right)
\quad
(k \in \mathbb{Z})
$$
Determining the Unbounded Intersection:
So we can use equation $(\#)$ to find out, if the intersection can have solutions. If it can, then we use the $s$ obtained by $(\#\#)$ to
calculate $n_0$ and use the first components of the above equation to calculate all $n$
and all elements
$$
x
=
a_1 + n \Delta x_1
=
a_1 + \left(
\frac{a_2-a_1}{\gcd(\Delta x_1, \Delta x_2)} s +
k \frac{\Delta x_2}{\gcd(\Delta x_1, \Delta x_2)}
\right) \Delta x_1
\quad
(k \in \mathbb{Z}) \quad (+)
$$
of
the unbounded intersection $Z_1 \cap Z_2$.
These then have to be tested against the boundaries of $I_1$ and $I_2$ to determine $S_1 \cap S_2$.
$$
a_1 \le x < b_1 \wedge a_2 \le x < b_2
$$
So it might a good idea to look even before $(\#)$ at $I_1 \cap I_2$ first, where we need
$$
a_1 < b_2 \wedge a_2 < b_1 \quad (++)
$$
for a non-empty intersection $I_1\cap I_2$.
Start, Stop and Step of the Intersection:
From the above we take that the step of the intersection set is
$$
\frac{\Delta x_1 \Delta x_2}{\gcd(\Delta x_1, \Delta x_2)}
\quad (\$)
$$
Start is found via the smallest feasible $k$, let us call it $k_1$
such that
$$
\left(
a_i - a_1 - \frac{a_2-a_1}{\gcd(\Delta x_1, \Delta x_2)} s \Delta x_1
\right)\frac{\gcd(\Delta x_1, \Delta x_2)}{\Delta x_1\Delta x_2}
\le k
$$
thus
$$
k_1 = \max_{i \in \{1,2\}}
\left\lceil
\left(
a_i - a_1 - \frac{a_2-a_1}{\gcd(\Delta x_1, \Delta x_2)} s \Delta x_1
\right)\frac{\gcd(\Delta x_1, \Delta x_2)}{\Delta x_1\Delta x_2}
\right\rceil
$$
The element $x$ just before stop is found via the largest feasible $k$, let us call it $k_2$
such that
$$
k <
\left(
b_i - a_1 - \frac{a_2-a_1}{\gcd(\Delta x_1, \Delta x_2)} s \Delta x_1
\right)\frac{\gcd(\Delta x_1, \Delta x_2)}{\Delta x_1\Delta x_2}
$$
thus
$$
k_2 = \min_{i \in \{1,2\}}
\left\lfloor
\left(
b_i - a_1 - \frac{a_2-a_1}{\gcd(\Delta x_1, \Delta x_2)} s \Delta x_1
\right)\frac{\gcd(\Delta x_1, \Delta x_2)}{\Delta x_1\Delta x_2}
\right\rfloor
$$
or one less if the argument of floor was already an integer.
Plugging the found $k_1$ and $k_2$ into equation $(+)$ then gives start and stop values of the intersection.
Summary:
We gave two criteria, equations $(\#)$ and $(++)$ to determine if there is a non-empty intersection at all.
We further listed the solution process which allows to determine all solutions enumerated by an integer parameter $k$ and gave conditions how to find the parameters $k_1$ for the smallest and $k_2$ for the largest feasible solution, which can be used via equation $(+)$ to get start and stop values.
We also listed the step value of the intersection, see equation $(\$)$.
The method looks complicated, but has the big advantage of being fast, the sizes of the sets do not really matter, so I would consider it $O(1)$.
Implementation:
I implemented a sample program in Ruby, to find out if this works as planned. You can find the source code here.
I am happy to not have to correct the above formulas.
The biggest bug I was running into during implementation was not using floating point arithmetics for the calculation of $k_1$ and $k_2$. The rest only needs integer arithmetics.
Testing went against a brute force implementation of the set intersection.
Over one million random test cases passed, so I think it mostly works. See an excerpt from a log here.
The output should help to understand this approach.
Comment: Thank you so much! It seems the problem is not quite as trivial as I first thought. It is going to take me a bit of time to digest your answer...
Comment: You write "solutions, we can find a particular solution by using the extended Euclidean algorithm to find integers s, t with the property ..." Why do the solutions satisfy this property? I am surprised since the offsets a1 and a2 do not seem to come into play.
Comment: The solutions of finding working  $n$ and $m$ show up after that, and involve the difference of $a_1$ and $a_2$.
Answer: If I understand correctly you are considering the sets
$$A= \{x| x= a+n*s_A, \space n\in\mathbb{Z}\}$$
and
$$B= \{x| x= b+n*s_B, \space m\in\mathbb{Z}\}$$
with the given boundaries (in other words intersected with $[start, stop]$).
To solve $A\cap B$, you need to solve the diophantine equation
$$s_A*n - s_B*m = b-a$$
See for example here how this can be done: Linear Diophantine Equation
Then take every $a+n*s_A$, for the $n$'s that are in a solution of the diophantine equation. Lastly intersect with the interval. Of course the way to actually do this is to start with the first non-negative $n$ and go on until $a+n*s_A$ becomes larger than the smaller of the boundaries.

Intersection of integer sets


Javascript merge object children to a new object

Question: I am trying to merge obj's children to be a new object.
const obj = {
  "1": {"string1": "string11"},
  "2": {"string2": "string22"},
  "3": {"string33": "string33"},
  "4": {"string44": "string144"},
};

Object.assign is able to merge multiple objects
can do this way:
Object.assign({}, obj[1], obj[2], obj[3], obj[4])
However, if obj is a dynamic object, more children objects would be added like
const obj = {
  "1": {"string1": "string11"},
  "2": {"string2": "string22"},
  "3": {"string3": "string33"},
  "4": {"string4": "string44"},
  "523": {"string5": "string55"}
  "more": {'something', "new string"}
  . . .
};

How to merge them automatically?
Answer: You can use the spread syntax:
Object.assign({}, ...Object.values(obj))

Comment: You can just merge one by one. Put `let result = {}` before the loop and `Object.assign(result, obj[key])` inside.
Comment: Ah! Thank you for the answer
Comment: Will take the answer. Thanks. If use loop like `for (let key in obj) {
  if (obj.hasOwnProperty(key)) {
    console.log(obj[key]);
  }
}` how to merge `(obj[key])` use this way? just curious if it is easy as well. thanks
Comment: Awesome! Thanks a lot


Comparação de caracteres de strings em C

Question: Estou tentando fazer um exercício que testa se existe algum espaço em branco antes de uma string e remove se tiver, porém está retornando o seguinte erro:

Falha de segmentação (imagem do núcleo gravada)

Não consigo entender o motivo.
Código:
<code>#include <stdio.h>
void removerEspacosEsquerda(char string[]) {
    int i, j, cont;
    char *string2, a;
    i = 0;
    cont = 0;
    while(string[i] != 0) {
        if(string[i] == ' ') {
            cont++;
        }
        i++;
    }
    i = 0;
    j = 0;
    printf("%d", cont);
    while(string[i] != 0) {
        if(i >= cont) {
            string2[j] = string[i];
        }
        i++;
        j++;
    }
    string = string2;
}
int main() {
    char *string;
    string = " teste";
    removerEspacosEsquerda(string);
    printf("%s", string);
}
</code>
Comment: Alguma das respostas resolveu sua dúvida? Acha que pode aceitar uma delas? Veja o [tour] como fazer isso, se ainda não o fez. Você ajudaria a comunidade identificando qual foi a melhor solução para você. Pode aceitar apenas uma delas. Mas pode votar em qualquer pergunta ou resposta que achar útil no site todo
Answer: Seu código é complexo demais e o erro ocorreu por causa disto, quando simplificamos ele o erro nem tem oportunidade de aparecer. Não precisa ter 2 loops (3 pela solução da outra resposta) e não precisa ter alocação de memória:
<code>#include <stdio.h>

void removerEspacosEsquerda(char string[]) {
    int cont = 0;
    for (int i = 0; string[i] != '\0'; i++, cont++) {
        if (string[i] == ' ') cont--;
        else string[cont] = string[i];
    }
    string[cont] = '\0';
}

int main() {
    char string[] = " teste";
    removerEspacosEsquerda(string);
    printf("%s", string);
}
</code>
Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Answer: A falha de segmentação ocorre porque o ponteiro "string2" não foi inicializado.
<code>#include <stdio.h>
#include <stdlib.h> // para malloc e free

void removerEspacosEsquerda(char string[])
{
  int i, j, cont;
  char *string2 = malloc(strlen(string)+1), a; // <-------------
  i = 0;
  ....
  ....
  strcpy(string, string2);
  free(string2); // <-------------
} // fim removerEspacosEsquerda
</code>
Note que não analisei se sua lógica de remoção de espaços está correta, estou apenas resolvendo o problema da falha de segmentação.


How do I add extra space or dashed symbol to select option?

Question: I want to make a select tree for my category. Here is for unordered list.
function generate_menu($parent, $menu_array = null)
{
    $has_childs = false;
    foreach ($menu_array as $key => $value) {
        if ($value['parent'] == $parent) {
            if ($has_childs === false) {
                $has_childs = true;
                echo "
\n";
            }
            echo '
'.$value['name'].'';
            generate_menu($key, $menu_array);
            echo "
\n";
        }
    }
    if ($has_childs === true)
        echo "
\n";
}

Here is the HTML output for unordered list.

    Ford

        Falcon

            Futura

FPV

GT

F6

GS

F150

Festiva

Question : How to make the current function for select option and the results will be something like this.
<select name="categories">
    <option value="Ford">Ford</option>
    <option value="Falcon">-Falcon</option>
    <option value="Futura">--Futura</option>
    <option value="FPV">--FPV</option>
    <option value="GT">---GT</option>
    <option value="F6">---F6</option>
    <option value="GS">---GS</option>
    <option value="F150">-F150</option>
    <option value="Festiva">-Festiva</option>
</select>

Comment: If you want to generate the `option` like you did with the `ul`, you need to provide another parameter for the `$level`. Each time you go into the function you increase the `$level` by one and each time you go out there, you decrease by one (that is beginning and end of the function in your case). Default value for `$level` is 0.
Comment: replace `ul` with `select`, and `li` with `option`
Comment: Please add also the HTML output of the ul/li list to your question. It's normally easy to convert that into the strings you want to use for the select.
Comment: @Ibu Yes sure, if in unordered list, it has `` to separate the children. On select option I want to add `- Sub`, `--Sub`, `---Sub`.
Answer: I would go with the text-list you have already, it's a breeze to turn it into the <select> element:
$list = <<<LIST
Ford
| Falcon
| | Futura
| | FPV
| | | GT
| | | F6
| | | GS
| F150
| Festiva
LIST;

echo '<select name="categories">', "\n";
foreach (explode("\n", $list) as $entry) {
    $label = strtr($entry, ['| ' => '-']);
    $value = trim($entry, ' |');
    printf("  <option value=\"%s\">%s</option>\n", htmlspecialchars($value), htmlspecialchars($label));
};
echo "</select>\n";

Output:
<select name="categories">
  <option value="Ford">Ford</option>
  <option value="Falcon">-Falcon</option>
  <option value="Futura">--Futura</option>
  <option value="FPV">--FPV</option>
  <option value="GT">---GT</option>
  <option value="F6">---F6</option>
  <option value="GS">---GS</option>
  <option value="F150">-F150</option>
  <option value="Festiva">-Festiva</option>
</select>

Otherwise if you were unable to generate this text-list but only the ul/li list, then work on that HTML but in the same fashion.
After you've updated and provided the HTML, here is it working of the ul/li list string ($ul) (PHP 5.4):
echo '<select name="categories">', "\n";
foreach ((new SimpleXMLelement($ul))->xpath('//li') as $li) {
    $label = htmlspecialchars(trim($li->xpath('text()[1]')[0]));
    $level = count($li->xpath('ancestor::li'));
    printf(
        "  <option value=\"%s\">%s%s</option>\n",
        $label, str_repeat('-', $level), $label
    );
}
echo "</select>\n";

How this works is outlined more in this earlier answer of mine: How can I extract structured text from an HTML list in PHP?. That one is with DomDocument not SimpleXMLElement like here, however, the more or less main part is the xpath here which both provide.
This is all fine and dandy. However you somewhat must have missed to actually provide the sample array - I just now assumed:
array (
  1 =>
  array (
    'parent' => 0,
    'name' => 'Ford',
  ),
  2 =>
  array (
    'parent' => 1,
    'name' => 'Falcon',
  ),
  3 =>
  array (
    'parent' => 2,
    'name' => 'Futura',
  ),
  4 =>
  array (
    'parent' => 3,
    'name' => 'FPV',
  ),
  5 =>
  array (
    'parent' => 3,
    'name' => 'GT',
  ),
  6 =>
  array (
    'parent' => 3,
    'name' => 'F6',
  ),
  7 =>
  array (
    'parent' => 3,
    'name' => 'GS',
  ),
  8 =>
  array (
    'parent' => 0,
    'name' => 'F150',
  ),
  9 =>
  array (
    'parent' => 0,
    'name' => 'Festiva',
  ),
)

to point you to some method that is aligned with what you already do for the ul/li list, a recursive function that works with your array:
function generate_dropdown($menu_array, $parent = 0, $level = -1) {
    ++$level || print('<select name="categories">'. "\n");
    foreach ($menu_array as $key => $value) {
        if ($value['parent'] != $parent) continue;
        $label = htmlspecialchars($value['name']);
        printf("  <option value=\"%s\">%s%s</option>\n", $label, str_repeat('-', $level), $label);
        generate_dropdown($menu_array, $key, $level);
    }
    $level-- || print('</select>');
}

generate_dropdown($array);

Output:
<select name="categories">
  <option value="Ford">Ford</option>
  <option value="Falcon">-Falcon</option>
  <option value="Futura">--Futura</option>
  <option value="FPV">---FPV</option>
  <option value="GT">---GT</option>
  <option value="F6">---F6</option>
  <option value="GS">---GS</option>
  <option value="F150">F150</option>
  <option value="Festiva">Festiva</option>
</select>

Comment: yes, that is possible. The [this answer shows that for the `CHILDREN` column](http://stackoverflow.com/a/14086249/367456) in the output (you turn that into a list of parents by changing the xpath axis from `./ul/li`  to `./ancestor::li`), see as well xpath axes here: http://dret.net/lectures/xml/xpath#xpath-axes
Comment: If your array list is sorted, it's also possible to obtain the parents by making `$level` an array of parent elements. The count of it provides the level and the array would give you parents stuff, like their labels. Let me cook that up, I think I still have the code on platter.
Comment: Yes that would be it. Was distracted, need to see if and when I add it here. It's basically like how I outlined.
Comment: Excellent! thank you so much @hakre. You made my day. Paypal button should be in your profile :)
Comment: It's possible to add parent name to chilren `Ford->Falcon`, `Falcon->Falcon->FPV`
Comment: currently i use your `generate_dropdown` function.
Comment: I got it :) First i rebuild the array http://stackoverflow.com/a/10332361/1286499 then http://stackoverflow.com/a/6812689/1286499 and cool!


The motivation behind axiomatisation

Question: Axiomatisation in the context of rings
I am in the middle of an elementary pure mathematics unit and have just started looking at the concept of rings. In lectures, we have divided up rings into several categories defined axiomatically:

Commutative rings - multiplication is commutative but there does not exist a multiplicative inverse for every non-zero element.
Division rings - a multiplicative inverse exists for all non-zero elements, but multiplication is not commutative.
Fields - multiplication is both commutative and invertible.

I can understand the motivation to separate and 'axiomatise' these structures so that their properties are inherited by 'sub'-structures which are consistent with their axioms (i.e. quaternions form a division ring and so they must have certain properties), but I am still confused about the purpose of this practise.
So here are the questions:

Why do mathematicians define these sorts of structures?
How do they aid pure mathematicians in their research?
What are some examples of non-obvious properties that can be inferred from these or other axioms?

I have some experience programming so if analogies can be drawn between this and object oriented programming (i.e. subclassing perhaps) then that could help. Also please keep in mind that I have only just started learning abstract algebra so I will not be familiar with many structures or advanced concepts.
Thanks.
Comment: Ah right, I keep mixing that up. Thanks.
Answer: You might be familiar with the programming rule of abstraction that the third time you write a piece of code to do something, you should refactor your program to move that functionality out into its own class or function.
Commutative rings, division rings, and fields have come up way more than three times in mathematics. :)
Encapsulation is just as useful in mathematics as in programming to hide away extraneous information, thus making it easier to work with something. The best example of this sort of thing I know came up in quantum physics (which I will describe somewhat glibly): when the field began, all of the math was deep in the theory of partial differential equations and differential operators, which are quite complicated and rather laborious to work with.
Then Dirac came along and said "this is all just linear algebra", introduced Hilbert spaces and bra-ket notation, and poof quantum physics quickly became much, much easier to work with and reason about.

My history is somewhat weak, but I believe commutative algebra really originated with the development of algebraic number theory: when people started studying number rings and number fields in the attacks on Fermat's Last Theorem, they quickly realized that there was a lot of interesting structure there... as well as lack of structure (e.g. many number rings don't allow unique factorization into elements).
As new structure was discovered, new ways rings could be pathological, and new sorts of arguments for reasoning about rings, definitions were given that supported these sorts of structures and reasoning, or separated the rings we are actually interested in from the badly behaved ones.
e.g. the notion of a Noetherian ring came about when Emmy Noether realized the power of making arguments based on the ascending chain condition: an infinite chain of ideals $I_1 \subseteq I_2 \subseteq \cdots$ is eventually constant. Rings people are interested in often have this property, but general rings do not: the structure "Noetherian ring" is thus defined, so that people have words to say that they are working with rings that allow this sort of argument.
Comment: You've explained well the abstraction aspect of axiomatisation and how historically it makes algebraic manipulation less arduous, but I'm also looking for a simple, concrete example (that I am capable of understanding at this stage!) of how a significant theorem or other result is derived from axioms and applied across a range of sub-structures as a result of 'axiomatic encapsulation'. Preferably a result that was discovered a reasonable period of time _after_ the invention of the 'axiomatic superstructure'. I ask for this because I want a tangible sense of how these definitions help.

The motivation behind axiomatisation


Running a bat file in XP as a windows service

Question: Im using Windows XP and i want to run a particular bat file as a windows service.Is there any way to do that ?
Please Help
Thank You
Comment: as a service or a schedule event? what does the bat file do?  The answer is yes but you need to get the windows 2003 resource kit to get the srvany.exe command.
Comment: A batch file won't make a very good service. For one thing it won't respond to any of the service commands like restart or stop. Batch files are also not designed to run continuously (like a service should).
Answer: You can use the sc command.  For example, from a command prompt:
sc create MyService binPath= "C:\Program Files\Windows Resource Kits\Tools\Srvany.exe" DisplayName= "My Windows Service"

To remove:
sc delete Service

Now, the service created is using Srvany.exe, which is part of the Windows Resource Kit.  This enables you to define a service with your software that otherwise would not support it.
After that, you will need to use RegEdit to create a "Parameters" key for your service under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MyService\.  Within that key, you will want to create a string value called "Application" and enter the full path to your batch file that you want to run as a service.
Microsoft has instructions for this as well using a different method to create the service initially.
Comment: does that work or do you need to host the process with srvany.exe
Comment: Good point, last time I created a service it was for something that supported it.
Answer: Running a batch file as a service is a fairly odd application, and there's a reasonable likelihood that you're going to have problems.
Assuming that you have a batch file that runs in a continuous loop, I suppose you could run the batch file as a service. Like Warner says, you're going to want have to use a "service manager" wrapper (like the SRVANY that Warner mentions, or the free Non-Sucking Service Manager (NSSM)) program.
Warner's description of creating a service w/ SC, referencing SRVANY, is all correct. For some technical background: A real service program responds to control functions from the service control manager (SCM). These control functions allow the service control manager (and, thus, the Services management console snap-in, etc) to stop, start, pause, etc, the service program. The basic flow is:
SCM --(invokes)--> wrapper (SRVANY, NSSM) --(invokes)--> your program
If your batch file spawns additional processes when you stop the service (which is really stopping the wrapper program) you'll find that programs spawned by your batch file won't be killed and will hang around indefinitely.
SRVANY also doesn't monitor your batch file (running in CMD.EXE), and if your program "dies" the "service" will remain listed as "started". (NSSM can monitor the child CMD.EXE and restart it, but NSSM still suffers from the problem of not killing child processes of the batch file on service stop).
NSSM has a GUI to help create the service and associate it with your program. You might like that if you're not a command-line and registry-manipulation kind of person.
All-in-all, running non-service programs in wrappers isn't a recommended practice. I do it in some production environments, but I'm always wary of it and try to test such applications a lot before I consider it "working".


DMARC and RFC2298 compliant MDNs with a null MailFrom... Can it work?

Question: This is an issue we're seeing with Exchange Online but it would be an issue with most hosted email I suspect. When Office 365 / Exchange Online sends an automatic reply (Out of Office for example) it adheres to RFC 2298 and the RFC5321.MailFrom is null:
RFC 2298 – Message Disposition Notifications
https://tools.ietf.org/html/rfc2298

   The From field of the message header of the MDN MUST contain the
   address of the person for whom the message disposition notification
   is being issued.

   The envelope sender address (i.e., SMTP MAIL FROM) of the MDN MUST be
   null (<>), specifying that no Delivery Status Notification messages
   or other messages indicating successful or unsuccessful delivery are
   to be sent in response to an MDN.

When the RFC5321.MailFrom is null SPF uses the "HELO/EHLO" identity of the sending server instead:
RFC 7208 - Sender Policy Framework (SPF)
https://tools.ietf.org/html/rfc7208

   SPF verifiers MUST check the "MAIL FROM" identity if a "HELO" check
   either has not been performed or has not reached a definitive policy
   result by applying the check_host() function to the "MAIL FROM"
   identity as the <sender>.

   [RFC5321] allows the reverse-path to be null (see Section 4.5.5 in
   [RFC5321]).  In this case, there is no explicit sender mailbox, and
   such a message can be assumed to be a notification message from the
   mail system itself.  When the reverse-path is null, this document
   defines the "MAIL FROM" identity to be the mailbox composed of the
   local-part "postmaster" and the "HELO" identity (which might or might
   not have been checked separately before).

The issues start when you're using DMARC because an OOF or NDR will look like this:

RFC5321.MailFrom: <>
RFC5322.From: "firstname.lastname@example.com"
HELO/EHLO identity: "mail-.outbound.protection.outlook.com"

When the receiving mail server does its spam checks they'll go something like this:

SPF against "postmaster@mail-.outbound.protection.outlook.com" -> PASS
DKIM against "c=relaxed/relaxed; d=company365.onmicrosoft.com; s=selector1-company-com" -> PASS
DMARC alignment between RFC5321.MailFrom and RFC5322.From -> FAIL because @*.outlook.com != @*.company.com

Actual header snippet (anonymized):
Return-Path: <>
From: John Doe <email@example.com>
Received: from xxx00-xx0-xxx.outbound.protection.outlook.com (mail-xxx00xx0xxx.outbound.protection.outlook.com. [104.47.xx.xxx])
        by mx.google.com with ESMTPS id y11si90960plg.98.2017.09.07.10.27.33
authentication-results: spf=none (sender IP is ) smtp.mailfrom=<>;
Received-SPF: pass (google.com: domain of email@example.com designates 104.47.xx.xxx as permitted sender) client-ip=104.47.xx.xxx;
Authentication-Results: mx.google.com;
       dkim=pass email@example.com header.s=selector1-company-com header.b=gb5VTzi+;
       spf=pass (google.com: domain of firstname.lastname@example.com designates 104.47.xx.xxx as permitted sender) smtp.helo=xxx00-xx0-xxx.outbound.protection.outlook.com;
       dmarc=fail (p=NONE sp=NONE dis=NONE) header.from=company.com

In that example p is equal to 'none' so the message arrives anyway but with reject or quarantine the message will never arrive and because the return-path is null no NDR is delivered to the user who sent the auto-reply (that's the point and why it's null.) So, the external contact doesn't get an auto-reply and doesn't know they were supposed to and the internal user doesn't know the external contact didn't get it. Lose-Lose.
Only through messages traces will you find the problem:
Event            : Fail
Action           :
Detail           : Reason: [{LED=550-5.7.1 Unauthenticated email from company.com is not accepted due to 550-5.7.1 domain's DMARC policy. Please contact the administrator of 550-5.7.1 company.com domain if this was a legitimate mail. Please visit 550-5.7.1
                   https://support.google.com/mail/answer/2451690 to learn about the 550 5.7.1 DMARC initi. OutboundProxyTargetIP: 74.125.xx.xx. OutboundProxyTargetHostName: gmail-smtp-in.l.google.com

With internal mail servers where the HELO/EHLO identity of the mail servers is whatever.mail.company.com this isn't an issue as aspf=r in the DMARC record will allow the subdomain to pass alignment; However, since the HELO/EHLO identity is a *.Microsoft domain and not *.company.com alignment will always fail.
Is there a way to overcome this limitation? Some sort of exception or policy flag? Using a rule to send automatic replies or using a transport rule are not in my mind solutions; They're workarounds and users will inevitably forget/ignore messaging and set auto-replies anyway.
Answer: If you set the DKIM for your custom domain "company.com" (d=company.com) it would be aligned with the RFC5322.From header and that would pass DMARC.
DMARC will pass if ANY of the two (SPF or DKIM) pass aligned with the RFC5322.From.
You can set the DKIM for your custom domain in the Exchange admin center -> Protection -> DKIM
Comment: Won't work unfortunately. When the from address is null such as with MDNs the RFC5322.From is interpreted as postmaster@ which for us is a Microsoft Office 365 server so there is no alignment. It's explained in detail in the post.
Comment: No, only Envelope From (RFC5321) is null. Header From (RFC5322) is 'email@example.com'. DKIM checks this against d= tag and if it passes, thats enough for DMARC to pass.


Changes from 3.5 to 4.0

Question: I need to help to port my 3.5 rc.lua to 4.0. I try to set one progressbar.
It used to be :
mybacklight = awful.widget.progressbar()
mybacklight:set_width(12)
mybacklight:set_height(10)
mybacklight:set_vertical(true)
mybacklight:set_background_color("#131211")
mybacklight:set_border_color(nil)

The new version should be :
mybacklight = wibox.widget.progressbar {
   max_value        = 1,
   value = brightness_new,
   forced_width = 12,
   forced_height = 10,
   background_color = "#131211",
   border_color = nil,
   color = {type="linear", from = {0, 0}, to = {0, 20},
            stops = { {0, "#F6F6F6"}, {0.5,
            "#bdbdbd"}, {1.0, "#3b3b3b"} } },
   widget           = wibox.widget.progressbar,
   direction        = 'east',
   layout           = wibox.container.rotate
}

The 3.5 version works (no errors) but does no more give the expected result, it should be a vertical progressbar, it is, but the progression itself is horizontal.
The 4.0 version makes no error, except that it takes all the place with red (default ?) colors.
Answer: First of all, the imperative syntax isn't gone, you can still do it "the old way". It is fully supported and the declarative one is "compiled to" the old one.
Now, to answer the question, the code should look like (untested):
mybacklight = wibox.widget {
   {
       max_value        = 1,
       value            = brightness_new,
       background_color = "#131211",
       color            = {type="linear", from = {0, 0}, to = {0, 20},
            stops = { {0, "#F6F6F6"}, {0.5,
            "#bdbdbd"}, {1.0, "#3b3b3b"} }
       },
       widget           = wibox.widget.progressbar,
   },
   forced_width     = 12,
   forced_height    = 10,
   direction        = 'east',
   layout           = wibox.container.rotate
}

Changes:

The composite widget constructor is wibox.widget. You used the progressbar constructor to contruct a rotate container
Indentation to make the code more readable
You had 2 widget in the same block, this isn't supported.

Reference https://awesomewm.org/apidoc/classes/wibox.widget.progressbar.html#
Comment: It works, but the call `mybacklight:set_value(0.5)` returns an error : set_value() : **nil value**, which is strange as this method does exist for progress bar in the provided link.
Comment: Got it ! It is better with `mybacklight.widget:set_value(0.5)`. However, the color setting `color =` does not work correctly. It is necessary to change it to `color = {type = "linear", from = {20, 0}, to = {0, 0}, stops = { {0, "#F6F6F6"}, {0.5, "#bdbdbd"}, {1.0, "#3b3b3b"} }` to make it appear as before.

Changes from 3.5 to 4.0


ConcurrentModificationException?

Question: I'm trying to order a list of time spans (represented as Time[] arrays with a start time and end time) by their start times. I'm trying to use the following nested loop to do so:
            for (Time[] span : workingList){
            Time[] compareTo = workingList.get(0);

                for (Time[] inSpan : workingList){
                    if (inSpan[0].before(compareTo[0])){
                    compareTo = inSpan;
                    }
                }
            workingList.remove(compareTo);
            toReturn.add(compareTo);
        }

    }

but it is throwing a java.util.ConcurrentModificationException at the line for (Time[] span : workingList) (the one on top). I've never seen this exception before, can someone please explain to me what it means and what causes it.
I'm also open to suggestions of better algorithms for this.
Comment: For future reference: when you have a question about an Exception, you can always consult the documentation.  If you google "_Java 7 ConcurrentModificationException_" the first result will bring you to the documentation.  If you read the overview at the top of that page, it explains this exact scenario.
Answer: workingList.remove(compareTo);

You are modifying a collection while iterating on it.
You should use something like:
ListIterator<Time[]> it = workingList.listIterator();

while (it.hasNext()) {
  Time[] time = it.next();
  ..
  it.remove();
}

There are ways also without using the list iterator but this seems the more correct.
Comment: Another option is to build a list of items you want to remove **WHILE** iterating, and to remove them **AFTER** iterating.
Comment: It mainly depends on the algorithm, in the OP case build a temporary list could be the only option if the element he is deleting is not always the same on which it is iterating.
Answer: My suggestion is that you use Collections.sort() for ordering lists. It does the sorting for you, and makes it a lot more readable what you are trying to do. You'll need to specify your own Comparator when calling the method - as such:
    Collections.sort(workingList,new Comparator<Time[]>() {
        @Override
        public int compare(Time[] time1, Time[] time2) {
            return time1[0].before(time2[0]);
        }
    });

This will sort workingList as your specs.

ConcurrentModificationException?


Embed unique custom form in all rows of a view

Question: I want to create a custom form that will be embedded on each row for visitor to submit an email for that specific row.
I suppose I have to create a custom form (which I have done before) but how do I embed it on each row ?  hook_views_data_alter(array &$data) is the right way ?
Other questions (but not that important) are how do I make it unique (know which row the user has submitted) ? Another requirement is to be submitted without reload of whole page (ajaxy form).
Comment: I would try and create a variable that contains the form using `THEME_preprocess_views_view_fields(&$variables) {` and then print out the custom variable on views-view-fields--[view-name].html.twig
Comment: If you want to avoid the template system all together. You can override a field value in [hook_views_pre_render](https://api.drupal.org/comment/62573#comment-62573)
Answer: That's a lot questions in one post. Two things may help you:
First, if you have more than one instance of a form on one page, you need different formIds. So implement the getFormId with a variable, like so:
public function getFormId() {
    return "mysuper_form-".$this->whatEverCounter;
}

Then, you will need to create your form yourself with the constructor (cause you need your state to be set from outside) and pass that instance to the formBuilder, for example like so
$idForm = new myForm($whatEverCounter);
$form = \Drupal::formBuilder()->getForm($idForm);

Second, for the "each row" topic:
If you really have one form per row, you will have one submit per row also - no problem. Or, you have one form with one element per row. Then just enumerate your elements like so:
public function buildForm(array $form, FormStateInterface $form_state) {
    foreach ($ems as $e) {
       $form['toggle'.$e] = []
    ]

If you need an ajax submit callback, use the '#ajax' attribute, like so:
'#ajax' => array(
        // Function to call when event on form element triggered.
        'callback' => [$this, 'toggleButtonPress'],
        // Effect when replacing content. Options: 'none' (default), 'slide', 'fade'.
        'effect' => 'fade',
        // Javascript event to trigger Ajax.
        'event' => 'click',
        'progress' => array(
        // Graphic shown to indicate ajax. Options: 'throbber' (default), 'bar'.
        'type' => 'throbber',
        // Message to show along progress graphic. Default: 'Please wait...'.
        'message' => NULL,
        ),

Comment: How do I embed a custom form to a view is the MAIN question, reformatted the question to make it more clear.
Comment: @GiorgosK while this doesn't answer the "main" question, you will still need to do all the above :)
Comment: @NoSssweat thanks I know and in my question I sort of hint that this is the part that I know.  The most pressing question is how to embed the form to views


1/n + 1/(n+2) and Prime Pythagorean Triples

Question: I need help proving this conjecture:
Suppose you have two Natural Numbers, n and m, such that n = m + 2. Then 1/n + 1/m is equal to some fraction which, when reduced, is equal to $\frac ab$ (for some a,b in the natural numbers) such that $a^2 + b^2 = c^2$ for some c in the natural numbers.
Comment: I would first get rid of all references to $n$ by swapping it with $m+2$. Also note that if the fraction gives a Pythagorean triple when reduced, then it gives one when it's not reduced (albeit not a primitive triple).
Answer: We have $\frac{1}{n}+\frac{1}{n+2}=\frac{2n+2}{n(n+2)}$.
Note that actually you do not need to have a reduced fraction. If the numerator and the denominator have a common factor just cancel it when you want.
We can see that $a^2+b^2=(2n+2)^2+(n(n+2))^2=n^4+4n^3+8n^2+8n+4=(n^2+2n+2)^2=c^2$
This proves your conjecture.
Comment: Ahh I knew I was close. I got to the big 4th power polynomial but didn't even think I could actually factorize it. Thanks for the help.


Are there periodic functions satisfying a quadratic differential equation?

Question:
Question: Are there periodic functions satisfying a quadratic differential equation, as opposed to just linear or cubic?
Bonus question: Are there periodic functions satisfying differential equations which are polynomials of any degree $n$?

Background: I know that on the real line, any periodic function can be decomposed into a (possibly infinite) sum of sines and cosines via Fourier series, and that this technique is somewhat extensible to the complex plane (I think).
Likewise, cosine and sine can be defined as the solutions to a linear systems of ordinary differential equation (at least on the real line, I am not sure about the complex plane), see e.g here.
A natural generalization/extension of the cosine and sine would be to either consider (1) functions defining the trigonometry of more general conic sections than the circle or (2) functions which have more "advanced" periodicity properties, like double periodicity.
Functions which seem to satisfy both of these criteria would be the elliptic functions, because they are (1) the inverses of elliptic integrals, and (2) doubly periodic.
However, what is surprising to me is that the (complex) differential equation which they satisfy is cubic in the function and its first derivative, rather than quadratic. This seems to suggest a substantial jump in complexity from the trigonometric functions.
This question is motivated by Algebraic Geometry: A Problem Solving Approach, which mentions the elliptic functions in the context of cubic curves, but does not mention any special functions related to conic sections -- is this because there aren't any, or are they just somehow less important?
Attempt: Maybe the hyperbolic tangent function? I don't think that it's periodic, but it is related to the exponential, which is periodic. Also it seems to satisfy a quadratic differential equation.
Note: I tagged this (complex-analysis) because it seems to be about complex differential equations.
Answer: (I assume you are talking about the second-order ODEs for trig functions or (Jacobi) elliptic functions?)
The equation $d^2 x/dt^2 = x^2-x$, which is quadratic in $x(t)$, has (some) periodic solutions, as can be seen by writing it as
$$dx/dt=y,\qquad dy/dt=x(x-1)$$ and sketching the phase portrait in the $xy$ plane. But if you try to integrate it explicitly, you get $(dx/dt)^2/2 = x^3/3-x^2/2+C$, which leads to an integral with a square root of a cubic polynomial, and thus to elliptic functions again.
Comment: I suppose that's what I meant -- the second order ODE for sine and cosine can be written as a system of first order ODEs (I think), whereas the ODE for the Weierstrass elliptic functions are first order. I don't know about the Jacobi elliptic functions though since I haven't studied those.
Answer: Update: I just realized that this is probably a really dumb question, specifically, consider that $\frac{d}{dx}\sin x = \cos x$. Set $y = \sin x$. Then since $\sin ^2 x + \cos ^2 x =1$, we have that $$(y')^2 + y^2 =1 $$ which is exactly the sort of thing I was thinking about. I.e. the sinusoidal functions correspond to the unit circle exactly in the way that elliptic curves correspond to (Weierstrass) elliptic functions.
Likewise, if one sets $y = \sinh x$, then one has that $$ (y')^2 - y^2 =1$$ which means that the hyperbolic trigonometric functions (unsurprisingly) correspond to the hyperbola conic sections. Thus the "quadratic differential equation periodic functions" I was talking about were just the trigonometric functions after all.
If anyone can think of a "parabola" counterpart to the unit ellipse and unit hyperbola examples I have above I would greatly appreciate it.
EDIT: a similar question has been asked before on Math.SE, see for example: Do "Parabolic Trigonometric Functions" exist?, also Are there parabolic and elliptical functions analogous to the circular and hyperbolic functions sin(h),cos(h), and tan(h)?
Also if anyone knows anything about whether or not there are corresponding special functions for all (smooth) algebraic curves, or if it is just the case for conic sections and elliptic curves, I would be both very interested and very grateful to know.
This might not be possible since if smooth quadratic curves correspond to singly periodic real-valued functions, and smooth cubic curves correspond to doubly periodic complex-valued functions, then smooth higher-degree curves might correspond to "n-th ly periodic" functions of even higher order division algebras -- however none exist that are fields. Also Jacobi proved that triply periodic functions and higher cannot exist, so my naive guess is that the answer is no.


How can I make same result for re.findall and re.finditer on regular expressions?

Question: Topic
I would like to extract words or quotes with quotations without quotations using re.finditer() function rather than re.findall().
text = 'This is a very "sweet" and "beautiful" cake.'

-> ['sweet', 'beautiful']

output an issue
The re.finditer() function returns with quotations and I have no idea how to get rid of the top and bottom double quotations.
['sweet', 'beautiful']
['"sweet"', '"beautiful"']

Code
import re
text = 'This is a very "sweet" and "beautiful" cake.'
all = re.findall('"(.*?)"', text)
print(all)

all_obj = re.finditer('"(.*?)"', text)
result = []
for obj in all_obj:
    result.append(obj.group())
print(result)

What I have tried to do
Without stripping, is there any solution to fix this issue?
final_result = []
for word in result:
    final_result.append(word.rstrip('"').lstrip('"'))
print(final_result)

['sweet', 'beautiful']

Comment: What is wrong with your current solution?
Answer: Please use .group(1) to match and extract your group:
result.append(obj.group(1))


Number of directed multigraphs with $n$ arrows?

Question: For context, I'm trying to work out the combinatorial properties of constructing a directed multigraph from a fixed number of arrows (with a vertex only existing when an arrow is connected to it).
How many possible directed multigraphs are there (up to isomorphism), given the following conditions?

There are a set number of edges.
There are no isolated vertices.
Edges and vertices are unlabelled.
There can be loops; that is, edges like $(a,a)$ are allowed in addition to $(a,b)$.
There can be multiple edges; that is, there can be more than one edge going from $a$ to $b$.

Another way to think about it is, how many isomorphism classes of multisets (with cardinality $n$) of ordered pairs (of, you could say, vertices) are there?
Answer: The case where vertices are labeled would be easy to count. The tool that lets us go from labeled to unlabeled vertices is the Pólya enumeration theorem. (The Wikipedia article gives an example of using this to count undirected graphs with a fixed number of edges, and the directed case is only slightly different.)
I will forget about isolated vertices for now, and allow directed edges $vw$ and $wv$ to coexist. So let's start with the complete directed graph (with $n$ vertices and all $N := n(n-1)$ possible directed edges), and color the edges with two colors: a color that represents "there is an edge" (with weight $1$) and a color that represents "there is no edge" (with weight $0$). The generating function of the set of colors is $f(t) = 1+t$. The weight of a coloring is the total weight of the colors used, so it's the number of edges in our graph; therefore, we want to find the number of colorings with a fixed weight.
We take $G$ to be the group $S_n$ acting on the vertices of the complete directed graph. To apply the Pólya enumeration theorem as in the Wikipedia article, we need to compute $Z_G(t_1, t_2, \dots, t_N)$. So, for each permutation $\sigma$ of the vertices and each $k \in \{1, \dots, N\}$, we need to compute $c_k(\sigma)$, the number of $k$-cycles in the action of $\sigma$ on the set of edges.
For example, let's try this for $n=3$ vertices, with $N = 6$ possible edges. Here, there are $3$ types of permutations:

The identity permutation fixes all edges, giving a $t_1^6$ term.
A swap like $(1\;2)$ acts on the set of edges by three $2$-cycles; the edges $12$ and $21$ are swapped, the edges $13$ and $23$ are swapped; the edges $31$ and $32$ are swapped. This gives a $t_2^3$ term, and there are three such permutations.
A permutation like $(1\;2\;3)$ acts on the set of edges by two $3$-cycles; the edges $12, 23, 31$ are permuted cyclically, and so are the edges $21, 32, 13$. This gives a $t_3^2$ term, and there are two such permutations.

So we get $Z_G(t_1, t_2, t_3, t_4, t_5, t_6) = \frac16(t_1^6 + 3 t_2^3 + 2 t_3^2).$ We might as well make this $Z_G(t_1, t_2, t_3)$ since no longer cycles appear.
By the Pólya enumeration theorem, the generating function of directed graphs on $3$ vertices up to isomorphism is
\begin{align}
   Z_G(1 + t, 1 + t^2, 1 + t^3) &= \frac16((1+t)^6 + 3(1+t^2)^3 + 2(1+t^3)^2) \\
       &= 1 + t + 4 t^2 + 4 t^3 + 4 t^4 + t^5 + t^6
\end{align}
so there are $1, 1, 4, 4, 4, 1, 1$ directed graphs on $3$ vertices with $0, 1, 2, 3, 4, 5, 6$ edges respectively. Here is a diagram of all these graphs to verify the count:

You also wanted to rule out isolated vertices, which this doesn't do, but that's easy to fix. Let's say that $a_{n,m}$ is the number of $n$-vertex $m$-edge digraphs without the isolated vertex condition, and $a_{n,m}^*$ is the number that have no isolated vertices. Then we have
$$
   a_{n,m} = a_{0,m}^* + a_{1,m}^* + a_{2,m}^* + \dots + a_{n,m}^*
$$
because the number of $n$-vertex $m$-edge digraphs with $k$ isolated vertices is counted by $a_{n-k,m}^*$. From this, we can get $a_{n,m}^* = a_{n,m} - a_{n-1,m}$.
Comment: You can allow loops and multiple edges with minor variation of the problem. For loops, you will just need to modify $Z_G$. For multiple edges, replace $f(t)$ by $1 + t + t^2 + \dots = \frac1{1-t}$. There are many variants of this problem, but all of them are counted in essentially the same way.
Comment: Thanks for the answer, but I was looking for a looser case (about to edit the question to reflect it), allowing loops and also allowing the number of vertices to vary. For the latter part, at least, I can see how this generating function could be used over all possible values of $n$ (vertices) and summed up. Also, the directed multigraph case is what I'm most interested in.


Bowing signs (?) in Lajos Montag's double bass method

Question: In volume II of Montag's double bass method, I found these signs above the staff which look like they should be bowing signs. My guesses for the arrows are either alternating down-bow and up-bow or whole bow. My guess for the sign that looks like a rotated rest would be "frog".

What do these signs mean? Are these standard signs or are these Montag's invention?  (They are not explained in that volume – maybe they are in volume I.)
Comment: Your guesses seem plausible to me, and I actually like the symbols. They should be standardized...
Answer: The are defined in the introduction. The arrows mean "full bow" and the other symbol (which is fairly standard) means "at the frog".
See the picture for the full set of symbols - apologies for the poor quality.
Answer: Yes, I agree that you are probably right.  The arrows mostly likely indicate using the whole bow.  I have been a professional double bass player for about 40 years and I have never come across those symbols.  They are not standard.  If the second symbol does mean play at the frog, it is slightly unusual since it is a pp passage and would be more comfortable further up the bow.
Comment: As "Guest" answered, these are edition-specific.  that is not at all unusual for various bowed-instrument study books.


Taxonomy Term Path to Search

Question: Running Drupal 7:
Problem: I have a vocabulary that contains a list of faculty, within each faculty member term page is a list of research interests (a separate vocabulary) that are clickable.  Currently they go to their individual term pages.
Goal: How can I make those "Research Interests" clickable and simply make it go to the search page with that term as the search query?
Answer: I see two options to achieves this.
The first one is to alter the page callback for the taxonomy/term/%taxonomy_term path through an implementation of hook_menu_alter. In the custom page callback, when displaying a term from your vocabulary, use drupal_goto() to redirect to the search page. And for terms in other vocabularies, you can re-use taxonomy_term_page() to preserve the original behavior.
The second option is to implement hook_entity_info_alter() to alter the uri callback of the taxonomy term entity type. In the custom URI callback, when getting the URI for a term of your vocabulary, returns the URI of the search page. For terms in other vocabularies, you can re-use taxonomy_term_uri() to preserve the original behavior.

Taxonomy Term Path to Search


How to install PL/CTL language into PostgreSQL database 8.1.22

Question: Hi I am using postgresql 8.1.22, I am trying to setup postgresql auditing using the following function.
CREATE OR REPLACE FUNCTION audit.if_modified_func() RETURNS TRIGGER AS $body$
DECLARE
    v_old_data TEXT;
    v_new_data TEXT;
BEGIN
    /*  If this actually for real auditing (where you need to log EVERY action),
        then you would need to use something like dblink or plperl that could log outside the transaction,
        regardless of whether the transaction committed or rolled back.
    */

    /* This dance with casting the NEW and OLD values to a ROW is not necessary in pg 9.0+ */

    IF (TG_OP = 'UPDATE') THEN
        v_old_data := ROW(OLD.*);
        v_new_data := ROW(NEW.*);
        INSERT INTO audit.logged_actions (schema_name,table_name,user_name,action,original_data,new_data,query)
        VALUES (TG_TABLE_SCHEMA::TEXT,TG_TABLE_NAME::TEXT,session_user::TEXT,substring(TG_OP,1,1),v_old_data,v_new_data, current_query());
        RETURN NEW;
    ELSIF (TG_OP = 'DELETE') THEN
        v_old_data := ROW(OLD.*);
        INSERT INTO audit.logged_actions (schema_name,table_name,user_name,action,original_data,query)
        VALUES (TG_TABLE_SCHEMA::TEXT,TG_TABLE_NAME::TEXT,session_user::TEXT,substring(TG_OP,1,1),v_old_data, current_query());
        RETURN OLD;
    ELSIF (TG_OP = 'INSERT') THEN
        v_new_data := ROW(NEW.*);
        INSERT INTO audit.logged_actions (schema_name,table_name,user_name,action,new_data,query)
        VALUES (TG_TABLE_SCHEMA::TEXT,TG_TABLE_NAME::TEXT,session_user::TEXT,substring(TG_OP,1,1),v_new_data, current_query());
        RETURN NEW;
    ELSE
        RAISE WARNING '[AUDIT.IF_MODIFIED_FUNC] - Other action occurred: %, at %',TG_OP,now();
        RETURN NULL;
    END IF;

EXCEPTION
    WHEN data_exception THEN
        RAISE WARNING '[AUDIT.IF_MODIFIED_FUNC] - UDF ERROR [DATA EXCEPTION] - SQLSTATE: %, SQLERRM: %',SQLSTATE,SQLERRM;
        RETURN NULL;
    WHEN unique_violation THEN
        RAISE WARNING '[AUDIT.IF_MODIFIED_FUNC] - UDF ERROR [UNIQUE] - SQLSTATE: %, SQLERRM: %',SQLSTATE,SQLERRM;
        RETURN NULL;
    WHEN OTHERS THEN
        RAISE WARNING '[AUDIT.IF_MODIFIED_FUNC] - UDF ERROR [OTHER] - SQLSTATE: %, SQLERRM: %',SQLSTATE,SQLERRM;
        RETURN NULL;
END;
$body$
LANGUAGE plpgsql
SECURITY DEFINER

But if you observe in the above function current_query() is not coming with the mentioned language plpgsql. It throws some error. When I googled I found that in order to use current_query() function PL/CTL language must be installed. I tried to install as mentioned below. It throws an error. So kindly help me how to install PL/CTL language into my database so that current_query() function should work
-bash-3.2$ createlang -d dbname pltcl
createlang: language installation failed: ERROR:  could not access file "$libdir/pltcl": No such file or directory

Okay as you suggested I created that current_query() function,but this time I got some thing like this , What i did is ,
CREATE TABLE phonebook(phone VARCHAR(32), firstname VARCHAR(32), lastname VARCHAR(32), address VARCHAR(64));

CREATE TRIGGER phonebook_auditt AFTER INSERT OR UPDATE OR DELETE ON phonebook
    FOR EACH ROW EXECUTE PROCEDURE audit.if_modified_func();

INSERT INTO phonebook(phone, firstname, lastname, address) VALUES('9966888200', 'John', 'Doe', 'North America');

for testing the function i created a table named phonebook and created a trigger so that the function mentioned above audit.if_modified_func() will be executed after any insert or update or delete.the row is getting inserted but I am getting a error reg the audit.if_modified_func() function .the error is as follows
WARNING:  [AUDIT.IF_MODIFIED_FUNC] - UDF ERROR [OTHER] - SQLSTATE: 42703, SQLERRM: column "*" not found in data type phonebook

Query returned successfully: 1 rows affected, 10 ms execution time.

Kindly tell me what can i do to get rid of the above error.
Comment: Or to be precise: update ***now***
Answer: Not sure where you found the information about current_query and pltcl. These are unrelated. The reason why you can't find pltcl is simply because you're using too old PostgreSQL. current_query() has been added to Pg in version 8.4.
Is there any particular reason why you're using such old version? It is no longer supported, and it lacks almost 8 years of added features!
If you have to use 8.1, you might want to define:
create function current_query() returns text as '
select current_query from pg_stat_activity where procpid = pg_backend_pid();
' language sql;

But it is much better idea just to upgrade.
As for edited and added second question - it's very likely that Pg 8.1 cannot use "row.*" construct. Find who wrote the original code with the "dance comments", and ask about it. Perhaps it was meant to work in newer Pgs.


Are these events independent or dependent? (Check my work)

Question: I'm studying for my exam, and unsure about my answers for these 3 practise questions:

My answers are as follow:
Q1) Independent, as can have HTH which satisfies B but not A.
Q2) Dependent, as the outcome of A affects B. Example if A is one head, then B is true.
Q3) Dependent, example: If B and C are satisfied, then A is not. Making A depend on B and C.
Overall, I don't think I understand the logic how to see if they are dependent or independent.
The exam will be multiple choice, so I don't need to prove or give formal reasoning, are there any tricks to figure out if events are dependent or independent?
Answer: Isn't the definition of independence that events $A$ and $B$ are independent if and only if $\Pr(A\cap B) = \Pr(A)\Pr(B)$? This is equivalent to the condition that $\Pr(A|B)=\Pr(A)$, and also to the condition that $\Pr(B|A)=\Pr(B)$.
Comment: I'm a bit confused, Pr(A)Pr(B) is probability of A multiplied by probability of B, but what's Pr(A∩B)?
Answer: Check the definition of the notion of independence and you will see that events are not independent per se, only with respect to some given probability measure. But none of your answers involves the underlying probability measure. Ergo.
Comment: Given the level of the practise questions in this post, I don't know if the OP will know measure theory yet...
Comment: @Eupraxis1981 Not sure I understand your comment. It is a little difficult to imagine a solution without any occurrence of P(...). How would you call this mysterious object?
Comment: I think the measure is implied by the question, it is the counting measure on possible triplets. However, for intro stats, its a very intuitive measure and hence is not explicitly addressed. The post and questions make it clear that they are talking about counting triplets of binary elements.
Comment: I see what you mean though about the OP's answers. None are *reasons* why one is dependent or independent, which is what you were getting at, correct?
Comment: @Stack Did you downvote this, by any chance?
Comment: I did not. I will upvote it too :). I just did not understand probability measure, therefore did not reply.
Comment: OK. But what is it you read when there is some P (or Pr) in a solution?
Comment: @Did BTW: I did not downvote you either - not sure who did. Your explanation was correct, I just offered a comment on language. I think downvoting is not a very constructive form of feedback, so I rarely do it (as can be seen from my record)
Comment: @Eupraxis1981 Thanks for the opinion. I try to downvote systematically wrong answers that are not corrected after the problem is signalled.
Answer: For question 1: $A:=\{THH, HHT, HHH\}, B:=\{HTH, THH, HHT, TTT\}, P(A|B)=P(\{THH,HHT\}|\{HTH, THH, HHT, TTT\})=\frac{2}{4} \neq P(A)=3/8$
so (1) is not independent, as A becomes more likely if we know B is true.
You just need to find one counterexample to the rule given by MPW above: P(A|B)=P(A) or $P(A\cap B)=P(A)P(B)$
Comment: P(A|B)={THH,HHT}=2/4≠P(A)=3/8, mind explaining this part please?
Comment: A = Two heads in a row, B = Even number of heads, there are only two outcomes in B that have two heads in a row, and there are 4 outcomes in B, so 2/4. However, there are three ways to get at least two heads in a row overall, and 8 possible outcomes from three coin flips, so 3/8.
Comment: If they were equal, will that make them independent?
Comment: @StackPWRequirmentsAreCrazy I've clarified my answer, as I breezed through a step.
Comment: Thank you, makes it much clearer. Say P(A) was somehow = 2/4, since it will be equal to P(A|B), would it be independent in that case?
Comment: @StackPWRequirmentsAreCrazy no, you need to have P(B|A)=P(B) and P(A|B)=P(A) if you are talking about two events. In general, independence is very onerous to prove from first principles because you have to check an ever-increasing set of 2-way, 3-way, ...n-way combinations, all of which must follow the multiplication rule for indpendent events....its a lot of work.
Comment: Thank you, was I correct with my other answers?
Comment: As @Did pointed out, none of your answers are in terms of probability, as mine was above. You need to either find a counterexample to the multiplication rule (as I have done) or show it holds for all pairwise combinations. Either way, you need to use probability statements, not vague statements about "affects"...that will not get you points with the teacher. Use my example as a template for the others...please try them yourself and see if you can verify/falsify that hypothesis that the probabilities multiply.
Comment: Thanks, for number 2 I did: P(A|B)=3/6 ≠ P(A)=3/8. Is my intuition correct?
Comment: Can you show your work? There are 4 ways to have *at most* 1 tail  in three tosses so P(A) is off
Comment: Looks like I did a dumb mistake, forgot TTT. Thank you!
Comment: @StackPWRequirmentsAreCrazy no problem, looks like you're able to set up the calculations now...just be sure to enumerate all outcomes that apply to that event :)


Application Insights Exception Rate Alert, Strange results

Question: I've created an alert for exception rate. Looking at the graph on the alert, I seem to have a constant exception rate of just over 1 exception per second. However, when I look at Metrics, or look in the analysis tool, I can't find these exceptions. Can anyone explain where they're coming from and which metric I need to look at to find them?
Answer: OK. I should have tried harder before asking the question!
The exception/sec performance counter counts both handled and unhandled exceptions. Here's the documentation:
# of Exceps Thrown / Sec
Displays the number of exceptions thrown per second. This includes both .NET exceptions and unmanaged exceptions that are converted into .NET exceptions.
  For example, an HRESULT returned from unmanaged code is converted to an exception in managed code.
  This counter includes both handled and unhandled exceptions. It is not an average over time; it displays the difference between the values observed in the
  last two samples divided by the duration of the sample interval. This counter is an indicator of potential performance problems if a large (>100s) number of exceptions are thrown.


Panda array from list of dictionaries

Question: I have a list of dictionaries like this
[{"Key":[val1,val2,...]}, {"Key2":[val1,val2,...]}, ...]

I would like to convert this to a csv format where the keys are column headers, and he values form the column values
To do this I had intended to use a pandas dataframe (which exports to csv readily), but I can't work out how to get my values into the data frame.
I've tried myPanda = pd.DataFrame.from_records(data) but alas, to no avail.
Comment: Is the only reason you are using `pandas` to export to csv?
Answer: I'm assuming your keys are unique, otherwise this wouldn't make much sense.
Option 1

merge your dictionaries to a single dict
pass the dict to pd.DataFrame
save as CSV using df.to_csv

dct = [{...}, {...}, ...]

r = {}
for d in dct:
    r.update(d)

pd.DataFrame(r).to_csv('file.csv')

Option 2
Using cytoolz, there's another possibility for dictionary merging -
from cytoolz.dicttoolz import merge
df = pd.DataFrame(merge(*dct))

Option 3
Create separate dataframes and concatenate them -
df = pd.concat(list(map(pd.DataFrame, dct)), axis=1)

This option works even if your lists are uneven.

Credit to piRSquared for the last two solutions!.
Comment: If you import `merge` from `cytoolz.dicttoolz` you can do this `pd.DataFrame(merge(*dct))`
Comment: Last one I swear... `pd.concat(list(map(pd.DataFrame, dct)), axis=1)`
Comment: @Bharath Woah... yeah. That does seem overly complicated!
Comment: @Bharath 's solution revisited `pd.DataFrame({k: v for d in dct for k, v in d.items()})`
Comment: Last one would take care of the caveat too ;)
Comment: I thought of this `pd.DataFrame([list(*i.values()) for i in di],columns = [list(i.keys())[0] for i in di])` But your approach is really neat.

Panda array from list of dictionaries


How do I use multiple this.state counters in the same page to increment separate variables

Question: I want to create three sets of +/- buttons that increase and decrease three separate progress bars. With this.state, I can increment one counter but all of them change at the same time.
The following prior solution tries to explain the answer but I can't use it because I am not using a  element.
Counter for each item in React.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import { Collapse,  Navbar,    NavbarToggler,    NavbarBrand,    Nav,
NavItem,    NavLink,    Container,    Row,  Col,  Jumbotron,  Button,
ButtonToolbar    } from 'reactstrap';
import { Progress } from 'react-sweet-progress';
import "react-sweet-progress/lib/style.css";

class App extends React.Component {
    constructor(props) {
  super(props)

  this.state = { countera: 0}
  this.addFive = this.addFive.bind(this)
  this.subFive = this.subFive.bind(this)
}

addFive(x) {
      this.setState(prevState => ({
         x: prevState.x + 5 }));

  }

subFive(x) {
    this.setState(prevState => ({
        x: prevState.x - 5 }));
}

render() {

var alpha = this.state.countera;
var beta = 30;
var gamma = 30;
var sum = alpha + beta + gamma;

return (

Welcome to FICO Reactor

      <ButtonToolbar>
        <Button tag="a"color="success" size="large" href=""
 target="_blank">Begin</Button>
      </ButtonToolbar>

Items Corrected

Items In Repair

Remaining Hits

<Progress width={200} type="circle"
   percent={100*alpha/sum} status="success" />

<Progress width={200} type="circle"
  percent={100*beta/sum} status="success" />

<Progress width={200} type="circle"
  percent={100*gamma/sum} status="error" />

{alpha} Items

{beta} Items

{gamma} Items

          **
<Button onClick={this.addFive()}>+
  </Button> - <Button onClick={alpha}>-</Button>
**

Buttons2

Buttons3

Disclaimer

);
 }
}

 export default App;

I want the have an increase function and a decrease function that accepts a parameter indicating which of the three buttons variables should be affected and do it to only that variable.
If only there was a this.state.counterA, this.state.counterB, this.state.counterC.
Comment: Nothing preventing you from initializing that in your state - counterA, counterB etc...
Comment: I just now did that but how to i pass which state (cA, cB, etc) to modify as a parameter to the increment function?
Comment: Or do i need to have separate increment and decrease functions for each counter?
Comment: Looks like you already got a detailed answer below... You should accept it as it is correct...
Answer: To increment/decrement a different counter, just we need to pass the name of the counter in the addFive and subFive function.

///update the state like this
this.state = { countera: 0, counterb: 0, counterc: 0 }

///pass the name of the counter on the click function
addFive(name) {
   this.setState(prevState => ({
       [name]: prevState[name] + 5
   }));

}

///pass the name of the counter on the click function
subFive(name) {
   this.setState(prevState => ({
       [name]: prevState[name] - 5
   }));
}

///update the render function

    var alpha = this.state.countera;
        var beta = this.state.counterb;
        var gamma = this.state.counterc;
        var sum = alpha + beta + gamma;

        return (

<Progress width={200} type="circle"
                            percent={100 * alpha / sum} status="success" />

<Progress width={200} type="circle"
                            percent={100 * beta / sum} status="success" />

<Progress width={200} type="circle"
                            percent={100 * gamma / sum} status="error" />

                        **
<Button onClick={() => this.addFive('countera')}>+
  </Button> - <Button onClick={() => this.subFive('countera')}>-</Button>
**

  **
<Button onClick={() => this.addFive('counterb')}>+
  </Button> - <Button onClick={() => this.subFive('counterb')}>-</Button>
**

  **
<Button onClick={() => this.addFive('counterc')}>+
  </Button> - <Button onClick={() => this.subFive('counterc')}>-</Button>
**

        );

If you want to simplify your state change function, then create one function and pass the name and the value (increment/decrement) like below:

changeFive(name, value) {
   this.setState(prevState => ({
       [name]: prevState[name] + value
   }));

}

<Button onClick={() => this.changeFive('countera', 5)}>+
  </Button> - <Button onClick={() => this.changeFive('countera', -5)}>-</Button>

Hope it helps :)
Comment: WOW thank you so much that worked! I didn't know about using [bracket references] to use taken parameters in functions. I am still kind of figuring out what '() =>' really means aside from shortening a function definition. But it worked!
Comment: @MarkWagner `() => ` is the arrow function introduced in ES6 for declaring a normal function. The difference between `() => ` and normal function is that `() =>` doesn't have a scope by itself.


IE doesn't display blinking cursor on pre-filled input fields

Question: In all versions of IE, I've noticed that if I have an input field with a preset value, the blinking cursor will not display when I hit tab to focus the field (though the field does focus and I can begin typing). It only appears once I begin typing, or, alternatively, if I click into the field with the mouse instead of using the tab key.
It seems like a legit bug since IE is the only browser that does it, and it happens even if there's no styling applied to the fields.
Any way around this?
Answer: The previous didn't work in my case but the .select() did the trick:
<code>$('input').focus(function () {
    if ($(this).val() == preFilledText) $(this).val('').select();
});
</code>
Answer: You could 'fake' typing into the field with something like this in jQuery. Not sure if it works, just a suggestion I freeformed right now. This clears the input box then refills it on focus time.
<code>var loInput = $("#MyInputBox");
loInput.focus(function() {
    var lcVal = loInput.val();
    loInput.val('');
    loInput.val(lcVal);
});
</code>


Read list of dicts as single column pandas while keeping comma separator

Question: I have a string
'1,10,aux,rank,[{"id": "1"}, {"id": "2"}, {"id": "3"}, {"id": "4"}]'

Which 5th element is generated from the code:
json.dumps([
                    {"id": "1"},
                    {"id": "2"},
                    {"id": "3"},
                    {"id": "4"},
                ])

I would like to read with pandas.
My current code is
TESTDATA = StringIO('1,10,aux,rank,[{"id": "1"}, {"id": "2"}, {"id": "3"}, {"id": "4"}]'
)

df = pd.read_csv(TESTDATA, names=["column1", "column2", "column3", "column4", "column5"],
                 header=None, usecols=[0, 1, 2, 3, 4])
df

but doesnt read the column5 correctly as is a list of dictionaries. the output is
    column1 column2 column3 column4 column5
0   1   10  aux rank    [{"id": "1"}

How can I correctly read column5 as [{"id": "1"}, {"id": "2"}, {"id": "3"}, {"id": "4"}] while keeping a comma separated csv? I know i could use other separators in order not to break the strings, but it isn't an option.
Ideal output would be:
    column1 column2 column3 column4 column5
0   1   10  aux rank    [{"id": "1"}, {"id": "2"}, {"id": "3"}, {"id": "4"}]

Comment: How do you get this string? Will there be break line in this string?
Comment: there wont be a break line, it comes from dumping a str in json format. I'll update the original post with it
Comment: If it's you generate this string, you can use an operator instead of comma like semicolon.
Answer: I'd use a normal csv reader here to format the data how you want it, then feed it to the DataFrame constructor:
import csv
import pandas as pd
from io import StringIO

TESTDATA = StringIO('1,10,aux,rank,[{"item_id": "1"}, {"item_id": "2"}, {"item_id": "3"}, {"item_id": "4"}]'
)

reader = csv.reader(TESTDATA)

columns = [f'column{i}' for i in range(1, 6)]

# unpack all of the columns, but group the list ones together
a, b, c, d, *e = next(reader)

# put the commas back into your json column
e = ','.join(e)

data = [dict(zip(columns, (a, b, c, d, e)))]

df = pd.DataFrame(data)

df
  column1 column2 column3 column4                                            column5
0       1      10     aux    rank  [{"item_id": "1"}, {"item_id": "2"}, {"item_id...

Or, to put it into a loop for the whole file:
with open('yourfile.csv', newline='') as fh:
    data = []
    reader = csv.reader(fh)
    columns = [f'column{i}' for i in range(1, 6)]

    for a, b, c, d, *e in reader:
        e = ','.join(e)
        data.append(dict(zip(columns, (a, b, c, d, e))))

df = pd.DataFrame(data)

Edit
To avoid the overhead of building a list for larger datasets, you could have pd.DataFrame consume a generator here:
def format_data(file):
    with open(file, newline='') as fh:
        reader = csv.reader(fh)
        columns = [f'column{i}' for i in range(1, 6)]

        for a, b, c, d, *e in reader:
            e = ','.join(e)
            yield dict(zip(columns, (a, b, c, d, e)))

df = pd.DataFrame(format_data('myfile.csv'))

Comment: that seems to add a lot of overhead prior to the pd read, let me benchmark its time when running against bigger strings.
Comment: There's no `pd.read` here, instead, I'm reading directly from the csv file itself. The only overhead you might consider is the construction of the list itself, but you could have it consume a generator instead if you wanted to


Como fazer um loop para gerar gráficos no R?

Question: Considere o seguinte Data Frame:
ITENS <-c("A","B","C","D","E")
Q.1 <-c(10,20,10,40,10)
Q.2 <-c(5,25,0,50,10)
Q.3 <-c(15,20,5,40,10)
Q.4 <-c(15,30,5,30,5)
Q.5 <-c(20,25,5,20,15)
Q.6 <-c(10,20,10,40,10)
df <- data.frame(ITENS,Q.1,Q.2,Q.3,Q.4,Q.5,Q.6)

Daí uso o código abaixo para gerar um gráfico:
library(ggplot2)
plot.grafico <- ggplot(data=df, aes(x=df$ITENS, y=df$Q.1)) +
geom_bar(stat="identity") +
xlab("Itens") +
ylab("Quantidade de Alunos") +
ggtitle("Titulo")+ guides(fill=FALSE)
plot.grafico

Ou seja, é um gráfico em barras da coluna Q.1 do meu data frame.
Gostaria de fazer um loop em que eu pudesse gerar o gráfico de cada coluna.
Atualmente faço o seguinte:
plot.grafico1 <- ggplot(data=df, aes(x=df$ITENS, y=df$Q.1)) +
geom_bar(stat="identity") +
xlab("Itens") +
ylab("Quantidade de Alunos") +
ggtitle("Titulo")+ guides(fill=FALSE)

plot.grafico2 <- ggplot(data=df, aes(x=df$ITENS, y=df$Q.2)) +
geom_bar(stat="identity") +
xlab("Itens") +
ylab("Quantidade de Alunos") +
ggtitle("Titulo")+ guides(fill=FALSE)

plot.grafico3 <- ggplot(data=df, aes(x=df$ITENS, y=df$Q.3)) +
geom_bar(stat="identity") +
xlab("Itens") +
ylab("Quantidade de Alunos") +
ggtitle("Titulo")+ guides(fill=FALSE)

library(gridExtra)

grid.arrange(plot.grafico1,plot.grafico2,plot.grafico3)

Gostaria de uma rotina para não poder repetir o código 6 vezes
Na verdade o meu data frame original tem 45 colunas.
Comment: @Phelipe Veja se ficou mais claro depois da edição. Se não puder ajudar, tranquilo ;)
Comment: O intuito do site não é resolver exercícios e sim tirar dúvidas de programação. Tente colocar o que você já fez e qual a sua dúvida.
Answer: Acho que o loop não é a melhor solução para o seu caso.
# alongue o data frame.
library(tidyr)
long <- df %>% gather(turma, quantidade, Q.1:Q.6)

# use facet_wrap
library(ggplot2)
ggplot(long) +
  geom_bar(aes(x = ITENS, y = quantidade), stat = "identity") +
  facet_wrap(~turma)

Comment: Gostei ! Obrigado. De fato não usar o loop pode economizar em tempo de processamento.


FIPS country codes in objective-c

Question: I need to use FIPS country codes in my app.
Is there a way to find them?
I've tried NSLocaleCountryCode but these codes are different than FIPS.
Does anyone know how can I do it?
Answer: The FIPS codes you're referring to are found easily using Google.    However, here are pointers to where you can locate them:

NGA Geopolitical Entities and Codes
Wikipedia Entry for FIPS 10-4
NIST FIPS 10-4 info

Note that FIPS had been officially withdrawn for certain uses by the US Government, but that's probably not relevant to your particular use case.
Also, make sure you really need the FIPS codes, because they're quite similar to ISO country codes, but they are different and governed by different groups.
Comment: My app uses API which needs in certain cases these FIPS codes. So it seems I have to copy all these countries with codes into my app...
Comment: Yes, iOS does not have them built in.    If you found this answer helpful, please upvote and accept it.

FIPS country codes in objective-c


Emulating a 415 Hz tuner?

Question: Is it possible to use a standard 440 Hz digital tuner to emulate a 415 Hz tuner, even if it doesn't explicitly support setting the A4 frequency?
I'm learning to play the viol, and I can't find a good 415 tuner and I'm not skilled enough to tune by ear. I've tried a dozen digital tuning apps for Android, but most don't support setting A4, and the few that do still don't seem to work well for the viol's range.
However, doesn't 415 Hz exactly correspond to a step down in the 440 scale? If a string is, say, D2 at 440, would the effective 415 Hz note be C# at 440? So if I just target a step down for all my notes with my regular tuner, would that work without needing a 415 tuner?
Comment: Why try to emulate, when you can buy a tuner which gives the exact Hz anyway?
Comment: Yes, tuning your strings to the notes a semitone "too low" according to a 440 tuner works perfectly. I.e. 440 A flat = 415 A, 440 D Flat  = 415 D etc. But tuning apps that let you adjust the pitch should be a dime a dozen, I'm a little surprised you can't find any. Are you perhaps only considering free apps? There a few rather good ones that are cheap (below 10$) but not free.
Comment: Pedantically, it would be off by (if I did my math right) about 1.27 cents. Which is imperceptible to almost everyone; but in the answers so far people are talking about how performers don't tune their fifths to equal temperament - which is only about 2 cents off.
Comment: How precisely are you tuning?  Are you trying to set a particular temperament or just tune the fourths pure?
Comment: Strictly speaking, in concert pitch with A = 440 Hz, an equal-tempered G#/Ab = 440×2^-1/12 ≈ 415.3047 Hz.  So tuning to concert G#/Ab should be close enough to 415 Hz for most purposes.
Comment: @Tim In most contexts, the A being exactly 415 Hz (however you define "exactly"; those familiar with significant digits will point out that "415" only implies +/- 0.5 Hz) is not really important. In fact, many harpsichords and organs have transposing keyboards, where one may switch between multiple reference pitches simply by moving the keyboard relative to the strings/pipes. In such a case, the A is pretty much guaranteed, no matter the temperament, to match the given frequency for only one of the pitches: the tiny differences elsewhere will of course be pretty much irrelevant.
Comment: I suspect this is part of why 415 is the "default" early music pitch, when the performers don't know what *exact* pitch the piece was originally performed at (or aren't troubled to be so precise, especially when programming multiple composers or time periods in a single concert). There are harpsichords where you can remove a little wooden block at the side of the keyboard and slide the entire action over by one string, so you can play at 415 or 440 without retuning. (Of course, that little trick doesn't work in all temperaments!...) Meanwhile, I enjoy the mobile app Cleartune.
Comment: @AndyBonner generally the harpsichord _will_ be retuned after moving the keyboard since they typically are tuned in an unequal temperament.  But harpsichords have to be retuned frequently anyway, so it's not much of a burden -- and changing the pitch by tuning strings up and down by a semitone would be unsustainable.
Comment: "generally the harpsichord will be retuned after moving the keyboard" - not always the case, particularly if the harpsichord is tuned to take into account this possibility (i.e. where I studied at university, the harpsichords were usually quite close to equal temperament, to allow for both 415 Hz with period instruments and 440 Hz with modern ones, without having to retune every time). For fixed pitch instruments like the organ this will be even more true.
Answer: String instruments usually tune by ear, based on a reference pitch for one of the strings (in most orchestral and chamber music settings, this will be the A, whether at 415, 440 or any other reference). Given that much music written for viols predates the widespread use of equal temperament, and that even in modern contexts pure fifths are preferred (violinists do not always, or even usually, tune their strings to equal temperament, see here) - this is a skill you should definitively work on. Exception, of course, if you need to play chamber music with a keyboard instrument tuned in equal temperament, in which case tuning to match that instrument might be best for ensemble playing (though this is something that can also be and is usually done by ear, since viols, like other string instruments and unlike keyboards, may adjust the exact temperament for each note).
That aside, however, a simple solution to your problem, in the meantime, would be to use a piano (or a digital piano app, of which there exist plenty) or other such instrument (organ, ...) and play a G#/Ab (whose frequency will be almost exactly 415 Hz, if the A is 440) instead.
Some "guitar" tuning apps also offer you the possibility to tune with any pitch, so you could employ the same process as above using those.
Comment: Fretted instruments were tuned in (something very close to) equal temperament from the 1500s.  But viols typically play with harpsichords that are not tuned in equal temperament, so the fifths will be rather more than 2 cents smaller than pure.  Viols are tuned in fourths with a major third, similar to a guitar, so the fourths may be a bit wider than pure -- and wider than equal -- and the major third definitely wider than pure but smaller than equal.
Comment: I did specifically write about "the widespread use" of equal temperament.
Answer: Since 415 Hz is a G# in A=440 tuning (to the nearest whole number) if you use your tuner and tune your Bb note to A=440 your A will be 415 Hz provided the instrument plays in tune with itself. At that point you can tune the other strings to the pitch that is its neighbor a semitone higher, so whatever the open string pitch is tune the first fret to that pitch. Your D string should be tuned to D at the first fret. Your C string should be tuned to C at the first fret, etc.
Another option is to get a chromatic tuner that allows has a setting to tune a semitone flat, which is sometimes done by rock or blues guitarists and bassists. If you use the flat tuning function it will basically give you A=415 Hz.
There also are some tuners that go down to a reference of 415 Hz for A4. Some Snark models can do that, maybe others.
Comment: Korg also make a range of tuners that can be calibrated down to 415 Hz
Comment: "At that point you can tune the other strings to the one you tuned as a reference": OP says "I'm not skilled enough to tune by ear."  The desire is for a tuner that can measure the pitch of each string.
Comment: @phoog You're right, I will adjust my answer to reflect that.
Answer: Simple question, simple answer.  Yes, if A = 440 G♯ = (very near enough) 415.   What you suggest will be fine.
Comment: What does this answer add that is not already covered in both previous ones?
Comment: Nothing. It rather subtracts a load of unnecessary waffle.
Comment: Given that the OP is "learning to play the viol", giving some additional advice and detailing it beyond a mere mathematical-equation-like "G# (440) = A (415)" is certainly not "unnecessary waffle".

Emulating a 415 Hz tuner?


PHP merge and sum arrays

Question: I have an arrays $vd_arr
array (size=3)
  0 =>
    array (size=3)
      'delivnote_id' => string '1' (length=1)
      'qty' => string '76' (length=2)
      'id' => int 17
  1 =>
    array (size=3)
      'delivnote_id' => string '1' (length=1)
      'qty' => string '87' (length=2)
      'id' => int 16
  2 =>
    array (size=3)
      'delivnote_id' => string '1' (length=1)
      'qty' => string '889' (length=3)
      'id' => int 17

I need to merge by id and sum of qty value, so result will be:
array (size=2)
  0 =>
    array (size=3)
      'id' => int 17
      'qty' => int 965
      'delivnote_id' => string '1' (length=1)
  1 =>
    array (size=3)
      'id' => int 16
      'qty' => int 87
      'delivnote_id' => string '1' (length=1)

this script do the job, but php notice me undefined index: qty
$vendel = array();
$indexArray = array();
foreach ($vd_arr as $miniarray) {
  $vendel[$miniarray['id']]['id'] = $miniarray['id'];
  $vendel[$miniarray['id']]['qty'] += $miniarray['qty'];
  $vendel[$miniarray['id']]['delivnote_id'] = $miniarray['delivnote_id'];
}

foreach($vendel as $value) {
  $indexArray[] = $value;
}

return $indexArray;

how to avoid undefined index from above script? thanks.
Comment: using isset() you can avoid the problem of undefined index
Comment: @AnkurTiwari could you please write of full code?
Comment: are you able to provide the line number on which you have the warning or notice.
Comment: this one `$vendel[$miniarray['id']]['qty'] += $miniarray['qty'];`
Answer: Try this
$vendel = array();
$indexArray = array();
foreach ($vd_arr as $miniarray) {
  $vendel[$miniarray['id']]['id'] = $miniarray['id'];

  if(isset($vendel[$miniarray['id']]['qty']))
  {
      $vendel[$miniarray['id']]['qty'] += $miniarray['qty'];
  }
  else
  {
      $vendel[$miniarray['id']]['qty'] = $miniarray['qty'];
  }

  $vendel[$miniarray['id']]['delivnote_id'] = $miniarray['delivnote_id'];
}

foreach($vendel as $value) {
  $indexArray[] = $value;
}

return $indexArray;

Comment: "Try this" answers are low-value on Stack Overflow because they do very little to educate/empower the OP and thousands of future researchers.
Answer: Adapted code to include checking array properties exist before accessing them:
    $vendel = array();
    $indexArray = array();
    foreach ($vd_arr as $miniarray) {

        // Skips adding this mini array if an ID is note present
        if(($id = isset($miniarray['id']) ? $miniarray['id'] : null) === null) {
            continue;
        }

        // The default values at the end of these lines can be swapped out for more suitable defaults
        $qty = isset($miniarray['qty']) ? $miniarray['qty'] : 0;
        $delivnote_id = isset($miniarray['delivnote_id']) ? $miniarray['delivnote_id'] : null;

        $vendel[$id]['id'] = $id;
        $vendel[$id]['qty'] += $qty;
        $vendel[$id]['delivnote_id'] = $delivnote_id;
    }

    foreach($vendel as $value) {
        $indexArray[] = $value;
    }

    return $indexArray;

This also skips adding a $miniarray item that does not have an 'id'.
Answer:
According to the code provided, issue is coming on  $vendel[$miniarray['id']]['qty'] += $miniarray['qty'];
This issue is popping since you have not defined the value of  $vendel[$miniarray['id']]['qty'].
To overcome this issue, you need to define the initial value to the $vendel[$miniarray['id']]['qty'].
You need to define initial value of qty as zero as specified below before the foreach statement that you have written.
foreach ($vd_arr as $miniarray) {  $vendel[$miniarray['id']]['qty'] = 0;}
Answer: As has been mentioned simply check if qty isset before adding to it:
$vendel = array();
$indexArray = array();
foreach ($vd_arr as $miniarray) {

  $vendel[$miniarray['id']]['id'] = $miniarray['id'];
  $vendel[$miniarray['id']]['delivnote_id'] = $miniarray['delivnote_id'];
  // the magic is in the next line
  if(!isset($vendel[$miniarray['id']]['qty']))
      $vendel[$miniarray['id']]['qty'] = 0;
  $vendel[$miniarray['id']]['qty'] += $miniarray['qty'];
}

foreach($vendel as $value) {
  $indexArray[] = $value;
}
return $indexArray;

with some refactoring we could get rid of the second for loop if we use the 'id' as the key of $indexArray
$vendel = array();
$indexArray = array();

foreach ($vd_arr as $miniarray) {
    if(!isset($indexArray[$miniarray['id']])) {
        $indexArray[$miniarray['id']] = array(
            'delivnote_id' => $miniarray['delivnote_id']
            ,'qty' => 0
        );
    }
    $indexArray[$miniarray['id']]['qty'] += $miniarray['qty'];
}

return $indexArray;

Or if you need those indexes to be numerical
$vendel = array();
$indexArray = array();
foreach ($vd_arr as $miniarray) {
    if(!isset($indexArray[$miniarray['id']])) {
        $indexArray[$miniarray['id']] = array(
            'id' => $miniarray['id']
            ,'delivnote_id' => $miniarray['delivnote_id']
            ,'qty' => 0
        );
    }
    $indexArray[$miniarray['id']]['qty'] += $miniarray['qty'];
}
return array_values($indexArray);

Answer: this another approach using funtional programming
    <?php

$data =  json_decode('[
    {
        "id": 1,
        "value1": 5,
        "value2": 10
    },
    {
        "id": 2,
        "value1": 50,
        "value2": 100
    },
    {
        "id": 1,
        "value1": 1,
        "value2": 2
    },
    {
        "id": 2,
        "value1": 15,
        "value2": 20
    },
    {
        "id": 3,
        "value1": 15,
        "value2": 20
    }
]');

//print_r(array_group_by($data,'id'));
print_r(array_sum_by($data,'id',['value1','value2']));
//print_r(array_sum(array_column($data,'value1')));

function array_sum_by($array,$group,$keys)
{
     $groupeddata = array_group_by($array,$group);
    return  array_map(function($items) use($group,$keys) {

        foreach($keys as $key)
        {
            $values[$key] = array_sum(array_column($items,$key));
        }
        $first = array_shift($items);
        if(is_object( $first ) && isset( $first->{ $group } )){
            $values = array_merge([ $group => $first->{ $group } ], $values);
        }elseif(isset($first[$group])){
            $values = array_merge([ $group => $first[$group] ], $values);
        }
        return $values;
    },$groupeddata);
}

function array_group_by( array $array, $key )
    {
        if ( ! is_string( $key ) && ! is_int( $key ) && ! is_float( $key ) && ! is_callable( $key ) ) {
            trigger_error( 'array_group_by(): The key should be a string, an integer, or a callback', E_USER_ERROR );
            return null;
        }
        $func = ( is_callable( $key ) ? $key : null );
        $_key = $key;
        // Load the new array, splitting by the target key
        $grouped = [];
        foreach ( $array as $value ) {
            if ( is_callable( $func ) ) {
                $key = call_user_func( $func, $value );
            } elseif ( is_object( $value ) && isset( $value->{ $_key } ) ) {
                $key = $value->{ $_key };
            } elseif ( isset( $value[ $_key ] ) ) {
                $key = $value[ $_key ];
            } else {
                continue;
            }
            $grouped[ $key ][] = $value;
        }
        // Recursively build a nested grouping if more parameters are supplied
        // Each grouped array value is grouped according to the next sequential key
        if ( func_num_args() > 2 ) {
            $args = func_get_args();
            foreach ( $grouped as $key => $value ) {
                $params = array_merge( [ $value ], array_slice( $args, 2, func_num_args() ) );
                $grouped[ $key ] = call_user_func_array( 'array_group_by', $params );
            }
        }
        return $grouped;
    }

PHP merge and sum arrays