Python: function that returns a dict whose keys are the names of the input arguments

Question: Is it possible to write a function f that takes an arbitrary tuple of mixed data:
T = 1.0
N = 20
L = 10
args = (T,N,L)

f(*args) # or maybe f(T,N,L)?

and returns as output:
{'T':1.0, 'N':20, 'L':10}

There is a related question using local, but I seem to lose the names once they are passed to the function. Is there a way to prevent this? I'm guessing that the variables are being passed by value and thus they are considered new objects.
Followup: Python: Using a dummy class to pass variable names?
Comment: You seem to be confusing concepts here.  Other languages have variables, but [Python has names](http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#python-has-names).
Comment: Probably not possible, but I'll leave this as a comment for when I'm inevetiably proven wrong (probably with bytecode analysis or some such silliness).
Comment: I think it's possible given some constraints, please see my answer. Not robust or commendable though.
Answer: No, this is not possible in general with *args. You'll have to use keyword arguments:
>>> def f(**kwargs):
...  return kwargs
...
>>> f(T=1.0, N=20, L=10)
{'T': 1.0, 'L': 10, 'N': 20}

The reason is that *args does not introduce names for the individual arguments; it only introduces the name args for the whole list of them. The function has no insight into how what names, if any, the arguments have outside of it.
When the number of arguments is fixed, you can do this with locals:
>>> def g(T, N, L):
...  return locals()
...
>>> g(T=1.0, N=20, L=10)
{'L': 10, 'T': 1.0, 'N': 20}

(or explicitly with return {'T': T, 'N': N, 'L': L}.)
Comment: Exactly.  And then you are back to explicitly describing the key names rather than implicitly deriving them when you do `(T=1.0, N=20, L=10)`.
Answer: In Python variables are just labels attached to values. So there is no way to know, from another scope, what labels you were using when calling the function.
Answer: Your guess is unfortunately wrong, and in fact the whole question betrays a misunderstanding of how Python names work.
Python objects, on the whole, don't know their names. That's completely understandable when you consider that you can easily assign a=b, and now a and b both refer to exactly the same object. Python's "variables" are simply names that point to objects, they do not contain those objects in any real way. When you pass arguments to a function, you're passing the underlying objects, not the names. The receiving function simply binds them to the names specified in the function signature - or, in your case, simply keeps them in args without giving them any names at all.
So, when you're asking how to get the names that objects had in a different scope, you can't ask the objects themselves. There probably is a way to do this, but it involves mucking about with inspecting calling frames, and I very much doubt you want to.
Answer: A solution using globals(). This will only work if the values are unique in the module scope, so it's fragile - if there are duplicates, it will choose the first name that points to that value, somewhat arbitrarily. And yes, you're probably better off not doing this anyway and rethinking the problem instead.
def f(*names):
    r = {}
    for n in names:
        r[[ name for name in globals() if globals()[name] is n ][0]] = n
    return r

T = 1.0
N = 20
L = 10

print f(T,N,L)
{'T': 1.0, 'L': 10, 'N': 20}

Answer: Yeah, as best I know, args is a list.  To preserve label names, you'd need to pass a dict to **kwargs, and explicitly or programaticly set the names using local.
You could do something like:
def filter_locals(caller_locals, *args):
    filtered = {}
    for key in args:
        filtered[key] = caller_locals[key]
    return filtered

Then:
X = 1
Y = 2
func(filter_locals(locals(), 'X', 'Y')

Where func processes the arbitrary length list as kwargs.
Answer: It'd be necessary to pass the keys and the values as separate arguments:
keys = ('T', 'N', 'L')
values = (1.0, 20, 10)
d = dict(zip(keys, values))

In your code, the line args = (T,N,L) evaluates to args = (1.0, 20, 10), the "names" of the variables T, N, L are replaced by their values.


Cauchy sequence. Using definition.

Question:
Prove that
$$x_n = 1 + \frac{1}{2!} + \cdots + \frac{1}{n!}$$
is a Cauchy sequence.

I already showed that this sequence converges using
$$1 + \frac{1}{2!} + \cdots + \frac{1}{n!} < 1 + \frac{1}{2} + \cdots + \frac{1}{2^{n-1}}.$$
But I couldn't show that the is a Cauchy sequence using the definition. Any suggestion?
Answer: Given $\epsilon>0$, for large $N$, if $m>n\geq N$, $x_{m}-x_{n}=\dfrac{1}{(n+1)!}+\cdots+\dfrac{1}{m!}<\dfrac{1}{2^{n+1}}+\cdots+\dfrac{1}{2^{m}}<\epsilon$.

Cauchy sequence. Using definition.


low marginal and high conditional R2 for mixed models

Question: I have a suspicious output in my linear mixed model lmer() (lmer package), where I have marginal r2 of 0.08 and conditional of 0.8.
I am not surprised by the low marginal r2, however, I am puzzled about the conditional. I have a dataset of 2137 observations, with multiple measures per respondent (total independent n = 909). Can this "detailed" grouping be a reason for such a high conditional r2?

MM_WTP = lmer(z_WTP ~ z_current + Support + Bio_cont + CH_importance + Easy_recogn + Frequency + (1|ID), data = z_all_SEM, REML = F)

Linear mixed model fit by maximum likelihood . t-tests use Satterthwaite's method ['lmerModLmerTest']

Formula: transformed_WTP ~ transformed_price + Support + Bio_cont + CH_importance +      Easy_recogn + Frequency + (1 | ID)

 AIC      BIC   logLik deviance df.resid
  4736.2   4787.2  -2359.1   4718.2     2128

Scaled residuals:
    Min      1Q  Median      3Q     Max
-3.9528 -0.4151  0.0095  0.4066  4.4646

Random effects:
 Groups   Name        Variance Std.Dev.
 ID       (Intercept) 0.7067   0.8407
 Residual             0.2193   0.4683
Number of obs: 2137, groups:  ID, 909

Fixed effects:
                    Estimate Std. Error         df t value Pr(>|t|)
(Intercept)       -1.519e+00  1.841e-01  1.116e+03  -8.254 4.30e-16 ***
transformed_price  6.307e-02  1.557e-02  1.677e+03   4.051 5.33e-05 ***
Support            2.607e-01  3.252e-02  9.101e+02   8.015 3.37e-15 ***
Bio_cont           1.944e-02  2.572e-02  1.998e+03   0.756   0.4499
CH_importance      4.619e-02  1.939e-02  2.051e+03   2.382   0.0173 *
Easy_recogn        9.502e-03  1.976e-02  2.046e+03   0.481   0.6306
Frequency         -2.850e-03  1.130e-02  1.793e+03  -0.252   0.8009
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Correlation of Fixed Effects:
            (Intr) trnsf_ Supprt Bi_cnt CH_mpr Esy_rc
trnsfrmd_pr  0.036
Support     -0.874 -0.029
Bio_cont     0.124 -0.153 -0.036
CH_importnc -0.142 -0.056 -0.097 -0.079
Easy_recogn -0.229  0.009 -0.023 -0.070 -0.334
Frequency   -0.128  0.024  0.028 -0.001 -0.154 -0.083

> r2_nakagawa(MM_WTP)
# R2 for Mixed Models

  Conditional R2: 0.781
     Marginal R2: 0.076

Comment: How are you calculating R-squared for a mixed model?
Comment: I am using r2 Nakagawa from performance package in R.
Comment: Thanks, Elena. Can you post the `lmer` sytanx and output for your model? it would help to know the complexity of the random effects you are estimating.
Comment: Hi Erik. Sorry, I should have put once I published the question. I updated the question.
Answer: According to the documentation for r2_nakagawa,

The marginal r-squared considers only the variance of the fixed
  effects, while the conditional r-squared takes both the fixed and
  random effects into account.

Looking at the random effect variances of your model, you have a large proportion of your outcome variation at the ID level - .71 (ID) out of .93 (ID+Residual). This suggests to me that ID is sucking up a lot of the outcome variance and I would suspect that this is the reason the conditional $R^2$ is so much larger than the marginal $R^2$. I don't know the  level at which your predictors are measured, but you can get a sense of how much ID explains outcome variation by running a simple lm model as such:
lmmod <-  lm(z_WTP ~ 1 + as.factor(ID), data=z_all_SEM)
My bet is that this model with just dummy variables for ID and no other predictors will give a large $R^2$.
Comment: If you didn't take into account the influence of ID, given what you now know, that would be a huge problem. The fact that you are dealing with it through the random intercept is a sound approach worth reporting.
Comment: Thanks a lot for your reply! You are right, testing ID in an lm gives 77% of explained variance. I am using ID as a random effect, to solve the observation dependency problem, and it is logical in this case that a respondent tends to give similar responses. But is such a difference is to be concerned of for the model's output, or it would be ok to mention the difference and briefly explain it? Simply, is this model worth reporting, or it is fully wrong?
Comment: Thanks a lot, Erik!


How many machines are broken?

Question: The question: Consider a company that manufactures toaster ovens. Let the probability that a toaster oven has a scratch be p = 0.01. Assume that different ovens get scratched independently. In one day, the company makes 100 ovens. Find the probability that 5 or more ovens get scratched.
My approach to this question:
Let X be a random variable denoting the number of scratched ovens
$$P(X \ge 5) = (.01)^5(1)^{95} $$
The first factor comes from the probability that 5 of them are scratched, the second factor is 1 because we don't care if the rest of them are scratched. We only care that there are are at least 5 of them, which is guaranteed by the first factor.
However, according to the solution manuel,
$$P(X \ge 5) = \sum_{i=5}^{100}(.01)^i(.99)^{100-i} = .00343...$$
I'm not sure why my approach doesn't produce the same answer, since I guarantee that 5 of the ovens are scratched and for the rest of the ovens it doesn't matter whether they're scratched or not(Probability of either scratched or not = 1)
Comment: $(0.01)^5(1)^{95}$ is the probability that *very specifically* the first, second, third, fourth, and fifth toaster ovens are scratched, while the remaining 95 toaster ovens can be either. The solution you write from the solution manual is *also* incorrect (*and evaluates to about$3*10^{-11}$*) and is the probability that there are at least five scratched toaster ovens but they all *very specifically* appear at the front of the line ahead of all unscratched ovens.  The correct answer should instead be $\sum\limits_{i=5}^{100}\color{red}{\binom{100}{i}}(0.01)^i(0.99)^{100-i}\approx 0.00343\dots$
Comment: The point being, it could have been that the first five toasters were all fine and it was the sixth, twentieth, fourty-second, and nintieth through the hundredth toasters which were scratched.  We do not require that the scratched toasters appear at the front of the line, they could have been interspersed throughout the whole batch, and your answer does not account for that.  You accounted for some but not all of the possibilities.  For more info on the corrected approach from the solution manual, read about the [binomial distribution](https://en.wikipedia.org/wiki/Binomial_distribution).
Comment: Ah. That makes sense! Thank you for taking the time to respond!
Answer: Firstly, I think the answer to be problem should actually be:
$$\sum_{i = 5}^{100} {{n} \choose {k}}(.01)^i (.99)^{100-i} \approx .0034 $$
You can interpret this as the probability of only five machines breaking plus only the probability that only six machines break plus only plus ... plus the probability that all the machines break. This covers all the possibilities of machines breaking such that there are at least 5 machines that break.
The probability you thought was:
Pick a specific five and have those be broken. What is the probability of that? Although that does guarantee that we have 5 broken toasters, what about the probability that a different five are broken and the rest are not? Your probability doesn't seem to account for that.

How many machines are broken?


Moving from fixed-pipeline to modern OpenGL

Question: I have done some simple OpenGL (old fixed pipeline ,without shaders ..etc) and want to start some serious "modern" OpenGL programming. (Should compile on Windows and Linux)
I have few questions.
1) In Windows , the "gl.h" doesnt have OpenGL2.0+ related API calls declared .(eg. glShaderSource() ) . How can I access these API calls?
    I dont want to install graphics-card specific  headers since, I want to compile this application in other machines.
2) In Linux ,If I install Mesa library can I access above OpenGL2+ APIs functions ?
Answer: There has been a long-held belief among some (due to the slowness of GL version updates in the late 90s/early 00s) that the way to get core OpenGL calls was to just include a header and a library. That loading function pointers manually was something you did for extensions, for "graphics-card specific" function. That isn't the case.
You should always use an extension loading library to get access to OpenGL functions, whether core or extension. GLEW is a pretty good one, and GL3W is decent if you can live with its limitations (3.0 core or better only).


TYPO3 Composer dependency conflict

Question: I'll be brief:
I have a TYPO3 with composer installed.
Let us have a look at the require part from TYPO3.
<code>"require": {
    "php": ">=5.5.0",
    "ext-fileinfo": "*",
    "ext-json": "*",
    "ext-pcre": "*",
    "ext-session": "*",
    "ext-xml": "*",
    "psr/log": "1.0.*@dev",
    "pear/http_request2": "~2.2.1",
    "swiftmailer/swiftmailer": "~5.4.1",
    "symfony/console": "~2.7.0",
    "symfony/finder": "~2.7.0",
    "doctrine/instantiator": "~1.0.4",
    "typo3/class-alias-loader": "^1.0",
    "typo3/cms-composer-installers": "^1.2.8",
    "psr/http-message": "~1.0",
    "cogpowered/finediff": "~0.3.1",
    "mso/idna-convert": "^0.9.1"
}
</code>
As you can see TYPO3 needs "symfony/console": "~2.7.0" so that means: (>=2.7 <= 2.8)
Next to it I run a CakePHP with the migrations plugin for the custom CakePHP Part.
Let's have a look at the require part from the database migration plugin as well:
<code>"require": {
    "php": ">=5.4",
    "robmorgan/phinx": "0.5.3",
    "cakephp/cakephp": "~3.1"
},
</code>
Nothing wrong here on the first look, but let us go in detail and have a closer look at "robmorgan/phinx": "0.5.3". This Plugin needs the following packages, and again let's have a closer look at the composer.json from "phinx".
<code>"require": {
    "php": ">=5.4",
    "symfony/console": "~2.8|~3.0",
    "symfony/config": "~2.8|~3.0",
    "symfony/yaml": "~2.8|~3.0"
}
</code>
And now as you can see this package needs "symfony/console" at least in 2.8, but it doesn't work because TYPO3 needs it in "~2.7.0" that means: (>=2.7 <= 2.8).
I figured out the issue, but I have no idea how to solve it. I only have one solution but it is not that great, it's forking TYPO3 and editing the composer.json. But that is the very last option.
Does anyone else have a good approach on how to fix this?
Comment: `Next to it I run a CakePHP` Why are your typo3 and CakePHP projects in the same repo - or do you mean something different (please edit the question to clarify what "next to it" means)? Are you actively using migrations?
Comment: Yes I use now active migrations cause mysql dump files were not the best practice to manage database across all developers and dev/live servers.
Comment: The short answer is: TYPO3 is in front of the app/website, but the customer wants to have a big custom part as well, so I started to code a TYPO3-Extension after I have seen how unproductive and hard to code a TYPO3-Extension is, I decided to load CakePHP 3.0 into a TYPO3-Extension, it was a bit work but its working now. I can use now the full power of Cake for example my Cake-Controllers/Tables/Entities/Views to write a TYPO-Extension. On the TYPO3-Extension I have the CakeRequest-Object and return the fully generated result from Cake as string. Cake is installed as Vendor of TYPO3.
Answer: You can use version 8.x of TYPO3. This version uses as requirement <code>"symfony/console": ">=2.7 <3.1",</code>which looks absolutly fine then.
8.x is very stable, you can use doctrine all over the place and it is the future.

TYPO3 Composer dependency conflict


Como criar um DataTable que possui uma estrutura de colunas dinâmica?

Question: Olá, preciso criar um DataTable no meu projeto MVC que não possuirá colunas pré-definidas. A quantidade de colunas deverá ser definida a partir da quantidade de dados existentes em um campo do BD.
Eu possuo um campo na minha Model que se chama Low Tier Id, ele é uma FK de outra tabela (tabela Low Tier). Eu preciso criar colunas para cada Low Tier Id que eu tiver registrado no banco. Além disso, as colunas não podem ter os Low Tier Id como título, mas sim o campo Low Tier Name, o qual eu devo puxar por meio da FK.
Os dados que aparecerão nos campos serão do campo Quantity (este campo é da tabela Base Hour, a principal da View). Cada coluna deverá mostrar as Quantity respectivas ao Low Tier Id da coluna.
Até então, eu estava tentando criar as colunas desta forma, mas ainda sem passar os dados que os campos deverão mostrar e nem os títulos das colunas corretos:
JAVASCRIPT
var colsBaseLT = [];
function CreateColumnsBH() {
$.ajax({
    url: urlLTList, //referencia o método LT List da Controller
    dataType: 'json',
    type: 'POST',
    aynsc: false,
    success: function (result) {
        //a result trás um array de Low Tier Ids
        //A função abaixo percorre o Array e tenta criar uma coluna para cada elemento dele
        var ltLength = result.length;
        for (var i = 0; i < ltLength; i++) {
            colsBaseLT.push({ data: null, orderable: false, className: 'col-sm-2 text-center', title: "titulo", defaultContent: '' });
        }
    }
});

function CreateTableBH() {
$.ajax({
    url: urlCreateTableBH, //referencia o método GetBaseHour da Controller
    type: 'POST',
    success: function (result) {
        dataTableBH = DataTablesAjaxScrollHeight('#tableBaseHour', colsBaseLT, result.Grid, null, "350px");
    }
});

$(document).ready(function () {
    CreateColumnsBH();
    DataTablesAjaxPagination("#tableBaseHour", colsBaseLT, null, null, 12, 'BaseHour');
    CreateTableBH();
}

CONTROLLER (C#)
    public JsonResult GetBaseHour()
    {
        //pega os dados da tabela Base Hour, a principal da View
        return Json(new { Grid = new BaseHourBusiness().GetList<BaseHour>(Util.AuxiliaryMethods.BMPerRequestInstance)});
    }

    public JsonResult LTList()
    {
        var lowTierList = new LowTierBusiness().GetList<LowTier>(Util.AuxiliaryMethods.BMPerRequestInstance).Select(
                s => new
                {
                    s.Name
                }).ToList();
        //no Join acima eu tento pegar os LowTierNames presentes na tabela Low Tier
        return Json(lowTierList);
    }

EDIT: Para exemplificar melhor a estrutura do DataTable que quero criar, deixo a seguinte imagem:

Os nomes nas colunas são os Low Tier Names, campos que provém da tabela Low Tier. A tabela do BD desta View se chama Base Hour e ela possui uma FK da tabela Low Tier que é o campo Low Tier Id.
Eu necessito puxar os Low Tier Names pelos Low Tier IDs para que as colunas possam adquirir estes nomes, além de é claro construir as colunas de acordo com a quantidade de Low Tier ID existentes.
Os números, que são os campos da tabela, provém do campo Quantity. Eles deverão ser mostrados de acordo com o Low Tier ID correspondente da coluna.
Comment: Não consegui entender a estrutura que está tentando montar
Comment: Você quer construir a DataTable a partir do front-end? É isso?
Comment: Editei a pergunta para exemplificar melhor!
Comment: É, o DataTable é construído no JavaScript (a View(HTML) apenas referencia essa construção por meio de tag). A Controller (C#) é utilizada apenas para pegar os dados que serão utilizados e exibidos.
Comment: Tente o seguinte: via json consulte e traga somente os campos que deseja montar na table thead, monte a tabela usando javascript e após conclusão chame suas funções para inserir conteúdo.
Answer: Se eu entendi bem sua questão, você precisa apenas montar uma grid/tabela com os dados dinâmicos vindos do code-behind, correto?
Se for este o caso, porque você não utiliza neste caso uma Viewbag, com uma lista das suas colunas para poder montar sua Table head. Junto a isto, você passa outro Viewbag com os resultados e coloca em um foreach para montar com Razor o seu HTML Dinamicamente assim que sua Action for solicitada? Teoricamente funcionaria tanto para uma View quanto para uma _PartialView;
Answer: Olá, usando o Jquery DataTables é possível fazer algo a respeito.
Como eu faço hoje:
Digamos que na minha consulta, meu json retorna uma lista de items onde o objeto item possui {id, name, email}
ajaxResponse = [
 {id: 1, name: "Pedro Santos", email: "firstname.lastname@example.com"},
 {id: 2, name: "Fulano Santos", email: "firstname.lastname@example.com"},
 {id: 3, name: "Beltrano Santos", email: "firstname.lastname@example.com"},
];

O Plugin do Jquery DataTables pode ser instanciado da seguinte maneira:
$("#myTable").DataTable({
 data: data,
 columns: columns
});

Onde a data espera um array de array com valores, e columns espera um array de objetos. Ficou estranho né, mas o exemplo vai clarear, vamos a ele.
data: como falei o data espera um array que contenha um array de valores apenas, então data deve ser interpretado assim:
data = [
 ["1", "Pedro Santos", "firstname.lastname@example.com"],
 ["1", "Fulano Santos", "firstname.lastname@example.com"],
 ["1", "Beltrano Santos", "email@example.com"],
];

columns: como falei o columns espera um array de objetos, mas esse objeto conterá apenas o atributo title, que é o titulo do campo da sua coluna, vamos ver como fica:
columns = [
 {title: "ID"},
 {title: "NOME"},
 {title: "EMAIL"},
];

Por fim desde que você retorne do seu backend, um cabeçalho de columns neste formato, e uma lista de de array de valores na ordem correta das colunas, a sua tabela dinamicamente terá o formato esperado.
Veja aqui um pouco de como ficou o meu codigo:

Primeiro eu crio um dataSet vazio;
Depois crio como eu quero exibir as colunas, lembrando como falei, essa informação pode vir do seu back-end, neste formato para tornar sua tabela com colunas dinamicas OK?

Agora eu peguei o meu retorno do ajax, e percorri, formatando-o como eu quero, mais uma vez, lembrando que você pode pre-formatar no back-end e trazer o dado do seu jeito. Aqui eu trago o dado limpo, e o dispositivo que for consumir trata como achar melhor.
Depois que montei a linha eu adiciono o array de valores, para dentro do meu dataSet.
E por fim??

Eu chamo uma função que passo a minha ID da tabela, os dados e as colunas.
IMPORTANTE: se sua ideia é ter coluna dinâmica, é necessário destruir a tabela antes e recriar com esse componente do Jquery DataTable, afinal tanto coluna quanto dados mudaram e sua quantidade também.
e de bonus ai vai o exemplo completo da minha tabela ficando assim:

Espero ter ajudado, essa foi a minha primeira contribuição no Stack Overflow, eu era apenas um consumidor.
Se você não usa o plugin Jquery DataTables recomendo que use, mas ainda sim é possível você fazer sua tabela dinamica de colunas e dados.
Primeiro, voce precisa retornar do seu back-end as colunas, sendo um array de valores com o nome das colunas:
ajaxResponse = {
 colunas: ["ID", "NOME", "EMAIL"],
};

Depois o seu back-end precisa retornas os dados das colunas ai pode ser um array de objetos:
ajaxResponse = {
 colunas: ["ID", "NOME", "EMAIL"],
 linhas: [
  {id: 1, nome: "Pedro Santos", email: "firstname.lastname@example.com"}
 ]
};

agora você precisa montar a tabela:

E o seu js, ou jquery ficara assim:
$(function(){
 $("#colunas").html(""); //apaga as colunas da ultima consulta se existir

 ajaxResponse.colunas.map((coluna) => {
  $("#colunas").append(`<td>${coluna}</td>`);
 });

 $("#linhas").html(""); //apaga as linhas da ultima consulta se existir

 ajaxResponse.linhas.map((linha) => {
  $("#linhas").append(`<tr><td>${linha.id}</td><td>${linha.nome}</td><td>${linha.email}</td></tr>`);
 });
});

assim você terá sua tabela de colunas dinamicas conforme o retorno do seu back-end.
Bom, espero ter ajudado você.


How to get placeholder instead of label in wordpress comments.php?

Question: I am using this code to display the default wordpress comments template:
<code><?php comments_template(); ?>
</code>
How can I change the name/email/url/comment label to a placeholder?
I thought that I could modify the comment-template.php in the wp-includes folder or should I create a comments.php file?
Answer: If your theme has comments.php file then edit that file and write your placeholder there. otherwise create your own comments.php file and design your own comment form. here is the reference link.
http://codex.wordpress.org/Function_Reference/comment_form
or you can see comments.php file in any default theme like "twenty twelve"
Cheeers!
Comment: But there are some specific links to functions, how about these? Sorry, I am a php noob :p


Low CPU Utilisation But High CPU Load Wordpress Ubuntu Apache2

Question: My Ubuntu 18.04 server with 2GB of RAM and 2 CPU cores experiences major CPU load spikes when someone accesses the Wordpress site that the computer serves. This slows down the website very much.
Below is the output from a top command

In the screengrab above, the load is shown to be 3.8, but most of the time it rises to 5.0 - 6.0.
The server runs Apache2 in Event MPM, MySQL 8 and PHP7.3. Redis caching is also present.
Due to this load spike, my website times out with a Cloudflare 524 error and I'm unable to log into wp-admin.
Is there any way to fix this?
EDIT:
Here is a link to the output of the MySQLTuner tool run on this system.
https://pastebin.com/awxRidr3
And here is the link to the output of cat /proc/meminfo.
https://pastebin.com/E9uvq5A9
Comment: Page caching for anonymous users can provide a good speed-up, since most Wordpress sites are mostly status. Use CloudFlare to do caching of static resources. My Amazon Linux server has 5% of a CPU core (bursting to 100%), 512MB RAM, 512MB swap, and serves six low traffic websites easily. Wordpress / PHP is VERY CPU hungry, but it shouldn't stop you SSHing in if it's busy. Reduce the number of PHP workers to the number of threads your computer has to prevent overloading the system.
Answer: Performance issues can be any number of things. Investigate everything and keep an open mind.
73% IO wait suggests the storage system is a limiting factor.
Install bpfcc-tools and run filetop to see reads and writes by file. Classify what gets lots of I/O: database, uploaded content, the web application, whatever. Use ext4slower (or xfsslower) scripts to find file system operations that take more than a few milliseconds.
Possible actions:

Migrate  to solid state disks if you have not already
Enable and review the slow query log
Consider a separate database host, possibly a managed service
Find some of the many WordPress checklists and evaluate their suggestions
Do a capacity analysis and determine if it is time to scale out or up.
Comment: (As a stop gap measure) Do you have swap enabled? Try changing VM.swappiness to 5.
Comment: Please post TEXT results from Ubuntu Command Prompt of cat /proc/meminfo and we can tell what has been set up on your server for the feature.
Comment: @WilsonHauck Hi, I've added both the complete MySQLTuner report and the output from the cat /proc/meminfo
Comment: @sids #1 get the USB device out of your operations ASAP - not a good idea to run an OS from USB - other than to prove it CAN can be done - but not well.  #2 from meminfo, there are NO HugePages_Total in use, do not know why it is listed in TOP.  #3 from MySqlTuner report detected Joins performed without indexes: 5996 in 5d 22h can be corrected with indexes. #4 I wonder why Aborted connections: 1,461 in 5d?  Disclaimer: I am the content author of website mentioned in my profile, Network profile where we have downloadable FREE Utility Scripts, FAQ and contact information.  Get in touch, please.
Comment: @JohnMahowald - Moved everything from my USB stick to the 40gb HDD. Everything is much faster and the IO Wait times only peaks up to 40% max. Huge speed improvement, now I'm planning to move everything to a new HDD with a really fast RPM, or an SSD. Thanks!
Comment: @WilsonHauck, Might take a look at those free scripts. As of now, website performance has increased exceptionally after moving from a USB stick to the HDD.
Comment: @sids Wonderful news.  HDD for OS, MySQL and other apps PLUS SSD for database storage would be best combo.  Looking forward to your download of our Utility Scripts to assist with performance tuning.
Comment: Thanks for the answer! I think the drive that the OS and all the software is installed on is the major bottleneck. I am currently using a USB memory stick to run Ubuntu. I think I should definitely invest in an SSD upgrade. I do have a 40GB HDD (really old), do you think that it would be faster if I use the HDD while I source an SSD?
Comment: I wondered why there was a usb-storage thread in state D. Try everything you have, spindle and solid state. Typical USB storage sticks have miserable write performance. Although one spindle would be less than 100 IOPS and not amazing either.
Comment: Please post COMPLETE MySQLTuner.pl (perl) report after 24 hours of UPTIME so we get some idea of your use of MySQL.  With a 2G server size, why would you need to use KHUGEPAGED?  Disable anything HUGEPAGE, you do not have the RAM to support it.
Comment: @davidgo I do have swap enabled, I will be moving to the 40GB HDD, that should make things faster, if it doesn't I might as well disable swap.
Comment: @WilsonHauck, Hi, I'm not quite sure what HUGEPAGE is, please could you elaborate.
Comment: @SidS if you have swap enabled on a standard Ubuntu 18.04 install you definately want to enable vm.swappiness.  (Google it, its fairly easy to do, and has been covered to death).  It won't solve your problem but it will mitigate it.  You do not want to disable swap as setting vm.swappiness close to 0 has all the upsides with none virtually of the downsides of disabling swap.
Comment: @sids On your TOP list posted, it is PID 29 - khugepaged.  Google search for ubuntu disable hugepage for ideas on disabling the overhead.  Please let me know when you have posted a complete MySQLTuner report, Thanks


Enable modules across platforms using Features/Drush

Question: I am wondering, could this be automated.

I download and enable contrib modules on @dev
I push files on @live (including new modules)
via Features/Drush I tell @live to enable new modules, so servers are in sync.

I do some needed disabling/enabling of dev modules when doing sql-sync to @dev, but this is case when I install new modules on @dev and want them on @live automagically when I commit.
I could, of course, do drush @live en [modulename] for each module I installed on dev.
Answer: Yes, this could be automated. I'd suggest the missing component is git or possibly another source control tool, so you can create commits that represent complete sets of configuration changes.
(I see you mention commit in your question so presumably you already use git).
Comment: I do not commit using git (as it is overhead for single-developer maintained project), I "commit" using drush rsync. But that does not enable module on target (Even if I commited from git, modules would not be enabled). I am wondering if module state (enabled/disabled) can be captured in features, or they can be enabled via Drush in bulk.


Pexect in Windows Batch File > Cygwin > Python > SSH

Question: I have a Linux box that runs Cisco IOS and need to SSH into it sometimes to reboot it.  I've written a batch file that calls on Cygwin.  Cygwin then calls on Python+PythonScript.
Batch File:
cd c:\cygwin64\bin
bash --login -i -c "python3 /home/Owner/uccxtesting.py"

Python Script
import pexpect
import time
import sys

server_ip = "10.0.81.104"
server_user = "administrator"
server_pass = "secretpassword"

sshuccx1 = pexpect.spawn('ssh %s@%s' % (server_user, server_ip))
sshuccx1.logfile_read = sys.stdout.buffer
sshuccx1.timeout = 180
sshuccx1.expect('.*password:')
sshuccx1.sendline(server_pass)
sshuccx1.expect('.admin:')
sshuccx1.sendline('utils system restart')
sshuccx1.expect('Enter (yes/no)?')
sshuccx1.sendline('yes')
time.sleep(30)

When I run this, it stops at Enter yes/no.  This is what I'm getting:

I've seen plenty of examples of pexpect with expect, but there is some white space out beside the question mark. I just don't know how to tell python to expect it.
Comment: does it work if you run the python script from Mintty ?
Comment: I get the same thing
Comment: How can I modify the sshuccx1.expect('Enter (yes/no)?') line so if the line contains "yes/no" it'll pick that up?   I've tried doing sshuccx1.expect('.*yes.*')  but it fails to pick that up.
Comment: are you sure the python and ssh are the Cygwin ones ?
Comment: Yes when I installed Cygwin, I picked to install python from its installation wizard.
Comment: Is there a way to expect anything, then give it yes?  Or is there a way to wait x amount of seconds then issue another command?  I've tried the later one but the script just terminates.
Answer: There may be a bug:
utils system restart prompts for force restart (https://bst.cisco.com/bugsearch/bug/CSCvw22828)
Replace time.sleep(30) with the following code to answer a possible force restart prompt. If it works, you can get rid of the try...except and print commands that I added for debugging:
try:
    index = -1
    while index != 0:
        sshuccx1.expect_exact(['succeeded', 'force', ], timeout=300)
        if index == 2:
            print('Forcing restart...')
            sshuccx1.sendline('yes')
    print('Operation succeeded')
    print(str(child.before))
except pexpect.ExceptionPexpect:
    e_type, e_value, _ = sys.exc_info()
    print('Error: ' + pexpect.ExceptionPexpect(e_type).get_trace())
    print(e_type, e_value)

Also, change sshuccx1.expect('Enter (yes/no)?') to sshuccx1.expect_exact('Enter (yes/no)?'). The expect method tries to match a regex pattern, and it may get caught on the parentheses (see https://pexpect.readthedocs.io/en/stable/api/pexpect.html#pexpect.spawn.expect_exact)


Pedaling in La fille aux cheveux de lin

Question: Throughout this piece, Debussy writes that certain notes are to be extended from measure to measure, e.g.,

but there's a problem here. Note that I'm a beginner on piano.
My hands aren't insanely huge, so there are really one one of two things that I think I could do.
1) Focus on holding the dotted half notes and pedal to the end of the fourth bar of the system.
i.e., use the pedal as follows:

As you can see above, what holding the pedal here does is give this sound that all of the notes, as they are played, are held until the pedal is released.
2) Grace note the lowest note, and use the sostenuto (middle) pedal on the lowest note while holding the pedal. Release the pedal on the fourth bar of the system but hold the sostenuto pedal.

How do experienced pianists handle the pedaling in this case?
Answer: This is one of those things that makes Debussy really hard, and not really appropriate for a beginner despite the slow tempo.  Debussy was an excellent pianist, and it seems that he leaned on his ability as a performer and didn't worry about the notation that much.  His piano music is full of places where what's written doesn't match what he intended (we have piano rolls of him playing to corroborate this), maybe most famously the completely unmarked double/half time tempo changes in La cathédrale engloutie.  In this case, as it's written, there's really not a good way to achieve what the notes say.  It should also be noted that Debussy did not have a sostenuto pedal.
I would suggest ignoring the tie on the low G flat.  Pedal the whole first measure and clear it on the bar line.
Comment: The sostenuto pedal was invented (in France) back in 1844, and Steinway started to manufacture it in 1876 (when Debussy was only 16 years old), but AFAIK there is nothing in Debussy that explicitly requires its use.
Comment: Somewhere I have read that Ricardo Viñes, the virtuoso pianist who was a friend of Debussy, might have had a piano with a sostenuto pedal. But I think that @MattPutnam is right in that Debussy never owned a piano with one.
Answer: Probably, you are missing the fact that Debussy was writing for a full size acoustic grand piano, not for a small upright or a digital piano that doesn't have a good implementation of the sustain pedal function.
On a concert grand, the bass strings have enough energy that a quick up-and-down movement of the pedal has very little effect. A quick pedal change can damp the notes around middle C and higher, but leave the bass note sounding.
Since the low D and G in the first bass chord fit with the harmony after the pedal change, it's not very important how well they "survive" the quick pedal change. Debussy's notation that doesn't show them being sustained is clearer to read.
You can use the sostenuto pedal if you want, but I don't think it's what Debussy meant. Playing the lowest note on its own first, just so you can "fire" the sostenuto pedal, interrupts the rhythm of the 16th notes and contradicts the "Mouvt" instruction.

Pedaling in La fille aux cheveux de lin


Codec error when writing Python dictionary into CSV

Question: Below is a sample of my dictionary:
dict = {'Croatia': '191', 'Cuba': '192', 'Curaçao': '531',
        'Cyprus': '196', 'Czechia': '203',  'Czechoslovakia': '200',
        "Côte d'Ivoire": '384',  "Dem. People's Rep. of Korea": '408',
        'Dem. Rep. of the Congo': '180', 'Denmark': '208'}

My goal is to try to write the diction into a csv file so each row will have one key and one value, such as:

Croatia, 191
Cuba, 192

and I am using csv for this purpose:
import csv
with open('dict.csv', 'w') as csv_file:
writer = csv.writer(csv_file)
for key, value in dict.items():
   writer.writerow([key.encode('utf-8'), value])

when not using key.encode('utf-8'), Python gives the error of 'ascii' codec can't encode character '\xf4' in position 1: ordinal not in range(128), presumably cuased by Côte d'Ivoire in the dictionary. However, even when a csv file can be successfully produced now, the csv file itself contains additional characters b'countryname' instead of countryname.
(see the image for reference: https://i.stack.imgur.com/F9dJu.jpg)
How do I solve this particular issue?
Answer: The docs cover how to handle encoding.  Trying to encode individual elements does not, as you have seen, work out well.
Comment: leveraging known python solutions is an excellent answer.  The python 3 version of [the docs](https://docs.python.org/3/howto/unicode.html)
Answer: Well, I recommend you to use Pandas for your purpose.
import pandas as pd

country_name = dict.keys()
cnt = dict.values()
df = pd.DataFrame({'countryname':country_name,'count':cnt})
df.to_csv('result.csv',sep=',',encoding='utf-8')


Find a parametric line equation that intersects two other lines at the point of closest approach

Question: I have two parametric line equations for a 3D space, $A(t)$ and $B(t)$. Both of these lines have a "velocity" vector as a direction vector. Both equations actually represent a point moving through space at a specific speed, and the line represents its path through space. Each line equation has a different "speed".
So, I have these two line equations that actually represent moving points (think two mosquitos travelling in straight lines at different speeds).
I need to find a line equation that will "hit" both $A(t)$ and $B(t)$ (think bug spray, trying to hit the mosquitoes). This line also has a "velocity" (and thus "speed"). However, once the line intersects ("hits" is the term I used above) one of the other lines ($A(t)$ or $B(t)$), it will take some amount of time for it to intersect the other (as it is travelling at a constant speed, and not instantaneously). However, I need this line equation to travel the least possible distance between intersecting one line and then the other.
My problem arises in finding this line equation, specifically the direction vector. I need the third line to almost "predict" the future location of the lines - it hits one (say, $A(t)$) and then, because both $B(t)$ and the (not yet found) line would be travelling at different speeds, the (not yet found) line would need to be perfectly position to intersect $B(t)$.
So far, I've deduced that the third line will intersect $B(t)$ at $t = t_c - a$ and $A(t)$ at $t = t_c + b$ ($B(t)$ travels faster than $A(t)$, and thus the third line must intersect it first). $t_c$ is the $t$ value when $A(t)$ and $B(t)$ are closest together. $a$ and $b$ are some real values that represent seconds (the same unit as $t$).
I don't know where to go from here, or if I'm even on the right track. How could you find a line that intersects two other lines, with different velocities, while also minimising the distance the third line travels between intersecting the other lines?
I was hoping for some insight into the problem (specific values weren't provided for this reason - I don't need the full working, I just need some guidance to the solution). This is a fairly unique problem, as the lines I am dealing with actually represent a point moving through a 3D space.
Thanks for any help.
Comment: do you know about the $\mathbb R^3$'s cross product?
Comment: Is there a given velocity for the third line?
Comment: @user2271513 yes, there is
Comment: @janmarqz Yeah, I do. Could I use that here?
Comment: hint to start: given the two directions use their cross product to find a direction perpendicular to them ... I hope this helps
Answer: Let $A(t)=tA_1+a_1$ and $B(t)=tB_1+b_1$ be your two lines.
Then $C=A_1\times B_1$ is a direction perpendicular to both directions $A_1,B_1$. Also this determine two planes $\Pi_1$ and $\Pi_2$ which contains directions $A_1$ and $B_1$ respectively.
With the vector $\vec{a_1b_1}$ we construct a triangle with vertices
$a_1,b_1$ and $E$. This last direction (also position) being the projection of the vector
$\vec{a_1b_1}$ on $\Pi_1$. Now we consider the Ansatz:
$$\vec{a_1b_1}=E+mC.$$
Pairing each side of this equation with $C$ we get
$\vec{a_1b_1}\cdot C=mC\cdot C$. We get this because $E$ and $C$ are perpendicular, so
$$m=\frac{\vec{a_1b_1}\cdot C}{C\cdot C},$$
and
$E=\vec{a_1b_1}-mC$ is got as a byproduct.
$\hspace{4cm}$
Comment: Thanks for you help! Quick question... how can I then use $E$ to find the third line? Using it as a direction vector makes a line that intersects $A(t)$, but not necessarily $B(t)$
Comment: $L(t)=tE+a_1$ is a line with direction $E$ that passes through $a_1$
Comment: yeah, but then how can I show that it passes through $B(t)$ as well?
Comment: it can't because it lies in the plane $\Pi_1$ which is a plane that doesn't intersect $\Pi_2$ since they are parallel planes, but the line $M(t)=t(b_1-a_1)+a_1$ can since $M(0)=a_1$ and $M(1)=b_1$.
Comment: Because all three lines need to have velocity, can you prove that the distance $M(t)$ travels between intersecting $A(t)$ and $B(t)$ is the smallest possible?
Comment: the picture is a little misleading, but the direction $E$ is parallel to the line $B(t)$ so by sliding $mC$ just to position $a_1$, a parallel line to $C$ will hit a point in $B(t)$ and which is at $-E$ from $b_1$. This point at the line $B(t)$ and $a_1$ are at the very same distance $\|mC\|$ as all points of $\Pi_1$ are from $\Pi_2$. Give me a little while to correct the picture.
Comment: Now is a better picture
Answer: In this answer I assume that the third line has a given speed $v$, and that the lines are not parallel. If the speed is just a maximum then this may not be the optimal solution. Let the first curve be given by
$$
\mathbf{l}_1 = t\mathbf{b}.
$$
Here we have just translated to remove one of the vectors. Suppose the second curve is given by
$$
\mathbf{l}_2 = \mathbf{a}' + t\mathbf{b}'
$$
Then if we leave at $\mathbf{l}_1$ at $t_1$ and arrive at $\mathbf{l}_2$ at $t_2$, we can calculate the vector between the points of intersection:
$$
\mathbf{d}(t_1, t_2) = \mathbf{a}' + t_2\mathbf{b}' - t_1\mathbf{b}.
$$
We know that
$$
\frac{\|\mathbf{d}\|}{t_2 - t_1} = v,
$$
and so
$$
t_2 = t_1 + \frac{\|\mathbf{d}\|}{v}.
$$
Hence
$$
\begin{align}
\|\mathbf{d}\|^2 &= (\mathbf{a}' + t_2\mathbf{b}' - t_1\mathbf{b}).(\mathbf{a}' + t_2\mathbf{b}' - t_1\mathbf{b}) \\
&= \left(\mathbf{a}' + \frac{\|\mathbf d\|}{v}\mathbf{b}' + t_1(\mathbf{b}' - \mathbf{b})\right).\left(\mathbf{a}' + \frac{\|\mathbf d\|}{v}\mathbf{b}' + t_1(\mathbf{b}' - \mathbf{b})\right)
\end{align}
$$
Which is a quadratic equation for $\|\mathbf d\|$ in terms of $t_1$ - if the roots are not real then this implies that we can't hit the other line when setting off from $\mathbf l_1$ at time $\mathbf t_1$.
We can rearrange the above equation to get an equation of the form
$$
\|d\|^2 - 2\beta(t_1)\|d\| + \gamma(t_1) = 0
$$
and so, from the quadratic formula
$$
 \|d\|(t_1) = \beta(t_1) \pm \sqrt{\beta(t_1)^2 - \gamma(t_1)} = f(t_1).
$$
where the appropriate root is chosen (this will depend on properties of the lines).
$\beta$ and $\gamma$ are smooth functions of $t$, so we can differentiate $f$ to find the critical points of the distance.
Comment: Ah yeah, I see now. Looks like my math was a bit funky before, thanks for clarifying
Comment: I've just come back to this (sorry for commenting so late after you posted this answer) but in your final equation, how is it possible to solve using the quadratic formula? Your final equation for $|d|^2$ is in terms of both $|d|$ and $t_1$... would this not make it implicit?
Comment: Yeah, the final expression is a quadratic equation in $|d|$ (as in of the form $a|d|^2+ b|d| + c$ after some rearranging, where the coefficients are functions of $t_1$) and so we can write $|d| = f(t_1)$ for some $f$ computed using the quadratic formula. Then pick $t_1$ to minimise $f$
Comment: but don't you end up with an equation with both $|d|$ and $t_1$? IN which case there are two unknowns - we don't know $|d|$ or $t_1$
Comment: Yeah exactly, but you can find the $t_1$ which minimises $|d|$ which is what you're after, in the same way that $y = x^2$ has two unknowns but $y$ is a minimum when $x$ is $0$
Comment: In rearranging, I've ended up with $|d|^2 = |a'|^2 + |\frac{|d|}{v}b'|^2 + |t_1 (b'-b)|^2 + 2(a'\cdot \frac{|d|}{v}b') + 2(a'\cdot t_1 (b'-b)) + 2(\frac{|d|}{v}b' \cdot t_1 (b'-b))$, which is implicit (I've tried to simplify it best I can). I cannot find a way to get $|d|$ on it's own on one side. Am I missing something?
Comment: You can use the quadratic formula, since this is a quadratic equation in $|d|$
Comment: But in order to use the quadratic equation I would need to get $a|d|^2 +b|d|^2 + c = 0$, and I can't seem to do that? Would you mind showing me what you mean? (you don't have to solve the whole thing, I just need to see what you mean)
Comment: sorry I should have been clearer - I've updated the answer


Determine the $C^\infty$ function $f$ on $\Bbb R$ satisfying $f(x)f(y)= \int_{x-y}^{x+y} f(t) dt,$ for any $x,y \in \Bbb R$

Question: Q. Suppose that $f \not \equiv 0$ is an inifinitely differentiable function on $\mathbb R$ satisfying $$f(x)f(y)= \int_{x-y}^{x+y} f(t) dt,$$ for any $x,y \in \Bbb R$,
Find the limit $\lim_{t \to \infty}\frac{f(t)}{e^{t/3}}$ whenever $f(1)=45$ and $f''(1)=5$.
I got $f(0)=0$ and tried with $f(x)=\frac{2}{45} \frac{F(x+1)-F(x-1)}{2}$, where $F$ is an antiderivative of $f$. But, How to connect this finite difference with $f''(1)$?
Or
Any thing can be done with $f(x)^2=\int_0^{2x} f(t)dt$ which essentially gives $f(x)f'(x)=f(2x)$?
Answer: Hints: Differentiation w.r.t. $x$ and $y$ gives  $f'(x)f(y)=f(x+y)-f(x-y)$ and $f(x)f'(y)=f(x+y)+f(x-y)$. So $f'(x)f(y)+f(x)f'(y)=2f(x+y)$. The right hand side has the same derivetive w.r.t. $x$ and $y$. So  $f''(x)f(y)+f'(x)f'(y)=f'(x)f'(y)+f(x)f''(y)$. This gives $\frac {f''(x)} {f(x)}=\frac {f''(y)} {f(y)}$ which makes $\frac {f''(x)} {f(x)}$ a constant $a$. Now you can find $f$ explicitly using the conditions $f(1)=45$ and $f''(1)=5$.


Evaluate the following integral : $\int\limits_0^{\infty}x\operatorname{arctanh}(x)e^{-ax^2}dx$

Question: How I find this integral :
$$\int\limits_0^{\infty} x \tanh^{-1}(x)\ e^{-a x^2}\ dx$$ where $a>1$
I post same similar question but I don't know how I evaluate the above integral.
At first I use integral by part but I find divergent integral.
And also I use series same problems divergent series.
I think use for $x>1$ $\operatorname{arctanh}x=\ln\left(\frac{1+y}{y-1}\right)+ \pi i$
But problem in this ?
$$\int\limits_0^1 x \ln(1-x)e^{-ax^{2}}\ dx$$
Comment: *Mathematica* gives: $\frac{\pi  e^{-a} \left(\text{erfi}\left(\sqrt{a}\right)-i\right)}{4 a}$ for $a>0$.
Comment: MMA gives this here $$\frac{e^{-a}
   \left(-\text{Hypergeometric1F1}^{(1,0,0)}\left(0,\frac{1}{2},a\right)-\text{Chi}(a
   )-\text{Shi}(a)+\log (a)+\gamma \right)}{4 a}$$
Comment: So this question is the same as your previous question, but with $\operatorname{arctanh}(x^2)$ replaced by $\operatorname{arctanh}(x)$?
Answer: As $\tanh^{-1}x=\frac{1}{2}\ln\frac{1+x}{1-x}$ for $|x|<1$, you must have $\tanh^{-1}x=\frac{1}{2}\ln\frac{x+1}{x-1}+(n-\color{red}{\frac{1}{2}})\pi i$ for some $n\in\mathbb{Z}$ when $x>1$. Making a definite choice $n\equiv 0$, we arrive at the result given by David G. Stork in his comment. Indeed, the given integral is (then) equal to $$\int_{0}^{\infty}\frac{x}{2}\ln\left|\frac{1+x}{1-x}\right|e^{-ax^2}\,dx-\frac{\pi i}{2}\int_{1}^{\infty}xe^{-ax^2}\,dx=\frac{e^{-a}}{4a}\big(I(a)-\pi i\big),$$ where \begin{align}I(a)&=\int_{0}^{\infty}\ln\left|\frac{1+x}{1-x}\right|\cdot 2axe^{a(1-x^2)}\,dx\\&=-\left.\ln\left|\frac{1+x}{1-x}\right|(e^{a(1-x^2)}\color{red}{-1})\right|_{0}^{\infty}+2\int_{0}^{\infty}\frac{e^{a(1-x^2)}-1}{1-x^2}\,dx\\&=2\int_{0}^{\infty}\frac{e^{a(1-x^2)}-1}{1-x^2}\,dx\end{align} and $I'(a)=2\int_{0}^{\infty}e^{a(1-x^2)}\,dx=e^a\sqrt{\pi/a}$. As $I(0)=0$, we get $$I(a)=\sqrt{\pi}\int_0^a\frac{e^x}{\sqrt{x}}\,dx=2\sqrt{\pi}\int_{0}^{\sqrt{a}}e^{y^2}\,dy=\pi\operatorname{erfi}\sqrt{a}.$$
Comment: Thank you , but I think this divergent integral ! $\int_{0}^{\infty}\frac{e^{a(1-x^2)}-1}{1-x^2}\,dx$
Comment: No, it converges. The integrand is $\mathcal{O}(x^{-2})$ when $x\to\infty$, and has a *removable* singularity at $x=1$ (this is the whole matter of introducing *that* $-1$ when integrating by parts).
Answer: Here is my solution that is slightly different from that of metamorphy: As metamorphy explained in his answer, we are looking to find the value of
$$V(a)=\int_{0}^{\infty}\frac{x}{2}\ln\left|\frac{1+x}{1-x}\right|e^{-ax^2}\,dx-\frac{\pi i}{2}\int_{1}^{\infty}xe^{-ax^2}\,dx =: J(a)-\frac{\pi i}{2}\int_{1}^{\infty}xe^{-ax^2}\,dx=J(a) - \frac{e^{-a}}{4a}\pi i.$$
To find
$$J(a)=\int_0^\infty xe^{-ax^2} \left\{\frac{1}{2}\ln\left|\frac{1+x}{1-x}\right|\right\}dx$$
we integrate by parts, whereby we use $\frac{d}{dx}\left\{\frac{1}{2}\ln\left|\frac{1+x}{1-x}\right|\right\} = \frac{1}{1-x^2}$ to arrive at
$$J(a)=\left. \left\{\frac{1}{2}\ln\left|\frac{1+x}{1-x}\right|\right\}\frac{-1}{2a}e^{-ax^2} \right|_0^\infty + \frac{1}{2a} \int_0^\infty \frac{e^{-ax^2}}{1-x^2}dx=\frac{1}{2a} \int_0^\infty \frac{e^{-ax^2}}{1-x^2}dx=:\frac{1}{2a}Y(a).$$
We can differentiate $$Y(a)=\int_0^\infty \frac{e^{-ax^2}}{1-x^2}dx$$ with respect to $a$ to obtain
$$\begin{align}Y'(a)&=\int_0^\infty \frac{(-x^2)e^{-ax^2}}{1-x^2}dx = \int_0^\infty \frac{e^{-ax^2}}{1-x^2}(1-x^2-1)dx\\
&=\int_0^\infty e^{-ax^2}dx - \int_0^\infty \frac{e^{-ax^2}}{1-x^2}dx = \frac{1}{2}\sqrt{\frac{\pi}{a}} - Y(a)\end{align}.$$
This ordinary differential equation
$$Y'(a) = \frac{1}{2}\sqrt{\frac{\pi}{a}} - Y(a)$$
can be solved by the variation of parameters:
$$Y(a)=C_0 e^{-a}+ e^{-a} \int da ~\frac{1}{2}\sqrt{\frac{\pi}{a}}e^a = C_0 e^{-a}+ \frac{\pi}{2}e^{-a} \textrm{erfi}(\sqrt{a})$$
Since $Y(a=0)=0$ (using the  Cauchy principal value) we have $C_0=0$ and hence
$$V(a)=\frac{\pi e^{-a}}{4a}\big(\textrm{erfi}(\sqrt{a})-i\big)$$


Erro em código teste: object() takes no parameters

Question: Eu fiz um código teste, mas não sei qual o erro, alguém me ajuda?
class Caneta:
    def _init_(self, cor, modelo, ponta):
        self._cor = cor
        self._modelo = modelo
        self._ponta = ponta
        self._carga = 100
        self._tampada = True
    def _getCor(self):
        return self._cor
    def _getModelo(self):
        return self._modelo
    def _getPonta(self):
        return self._ponta
    def _getCarga(self):
        return self._carga
    def _isTampada(self):
        return self._tampada
    def _setCor(self, cor):
        self._cor = cor
    def _setModelo(self, modelo):
        self._modelo = modelo
    def _setPonta(self, ponta):
        self._ponta = ponta
    def _setCarga(self, carga):
        self._carga = carga
    def _setTampada(self, tampada):
        self._tampada = tampada
    def tampar(self):
        if(not self._isTampada):
            setTampada(True)
            print("Caneta tampada com sucesso")
        else:
            print("A caneta ja esta tampada")
    def destampar(self):
        if(self._isTampada):
            setTampada("False")
            print("Caneta destampada com sucesso")
        else:
            print("A caneta ja esta destampada")
    def recarregar(self):
        if(getCarga() < 100):
            print("Caneta recarregada de {} para 100 com sucesso.".format(str(getCarga())))
            setCarga(100)
        else:
            print("A caneta esta cheia.")
    def escrever(self, msg):
        if(getCarga()>=(getCarga()-len(msg)/2) and msg!=null and self._isTampada):
            print(msg)
            self._carga-=len(msg) / 2
    def status(self):
        print("Cor:{}\nModelo:{}\nPonta:{}\nCarga:{}\nTampada:{}".format(self._cor, self._modelo, str(self._ponta), str(self._carga), str(self._tampada)))
c = Caneta("Azul", "Bic", 0.5)
c.status()

Answer: O metodo init está escrito errado, a maneira correta de escreve-lo seria com dois underlines, da seguinte maneira:
class Caneta:
  def __init__(self, cor, modelo, ponta):
    self._cor = cor
    self._modelo = modelo
    self._ponta = ponta
    self._carga = 100
    self._tampada = True

Realizei um teste e rodou normalmente após a correção.


Can not display Proxmox console due to Connection time out

Question: When I try to open console in proxmox ve nothing happens and I see this error in logs:
no connection : Connection timed out
TASK ERROR: command '/bin/nc -l -p 5900 -w 10 -c '/usr/sbin/qm vncproxy 100 2>/dev/null'' failed: exit code 1

How can I fix this please?
Comment: I've got the some error. I couldn't find any solution.
Answer: This is caused by the netcat command timing out due to there being no VNC connection in 10 seconds. In my case, this is because Java was slow to start up.
You can log into SSH on the box and manually run the netcat command with a longer timeout, e.g.
/bin/nc -l -p 5900 -w 100 -c '/usr/sbin/qm vncproxy 1301 2>/dev/null'
I've not yet found a way to change this timeout value globally.
Answer: The solution for me was ESET, if you turn off all SSL/TLS ... it works !


Prove the unit circle is uncountable

Question: This is a homework problem, so avoid giving the answer. I think a discussion of my attempt at a proof would be more appropriate. The problem goes as follows:
Let $S$ be the circle of unit radius in the Euclidean plane:
$$S = \{ (x,y) \in \mathbb{R}^2:   x^{2} + y^{2}=1 \}$$
Prove that $S$ is uncountable.
This is my attempt at a proof. I don't know if it is valid, or if my logic, and for that matter my approach to the proof, is correct. Feedback/comments/thoughts of any kind are welcome.
Let $G^{+} = \{(x,y)\in G: y \geq0\}$ and $G^{-} = \{(x,y)\in G: y \leq 0 \}.$These are the upper and lower segments of the unit circle.
Notice that $G^{+}\subset S$ and $ \hspace{1mm}G^{-}\subset S$, so $S=G^{+} \cup G^{-}.$
Let $f: G^{+} \rightarrow [-1,1],$ where $f(x,y)=x$. This can be thought of as a projection of the semi-circle onto the $x$-axis.
Since the image of $G^{+}$ under $f$ is equal to the codomain; i.e., $f(G^{+})= [-1,1]$, then $f$ is surjective.
Now since for every $(x,y) \in G^{+}$ we have the cardinality $|f(x,y)|=1$, there exists an inverse function $f^{-1}:[-1,1] \rightarrow G^{+}$ defined by $f^{-1}(x) = (x,\sqrt{1-x^{2})}$.
Thus, there exists a bijection between $G^{+}$ and $[-1,1].$
Similarly we have the same argument for $G^{-}.$ Let $g:G^{-} \rightarrow [-1,1]$ then

$ g(G^{-})=[-1,1]$ (surjective)
$|g(x,y)|=1 \hspace{4mm}  \forall (x,y)\in G^{-}$ (one-to-one)
$g^{-1}: [-1,1] \rightarrow G^{-}, \hspace{4mm} g^{-1}(x)= (x,-\sqrt{1-x^{2}})$ (inverse)

which shows the bijection.
Since the set of real numbers $[-1,1]$ is uncountable as can be shown by Cantor diagonalization, and we have $G^{+} {\raise.17ex\hbox{$\scriptstyle\sim$}} [-1,1]$ and  $G^{-} {\raise.17ex\hbox{$\scriptstyle\sim$}} [-1,1]$, then that implies that $G^{+}$ and $G^{-}$ are uncountable. Therefore $S= G^{+} \cup G^{-}$ must also be uncountable. q.e.d.
One other approach I thought about was to think of the semicircles as intervals in their own right, where the length of the upper semicircle would be $[0,\pi]$ and the interval of the lower semicircle would be $[\pi,2\pi],$ and I suppose the metric would be the arc length. So essentially you take the arc length and straighten it out, but I didn't know how to approach it or even formalize it. However, I think it is essentially the same thing as what I did in my proof.
Comment: This certainly works, but it seems easier just to note that $f(x) = (\cos(2\pi x), \sin(2\pi x))$ is a bijection from $[0,1)$ to $S$.
Comment: Looks good - though you could shorten it a bit once you know that $x \mapsto (x, \sqrt{1-x^2})$ is an injective map $[-1, 1] \to S$.  And similarly, for the other approach, $t \mapsto (\cos t, \sin t)$ is an injective map (and in fact a bijective map) $[0, 2 \pi) \to S$.
Comment: Seems like the easiest thing is to note that the projection of the circle to a line (say, the x-axis) is an interval, which is uncountable: $\pi_x(S)=[-1,1]$.
Comment: I agree with eyeballfrog
Comment: So this was a bit overkill? Thanks for the suggestions. The idea about using sine and cosine maps crossed my mind, but I didn't know exactly how to approach it.
Comment: What does the notation $\pi _{x}$ mean?
Comment: @physicsmajor The projection operator onto the $x$-axis.
Comment: Oh okay. Thanks.
Answer: I think the proof is fine.
You might also like to note that a unit circle can be charactherized by using the corresponding angle, $\theta \in [0, 2\pi)$.
Since $[0, 2\pi)$ is uncountable, you obtain your result as well.
Comment: Can you elaborate? I get that $[0,2\pi)$ is uncountable, but what would the function $f$ look like? For $\theta \in [0,\pi],$ we could have $f(x) = cos^{-1}(x) = \theta$, but $2\pi$? I think what you are saying is what I was talking about towards the end in my original post.
Comment: https://en.wikipedia.org/wiki/Atan2 check out atan2 function which map $(x,y)$ to $(-\pi, \pi]$.
Comment: One could also establish a surjection from the unit circle to $[-1,1]$ by projecting onto the $x$-axis (or $y$-axis).
Comment: nice, in fact, showing surjection is sufficient to conclude that it is uncountable.
Answer: Your solution is fine, but as a refinement, note that to prove a set is uncountable, it suffices to show that it has uncountable subset. Since you prove $G^+$ is uncountable, you're done, and don't need to consider $G^-$ at all.
e: It's also worth nothing that you also don't need to prove that $g$ is injective; proving that it's surjective is enough; this proves that the cardinality of the domain is at least the cardinality of the codomain.
Comment: for e, you mean if I only considered $G^{-}$ and not $G^{+}$, then I don't need to show $g$ is injective. So I could have stopped when I showed $f$ was surjective-- meaning $G^{+}$ was mapped onto $[-1,1]$ under  $f$?
Comment: Yes. You only need to consider one of $G^-$ and $G^+$, and you would only need to prove your function to be surjective.

Prove the unit circle is uncountable


SQL - Max() value from the group is not working

Question: Image1: Sample Data

Image2: Incorrect Output

Image3: Desired Output

Query: I'm trying to query the Maximum value from column (Median_Percentage) by the Class_Name and Customer (image1 sample data)
Issue: the query is showing all customers instead of the one that has the Max median value (image2 incorrect result). It is calculating the Max() correctly but the query is putting the value for all the Customers instead of the one that has that Max value within Class_Name
What I need is only the Class_Name which has the Max(Median_Percentage) and show the customer. (image3 desired output)
Select
       distinct
        C.Class_Name,
        C.Customer,
        C.Max_Median_Percentage

FROM (

    SELECT

        B.Class_Name,

        case (when B.Median_Percentage =  Max(B.Median_Percentage) OVER(PARTITION By B.Class_Name ORDER BY B.Median_Percentage desc  )
            then B.Customer
        end as Customer,

        Max(B.Median_Percentage) OVER(PARTITION By B.Class_Name ORDER BY B.Median_Percentage desc  ) as Max_Median_Percentage

    FROM (

        SELECT

            A.Class_Name,
            A.Customer,
            A.Date_Time

            A.Median_Percentage

        From table1 as A

    ) as B

) as C

Comment: Tag your question with the database you are using.  I'm not sure what the SQL has to do with the question, which seems pretty clear by itself.
Comment: Which DBMS product are you using? "SQL" is just a query language, not the name of a specific database product. Please add a [tag](https://stackoverflow.com/help/tagging) for the database product you are using. [Why should I tag my DBMS](https://meta.stackoverflow.com/questions/388759/)
Comment: Thanks! I have added tags for the database. I've also simplified the query that I'm working on, hoping it helps
Answer: You can use percentile_cont() if your database does not directly support a "median" function:
select t.*,
       boot_time / percentile_cont(0.5) within group (order by boot_time) over (partition by classid)
from t;

If your database doesn't have the percentile_cont() or percentile_disc() function, you can get very close using a simple ntile():
select t.*,
       boot_time / max(case when tile = 1 then boot_time end) over (partition by classid)
from (select t.*,
             ntile(2) over (partition by classid order by boot_time) as tile
      from t
     ) t

This works exactly if there are an odd number of rows in the classid.  For even numbers, it is off by 1.  You can handle that easily, but with more complication:
select t.*,
       (boot_time /
        (( max(case when tile_asc = 1 then boot_time end) over (partition by classid) / 2 +
           max(case when tile_desc = 1 then boot_time end) over (partition by classid)
         ) / 2
        )
       )
from (select t.*,
             ntile(2) over (partition by classid order by boot_time) as tile_asc,
             ntile(2) over (partition by classid order by boot_time desc) as tile_desc
      from t
     ) t

Comment: Thanks for your reply, percentile_cont() is not applicable in my database
Answer: Perhaps this is useful -
Load the test data provided
val df = spark.sql(
      """
        |select Class_Name, Customer, Date_Time, Median_Percentage
        |from values
        |   ('ClassA', 'A', '6/13/20', 64550),
        |   ('ClassA', 'B', '6/6/20', 40200),
        |   ('ClassB', 'F', '6/20/20', 26800),
        |   ('ClassB', 'G', '6/20/20', 18100)
        |  T(Class_Name, Customer, Date_Time, Median_Percentage)
      """.stripMargin)
    df.show(false)
    df.printSchema()

    /**
      * +----------+--------+---------+-----------------+
      * |Class_Name|Customer|Date_Time|Median_Percentage|
      * +----------+--------+---------+-----------------+
      * |ClassA    |A       |6/13/20  |64550            |
      * |ClassA    |B       |6/6/20   |40200            |
      * |ClassB    |F       |6/20/20  |26800            |
      * |ClassB    |G       |6/20/20  |18100            |
      * +----------+--------+---------+-----------------+
      *
      * root
      * |-- Class_Name: string (nullable = false)
      * |-- Customer: string (nullable = false)
      * |-- Date_Time: string (nullable = false)
      * |-- Median_Percentage: integer (nullable = false)
      */

find the max Median_Percentage row by Class_Name
    df.groupBy("Class_Name")
      .agg(max(struct($"Median_Percentage", $"Date_Time", $"Customer")).as("struct"))
      .selectExpr("Class_Name", "struct.Customer", "struct.Date_Time", "struct.Median_Percentage")
      .show(false)

    /**
      * +----------+--------+---------+-----------------+
      * |Class_Name|Customer|Date_Time|Median_Percentage|
      * +----------+--------+---------+-----------------+
      * |ClassA    |A       |6/13/20  |64550            |
      * |ClassB    |F       |6/20/20  |26800            |
      * +----------+--------+---------+-----------------+
      */


Unable to create a google document with contents

Question: I'm currently trying to create a google document with Google Document API.
https://developers.google.com/docs/api/reference/rest/v1/documents/create
I try to use the website tool and create a document with the following body.
<code>{
  "body": {
    "content": [
      {
        "paragraph": {
          "elements": [
            {
              "textRun": {
                "content": "This is a test"
              }
            }
          ]
        }
      }
    ]
  },
  "title": "Hello"
}
</code>
But what it returns doesn't contain the word "This is a test".
The return JSON message
<code>{
  "title": "Hello",
  "body": {
    "content": [
      {
        "endIndex": 1,
        "sectionBreak": {
          "sectionStyle": {
            "columnSeparatorStyle": "NONE",
            "contentDirection": "LEFT_TO_RIGHT"
          }
        }
      },
      {
        "startIndex": 1,
        "endIndex": 2,
        "paragraph": {
          "elements": [
            {
              "startIndex": 1,
              "endIndex": 2,
              "textRun": {
                "content": "\n",
                "textStyle": {}
              }
            }
          ],
          "paragraphStyle": {
            "namedStyleType": "NORMAL_TEXT",
            "direction": "LEFT_TO_RIGHT"
          }
        }
      }
    ]
  },
  "documentStyle": {
    "background": {
      "color": {}
    },
    "pageNumberStart": 1,
    "marginTop": {
      "magnitude": 72,
      "unit": "PT"
    },
    "marginBottom": {
      "magnitude": 72,
      "unit": "PT"
    },
    "marginRight": {
      "magnitude": 72,
      "unit": "PT"
    },
    "marginLeft": {
      "magnitude": 72,
      "unit": "PT"
    },
    "pageSize": {
      "height": {
        "magnitude": 841.8897637795277,
        "unit": "PT"
      },
      "width": {
        "magnitude": 595.27559055118115,
        "unit": "PT"
      }
    }
  },
  "namedStyles": {
    "styles": [
      {
        "namedStyleType": "NORMAL_TEXT",
        "textStyle": {
          "bold": false,
          "italic": false,
          "underline": false,
          "strikethrough": false,
          "smallCaps": false,
          "backgroundColor": {},
          "foregroundColor": {
            "color": {
              "rgbColor": {}
            }
          },
          "fontSize": {
            "magnitude": 11,
            "unit": "PT"
          },
          "weightedFontFamily": {
            "fontFamily": "Arial",
            "weight": 400
          },
          "baselineOffset": "NONE"
        },
        "paragraphStyle": {
          "namedStyleType": "NORMAL_TEXT",
          "alignment": "START",
          "lineSpacing": 115,
          "direction": "LEFT_TO_RIGHT",
          "spacingMode": "COLLAPSE_LISTS",
          "spaceAbove": {
            "unit": "PT"
          },
          "spaceBelow": {
            "unit": "PT"
          },
          "borderBetween": {
            "color": {},
            "width": {
              "unit": "PT"
            },
            "padding": {
              "unit": "PT"
            },
            "dashStyle": "SOLID"
          },
          "borderTop": {
            "color": {},
            "width": {
              "unit": "PT"
            },
            "padding": {
              "unit": "PT"
            },
            "dashStyle": "SOLID"
          },
          "borderBottom": {
            "color": {},
            "width": {
              "unit": "PT"
            },
            "padding": {
              "unit": "PT"
            },
            "dashStyle": "SOLID"
          },
          "borderLeft": {
            "color": {},
            "width": {
              "unit": "PT"
            },
            "padding": {
              "unit": "PT"
            },
            "dashStyle": "SOLID"
          },
          "borderRight": {
            "color": {},
            "width": {
              "unit": "PT"
            },
            "padding": {
              "unit": "PT"
            },
            "dashStyle": "SOLID"
          },
          "indentFirstLine": {
            "unit": "PT"
          },
          "indentStart": {
            "unit": "PT"
          },
          "indentEnd": {
            "unit": "PT"
          },
          "keepLinesTogether": false,
          "keepWithNext": false,
          "avoidWidowAndOrphan": true,
          "shading": {
            "backgroundColor": {}
          }
        }
      },
      {
        "namedStyleType": "HEADING_1",
        "textStyle": {
          "fontSize": {
            "magnitude": 20,
            "unit": "PT"
          }
        },
        "paragraphStyle": {
          "namedStyleType": "NORMAL_TEXT",
          "direction": "LEFT_TO_RIGHT",
          "spaceAbove": {
            "magnitude": 20,
            "unit": "PT"
          },
          "spaceBelow": {
            "magnitude": 6,
            "unit": "PT"
          },
          "keepLinesTogether": true,
          "keepWithNext": true
        }
      },
      {
        "namedStyleType": "HEADING_2",
        "textStyle": {
          "bold": false,
          "fontSize": {
            "magnitude": 16,
            "unit": "PT"
          }
        },
        "paragraphStyle": {
          "namedStyleType": "NORMAL_TEXT",
          "direction": "LEFT_TO_RIGHT",
          "spaceAbove": {
            "magnitude": 18,
            "unit": "PT"
          },
          "spaceBelow": {
            "magnitude": 6,
            "unit": "PT"
          },
          "keepLinesTogether": true,
          "keepWithNext": true
        }
      },
      {
        "namedStyleType": "HEADING_3",
        "textStyle": {
          "bold": false,
          "foregroundColor": {
            "color": {
              "rgbColor": {
                "red": 0.2627451,
                "green": 0.2627451,
                "blue": 0.2627451
              }
            }
          },
          "fontSize": {
            "magnitude": 14,
            "unit": "PT"
          }
        },
        "paragraphStyle": {
          "namedStyleType": "NORMAL_TEXT",
          "direction": "LEFT_TO_RIGHT",
          "spaceAbove": {
            "magnitude": 16,
            "unit": "PT"
          },
          "spaceBelow": {
            "magnitude": 4,
            "unit": "PT"
          },
          "keepLinesTogether": true,
          "keepWithNext": true
        }
      },
      {
        "namedStyleType": "HEADING_4",
        "textStyle": {
          "foregroundColor": {
            "color": {
              "rgbColor": {
                "red": 0.4,
                "green": 0.4,
                "blue": 0.4
              }
            }
          },
          "fontSize": {
            "magnitude": 12,
            "unit": "PT"
          }
        },
        "paragraphStyle": {
          "namedStyleType": "NORMAL_TEXT",
          "direction": "LEFT_TO_RIGHT",
          "spaceAbove": {
            "magnitude": 14,
            "unit": "PT"
          },
          "spaceBelow": {
            "magnitude": 4,
            "unit": "PT"
          },
          "keepLinesTogether": true,
          "keepWithNext": true
        }
      },
      {
        "namedStyleType": "HEADING_5",
        "textStyle": {
          "foregroundColor": {
            "color": {
              "rgbColor": {
                "red": 0.4,
                "green": 0.4,
                "blue": 0.4
              }
            }
          },
          "fontSize": {
            "magnitude": 11,
            "unit": "PT"
          }
        },
        "paragraphStyle": {
          "namedStyleType": "NORMAL_TEXT",
          "direction": "LEFT_TO_RIGHT",
          "spaceAbove": {
            "magnitude": 12,
            "unit": "PT"
          },
          "spaceBelow": {
            "magnitude": 4,
            "unit": "PT"
          },
          "keepLinesTogether": true,
          "keepWithNext": true
        }
      },
      {
        "namedStyleType": "HEADING_6",
        "textStyle": {
          "italic": true,
          "foregroundColor": {
            "color": {
              "rgbColor": {
                "red": 0.4,
                "green": 0.4,
                "blue": 0.4
              }
            }
          },
          "fontSize": {
            "magnitude": 11,
            "unit": "PT"
          }
        },
        "paragraphStyle": {
          "namedStyleType": "NORMAL_TEXT",
          "direction": "LEFT_TO_RIGHT",
          "spaceAbove": {
            "magnitude": 12,
            "unit": "PT"
          },
          "spaceBelow": {
            "magnitude": 4,
            "unit": "PT"
          },
          "keepLinesTogether": true,
          "keepWithNext": true
        }
      },
      {
        "namedStyleType": "TITLE",
        "textStyle": {
          "fontSize": {
            "magnitude": 26,
            "unit": "PT"
          }
        },
        "paragraphStyle": {
          "namedStyleType": "NORMAL_TEXT",
          "direction": "LEFT_TO_RIGHT",
          "spaceAbove": {
            "unit": "PT"
          },
          "spaceBelow": {
            "magnitude": 3,
            "unit": "PT"
          },
          "keepLinesTogether": true,
          "keepWithNext": true
        }
      },
      {
        "namedStyleType": "SUBTITLE",
        "textStyle": {
          "italic": false,
          "foregroundColor": {
            "color": {
              "rgbColor": {
                "red": 0.4,
                "green": 0.4,
                "blue": 0.4
              }
            }
          },
          "fontSize": {
            "magnitude": 15,
            "unit": "PT"
          },
          "weightedFontFamily": {
            "fontFamily": "Arial",
            "weight": 400
          }
        },
        "paragraphStyle": {
          "namedStyleType": "NORMAL_TEXT",
          "direction": "LEFT_TO_RIGHT",
          "spaceAbove": {
            "unit": "PT"
          },
          "spaceBelow": {
            "magnitude": 16,
            "unit": "PT"
          },
          "keepLinesTogether": true,
          "keepWithNext": true
        }
      }
    ]
  },
  "revisionId": "XXXXXXXXXXXXX",
  "suggestionsViewMode": "SUGGESTIONS_INLINE",
  "documentId": "XXXXXXXXXXXXX"
}
</code>
Does anyone know how to correctly use the API to create a google document with specific content?
Answer: From the official documentation:

Method: documents.create
Creates a blank document using the title given in the request. Other fields in the request, including any provided content, are ignored.

If you want to create a document with text, you must:

Create the document using documents.create.
Add content to it using documents.batchUpdate.


How can I get the repository name or URL of a GitChangeSet object?

Question: I have a GitChangeSet object (that ultimately came from a build).  I would like to find the repository name or URL associated with that commit.  However, none of the properties of the object seem to hint at where this commit ultimately came from.  E.g.:
affectedFiles=[hudson.plugins.git.GitChangeSet$Path@2a7ac0cb, hudson.plugins.git.GitChangeSet$Path@1d9fb12a, hudson.plugins.git.GitChangeSet$Path@3b47e461, hudson.plugins.git.GitChangeSet$Path@35be1e86]
comment=CF-703 - remove testing-only hostsfile entry that caused "hostname -f"
to return "localhost"

date=2017-12-19 16:25:17 -0700
id=cfc01dfbf1015496074c2c1e6c9663cfb0f49751
commitId=cfc01dfbf1015496074c2c1e6c9663cfb0f49751
branch=null
msgEscaped=CF-703 - remove testing-only hostsfile entry that caused "hostname -f"
timestamp=1513725917000
authorName=hendrenj
parentCommit=bf4b919e74c635c61c4761134d6b53445829593d
msg=CF-703 - remove testing-only hostsfile entry that caused "hostname -f"
class=class hudson.plugins.git.GitChangeSet
msgAnnotated=CF-703 - remove testing-only hostsfile entry that caused "hostname -f"
commentAnnotated=CF-703 - remove testing-only hostsfile entry that caused "hostname -f"
to return "localhost"

revision=cfc01dfbf1015496074c2c1e6c9663cfb0f49751
paths=[hudson.plugins.git.GitChangeSet$Path@2a7ac0cb, hudson.plugins.git.GitChangeSet$Path@1d9fb12a, hudson.plugins.git.GitChangeSet$Path@3b47e461, hudson.plugins.git.GitChangeSet$Path@35be1e86]
createAccountBasedOnEmail=false
affectedPaths=[recipes/default_vhost.rb, metadata.rb, test/integration/shared/serverspec/default_vhost/default_vhost.rb, Policyfile.lock.json]
authorEmail=*******@*******.***
parent=hudson.plugins.git.GitChangeSetList@2eb9acad
author=Jay Hendren

I got this commit object by iterating over build.changeSets (which I believe comes from the class hudson.model.AbstractBuild).  I do know that this particular commit came from a global Shared Library repository, not the main repository associated with this build, but I don't see any obvious way to extract that information programmatically.  How can I programmatically determine which repository the GitChangeSet objects (or other objects in hudson.model.AbstractBuild.changeSets in general)  came from?

For context, I'm developing an e-mail report for failed builds that, among other things, collects a list of commits associated with the failed build.  Since I have complex upstream/downstream relationships between my jobs, a commit in one repository may trigger a series of builds as successful builds trigger downstream jobs that depend on the upstream ones.  Additionally, there are other repositories associated with my builds, in particular a global Shared Library repository.  I would like my report to mention what commits are ultimately responsible for the series of builds resulting in the current one.  Finding these upstream commits has not been too painful so far (thanks to UpstreamJobCause), but I've become hung up on determining where those commits ultimately came from.  I would appreciate any suggestions on alternative approaches to this problem in the comments if you don't know of an answer to my question as stated.
Comment: I don't think it's currently possible. I deal with the Jenkins API quite a bit and this shortcoming has always annoyed me. I finally got around to creating a ticket for it: [JENKINS-52747](https://issues.jenkins-ci.org/browse/JENKINS-52747)
Answer: Use getChangeSetLink to build the URL for you. In this way you don't need to hard-code any part of the URL.
build.changeSets.each { changeSetList ->
  def browser = changeSetList.browser
  changeSetList.items.each { changeSet ->
    println browser.getChangeSetLink(changeSet)
  }
}

Answer: You can get commit url using below code which can be tested in jenkins script-console

// Jenkins
//  .instance
//  .getItem('JobName')
//  .getBuild('buildnumber')
build
 .changeSets.each{ changeSetList ->
   changeSetList.items.each{ changeSet ->
     println "${changeSetList.browser.repoUrl}commit/${changeSet.commitId}"
   }
 }

Comment: Thanks, but I was asking how to get the URL given a commit object (i.e. `GitChangeSet`), not given a build object.
Comment: Instead of `Jenkins.instance.getItem('JobName').getBuild('buildnumber').changeSets` you should use `build.changeSets`
Answer: This can do the trick sometimes - given a GitChangeSet object named commit:
commit.getParent().getBrowser().getRepoUrl()

Repo URLs are attached to instances of hudson.plugins.git.browser.GitRepositoryBrowser, so your job configuration must have a browser set for your repository sources in order for this to work (the default "auto detect browser" option usually works pretty well).


Is there an automated way to report and open cases with HP for drive failure?

Question: I want to take failed drives, send a diagnostic report to HP so I can automatically have the drives shipped to the right location.
I'm considering writing C# code to automatically log in, post a case below, with the drive diagnostics as an attachment. This is possible using some C# magic, but I'd rather have a supported way.
Question

Is there an automatic way to open a case with HP support?

How to access the HP Service Center
<code>1. Navigate www.hp.com/go/hpsc
2. Login into your account. (If you dont have one, you can register yourself in the HPSC website).
3. Click Get help from HP
4. Click Submit or manage support cases
5. Select the option ;Submit a case from the left side pane
6. Enter the product serial number in the Contract or warranty id box.
7. Click Submit Case and proceed further.
</code>
Comment: Note to self- this is a follow on to this question; will post the powershell script later... http://serverfault.com/q/714408/51457
Answer: I admire your effort to try to automate this process...
However, I don't think it's necessary.

You don't have to send a diagnostic report to HP to obtain a warranty part.
The IML log or RAID controller status is good enough to open a support case.

Some things shouldn't be automated. If drive failures are frequent enough to need to automate the case process (and I'm sure they're not), I suggest keeping a few spares on hand and backfilling those spares with the warranty parts from HP.
HP's official answer would be to sign up for their Proactive Care service, which will run system scans, predictive tests and automatic support case logging.
Comment: It seems this is an additional thing I need to pay for... that's unfortunate.  EMC uses SRS to phone home with failed disks and that is at no charge.  Because of the cost difference, I think I might pursue writing my own app (I'll open source it)


Limit as x approach to infinity of Log.

Question: I'm trying to solve this:
$$\lim_{x\rightarrow+\infty} (x-\ln(1+2e^x))= ?$$
I tried L'Hôpital's rule but it didn't get me where I want to...
Any hints?
Comment: Please include your workings when applying L'Hopital's rule.
Answer: $x-\ln(1+2e^x)=$
$ \ln (e^x) -\ln(1+2e^x)=$
$\log (\dfrac{e^x}{1+2e^x}).$
Set $y:= e^x$, and consider $y \rightarrow \infty$ :
$f(y) := \dfrac{y}{1+2y} = \dfrac{1}{1/y +2}.$
$\lim_{y \rightarrow \infty} (\log f(y)) =$
$\log( \lim_{y \rightarrow \infty} f(y)) =$
$=\log(1/2)= -\log 2$.
Used:
1) $\lim_{y \rightarrow \infty} f(y) = 1/2;$
2) $\log$ is continuous.
Comment: How x became ln(e^x) ? i mean from first line to the second line?
Comment: Andrew. log (e^x)= x log(e) =x ×1, since log(e)=1. Is this ok?
Comment: OK got it thanks. BUT how is ln(1/2) becomes -ln2?
Comment: Andrew: log (a/b) = log (a) - log (b) (look up log rules).log(1/2) = log( 1) - log (2), and note :log (1)=0.Ok?
Comment: Yes, now its clear thank you!
Answer: Note that
$$x-\ln(1+2e^x)=x-\left[\ln e^x+\ln \left(\frac1{e^x}+2\right)\right]=x-x-\ln \left(\frac1{e^x}+2\right)\to -\ln 2$$
To figure out at first sight the result note that for $x\to +\infty$

$\ln(1+2e^x)\sim \ln 2e^x=\ln2+\ln e^x=\ln 2 +x$

observe that the latter is not a proof but only a method to guess what the limit could be.
Comment: +1 for advice in last sentence. Often people think that reasoning as a proof.
Comment: @gimusi how did you split the -ln(1+2e^x) to that form?
Comment: @AndrewM use that $\log ab= \log a + \log b$
Answer: use that $$\ln(1+2e^x)=\ln\left(e^x\left(\frac{1}{e^x}+2\right)\right)=x+\ln\left(\frac{1}{e^x}+2\right)$$

Limit as x approach to infinity of Log.


Proving AM-GM via $n \cdot (a_1^n + a_2^n + \dots + a_n^n) \ge (a_1^{n-1} + a_2^{n-1} + \dots + a_n^{n-1}) \cdot (a_1 + a_2 + \dots + a_n)$

Question: I want to prove the arithmetic–geometric mean inequality.
To prove that, I need the following inequality:
Suppose that $n$ is an integer which is greater than or equal to $1$ and $a_1, a_2, \dots, a_n \in \Bbb{R}$.
Then,
$$n \cdot (a_1^n + a_2^n + \dots + a_n^n) \ge (a_1^{n-1} + a_2^{n-1} + \dots + a_n^{n-1}) \cdot (a_1 + a_2 + \dots + a_n).\ \cdots (1)$$

For any n positive real numbers $a_1, a_2, \cdots, a_n$,
$$\frac{a_1 + a_2 + \cdots + a_n}{n} \ge \sqrt[n]{a_1 a_2 \cdots a_n}.$$
This inequality is obviously equivalent to the next inequality:
For any n positive real numbers $b_1, b_2, \cdots, b_n$,
$$b_1^{n} + b_2^{n} + \cdots b_n^{n} \ge n (b_1 b_2 \cdots b_n)$$
We prove the second inequality by induction.
(i) When $n=1$, $b_1^{1} = b_1 \ge 1\cdot b_1.$
(ii)When $n=k$, suppose that the above inequality holds.
Let $c_1, c_2, \cdots, c_{k+1}$ be $k+1$ positive real numbers. Then, by the assumption above,
$$
\left\{
\begin{array}{c}
c_1(c_2^{k} + c_3^{k} + \cdots + c_{k+1}^k) \ge c_1(k c_2 c_3 \cdots c_{k+1}) = k \prod_{j=1}^{k+1} c_j \\
c_2(c_1^{k} + c_3^{k} + \cdots + c_{k+1}^k) \ge c_2(k c_1 c_3 \cdots c_{k+1}) = k \prod_{j=1}^{k+1} c_j \\
\cdots \\
c_{k+1}(c_1^{k} + c_2^{k} + \cdots + c_{k}^k) \ge c_{k+1}(k c_1 c_2 \cdots c_{k}) = k
\prod_{j=1}^{k+1} c_j,\\
\end{array}
\right.
$$
i.e., for $1 \le i \le k+1$,
$$\sum_{j=1}^{k+1}\delta_{ij}^{'} c_j^k c_i \ge k \prod_{j=1}^{k+1} c_j$$
where, $\delta_{ij}^{'} = 1 - \delta_{ij}$, $\delta_{ij}$ is Kronecker's delta.
So,
$$\sum_{i=1}^{k+1} \sum_{j=1}^{k+1} \delta_{ij}^{'} c_j^k c_i \ge \sum_{i=1}^{k+1} k \prod_{j=1}^{k+1} c_j = k(k+1) \prod_{j=1}^{k+1} c_j.$$
$$\sum_{i=1}^{k+1} \sum_{j=1}^{k+1} \delta_{ij}^{'} c_j^k c_i = \sum_{i=1}^{k+1} \sum_{j=1}^{k+1} c_j^k c_i - \sum_{i=1}^{k+1} c_i^{k+1} = \sum_{j=1}^{k+1} c_j^k \cdot \sum_{i=1}^{k+1} c_i - \sum_{i=1}^{k+1} c_i^{k+1}.$$
If (1) holds, then
$$(k+1) \sum_{i=1}^{k+1} c_i^{k+1} \ge \sum_{j=1}^{k+1} c_j^k \cdot \sum_{i=1}^{k+1} c_i.$$
So,
$$k \sum_{i=1}^{k+1} c_i^{k+1} \ge \sum_{j=1}^{k+1} c_j^k \cdot \sum_{i=1}^{k+1} c_i - \sum_{i=1}^{k+1} c_i^{k+1} \ge k(k+1) \prod_{j=1}^{k+1} c_j.$$
When we divide both sides of the above inequality by k, we get
$$\sum_{i=1}^{k+1} c_i^{k+1} \ge (k+1) \prod_{j=1}^{k+1} c_j.$$
Comment: Well well, this is [Chebyshev's inequality](http://www.artofproblemsolving.com/Wiki/index.php/Chebyshev%27s_Inequality) given that a1 > a2 > ... more in that link.
Comment: I didn't know Chebyshev's inequality. Thank you very much for your answer.
Answer: There is the following reasoning for even $n$. $$n\sum_{k=1}^na_k^n-\sum_{k=1}^na_k^{n-1}\sum_{k=1}^na_k=\sum_{1\leq i<j\leq n}\left(a_i^n-a_i^{n-1}a_j-a_ia_j^{n-1}+a_j^n\right)=$$
$$=\sum_{1\leq i<j\leq n}\left(a_i^{n-1}-a_j^{n-1}\right)\left(a_i-a_j\right)\geq0.$$
For odd $n$ it's wrong.
For example, take $n=3$.
We get $3(a^3+b^3+c^3)\geq(a^2+b^2+c^2)(a+b+c),$ which is wrong for $b=c=0$ and $a=-1.$
Also, we can say that it's true for non-negative variables by Muirhead because $$(n,0,0,...,0)\succ(n-1,1,0,...,0).$$
Comment: @Wojowu For non-negative variables it's true for all  $n\geq1$, of course . The proof is the same. Also, we can use Chebyshov here.
Comment: What if we restrict to nonnegative $a_k$? It should work for all $n$ then.


trying to connect to a mysql database using php

Question: I have an HTML form, and I need to past data from it to mysql database in phpMyAdmin. I'm far from php and I don't know what to do with these errors, also I was unable to set up server and phpMyAdmin locally so I test it right away on the hosting.
index.html:

        <form class="form__wrapper" action="form.php" method="post">

Leave your contacts below

Phone

                    <input type="tel" value="+380">

Name

                    <input type="text">

Company

                   <input type="text">

Email

                    <input type="email">

Consumption

                    <input type="text" pattern="[0-9]*">

                <button type="submit" class="form__wrapper_inputs_send">Submit</button>

        </form>

form.php:
<?php
$dbhost = "***Link to phpmyadmin of my hosting***";
$dbuser = "***phpmyadmin unsername***";
$dbpass = "***phpmyadmin password";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);

if(! $conn) {
    die('Could not connect: ' . mysqli_error());
}

if(isset($_POST['submit']))
{
    $number = $_POST['number'];
    $name = $_POST['name'];
    $company = $_POST['company'];
    $email = $_POST['email'];
    $consumption = $_POST['consumption'];

    $insert = mysqli_query($db,"INSERT INTO `form`(`number`, `name`, `company`, `email`, `consumption`) VALUES ('$number',
    '$name', '$company', '$email', '$consumption')");

    if(!$insert)
    {
        echo mysqli_error();
    }
    else
    {
        echo "Records added successfully.";
    }
}

mysqli_close($conn);
?>

When I press submit button, I get following errors:
Warning: mysqli_connect(): php_network_getaddresses: getaddrinfo failed: Name does not resolve in /sata2/home/users/***user***/www/***site***/form.php on line 5

Warning: mysqli_connect(): (HY000/2002): php_network_getaddresses: getaddrinfo failed: Name does not resolve in /sata2/home/users/***user***/www/***site***/form.php on line 5

Warning: mysqli_error() expects exactly 1 parameter, 0 given in /sata2/home/users/***user***/www/***site***/form.php on line 8
Could not connect:

In comments I've been told that $dbhost variable is wrong, but I'm not sure what to use there. If I assign it IP of my hosting, I get timed out error.
Comment: please note that **Phpmyadmin** is a tool to connect to the database, not a DB itself. You are connecting to your **mysql** installation and you should have an ip address or localhost. The address to connect to phpmyadmin here is not relevant
Comment: **Danger**: You are **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that you need to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from.
Comment: dbhost should is server name. exp : localhost or abc.com. it is not Link to phpmyadmin of my hosting
Comment: @MaiTruong so the address of my site? Or what server?
Comment: Yes, Your server. You need Specifies a host name or an IP address
Comment: @MaiTruong but in what way will it access phpmyadmin?
Comment: mysqli_connect() function opens a new connection to the MySQL server.
https://www.w3schools.com/Php/func_mysqli_connect.asp
Comment: @MaiTruong let's say my hosting is hosting.com, and phpmyadmin is accessible by db.hosting.com/phpmyadmin, and also my site is site.com. What should I write? I tried db.hosting.com (same error) and hosting.com (operation timed out)
Comment: PhpMyAdmin is just a regular web site, like Google or Amazon. There're no point in trying to connect to it from a MySQL client of any kind, PHP or not. You need to get your MySQL Server's credentials and use those instead.
Answer: index.html (note: you are missing the HTML input element name attributes, so nothing is being sent)

        <form class="form__wrapper" action="form.php" method="post">

Leave your contacts below

Phone

                    <input name="number" type="tel" value="+380">

Name

                    <input name="name" type="text">

Company

                   <input name="company type="text">

Email

                    <input name="email" type="email">

Consumption

                    <input name="consumption" type="text" pattern="[0-9]*">

                <button type="submit" class="form__wrapper_inputs_send">Submit</button>

        </form>

form.php
<?php

// check if form is empty out here before wasting a database connection
if (!empty($_POST['submit'])) {

    $dbname = "database_name"; // you must specify the database name
    $dbhost = "127.0.0.1";
    $dbuser = "database_username"; // add your username here
    $dbpass = "database_password"; // add your password here

    // use PDO instead, it is safer than mysqli functions
    // see: https://www.php.net/manual/en/book.pdo.php

    // pdo options
    $pdo_options = [
        PDO::ATTR_EMULATE_PREPARES => false,
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    ];

    try {

        // connect to database
        $db = new PDO("mysql:host={$dbhost};dbname={$dbname};charset=utf8mb4", $dbuser, $dbpass, $pdo_options);

        // use prepared statements to help prevent sql injection

        // insert query
        $query = "INSERT INTO `form` (`number`, `name`, `company`, `email`, `consumption`) VALUES (?, ?, ?, ?, ?)";

        // prepare statement
        $stmt = $db->prepare($query);

        // execute with bound parameters
        $stmt->execute([
            $_POST['number'],
            $_POST['name'],
            $_POST['company'],
            $_POST['email'],
            $_POST['consumption']
        ]);

        // success
        echo "Form submitted successfully";

    } catch (Exception $e) {
        // error
        echo "Error inserting record into database, " . $e->getMessage();
    }
}

Answer: You are connecting to mysql not to phpmyadmin.
So you should change your credentials like this:
$dbhost = "***Link to mysql of my hosting***";
$dbuser = "***mysql username***";
$dbpass = "***mysql password";

These credentials have been provided to you by your hosting. $dbuser and $dbpass are the same that you use for phpmyadmin but the dbhost should be different
Comment: note that you should learn how to use prepared statements since your code is open to **SQL injections**
Comment: Thanks! I found the mysql link. I don't get an error, but still the data doesn't appear in phpmyadmin. I understand that it's outside of the question and you still get bounty for answer, but I would be very thankful if you could show me a direction where to move.
Comment: simply put, in your form, each input should have a `name` attribute that is the posted value. So for example to do ` $name = $_POST['name'];` you need an input with `name="name"` in your html. If you fix this you should be able to post to your database
Comment: what is the error mysqli is throwing? Have you tried echoing the values before running the query? _"still not working"_ is not that usefull by itself
Answer: it would be network configuration. The database server is blocking ext-connection to port 3306.
$dbhost = "***Link to phpmyadmin of my hosting***";
$dbuser = "***phpmyadmin unsername***";
$dbpass = "***phpmyadmin password";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);

Those info should be:
$dbhost = "***Database server IP***";
$dbuser = "***phpmyadmin unsername***";
$dbpass = "***phpmyadmin password";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);

Make sure your server open port 3306 from your webserver.
Thanks.


AWS instance related issue

Question: I have an t2.small instance over AWS from last 3 months. Once in every week instance get down and I resolve it with instance stop and start. Can anyone suggest me the final solution for this?
Comment: Just imaging bringing your car to your car repair shop with _this_ detail-level of error description.
Comment: See also: "[How do I ask a good question?](https://stackoverflow.com/help/how-to-ask)".
Comment: BTW: What is an "AWS instance"? Most likely, you are talking about EC2 or Lightsail.
Answer: Although your description is not that detailed, this sounds like a memory issue. I would go over this tutorial:
https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/mon-scripts.html
that sends monitoring metrics to cloudwatch, then see if there is any spike in memory before the instance crashes. Solution may vary to check what is causing the spike, or increase the instance size to get more memory.
Answer: You may want to look into automation of instance reboot on Health Check failure described at this CloudWatch User Guide. Though as suggested by @Uwe Keim, this is addressing symptoms, not all the potential root causes that can lead to instance becoming unresponsive.
Answer: You can install the CloudWatch agent to monitor custom metrics to check the health of a specific component running on your EC2 instance then use CloudWatch events to reboot the EC2 if it is not healthy.

AWS instance related issue


Windows License Logging Server

Question: When I first setup a Windows 2000 and then 2003 Server in our office using per-server licensing, we got the default 5-user CAL pack.  I noticed that after 3 users logged in, the Server would kick out a notice that I had too many people has logged in.  That's when I noticed that the Server was counting users twice - once for their login, and once for their computer...  For example, if User X logs in from Computer Y, then both X and Y would show up as having used a license.
The only workaround I found was to disable the License Logging Service.
What was I doing wrong?
Answer: You weren't doing anything wrong, per se. The License Logging Service is deprecated (except on some of the "Small Business Server" flavors) and you're safe to disable it.

The License Logging service is a tool that was originally designed to help customers manage licenses for Microsoft server products that are licensed in the Server Client Access License (CAL) model.
By default, the License Logging service is disabled in Microsoft Windows Server™ 2003. Because of original design constraints and evolving license terms and conditions, the License Logging service cannot provide an accurate view of the total number of CALs that are purchased as compared to the total number of CALs that are used on a single server or across the enterprise. The CALs that are reported by the License Logging service may conflict with the interpretation of the End User License Agreement (EULA) and with Product Usage Rights (PUR). The License Logging service will not be included in future versions of the Windows operating system.

From http://technet.microsoft.com/en-us/library/aa995711.aspx
See also: http://support.microsoft.com/kb/316631
Answer: The License Logging Service is deprecated in Windows Server 2003.  It does not count license usage correctly, as you have seen, and so you did the right thing by disabling it.  On a fresh installation of Windows Server 2003, the service is disabled by default.
Microsoft explains this in KB824196:  http://support.microsoft.com/kb/824196.

Windows License Logging Server