I can't connect to my AWS server after yum update on centOS 7

Question: I created a new server (EC2) with centOS 7, and after the first "yum update" and a reboot I can't connect anymore.
<code>====================================================================================================================================================================
 Package                                    Arch                      Version                                            Repository                            Size
====================================================================================================================================================================
Installing:
 kernel                                     x86_64                    3.10.0-693.21.1.el7                                updates                               43 M
 mysql-community-libs                       x86_64                    5.6.39-2.el7                                       mysql56-community                    2.0 M
     replacing  mariadb-libs.x86_64 1:5.5.56-2.el7
Updating:
 binutils                                   x86_64                    2.25.1-32.base.el7_4.2                             updates                              5.4 M
 cloud-init                                 x86_64                    0.7.9-9.el7.centos.6                               updates                              628 k
 dhclient                                   x86_64                    12:4.2.5-58.el7.centos.3                           updates                              282 k
 dhcp-common                                x86_64                    12:4.2.5-58.el7.centos.3                           updates                              174 k
 dhcp-libs                                  x86_64                    12:4.2.5-58.el7.centos.3                           updates                              130 k
 epel-release                               noarch                    7-11                                               epel                                  15 k
 initscripts                                x86_64                    9.49.39-1.el7_4.1                                  updates                              435 k
 iptables                                   x86_64                    1.4.21-18.3.el7_4                                  updates                              428 k
 iwl7265-firmware                           noarch                    220.127.116.11-58.el7_4                                  updates                              3.5 M
 kernel-tools                               x86_64                    3.10.0-693.21.1.el7                                updates                              5.2 M
 kernel-tools-libs                          x86_64                    3.10.0-693.21.1.el7                                updates                              5.1 M
 kmod                                       x86_64                    20-15.el7_4.7                                      updates                              121 k
 kmod-libs                                  x86_64                    20-15.el7_4.7                                      updates                               50 k
 kpartx                                     x86_64                    0.4.9-111.el7_4.2                                  updates                               73 k
 libdb                                      x86_64                    5.3.21-21.el7_4                                    updates                              719 k
 libdb-utils                                x86_64                    5.3.21-21.el7_4                                    updates                              132 k
 libgcc                                     x86_64                    4.8.5-16.el7_4.2                                   updates                               98 k
 libgomp                                    x86_64                    4.8.5-16.el7_4.2                                   updates                              154 k
 libstdc++                                  x86_64                    4.8.5-16.el7_4.2                                   updates                              301 k
 libteam                                    x86_64                    1.25-6.el7_4.3                                     updates                               47 k
 microcode_ctl                              x86_64                    2:2.1-22.5.el7_4                                   updates                              786 k
 nfs-utils                                  x86_64                    1:1.3.0-0.48.el7_4.2                               updates                              399 k
 python-perf                                x86_64                    3.10.0-693.21.1.el7                                updates                              5.2 M
 selinux-policy                             noarch                    3.13.1-166.el7_4.9                                 updates                              437 k
 selinux-policy-targeted                    noarch                    3.13.1-166.el7_4.9                                 updates                              6.5 M
 systemd                                    x86_64                    219-42.el7_4.10                                    updates                              5.2 M
 systemd-libs                               x86_64                    219-42.el7_4.10                                    updates                              378 k
 systemd-sysv                               x86_64                    219-42.el7_4.10                                    updates                               72 k
 teamd                                      x86_64                    1.25-6.el7_4.3                                     updates                              112 k
 tuned                                      noarch                    2.8.0-5.el7_4.2                                    updates                              234 k
 tzdata                                     noarch                    2018c-1.el7                                        updates                              479 k
 yum                                        noarch                    3.4.3-154.el7.centos.1                             updates                              1.2 M
Installing for dependencies:
 linux-firmware                             noarch                    20170606-58.gitc990aae.el7_4                       updates                               35 M
 mysql-community-common                     x86_64                    5.6.39-2.el7                                       mysql56-community                    257 k

Transaction Summary
====================================================================================================================================================================
Install   2 Packages (+2 Dependent packages)
Upgrade  32 Packages
</code>
When I try to connect via ssh, returns "ssh: connect to host {the ip server here} port 22: Operation timed out".
When I request a screenshot of the instance, it shows:
Comment: I would try disabling iptables before you did the update. I'd also double check that the public IP hasn't changed - it shouldn't if you reboot the server, only when you stop and start. An elastic IP works around that issue.
Comment: I made sure of that. I'm using Elastic IP and before restarting I checked if iptables was disabled. I don't understand what's happening.
Answer: I found the solution (and the bug) here:
https://bugs.centos.org/view.php?id=14585
Copied from the bug report

Running "yum update" bricks network connectivity for AWS instances
  which have IPv6 enabled per the AWS docs.
Image is the "CentOS 7 (x86_64) - with Updates HVM" AMI
Unfortunately, if you update a production instance without a snap, you
  have no console access to try and recover it by disabling IPv6.
Did a lot of testing over the past several days and it seems to be
  related to cloud-init and the config of the network stack. In the
  steps to reproduce, there are two scenarios, one where it doesn't work
  and a workaround which bypasses cloud-init and does work.
Versions of kernel and cloud-init are in the "Steps" dialogue.


error in c++ matrix*vector multiplication

Question: I need a function that multiply a matrix and a vector (Matrix*vector)
It takes in a matrix A and a vector B, with int describing the dimensions. Somehow it isn't running correctly. Any help??
void Multiply(double *res, double **A, double *B, int ARows, int ACols, int BRows)
{

    if (ACols !=BRows)

    {

        return;
    }

    for (int i = 0; i < ACols; i++)
    {
        res[i] = 0;
        for (int j = 0; j < BRows; j++)
        {
            res[i] += A[i][j]*B[j];
        }
    }
}

Comment: Shouldn't `ARows` be used in there somewhere?
Comment: It should be Arows in the first for, not Acols. Note that res will have the same number of rows as A,  has it been allocated correctly?
Comment: Perhaps [`std::valarray`](https://en.cppreference.com/w/cpp/numeric/valarray) could help.
Comment: [Row major order](https://en.wikipedia.org/wiki/Row-_and_column-major_order)
Answer: It seems you mean
for (int i = 0; i < ARows; i++)
{
    res[i] = 0;
    for (int j = 0; j < ACols; j++)
    {
        res[i] += A[i][j]*B[j];
    }
}

It would be better if the function returns a boolean value that signals whether the function execution was successful for example
bool Multiply(double *res, double **A, double *B, int ARows, int ACols, int BRows)
{
   bool success = ACols == BRows;

    if ( success )
    {
        for (int i = 0; i < ARows; i++)
        {
            res[i] = 0;
            for (int j = 0; j < ACols; j++)
            {
               res[i] += A[i][j]*B[j];
            }
        }
    }

    return success;
}

Instead of the manually written loops you could use the standard algorithm std::inner_product declared in the header <numeric>.
Comment: A.k.a `res[i] = std::inner_product(A[i], A[i] + ACols, B, 0);`


Qual a melhor forma de enviar post de cadastrar junto com os elementos filhos?

Question: Estou criando uma aplicação Asp.net com o cadastro de clientes. Estou criando a página Create, que possui os campos de cadastro do próprio cliente. No entanto, o cliente pode ter vários telefones. Logo, minha ViewModel tem a seguinte estrutura:
public class ClienteViewModel
{
    public ClienteViewModel()
    {
        Id = Guid.NewGuid();
    }

    [Key]
    public Guid Id { get; set; }

    [Required(ErrorMessage = "O nome é requerido")]
    [Display(Name = "Nome")]
    [StringLength(80, MinimumLength = 5, ErrorMessage = "{0} deve ter no mínimo 5 e no máximo 80 caracteres.")]
    public string Nome { get; set; }

    [Required(ErrorMessage = "A Data de Nascimento é requerida")]
    [Display(Name = "Data de Nascimento")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime DataNascimento { get; set; }
}

Porém, como posso enviar essa lista de telefones na Controller em uma estrutura como essa? Poderia usar Ajax com partialView, mas aí eu teria que ter o ID (o cliente cadastrado primeiro). Gostaria de saber a melhor forma pra fazer algo parecido com a tela abaixo:
   [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(ClienteViewModel clienteViewModel)

Comment: é um `array` de `string` tipo `public string[] Telefones {get;set;}`
Comment: Mas como passar isso, já que estão em campos diferentes? Como organizo para que envie por post (sem ajax)?
Answer: De maneira simples coloque na sua classe ClienteViewModel um campo que vai receber a coleção de telefones citados na sua pergunta public string[] Telefones { get; set; }:
public class ClienteViewModel
{
    public ClienteViewModel()
    {
        Id = Guid.NewGuid();
    }

    [Key]
    public Guid Id { get; set; }

    [Required(ErrorMessage = "O nome é requerido")]
    [Display(Name = "Nome")]
    [StringLength(80, MinimumLength = 5")]
    public string Nome { get; set; }

    [Required(ErrorMessage = "A Data de Nascimento é requerida")]
    [Display(Name = "Data de Nascimento")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime DataNascimento { get; set; }

    public string[] Telefones { get; set; }
}

logo após essa mudança do seu modelo reparei que foi criado dinamicamente essas caixas de textos na sua View e para que as informações de telefone sejam trazidas precisa seguir uma nomenclatura de nome do campo e chave de índice que cada elemento criado, exemplo:

  <input asp-for="Telefones[0]" class="form-control" />

  <input asp-for="Telefones[1]" class="form-control" />

ou seja, no exemplo tem o campos Telefones[0] e Telefones[1] isso significa que o nome do campo e seu índice que começa do 0 até o total de telefones que assim deseja enviar para o seu objeto da classe ClienteViewModel.
Então, reafirmando quando for criado os campos dinamicamente precisa seguir o nome do campo e em colchetes o número do seu índice começando do número 0.
Comment: Show de bola. Obrigado!!!! Era isso mesmo que eu queria. Tem como fazer com List também?
Comment: Tem sim @ComplexityAlg ... é só colocar esse tipo no lugar do outro.


Recursive function with p=2/3 to call itself and 1/3 to return always ends?

Question: So I was reading Godel, Escher, Bach and this problem came up:
Let f(t) {
1)Generate random number k
2) if( k mod 3 = 0 or k mod 3 = 1 ) call f(t)   //so 2/3's of the time, a new recursion level starts
3) else return
}
The claim the book makes is that this sort of function call will "always end". First of all I'm not even sure what they mean by that but I assume they mean that the function will stop with high probability (1 - $\epsilon$) but I don't know how to prove something like this can anyone help?
My attempt:
1/3 of the time the program stops immediately.
In the other 2/3 of the time, we now need 2 returns to stop the program.
So it's something like this:
$p(stopping)=1/3+2/3*(1/3)^2+(2/3)^2*(1/3)^3+...+(2/3)^n*(1/3)^{(n+1)} $
$p(stopping)=\sum_{i=0}^{n}(2/3)^i*(1/3)^{i+1}=1/3*\sum_{i=0}^{n}2^i/3^{2i}=1/3*\sum_{i=0}^{n}2^i/9^{i}=1/3*\sum_{i=0}^{n}(2/9)^i$
$p(stopping)=1/3*\dfrac {1-(2/9)^{n+1}} {1-2/9}$ taking limit as n goes to infinity we get:
$p(stopping)=1/3* \dfrac{1}{7/9}=(9/7)*(1/3)=3/7$ which is far from "always".
Any help would really be appreciated!
Thank you for your time
Comment: k % 1 is always zero
Comment: There is something fundamentally wrong in your description. If $k$ is a class modulo$~3$, you cannot reduce it modulo$~2$ (if $k$ is just an integer this is possible of course, but what doe the "modulo$~3$" mean in that case?).
Comment: I'll correct it right away thanks for the comments!
Answer: The probability that the function will stop after at most $n$ recursive calls is actually
$$
\frac 13 + \frac 23\cdot \frac 13+\dots+ \left(\frac 23\right)^n \cdot \frac 13.
$$
($1/3$ does not have any power, because the function needs to stop only once.) The limit as $n$ goes to infinity is $\frac 13\cdot \frac 1{1-\frac 23} = 1$. And this is what it means that the function will always end.


Amazon WorkMail have emails go to two different addresses

Question: Using Amazon WorkMail service we have an email address setup - lets say it's firstname.lastname@example.com . When someone sends that email address an email I would like the email to go to two different places.

To that actual email inbox
firstname.lastname@example.com

Is this possible? I think it is using the SES service but not sure how to set it up.
Answer: What you're looking for is called email forwarding. Amazon has a guide here which tells you how to set it up.
It's not clear from that page whether the email is delivered to both inboxes, or just the forwarded inbox. Try it and see. If it doesn't work report back and someone may have another solution for you.
Here's the current contents of the steps

Sign in to the Amazon WorkMail web application using the user account credentials for the account that you want to forward emails from.
Note: To locate your Amazon WorkMail web application URL, open the Amazon WorkMail console and choose Organization settings from the left navigation pane. Under the General settings tab, select Web Application.
In the Amazon WorkMail web application, choose the gear icon in the top-right corner, select Email rules in the left navigation pane, and then choose New.
In the Rule name field, enter a name and ensure the Active rule check box is selected.
Under Conditions, select the drop-down menu and then choose is sent to … , choose Select recipient(s), select the user account that you want to forward email from, choose To, and then choose Ok.
Note: You can choose other conditions such as received from ... , includes these words in the subject ... , etc.
Under Actions, select the drop-down menu and then choose Forward the message to … , choose Select recipient(s), enter the email address that you want to forward emails to in the To field, choose Ok, then choose Ok again to close the rule.
Note: You can forward messages to an external email address, WorkMail users, resources, and groups, but not to personal Distribution Lists in your contact folder. Bounced emails will not be forwarded.
Choose Save changes.


How to produce 100 with only four 3s and mathematical symbols

Question: An approach like this doesn't count!
       $\underset{k \in \mathbb N, k \leq (3+3/3)} {\sum k^3}$
Thanks for your answers but I need something more strong... You are only allowed to use +, -, *, /, !, (, ), ^ and sqrt !
Comment: That's very clever!
Comment: Do you know the answer?
Comment: Unfortunately, no... :(
Answer: $3 \times 33.\dot3{}{}{}{}{}{}{}{}{}{}$
Comment: It's interesting to note that, at this very point in time, the number of upvotes for this solution is 3 :)
Answer: $\dfrac{33}{33\%} = \dfrac{33}{.33}{}{}{}{}{}{}{}{}{}$
Answer: $(\dfrac{ 3}{ .3})^\dfrac{3!}{3}$.
Comment: It's interesting to note that, at this very point in time, the number of upvotes for this solution is 3 :)
Answer: $\lceil33\times3+\log3\rceil{}{}{}{}{}{}{}$


What can cause Anchor Links to reload the page?

Question: Recently, I've been working on a WordPress website powered by the Divi theme and builder. Some of the pages have a menu with the URLs set to ID's of certain sections of the page (anchor links) but when clicked, the page refreshes and then scrolls to the relevant section.
What would cause a page to refresh when an anchor link is clicked? I'm baffled!
I've tried changing the URLs (to the below) but still have the same problem.
https://www.domain.co.uk/tables/#breakpoint-one
https://www.domain.co.uk/tables#breakpoint-one
In static HTML, coding something like this would take a matter of minutes so I cannot understand why the page refresh occurs.
Answer: Is the refreshing ocurring only the first time you click on an anchored link? or does it happen every time.
Perhaps you have POST data present (like you arrived on the page after submitting a form). I think the behaviour you describe matches that scenario.
Comment: It refreshes every time you click on any of the anchored links. The user arrives on the page via the main site navigation, not via a form so there shouldn't be any post data present. I have enabled a lot of caching on this site and a CDN - I'm wondering if that has anything to do with it?
Comment: Yes the problem is weird indeed. Perhaps you have some javascript acting on links.
Comment: In firefox's code inspector you can see if there are events linked to tags.
Comment: How do you check the events?
Comment: In Firefox: hover the cursor over a link and right-click, select 'inspect element'. Inspector will open up with the link tag focused. The tag will show a label [event] if there is a javascript event attached to it.
Comment: There are three events. Is there any way to disable them from running - one at a time?
Comment: For that you need to edit the javascript programs acting on your html. This can be though if you're using a third-party template or plugins.


Tricky Indefinite Integral

Question: $\int \frac{(x^2 + x)}{(e^x + x + 1)^2}dx$
I was thinking along the lines of breaking the numerator into denominator differentiation and generic function with help of division rule.
Answer: HINT:
Divide the numerator & denominator by $e^{2x}$
$$\dfrac{x^2+x}{(e^x+x+1)^2}=\dfrac{xe^{-x}\cdot(x+1)e^{-x}}{\{1+e^{-x}(x+1)\}^2}$$
Set $1+e^{-x}(x+1)=u$
Comment: ok, granted, is there a better {more general} way to reach it, suppose coefficients were not as simple as all 1's, is there a general way to approach these type of questions where e^x and polynomials are mixed?
Comment: @ELiT generally no, for example, there is no closed form for the integral $\int \frac{e^x}{x}dx$
Comment: I'm talking about exactly the same type of questions with just different coefficients , given that it is solvable and also quite easy with one or two step problem like the problem given above, How should we go about breaking the numerator {and then finding values like we do in partial fractions} or is there a better method?

Tricky Indefinite Integral


what is the meaning of that in C#? x ^ y

Question: what is the meaning symbol ^ in c#?

like example below.

if(x ^ y)
{
    return false;
}

Answer: ^ is XOR.
In this case, can be written as:
if(x != y)

which may be easier to understand (if you are unfamiliar with the XOR operator)
Answer: ^ means XOR:
x ^ y is True if only (x == true && y == false ) || (x == false && y == true).
More information
Comment: I don't think your expression is correct. If both are false, `x^y` will return false. Your expression will return true due to right side of the `||`. I think you meant `(x == true && y == false ) || (x == false && y == true)`
Comment: Umm... what?? If both are false, `(x == false && y == false)` is obviously going to return true...
Comment: That mistake also exists in your answer... Run your code with x and y both as false and tell me what you get... Because I get true when it should not for XOR.
Comment: @BrootsWaymb its the logic of Xor . if both are false, `(x== true && y== false)` would be false and also  `(x == false && y == true)` be false, and false || false would be false
Comment: @BrootsWaymb I made a mistake in my comment (it was not what I wrote in my answer). I edited it. It is what we have studied in mathematics. I have studied pure mathematics ;)
Comment: @BrootsWaymb ohhhhh yes I had made a mistake in answer too. Thanks. I corrected it.
Comment: it was a really silly mistake


C++ delete[] operator confusion

Question: I am studying pointers atm. and I got confused with delete[] operator.
Here is an example:
int* a = new int[12];

for (int i=0; i<12; i++)
    a[i]=123;

delete[] a;

for (int i=0; i<12; i++)
  cout <<a[i]<<" ";

If I got it correctly, delete[] operator should destory all objects in an array.
But my output is this:
10621288 10617028 123 123 123 123 123 123 123 123 123 123

Only first two elements are destroyed.
Have I made something wrong?
Answer: Your code invokes an Undefined Behavior, since you're trying to get access to already released memory. Anything could happen.
Answer: What you have done wrong is trying to access the contents of a after it has been deleted. This invokes undefined behavior (UB), which means "anything goes". You must never do that, it is a crash-worthy bug in the code.
The results you see are simply one particular specialization of "anything". Running this program on another system, or using a different compiler, or using the same compiler with different settings, is likely to end up doing something else.
Comment: @kr4lj: In this case there is nothing to destroy because the array contains integers -- only the memory for the array itself is released. If the array contained objects you would see their destructors being called one by one.
Comment: I did the same, got the first 2 elements zeroed. You cannot physically dleete a memory location :D just makes zero if zero is a null for compiler and releases for later use.
Answer: You just got lucky that the output still shows as if the data actually exists. But your understanding is correct. You have to perform a delete[] a.
On any other day you would have seen a crash. Invalid pointer deferencing exception.
Answer: Your code exhibits undefined behavior. Destroying memory is not the same as destroying, say, a book or a vase: the memory does not disappear, and some of its content may remain untouched.
However, accessing such memory makes your program illegal: your program no longer owns that chunk of memory, it belongs to some other code or to another part of your program. Any part of that memory can be overwritten at any time. Moreover, your program can crash when you access such memory.

C++ delete[] operator confusion


Recurrent neural networks - why is the vanishing gradient a problem?

Question: I understand why the gradient tends to become small in the early layers of a deep network. However I am trying to clarify why this is a problem in the case of RNNs.
This is what I understand: the gradient $\frac{\partial E}{\partial w} $ of a weight $w$ is computed as the average of the gradients at each time step. If the gradients of the early time steps are close to $0$, then they have no influence on the final gradient. Effectively this means the beginning of the sequence has no influence on how the RNN weights are learnt.
Is this the problematic aspect of the vanishing gradient?
Answer: If I understood your question properly, then what you have thought of vanishing gradient in RNN is wrong.
In RNN we known compute the current timestep value based on previous output values .
The main reason we compute gradients of the weights is to see how much of influences does it make on the network's output.
In RNN we take in previous output to compute current value.

The above image is from wildml where Denny Britz has written elegantly.
The red lines in the image is where we calculate the gradients. So while we compute chain rule to find the gradients, if the previous time step computation we take keeps on increasing then the gradient values will get small. This is known as Vanishing Gradient and a problem in RNN. We use LSTM, GRU to solve these problems.
Comment: But in RNN's the weight matrix W is common in all steps and it has connection to all steps. So we need to sum over all these gradient paths (shown as red in the diagram). That is, although the contribution from earlier layers on the gradient of weights might be small, later layers can contribute more to the local gradient. Why it is a problem then if gradients can be updated?


I was doing K-means Clustering, before that, each data in the database has to be assigned to an index. However, TypeError occurs, how to fix it?

Question: Here's my code:
with connection:
    with connection.cursor() as cursor:
        sql = """
              SELECT `CPC-Current-DWPI`,`Assignee/Applicant First` FROM final.f01l_patent;
              """
        cursor.execute(sql)
        result = cursor.fetchall()

        count = []
        ro=0
        for i in range(1,10):
            for j in result :
                if j['CPC - Current - DWPI.split()'][3]==str(i):
                    co+=1
            count.append(co)
            co=0

I know i can't index a tuple with a list, so i added .split() after CPC - Current - DWPI, but actually i have no idea with how to change lists into slices
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_19312\1811172777.py in <module>
     16         for i in range(1,10):
     17             for j in result :
---> 18                 if j['CPC - Current - DWPI.split()'][3]==str(i):
     19                     co+=1
     20             count.append(co)

TypeError: tuple indices must be integers or slices, not str

Comment: This question would benefit from a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). Can you edit your question to include a sample of what `result` includes?
Answer: Your result is a list of Tuples. Try replacing the string 'CPC - Current - DWPI.split()' with the index (as an integer) of the item you want.


Pegar valor aleatório mysql

Question: Gostaria de saber alguma forma de pegar algum valor aleatório do MySQL sem repetir, eu estou usando esta linha:
$query = mysql_query("SELECT * FROM users ORDER BY RAND()");
mas ele repete bastante os usuários que eu mostro na tela, e se possível, se passar pelo usuário, pelo id ele não mostre mais, algo desta forma.
Comment: Aí não é aleatório ;).
Comment: [Randomizar resultados com PHP](http://pt.stackoverflow.com/a/31178/91)
Comment: @rray, eu pensei em algo como tinder, que exibe pessoas diferentes... o rand até funciona mas não como eu imaginei...
Answer: O Método RAND() do MYSQL suporta SEED que força a gera um número aleatório diferente para cada SEED o que fará com que tenha uma ordem diferente para cada uma delas, mas a mesma ordem para um mesmo SEED.
Você pode usar os segundos do dia para um SEED adequando.
$sql = sprintf("SELECT * FROM users ORDER BY RAND(%d)", time()%(24*60*60) );
$query = mysql_query($sql);

Para usar minutos use time()%(24*60)
Este código fará com a ordem sempre se repita no mesmo instante do dia.
Em que isso ajuda?
Bom, fica mais fácil por exemplo, mostrar uma lista aleatoriamente para alguém e manter essa lista pelo tempo que desejar.
Supondo que para cada usuário você queira mostrar uma lista aleatoria diferente, mas quer que a lista seja a mesma enquanto o usuario estiver logado. Você pode usar o id desse usuario juntamente com alguma informação que sempre mude como o numero do dia para o seed e desta forma durante um periodo qualquer terá uma lista aleatoria identica sempre que executar a consulta, evitando ter de codificar isso na linguagem.
Answer: Você pode tentar pegar todos os usuários de uma vez.
SELECT DISTINCT * FROM users LIMIT X ORDER BY RAND()

Onde o X é a quantidade de usuários

Pegar valor aleatório mysql


Why does my UniFi hardware tell me "Adoption failed"?

Question: I'm battling with a piece of UniFi hardware that refuses to be adopted by a controller.
Every attempt is rejected with the unhelpful message "Adoption failed". No other indication or information is available.
How can I determine what the actual problem is?
Comment: @Orphans Oh, thanks for explaining Stack Exchange to me ;P
Comment: @Orphans Touché. However, I was being deliberately vague to indicate that the question is more focused on general pointers, so that the user can find their root problem, rather than the solution to the actual problem I was facing at the time. Some (myself included) would argue that these generic question/answer combinations are more helpful as they are more widely applicable to problems of other users. I didn't have the time to go into details earlier.
Comment: Well, I can see that you already answered your own question. But next time. Please provide ut with information how your network topology looks like so other can come up with the correct solution.
Comment: obviously it was needed
Answer: A common issue is that the controller and the target device don't share the same network. During adoption, the controller will attempt to establish a direct connection to the device, this may fail.
Connecting to the device via SSH and checking /var/log/messages can also be very helpful.
Also, avoid using the root account for anything. Especially device authentication. It can really mess up your network, as the controller might try to create the named user on new devices. This will fail, as root already exists.
Configuring a different user name for Device Authentication in the controller settings can magically resolve weird adoption errors.
When you're deploying a USG in your network, you can end up in a situation where your controller tries to configure the site for a certain network, but your USG still provides an outdated configuration via DHCP. The result is that the USG is in a different network than the rest of your devices. This will make it impossible to adopt the USG.
In such a scenario, you will have to connect to the USG via SSH and add an additional IP address to the LAN interface you're using. This will allow the controller to communicate with your USG, adopt and deploy as configured.
The key command sequence here is:
configure
set interfaces ethernet eth0 address 192.168.1.2/24
commit
exit

Answer: I had an AP that wouldn't be adopted. Nor could it be reached through SSH, even though the IP address was right and it replied to ping.
Restarting the AP miraculously solved both problems.
Comment: restarting in the same network solved the issue. I guess you have started in different networks which looked similar...
Answer: In my case it was the antivirus software. just disabling antivirus worked for me.
Answer: My USG-3P was looking for my UniFi Network application in another IP, so I changed my UniFi Network application IP (my Windows IP) and I adopted the USG-3P successfully.


Ansible library strategy?

Question: I'm starting to use ansible for configuration management and wondering how to structure my ansible directory. For instance, web1 is a host which needs configuration edits made to Apache and /etc/ssh/sshd_config. jira1 is a host which doesn't use Apache, but does need the same edits made to /etc/ssh/sshd_config.
My thought was to make a library directory under my ansible directory and put a sshd.yml under the playbooks. I could make host directory with symlinks to the library:
ansible
   |
   |
   + library
   |       |
   |       +- sshd.yml
   |       +- apache.yml
   |       +- nginx.yml
   + web1
   |    |
   |    + playbooks
   |              |
   |              +- symlink_to_../../library/sshd.yml
   |              +- symlink_to_../../library/apache.yml
   + jira1
        |
        + playbooks
                  |
                  +- symlink_to_../../library/sshd.yml
                  +- symlink_to_../../library/nginx.yml

This eliminates duplicate .yml files and ansible doesn't seem to mind the symlinks. At a glance into a subdirectory I can tell exactly which playbooks are needed/used for configuring a given host. It seems like a good scheme but is there a better way of doing this?
The only other thing I can think of is outfit every playbook with vars/facts which include/exclude every single host from configuration. That seems like the long way around though; edting every single playbook any time I add or remove a host from the LAN.
Comment: `sshd`, `apache` and `nginx` seems to be good candidates for `roles` and `web` and `jira` – for `groups` in your inventory.
Comment: Are you aware of [inventory](http://docs.ansible.com/ansible/latest/intro_inventory.html) concept?
Comment: Somewhat. I have a basic inventory setup with 70 hosts under an '[all]' group. I watched a couple 'ansible basics' webinars that didn't really get into large scale deployments. Clearly I need to do more research. thanks.
Answer: As Konstantin wrote, you should have roles for those standard building blocks, groups per server type and playbooks to apply those roles. So your structure would be something like this:
ansible
   |
   |
   +-roles
   |   |
   |   +-sshd
   |   +-apache
   |   +-nginx
   |
   +-playbook_for_group_web.yml
   |
   +-playbook_for_group_jira.yml

Comment: Starting to make more sense now. I wasn't clear how roles were used. Thanks for the additional clarification.

Ansible library strategy?


ResponseEntity - How to handle status codes that are different from 200 ok?

Question: I am working on a REST API client and I have one Class responsible for all request directives since for that I am going to be using the exact same provider. I am currently being able to send, receive and process the responses as long as they are 200 OKs.
However, as soon as I start to receive anything different from it, I get errors and my program stops running.
    Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-02-09 15:17:09.359 ERROR 24504 --- [           main] o.s.boot.SpringApplication               : Application run failed

java.lang.IllegalStateException: Failed to execute CommandLineRunner
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:807) ~[spring-boot-2.4.0.jar:2.4.0]
    at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:788) ~[spring-boot-2.4.0.jar:2.4.0]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:333) ~[spring-boot-2.4.0.jar:2.4.0]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1309) ~[spring-boot-2.4.0.jar:2.4.0]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1298) ~[spring-boot-2.4.0.jar:2.4.0]
    at com.infobipcommunity.InfobipApisApplication.main(InfobipApisApplication.java:38) ~[classes/:na]
Caused by: org.springframework.web.client.HttpClientErrorException$BadRequest: 400 Bad Request: [{
    "requestError": {
        "serviceException": {
            "messageId": "BAD_REQUEST",
            "text": "[from : may not be null, to : size must be between 1 and 2147483647]"
        }
    }
}]
    at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:101) ~[spring-web-5.3.1.jar:5.3.1]
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:186) ~[spring-web-5.3.1.jar:5.3.1]
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:125) ~[spring-web-5.3.1.jar:5.3.1]
    at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63) ~[spring-web-5.3.1.jar:5.3.1]
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:818) ~[spring-web-5.3.1.jar:5.3.1]
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:776) ~[spring-web-5.3.1.jar:5.3.1]
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:710) ~[spring-web-5.3.1.jar:5.3.1]
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:601) ~[spring-web-5.3.1.jar:5.3.1]
    at com.infobipcommunity.configuration.Request.requestExecutor(Request.java:72) ~[classes/:na]
    at com.infobipcommunity.controller.RequestManagerSms.getDeliveryReport(RequestManagerSms.java:33) ~[classes/:na]
    at com.infobipcommunity.InfobipApisApplication.run(InfobipApisApplication.java:62) ~[classes/:na]
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:804) ~[spring-boot-2.4.0.jar:2.4.0]
    ... 5 common frames omitted

As per evidence you can see I am getting the response body and I am being able to print it, unfortunately I cannot pass it on to the next class.
This is the method I am using to fetch data:
public AdvanceSmsDlrResponse getDeliveryReport() {

        AdvanceSmsDlrResponse dlrResponse = new AdvanceSmsDlrResponse();
        try {
            dlrResponse = objectMapper.readValue((String) requestExecutor(null, "/sms/1/reports", HttpMethod.GET,
                    "com.infobipcommunity.models.responses.sms.getDeliveryReport.AdvanceSmsDlrResponse"), AdvanceSmsDlrResponse.class);
            return null;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return new AdvanceSmsDlrResponse();
        }
    }

The generic method that is being called in the previous snippet:
public Object requestExecutor(Object requestBody, String requestPath, HttpMethod httpMethod, String className) {

    entity = new HttpEntity<>(requestBody, httpHeaders);
        response = requestRestTemplate.exchange(getUrlhost() + requestPath, httpMethod, entity, className.getClass());
        LOGGER.info("\n" + response.toString());
        return response.getBody();

}

So my question is, how is this meant to be handled?
Additionally, I wanted to ask if there is a way I can make sure that the object using the method getDeliveryReport is able to handle the positive and negative results (AdvanceSmsDlrResponse.class or ApiException.class)
Answer: You can catch RestClientResponseException and get the result using getResponseBodyAsString() from the exception. Then you can use jackson to map it to an object.
This is how I handled it, maybe there are other ways.
Regarding the last question, I guess you will need to add another field in the response object in order to be able to pass the JSON from the exception. Another way would be to rethrow the exception using another expcetion and catch later or not rethrow it at all and catch it later.
Comment: tzortzik, thanks for the information... I did it like this:


Dealing with mixed categorical data: e.g. Heritage Health Prize data

Question: Looking at the Heritage Health Prize, the data is structured as follows:

Each of the Data Sets will be comprised of tables as follows:

<code>a. Members Table, which will include:
    i. MemberID (a unique member ID)
    ii. AgeAtFirstClaim (member's age when first claim was made in the Data Set period)
    iii. Sex
b. Claims Table, which will include:
    i. MemberID
    ii. ProviderID (the ID of the doctor or specialist providing the service)
    iii. Vendor (the company that issues the bill)
    iv. PCP (member's primary care physician)
    v. Year (the year of the claim, Y1, Y2, Y3)
    vi. Specialty
    vii. PlaceSvc (place where the member was treated)
    viii. PayDelay (the delay between the claim and the day the claim was paid for)
    ix. LengthOfStay
    x. DSFS (days since first service that year)
    xi. PrimaryConditionGroup (a generalization of the primary diagnosis codes)
    xii. CharlsonIndex (a generalization of the diagnosis codes in the form of a categorized comorbidity score)
    xiii. ProcedureGroup (a generalization of the CPT code or treatment code)
    xiv. SupLOS (a flag that indicates if LengthOfStay is null because it has been suppressed)
c. Labs Table, which will contain certain details of lab tests provided to members.
d. RX Table, which will contain certain details of prescriptions filled by members.
e. DaysInHospital Tables - Y2 and Y3, which will contain the number of days of hospitalization for each eligible member during Y2 and Y3 and will include:
    i. MemberID;
    ii. ClaimsTruncated (a flag for members who have had claims suppressed. If the flag is 1 for member xxx in DaysInHospital_Y2, some claims for member xxx will have been suppressed in Y1).
    iii. DaysInHospital (the number of days in hospital Y2 or Y3, as applicable).
These two Tables are intended for use by Entrants to train and validate their algorithms. DaysInHospital Tables are based on the Claims Table with admissions in Y2 or Y3, as applicable. As a privacy measure, any member who spent more than two weeks in hospital is grouped; they are treated as though they spent 15 days in hospital.
f. Target - is "DaysInHospital_Y4" but doesn't include DaysInHospital. DaysInHospital data for Y4 are to be filled in by Entrants to produce entries. Seem SampleEntry.csv as an example.
</code>
So the goal is to predict the values in table f.
Clearly the first thing to do is to do a JOIN across the tables using member IDs.
Some of these appear to be standard discrete variables (age, sex etc) but others are much more tricky to deal with. For example, the labs index and RX index point to other tables. Also, there are many categorical types. Some of the categorical types (such as PrimaryConditionGroup) have many possible values. Normally for categorical data, these can be made into features using a binary flag for each category (simply using the index will fail as there is no ordering). However when there are many thousands of these this seems like an inefficient approach. Are there any better ways to deal with the mixture of numerical and categorical data such as this?
Answer: Here's the approach I used: Any categorical variables with fewer than about 50 levels were turned into binary variables.  For categorial variables with greater than 50 levels, I also split them into binary variables, but only kept the 50 most "predictive" levels, using a simple filter.
This is a form of feature selection, so it isn't optimal, and should be included within any cross-validation you do to validate your algorithm.
Note that the team that won milestone 1 (currently in 2nd place) posted their SQL code to create the "analysis dataset" by merging and aggregating all of those tables.  It's a great place to start.
Answer: I haven't looked at this specific data set, but from a project I was involved in a long time ago, we had a questionnaire response that was the specific drugs a patient took. Given the number of possible drugs, turning each into a category was not feasible. I broke out several discrete features from this varying length set: number of prescriptions, presence of certain prescriptions and the ratio of those prescriptions to all the prescriptions taken. In my project, if someone took a narcotic and three non-narcotics, they would have f_total = 4, f_narcotics = 1, f_ratio = 0.3. I used the Physician's Desk Reference and a list of the 100 most prescribed drugs to do an estimate of these values (since I didn't have access to a database of all prescription drugs). I'm not sure if those features are relevant for the Heritage Health competition, but I presume that determining the relevant features is the added-value they are looking for.


Expo EAS Updates Group ID

Question: EAS-published updates create a group ID (platform-agnostic) and an update ID (platform-specific). The Updates package (expo-updates) only exposes Updates.updateId which corresponds to the platform-specific ID. https://docs.expo.dev/versions/latest/sdk/updates/#updatesupdateid
Is there no way to get the current update group ID from a running Expo application?
Comment: I'd love to know as well. Either that, or expose the  `iOS update ID` / `Android update ID` in `eas branch:view`. There's now way that I know of at the moment to match the update on a device to a branch update so you can debug.
Answer: Just found out that one way to access the Update group ID is via Constants
import Constants from 'expo-constants';

const updateGroup = Constants.manifest2?.metadata?.["updateGroup"];

It feels pretty janky and I wish there was a first class way to do it via Updates but it kinda works for now.

Expo EAS Updates Group ID


Getting amazon network IP's and not actual client IP's behind ALB (Xforward proto)

Question: Hello Community members,
I am using ALB (application load balancer) for my e-commerce website. behind the load balancer there are two ec2-linux instances which are getting the client traffic through ALB (there is web server tomcat7 on both ec2-instances).
I am using X-Forwarded-For header to get the actual client IP on my ec2-instances, which is working fine in terms of getting the client IP.
My 70% client IP's are actual client IP's which is accessing a payment page of my website ( i am getting the production sale on my e-commerce website.)
30% IP's are AWS network operations IP just like below ip those Ec2-network IP' are also accessing payment page of my website (but i am not getting any production sale from these amazon network IP's)
https://www.whois.com/whois/184.108.40.206
https://www.whois.com/whois/220.127.116.11
https://www.whois.com/whois/126.96.36.199
https://www.whois.com/whois/22.214.171.124

Please check above 4 example URL's here
OrgName: Amazon Technologies Inc.
OrgTechName: Amazon EC2 Network Operations

So i am confused that why i am getting Amazon network IP's (are these amazon ec2-network IP's are routers between actual client and amazon ALB OR these Ip's are load balancer's IPs instead of client Ip's : my java code is given below to fetch client IP)
Should i block them using aws waf on amazon ALB or not.
If i block them will i be ended up loosing actual client traffic ?
OR
Why i am not getting client real IP for 30% of all traffic while I am using x-forward-for header?
My java code is :
public static String getClientIpAddr(HttpServletRequest request) {
    String ip = request.getHeader("X-Forwarded-For");
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("HTTP_CLIENT_IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("HTTP_X_FORWARDED_FOR");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getRemoteAddr();
    }
    return ip;
}

I only want to save real client IP(using x-forward header) who are actually accessing my website.
Does X-Forward header provide null values ??
Regards,
Yugdeep
Comment: You should probably try to capture the *complete* requests, here... the `User-Agent` header, for example, might give you an idea of the nature of your traffic.  In one organization I work with, much of their Internet access traffic rides a private circuit to AWS and then actually hits external sites via outbound connections through EC2 proxy instances (this is counter-intuitive, but it is for auditing and compliance and egress control purposes)... so if somene from that office connected to your site, this is exactly what you'd see.
Comment: Thanks Michael.. i blocked that specific User Agent.
Answer: Those 4 IPs are Amazon owned IPs. I see two possibilities here:

They aren't your ELB. I believe if they were your ELB you should see an IP from your VPC CIDR block (check what the IP shows as for health check requests for an example). You can check the current IP of your ELBs in EC2 > Network Interfaces in the console. Here you will find the network interfaces for everything, including load balancers. Both their public and private IPs will be shown. Verify these IPs don't show anywhere in that list to confirm they aren't something of your own.
If they are your ELB IPs then your code may be getting the public IP of your ELB health checks, double check what page your health check is hitting.
Comment: Thanks Brandon.. Yes those were not ELB IP's or ELB health checks.  i blocked that specific User Agent.


Transition between @try @catch

Question: I'm having a hard time understanding the transition from @ try to @ catch
I understand that if a statement from the @try block throws an exception, the @catch block gets executed.  I don't understand how an NSException object containing information about the exception gets passed as the argument.  A lot of stuff I'm reading online about exceptions skip this detail.
The example from my book is
<code>@try {
    [myArray objectAtIndex: 2];
}

@catch (NSException *exception){
    NSLog(@"Caught %@%@", exception.name, exception.reason);
}
</code>
So once the exception is detected is an exception object automatically created and sent to the @catch block?
Comment: **do not use exceptions as recoverable errors**.  Excaptions should be treated as fatal errors in iOS and OS X applications.
Comment: once the exception is caught by the @catch block, it is created by the exception pointer, and the name and reason are part of the created exception
Comment: So once the exception is caught by the @catch block a pointer is created to reference to that exception?
Comment: exactly. The NSException creates it as a pointer to the exception, and the pointer is set to whatever kind of exception is called. There are generic exceptions for NSException, and then NSException has the ability to create new ones for ones that the generic will not work with.
Comment: Just to clarify the order of the process:
1. exception occurs (in @try block)
2. exception pointer is created to reference an exception object that stores the exception name and reason?
Answer: Try and Catch are used for Exception handling. Whenever a error occurs in the try block, the compiler jumps to the corresponding Catch block and passes the Exception object to it.
We simply access the exception object to know the details of the error.
Answer: Yes. When an error occurs, the stack frames generated by the callstack are checked in order to verify if there is a 'try' statement with a 'catch' block. When it finds, an Exception object is instantiated containing the execution context (e.g. context about the callstack, thread and details about the error) and this object is passed as parameter to the catch block.

Tip: Verify the best practices to rethrow exceptions in objective-c. In C#, I know that the rethrow operation can change scope of the exception.
Hope it helps.

Transition between @try @catch


What would be the judicious choice of a random variable in a coin toss experiment

Question: Consider the following random variable:

$X = 1$ if the flip of the coin is a head
$X = 0$ if the flip of the coin is a tail

How the above definition of random variable is different from

$X = 1$ if the flip of the coin is a head
$X = 1.01$ if the flip of the coin is a tail

What would be a judicious choice of random variable in a coin toss experiment? How the values assigned to the outcomes matters?
Can you please help me to understand the concept of random variable?
Comment: I guess it depends on what you would want to calculate with this. Do you want to, for example, count how many heads/tails you get in a repeated experiment?
Comment: Sure, counting.  If you flip the coin a thousand times, add up the observed values of $X$, and get $467$, then that means you got $467$ Heads.  But, of course, you could add up the second one as well and then get the number of Heads via algebra.
Comment: As a general rule, the problem you are looking at clarifies the variables.  If I am interested in how many Heads I threw, it's natural to assign a variable that counts them.  If I am looking at something more graded than a count, my variable should reflect that.  But, in all cases, the problem comes first.
Comment: That is to say, variables measure things.  If you are interested in the distribution of the heights of trees in a forest, I should have a variable that records the height of an observed tree.  If I am interested in counting, I should have a variable that records the presence of the thing I want to count.  Again, the variable should be linked to its purpose...to whatever it is you are interested in studying.
Comment: I don't understand.  "judicious" with respect to what goal?  Indicator variables, the first one you gave is an example, are often useful, but that doesn't mean you can't make other chocies.
Comment: @lulu Can you give an example of a goal in a coin toss experiment. In which situation $X=0$ and $X=1$ helpful.
Comment: But, it's your variable.  You can assign values to it however you like.
Comment: Note that in more complex settings, you can't always untangle the total.  For instance, if you are tossing a fair die.  The indicator variable for the $6$ still counts the $6's$ but if your variable gave $1$ for a $6$, $.5$ for a $5$, and $0$ for the others, then if you tossed it $10$ times and got a score of $3$, you wouldn't know how many $6's$ you had.  But, of course, that might not have been your goal.  Maybe your goal was to determine how "happy" the outcome made you, and a $6$ makes you twice as happy as a $5$ and the other scores don't make you happy at all.
Comment: @lulu I doubt I understood random variables in a correct way.  Can you point out references on how to design random variables related to a problem at hand.
Comment: Your first choice of $X$ seems more sensible for coin tosses simply because $E(X) = .5$ if the coin is fair.
Answer: Remember the definition of a random variable. It is a function on the sample space. That means each function is a new random variable.(being a finite set I am ignoring measurability issues).
If your sample space is students in a college and you are taking one person at random, then you can measure their weight in kg which could be a number anywhere between 40 to 100 or something like that with some mean and some variance. (Think of the function that assigns weight to every individual).  Or it could be age which is a different random variable with a much narrower band perhaps taking values  mostly between 17 and 25.  For every outcome (an element of sample space) what you are interested and what you choose to track is one random variable. One simplistic view of random variable is a numerical measurement on each outcome of a random experiment.


In a sparse reward problem, is it possible to remove reward shaping once the RL agent trains long enough to consistently reach the final reward?

Question: I'm new to machine learning, and primarily looking at it from the perspective of it's applications to control theory.
In the application found in this paper, a RL agent attempts to land a spacecraft near a target. The optimization environment is very sparse, with a large reward gained if the spacecraft can successfully land, along with small penalties for fuel use along the way. In order to overcome the sparsity and allow the RL agent to successfully land, the authors employ reward shaping and eventually achieve a successful agent.
From this point, the authors discuss improving the reward shaping function to increase fuel efficiency. However, couldn't they just continue training this same agent without any shaping, thus allowing the fuel efficiency rewards alone to shape training?
I'm very new to the field, so I suspect I'm missing some fundamental or practical issue with this approach.
Answer: It seems that the hyperlink is broken, so for now, I will attempt to clarify some details without having read the paper and can answer the specifics later.

I suspect that even though the agent has found a solution, it may not be the optimal solution and that finding the optimal solution may still require a whole bunch of extra exploration in both state and action space. Reward-shaping is one way of exploring efficiently, and useful priors such as fuel efficiency may allow the agent to find the optimal solution quicker even after having found the reward. That being said, I think that in the case of 2D navigation in a grid-like world, what you are proposing may work totally fine as long as the discount factor $\gamma \neq 1$ which would effectively be the same as fuel efficiency in the spacecraft game.

Since you said that you're new to the field, here's a more detailed answer to make sure that we're on the same page re. your question.
When the rewards are sparse and the state-space is very large, RL agents are often unable to learn because there is a very low probability of reaching the rewarding state(s) by random exploration in a finite amount of time. This problem is best known in the game Montezuma's revenge, where Deep RL agents without tweaks (vanilla DQN; Mnih et al 2015) have struggled to perform well (though recent attempts have fared well). Ideally, an agent should learn to explore the state-space better, see whether you have visited some states before, and if not, go visit those to reduce your uncertainty about them and see whether they are rewarding. People use prioritized experience replays, reward shaping, uncertainty-based exploration, and a bunch of other tweaks to solve this. The point of these tweaks is to help the agent with the exploration problem such that it can.
However, once the agent learns to find the correct area of the state-space, i.e. one that leads it to the rewarding locations which are sparse, you could remove the bonuses that you artificially constructed, for instance, by reward-shaping since the exploration problem is not as difficult because the agent knows where the reward is.
If I understand correctly, this is the logic you are using when you framed your question.
Comment: Thanks for the detailed answer! What you describe is the logic I was using. Here's a hopefully working link http://arclab.mit.edu/wp-content/uploads/2020/01/J18_2020.pdf.
In summary, it is a 6DOF problem, and the reward shaping uses the [gaze heuristic](https://en.wikipedia.org/wiki/Gaze_heuristic) to find a good path to land. I propose removing the heuristic, and keeping the fuel efficiency penalty to continue training (using a discount rate as fuel efficiency is smart and makes sense, but in this case fuel efficiency is more complex)


"No emulator images (avds) found" mesmo depois de criar imagens de emulador

Question: Tenho o seguinte problema:
Error: No emulator images (avds) found.
1. Download desired System Image by running: /usr/local/Cellar/android-sdk/24.4/tools/android sdk
2. Create an AVD by running: /usr/local/Cellar/android-sdk/24.4/tools/android avd
HINT: For a faster emulator, use an Intel System Image and install the HAXM device driver

Já criei duas imagens de emulador pelo comando android avd
Comment: Qual a saída do comando `which android`? Outra coisa, você já baixou (`android sdk`) as imagens que quer emular?
Comment: @zekk já consegui emular. O problema agora é o tamanho da tela do emulator. Fica uma dimensão baixa e tudo expremido. Como alterar isso? E como acelerar o emulador, que é tão lento?
Comment: Veja aqui o ponto 3 a ver se ajuda: http://www.markupjavascript.com/2015/03/most-common-phonegap-errors-with-solutions.html
Answer: para ficar mais rapido ai mesmo fala
 HINT: For a faster emulator, use an Intel System Image and install the HAXM device driver

pela msg vc deve estar usando Windows, se seu CPU for compativel instale o HAXM e ao criar o AVD use imagem X86 (Nao use X86_64) , no meu laptop , com Linux e usando KVM (o HAXM pra Linux) meu AVD roda em 9 segundos .
ja sobre a tela , tente fazer um AVD usando API23 , ainda tenho problemas de Rendering com a API24 tambem.


Speeding up R Loops in an EM algorithm implementation

Question: I am writing an implementation of the EM algorithm to estimate parameters in a GLMM in R. My model is $$y_{ij}|\alpha_i \sim Bin(1,p_{ij})\textrm{, where }logit(p_{ij}) =  \mu + \alpha_i \textrm{ and } \alpha_i \,\,iid \sim N(0,\sigma^2).$$ In other words, my data has a binary response that can be modeled with a fixed intercept, $\mu$, and a random effect, $\alpha_i$.
I am interested in performing EM for the sake of better robustness than I'd get through an ML or REML estimator like the ones used in lmer. My procedure for estimating $\mu$ and $\sigma^2$ goes as follows:

Choose starting values for $\mu$ and $\sigma^2$ based on REML estimates.
Using Metropolis-Hastings, randomly generate L $\alpha_i$ vectors.
Compute the expectation for the log-likelihood for $\mu$ and $\sigma^2$ using the L simulated values of $\alpha_i$ in a pretty standard Monte Carlo scheme.
Maximize the expectation in (3) wrt $\mu$ and $\sigma^2$.
Use these maximize estimates as new starting values, and return to (1).
Repeat k times. This produces two k-length vectors, $\bf{\mu}$ and $\bf{\sigma^2}$.

My concern is the following: speed. I have largely vectorized the procedure, but my program chokes takes awhile for values of L larger than 5,000 and k$\geq$100. I have determined that the slowest step is unfortunately Step 6. This could mean that any of the steps 1-5 are slow. I suspect that because of the slowdown with high L, the slowdown occurs during the M-step. My likelihood is separable wrt $\mu$ and $\sigma^2$ (no cross-products), so instead of one multivariate optimization, I am able to get by with two single-variable optimizations, which has sped up the computation.
Things I would like:

Is there a way to compile R code? I call an intensive series of functions thousands of times. Variables are pre-allocated before assignments and functions are all vectorized, so I can't imagine many more gains in speed in those areas. Compiling the code would drastically improve my run time. My code is already written, so I'm very averse to converting it to C or C++.
I have been using the optimize() function on the relevant parts of the log-likelihood to get the appropriate maximizations of $\mu$ and $\sigma^2$ at the given iteration. In MCEM problems in the mixed models framework, is there an algorithm or function that leverages the structure better than a general optimization routine that could give me better run times?
Comment: I suggest that you check with the R-SIG-Mixed list (https://stat.ethz.ch/mailman/listinfo/r-sig-mixed-models) to see if they have any input on your endeavour
Comment: @MikeLawrence: Thanks. The question was probably worded too specifically to receive responses. My main question is just if there is a way to compile R code. That doesn't involve any knowledge of mixed models or EM algorithm.
Answer: In case someone else is interested, digging into the issue, a friend of mine found a post from Dirk Eddelbuettel's blog about the R compiler added in 2.13.0. It did not give amazing speed increases because most of my functions were already vectorized and I only had a couple for-loops, but someone else may find it useful. The hope was to avoid writing the code in C or C++, and this compiler does that, though there are better options.
Thinking Inside the Box, Dirk Eddelbuettel, April 12, 2011.


Apache James: eval: /opt/james/bin/./wrapper-linux-x86-32: not found

Question: I'm setting up a James server for the first time. I'm using 3.0-beta4. After I copied the binaries to /opt, I tried running it:
neonorb@neonorb /opt/james/bin
 % ./james start
Starting Apache James Server App...
./james: 1: eval: /opt/james/bin/./wrapper-linux-x86-32: not found

I'm running Ubuntu 15 64bit. I checked, and that file does exist.
Comment: Assuming `/opt/james/bin/wrapper-linux-x86-32` is a shell script, what does `sh -x /opt/james/bin/wrapper-linux-x86-32` show?  (This should run that shell script in a "verbose" mode, which hopefully will indicate/provide more information on the source of the "not found" error.)
Comment: /opt/james/bin/wrapper-linux-x86-32: 1: /opt/james/bin/wrapper-linux-x86-32: Syntax error: "(" unexpected
Comment: This doesn't seem to be a bash script, more like an executable. Editing with nano, it's a bunch of '?' and escaped letters. It starts with "^?ELF^A^A^A........" though.
Comment: Hmm. Perhaps it's a binary format that doesn't match your machine...
Answer: A possible reason is that the prerequisite libc6 is not OK in your system. Use
sudo apt-get install libc6-i386 libc6-dev-i386

and then
$ sudo ./james start

will run


FILESTREAM - Read and write a large file in FILESTREAM column

Question: Should I use System.Data.SqlTypes.SqlFileStream to read and write a FILESTREAM column?
For example:
var sqlCommand = sqlConnection3.CreateCommand();
sqlCommand.CommandText = "Select FileData.PathName() As Path, GET_FILESTREAM_TRANSACTION_CONTEXT() As TransactionContext From PictureTable Where PkId = (Select Max(PkId) From PictureTable)";

var reader = sqlCommand.ExecuteReader();
reader.Read();
var filePath = (string)reader["Path"];
var transactionContext = (byte[])reader["TransactionContext"];
var sqlFileStream = new SqlFileStream(filePath, transactionContext, FileAccess.Read);
var data = new byte[sqlFileStream.Length];
sqlFileStream.Read(data, 0, Convert.ToInt16(sqlFileStream.Length));

In above code I can use the query shown here and directly access the FileData:
Select FileData From PictureTable Where PkId = (Select Max(PkId) From PictureTable)

What happens if don't use SqlFileStream and use varbinary(max) to read and write?
When SQL Server and Application installed in separate server, I have some problem in setup Windows Authentication to access SqlFileStream file path. How I can avoid this problem?
Answer: According to Microsoft's doc, SqlFileStream is the appropriate solution (see here). The SqlFileStream handles other things like file handles as data stored in a file stream is different from data stored in a row-based data file (see here).
Hope this helps!


How to find integer solutions to $(pk-1)(p-1)(p+1)=(p-2)!$

Question: Let $p$ be a prime. How can we find whether there is a positive integer $k$ satisfying the equation,
$$(pk-1)(p-1)(p+1)=(p-2)!$$
Clearly there are no solutions when $p=2,3$. What about for other primes $p$ ?
(I want to find prime numbers $p$ such that $(p^2-p)(p^2-1)|p!$. Since $(p-2)!=1\mod p$, we get that there is $k\in\mathbb{N}$ with $(pk-1)(p^2-1)=(p-2)!$ iff $(p^2-p)(p^2-1)|p!$. )
Comment: It better to focus on the divisibility $p^2-1 \mid (p-2)!$ than trying to find a solution to the equation.
Comment: Welcome to MSE. Remember to include your work on the problem, otherwise it looks like you are trying to get others to do your homework.
Comment: just solve the equation: $k=(1+\frac{(p-2)!}{(p-1)(p+1)})/p$.
Comment: @DavidC.Ullrich But then how do you know $k$ is an integer?
Comment: Are there any conditions on $p$? Because if p=3 then we get $(3k-1)(2)(4)=1!$
Comment: @IrbidMath That only mean that for $p=3$ there's no solution. The OP didn't claim that always were one.
Comment: I want to find all primes where there is a solution for $k$.
Comment: @jjagmath then the question should said find $p$ prime and $k$ integer such that...
Comment: @IrbidMath No, it shouldn't. Because then $p=11, k=275$ would solve the problem. But the OP wants to know for which primes there is such $k$
Answer: Hint: Study the small cases first. Then use that $$\left(\frac{p-1}{2}, \frac{p+1}{2}\right)=1$$


Derby : No Current Connect?

Question: I am using derby for database. and my normal insert/update operation is working fine. But some times while insert query I am getting "No Current Connect" error message.
I searched about it but not found proper solution.
Do any one knows why this exception occurred ?
Thanks
Tej
Comment: Are you closing your connections properly once you are done with them?
Comment: "No Current Connect" is the error you get ?? or any other wording?
Comment: I believe it will be "No Current Connection"
Answer: its caused when you are trying to execute operations on a closed connection object.
So you need to check if the connection is closed, if so ..then connect again:-
<code>public Connection getConnection() throws SQLException {
    if(connection==null || connection.isClosed()) {
        connect();
    }
    return connection;
}

private void connect() throws SQLException {
    try {
        connection = DriverManager.getConnection(DBURL);
        logger.info("database connection established");
    } catch (SQLException e) {
        logger.error(e.getMessage());
        throw e;
    }
}
</code>

Derby : No Current Connect?


Boxplots as tables

Question: We are preparing a manuscript and the editor asked us to convert a figure with a boxplot into a table "because of the more exact data content". While I think boxplots are pretty decent in revealing something about the data, I was wondering what you guys think about this? Do you (often) opt for tables over boxplots for presenting your data?
Answer: I tend to think that boxplots will convey more effective information if there are numerous empirical distributions that you want to summarize into a single figure. If you only have two or three groups, editors may ask you to provide numerical summaries instead, either because it is more suitable for the journal policy, or because readers won't gain much insight into the data from a figure. If you provide the three quartiles, range, and optionally the mean $\pm$ SD, then an advertised reader should have a clear idea of the shape of the distribution (symmetry, presence of outlying values, etc.).
I would suggest two critical reviews by Andrew Gelman (the first goes the other way around, but still it provides insightful ideas):

Gelman, A, Pasarica, C, and Dodhia, R. Let's practice what we preach. The American Statistician (2002) 56(2): 121-130.
Gelman, A. Why Tables are Really Much Better than Graphs. (also discussed on his blog)
Answer: It depends on your objective, if it is a quick visualization I will stick with boxplot but if it is a more detailed examination I would stay with the data

Boxplots as tables


Sketching phase portrait of an ellipse

Question: I have a system of linear ODE's as follows:
$$\frac{dx}{dt} = y, \frac{dy}{dt} = -4x$$
which has solution
$$\begin{bmatrix}x\\y\end{bmatrix} = \alpha\begin{bmatrix}\cos2t\\-2\sin2t\end{bmatrix} + \beta\begin{bmatrix}\sin2t\\2\cos2t\end{bmatrix}$$
And I'm having some issues trying to sketch the phase portrait.
I know the eigenvalues are $-2i$ and $+2i$
Clearly this means the critical point $(0,0)$ is a "centre" of ellipses.
But I don't know how to find the indicative equation of one of the solution curves.
In other words, how do I find the shape of the ellipses? How do I know which of x,y is the major and minor axis of the ellipses?
Thanks.
Answer: $$
     \frac{d}{dt}\{ 4x^{2}+y^{2}\} = 8x\frac{d x}{dt}+2y\frac{dy}{dt}=8xy-8yx=0.
$$
Therefore, $4x^{2}+y^{2}=C$ is constant in time.
Comment: How did you get to 4x^2 + y^2?
Comment: I'm sorry, I don't understand what you did here.
Comment: @PythonNewb : What step do you not understand?
Comment: I don't get where that first equation for d/dt came from
Comment: @PythonNewb : The first equality comes from the chain rule. The second equality comes from your stated differential equations. The conclusion is that any solution $\left[\begin{array}{c}x(t) \\ y(t)\end{array}\right]$ of the differential equation must satisfy $4x^{2}+y^{2}\equiv C$ is constant, which is the equation of an ellipse.
Comment: @PythonNewb : Experience. The 0 on the far right is because of dotting the tangent to the curve with the normal to the curve. For a circle you know what the tangent and normal must be. An axis-aligned ellipse comes from scaling one of the two coordinates; so you can adjust a little.

Sketching phase portrait of an ellipse


gaussian integral solution..error in logic?

Question: Why oh why have I never seen anyone mention the apparent flaw in the logic of solving this integral by squaring it?? When you make the second integral integrable over y, yes y is just the name of the variable so it be du, dt, etc. anything BUT when you change to polar coordinates x and y have specific and DIFFERENT definitions.. x=rcos theta and y=rsin theta..Thus x and y do NOT euqal each other and therefore e^-x^2 times e^-y^2 is NOT the same as the square of e^-x^2..because when you square something it means you multiply it by ITSELF and sin theta does not always equal cos theta..Therefore the integral e^-x^2 dx does NOT equal the integral e^-y^2dy..only when theta equals 45 degrees or some multiple of it do the sin theta and cos theta terms equal and cancel each other and thus the x and y exponents would be equal and this would work..andOtherwise has no one ever aksed wy they cant solve it using e^-2rcos theta^2 ...by truly squaring the e^-x^2 integral..I don't see any flaw in my reasoning so can someone please explain if and why I am wrong..does it have to do with the power series expression for pi happening to work only for angles where cos theta and sin theta are equal or cancel each other?? Please someone answer Thanks in advance.
Comment: @Leif: [Please see here](http://meta.math.stackexchange.com/q/5020/264) for a guide to writing math with MathJax, and [see here](http://math.stackexchange.com/help/formatting) for a guide to formatting posts with Markdown.
Comment: The main idea of the proof is geometric: we find the "volume" under the surface $z=e^{-(x^2+y^2)}$ and above the $x$-$y$ plane in two different ways, by rectangular coordinates integration and by polar coordinates integration.
Comment: Your question will be more readable if you break it up into paragraphs.
Answer: Answering by a finite analogy with integrals replaced by sums.
Surely you know that
$$
S=\sum_{n=1}^3n=1+2+3=6,
$$
and also that
$$\sum_{m=1}^3m=1+2+3=6=S.$$
Notice that there is no need to declare that $(m,n)$ should be on the
line with $\phi=\pi/4$. We never studied $m$ and $n$ together here.
It should not be a surprise that the double sum
$$
\sum_{n=1}^3\sum_{m=1}^3mn=36=\left(\sum_{n=1}^3n\right)\left(\sum_{m=1}^3m\right)=S^2.
$$
Let's check:
$$
\sum_{1\le m.n\le 3}mn=(1+2+3)+(2+4+6)+(3+6+9)=6+12+18=36=S^2.
$$
This was just the distributive law of multiplication and addition of integers at work.
Do notice that we can compute the last sum also by grouping together the terms, where $m+n$ is a constant:
$$
\sum_{1\le m,n\le 3}mn=(1)+(2+2)+(3+4+3)+(6+6)+(9)=36.
$$
Here the second group $2\cdot1+1\cdot2$, the third group $3\cdot1+2\cdot2+1\cdot3$ et cetera.
Basically that's what happening here. Except that in this case we were unable to calculate the value of $S$ directly, but we are able to calculate the value of $S^2$ after writing it as a double sum, and then regrouping according to the value of $x^2+y^2$. There are tons of technical details, because we are dealing with an integral: convergence, Jacobian, et cetera. But the basic idea is similar.
Answer: Which of the following is equal to $\left[\int_a^b f(x)\,dx\right]^2,$
$$
\int_a^b\left[f(x)\right]^2\,dx\qquad\text{or}\qquad\int_a^bdx\int_a^bdy\,f(x)f(y)?
$$
If you answered the first one, then that is at the root of your difficulties in understanding the computation of $\int_{-\infty}^\infty e^{-x^2}\,dx.$  If that is indeed the problem, I would recommend trying some examples where you can compute all three integrals by hand, such as $f(x)=x^2$ with limits $a=0,$ $b=1.$
It should be said that your statement that $x\ne y$ is right, as is your statement that $e^{−x^2}\ne e^{−y^2}.$  In fact, how could they be equal in general?  Both $x$ and $y$ are variables, so they can take different values, which will generally not be the same.  When the integrals $\int_{-\infty}^\infty e^{-x^2}\,dx$ and $\int_{-\infty}^\infty e^{-y^2}\,dy$ are performed (taking a Riemann-sum point of view), $x$ and $y$ independently take on all the values between $-\infty$ and $\infty.$  While the variables and the integrands are not equal, the integrals are equal, since, as you pointed out, $x$ and $y$ are just different names for the integration variable.
It doesn't make sense to replace the variable $x$ in $\int_{-\infty}^\infty e^{-x^2}\,dx$ with $r\cos\theta.$  This replacement only makes sense in the context of the double integral $\int_{-\infty}^\infty dx\int_{-\infty}^\infty dy\, e^{-(x^2+y^2),}$ where $y$ would be replaced by $r\sin\theta$ at the same time.  Since the $x$-axis corresponds to $\theta=0,$ it would make sense to replace $x$ with $r\cos 0,$ but this just amounts to renaming $x$ to $r.$


Traveling Salesman with exceptions

Question: Assume a regular TSP problem with n cities. However, in this particular problem, we do not have to visit all the n cities, only a specific subset of them, m, where m<=n. The cities in n but not in m don't need to be visited, but they might if the path m1->m2 is larger than m1->n1->m2 for example.
Is this problem still NP-hard ? If yes, to which problem can it be reduced to or what proof could be used to show that it's still NP-hard?
Thanks in advance.
EDIT: m >= 3. We have at least an starting city, an ending city and m-2 cities in between that must be visited.
Comment: If m=n is a particular case of your problem then it's trivially NP-hard...
Comment: How are $m,n$ related?
Comment: **m** is a subset of **n**. **m** <= **n**.
If **m=n**, than its the regular TSP. The problem is when **m<n**.
Comment: This is essentially the traveling salesman problem on $m$ cities. It is *exactly* the same as the usual problem on $m$ cities if the distances between cities forms a metric space. Otherwise, we can more or less just find the shortest path between each pair of cities and use that as the distance between them (but this runs into problems too since we shouldn't traverse cities twice). It would certainly seem to be at least as hard as the usual problem on $m$ cities.
Comment: The particularity of stating that *m* is a subset of *n* is that two cities in *m* could not have any path between them in *m*.
Answer: This problem, as stated, is too vague to answer.  What is critical is the relationship between $m,n$.  If $m=n$, then this is identical to TSP.  If $m=n-1$ or similar, it is polynomially equivalent to TSP.  If $m=2$, then the problem is polynomial-time: find the shortest path between the two vertices with Dijkstra's algorithm.
Comment: I see, thanks! In this particular case **m>=3** (We have at least a starting city, an ending city and a city in-between that must be visited.) polynomially equivalent to TSP then, right?
Comment: With any constant $m$ it's still polynomial.  You can use Dijkstra's algorithm to find the shortest path between any two vertices of $m$, then do a mini-TSP on those $m$ vertices.  The point of NP-hard is that $n$ is growing to infinity, and we are watching how the algorithm slows down as $n$ does so.

Traveling Salesman with exceptions


What's the role of domain compactness in the Ascoli-Arzela theorem?

Question: The problem
From what I've read in the literature I get the idea that domain compactness is quite crucial in the theorem, and yet looking at the proof it seems to me as an unnecessary assumption. I surmise I'm probably missing an important part of the picture. In order to fix some notation and say what I mean precisely, allow me to repeat the proof down here. I will assume we are all familiar with the notions of equicontinuity and uniform boundedness.
The theorem
If a family $\mathcal{F}$ of functions from [a,b] to $\mathbb{R}$ is uniformly bounded and  uniformly equicontinuous, then every sequence of functions in $\mathcal{F}$ admits a convergent subsequence.
Proof. Let us fix a sequence $(f_n)\subseteq\mathcal{F}$ and an enumeration $(q_n)$ of the rationals in $[a,b]$. Since the numeric sequence $\big(f_n(q_0)\big)_{n\in\mathbb{N}}$ is bounded, by the Bolzano-Weierstrass theorem, it admits a convergent subsequence $\big(f_{n_k}(q_0)\big)_{k\in\mathbb{N}}$, which defines a corresponding subsequence of functions $(f_{n_k})_{k\in\mathbb{N}}$. By the same token, the numeric sequence $\big(f_{n_k}(q_1)\big)_{k\in\mathbb{N}}$ admits a convergent subsequence $\big(f_{n_k}^{(1)}(q_1)\big)_{k\in\mathbb{N}}$, to which corresponds the subsequence of functions $(f_{n_k}^{(1)})_{k\in\mathbb{N}}$, and so on. Iterating this process by induction, we get an infinite chain of nested subsequences
\begin{equation}
(f_{n_k})_{k\in\mathbb{N}}\supseteq (f_{n_k}^{(1)})_{k\in\mathbb{N}}\supseteq (f_{n_k}^{(2)})_{k\in\mathbb{N}}\supseteq (f_{n_k}^{(3)})_{k\in\mathbb{N}}\supseteq \,...
\end{equation}
Consider now the `diagonal' subsequence $(f_{n_k}^{(k)})_{k\in\mathbb{N}}$. By construction, this sequence of functions converges at all rational points in $[a,b]$. Therefore, given a $q_m$ and an $\epsilon>0$ there is a $\nu\in\mathbb{N}$ such that
\begin{equation}
|f_{n_k}^{(k)}(q_m)-f_{n_h}^{(h)}(q_m)| \le \frac{\epsilon}{3},
\end{equation}
for all $k,h\ge\nu$. Furthermore by the uniform equicontinuity of $\mathcal{F}$, for any $x\in [a,b]$ there is an interval $J_x$ such that
\begin{equation}
|f_{n_k}^{(k)}(y)-f_{n_k}^{(k)}(z)| \le \frac{\epsilon}{3},
\end{equation}
for all $y,z\in J_x$ and all $k\in\mathbb{N}$. (#) These intervals form an open cover of $[a,b]$ from which we can extract a finite subcover $\{J_{x_1},\,...,J_{x_p}\}$. By the density of $\mathbb{Q}$, each of these intervals contains a point of $(q_m)$, and thus there is an $M\in\mathbb{N}$ such that every interval of the finite subcover contains a rational $q_m$ with $0\le m\le M$. Moreover, for any $x\in[a,b]$ there is a $J_{x_j}$ with $1\le j\le p$ containing a $q_m$ with $1\le m\le M$. (#) But then, chosen a $q_m$ lying in the same interval as $x$ and $k,h$ sufficiently large,
\begin{align}
&|f_{n_k}^{(k)}(x)-f_{n_h}^{(h)}(x)| \le\nonumber\\
&|f_{n_k}^{(k)}(x)-f_{n_k}^{(h)}(q_m)| + |f_{n_k}^{(k)}(q_m)-f_{n_h}^{(h)}(q_m)| + |f_{n_h}^{(h)}(q_m)-f_{n_h}^{(h)}(x)| \le\nonumber\\
&\hspace{3.5cm}\le\frac{\epsilon}{3} + \frac{\epsilon}{3} + \frac{\epsilon}{3} = \epsilon,
\end{align}
therefore the sequence is uniformly Cauchy and thus $(f_{n_k}^{(k)})_{k\in\mathbb{N}}$ converges uniformly.
The question
The entire part enclosed by the symbol (#) seems completely inessential to me. Why can't we just say that by the density of rationals, $J_x$ contains some $q_m$ and be done with it? If that was the case we would not even need to assume compactness to begin with! What am I missing here?
Comment: The theorem @MoisheKohan is gently mentioning does not give uniform convergence. If we are ok with locally uniform convergence, then we don't need compactness of the interval (or the metric space). If instead we want uniform convergence, we need compactness. It is not clear from the theorem stated by the OP whether uniform convergence is inthe thesis or not, I think that's the main point of the discussion.
Comment: I don't see how the argument is "done" using just that $q_m$ is dense. Can you elaborate?
Comment: What you are proposing will only give uniform convergence locally.  Consider what would happen if $f_{n}(x) = x/n$ and the domain is $\mathbb{R}$.
Comment: By density I should be able to find a $q_m$ inside $J_x$ which then allows me to use the first inequality as well as the second.
Comment: @PeterMorfe You need a bounded (counter)-examples.
Comment: A-A theorem holds in much greater generality, it suffices to have a **locally compact**  domain, e.g. ${\mathbb R}$, see a reference [here](https://math.stackexchange.com/questions/20670/theorem-of-arzel%C3%A0-ascoli). Whoever wrote that compactness of the domain is *critical* should have done a better job here.
Comment: It is clear that the proof is dealing with uniform convergence though. So, the theorem should probably state it.
Comment: @ArcticChar, so $f_{n}(x) = \sin(x/n)$ instead.
Comment: @LorenzoPompili: You are right, I did not read the question in all the detail, only the two introductory paragraphs.
Comment: @LorenzoPompili I want to understantand if we can prove any form of convergence at all, and what the role of compactness is. So if I'm not mistaken you seem to think my argument is correct and compactness is only needed to ensure the convergence is uniform?
Comment: @PeterMorfe so what you're getting at is that without compactness the domain of convergence might be smaller than [a,b]?
Answer: I think an answer might go as follows. The theorem you wrote doesn't say in which sense the subsequence converges.
If the theorem states that there exists a uniformly converging subsequence, then you need that the interval is at least bounded, see the example by Peter Morfe in the comments.
There are also "almost" counterexamples for bounded non-closed intervals, which are more subtle: the sequence
$$f_n\colon [0,1)\to\mathbb R,\;\;\;f_n(x)=\sin(\tan(2x/\pi)/n)$$
is uniformly bounded and equicontinuous, but not uniformly equicontinuous (check the difference e.g. here https://en.wikipedia.org/wiki/Equicontinuity) and it doesn't go to 0 uniformly, but only locally uniformly.
On the other hand, if you ask for uniform equicontinuity of the family of functions (as the theorem actually does), I think the theorem still works for bounded non-compact intervals, such as $[a,b)$. In fact, from uniform equicontinuity you have in particular uniform continuity, which implies that you can extend the functions of your family $\mathcal F$ uniquely to be continuous functions on the closure of the domain. It is then an easy check that this new family of functions is still uniformly bounded and uniformly equicontinuous, but this time you are on a compact interval, so you can apply the theorem for the compact case and conclude.
It seems to me that in the proof you provided, if we are dealing with a bounded interval, what you say is enough and we don't need the part enclosed in (#).
In case you want the theorem to state that the convergence is locally uniform, you just don't need anything, as any interval is locally compact (see the theorem linked by Moishe Kohan). This also implies pointwise convergence, for which I think again what you say in the question (convergence on all rationals+equicontinuity) is enough. But I might miss something, maybe someone could elaborate more on this point.
Comment: See also the comments of Daniel Fisher in this post: https://math.stackexchange.com/questions/2623481/arzelá-ascoli-theorem-precompact-sets


Drupal 7 + Services : Error 500 on user registration (Integrity constraint violation: 1048 Column 'uid' cannot be null)

Question: I'm still working on user registration with Drupal 7 and Services 3 and I got a weird Error 500 :

Integrity constraint violation: 1048 Column 'uid' cannot be null

Here is the code I'm using :
<code>// REST Server URL for auth
$request_url = SERVER_URL . 'rest/user/register';

// User data
$user_data = array(
  'name' => 'newuser',
  'mail' => 'firstname.lastname@example.com',
  'pass' => 'newpass',
  'field_city' => array('und' => array('0' => array('value' => 'NA'))),
);

$user_data = json_encode($user_data);
// cURL
$curl = curl_init($request_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json'));
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $user_data);
curl_setopt($curl, CURLOPT_HEADER, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_VERBOSE, true);

$response = curl_exec($curl);

$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  if ($http_code == 200) {
  return json_decode($response);
}
else {
  $http_message = curl_error($curl);
  return $http_message;
}
</code>
Is there something I'm doing wrong ?
Comment: It says you can't set `uid` to null, or omit it. But I don't see where you are setting it. So it looks like you *are* omitting it. Or am I missing something? Also, for `uid` there should be some kind of auto increment and `null` should be allowed, and mean "generate next one". Was you altering things directly in database?
Comment: Hello Molot and thanks for your quick comment, but I didn't know the uid at that point, cause I'm trying to create the user, so I can't pass it to $user_data.

The table "users" isn't auto-incremented and Null is not allowed, but this is not a problem when I create a new user with the Drupal form or with Drush.

This error only appears when I try to create a user using Services, and I prefer not to alter this table.
Answer: I think that on the other side of your code you are trying to save the user. So, to create a new user using user_save() function you have to left the first parameter blank so a new user is created. Also, add the parameter true to your json_decode($response, true) to obtain an array rather than an object.
$account = user_save('', $fields);
Comment: Hello MMC, yes I'm trying to save the user but with Drupal Services API.

So I won't use `user_save()` neither bootstrap Drupal.


How to change programmatically the link of a field in a View

Question: I have a View, with a hidden field with a URL, and an image field which has the following property:
Output this field as a link and linked to the URL field: [field_url_slider] and _blank as Target.
I want to change dynamically the behaviour, so when the image is a given one, to rewrite programatically the URL and also the Target.
In hoo_views_pre_render don't see how to do it, because the complete link, i.e. a href="", etc. is not any data of view->result and I don't know if this can be achieved via $view->display (I only want to change a result). So, in a few words, I want to change the HTML output of the Views display for just a result.
Answer: I have finally solved using hook_views_pre_render and setting the display of one of the fields to "do not display", and adding as pure HTML around the field, replacing the content with the other field. In other words, by writing at low level the link of the field.
Surely there must be another way of doing this.


Devo liberar toda a memória alocada ao terminar um programa?

Question: É comumente aceito que quando eu aloco um bloco de memória eu sou o responsável por liberar-lo. Isso é particularmente verdade quando programando baseado em RAII. No entanto o seguinte programa funciona perfeitamente:
int main() {
    int* ptr = new int[99999];
    return 0;
}

Aqui o sistema deve ser capaz de liberar tudo que o processo alocou.
O que é considerado boa prática aqui? Devo sempre liberar a memória que eu aloco? Há algum problema/vantagem em deixar esse trabalho para o sistema?
Comment: Se o Dollynho Programador diz que você pode deixar alocado sim quando o programa é encerrado, então é porque você TEM que desalocar quando o programa encerra XD
Answer: Um ponto a se considerar é que código que hoje em dia é um programa completo pode eventualmente ser refatorado para se tornar uma funcionalidade de outro programa maior. Se o programa original não se preocupava em liberar os recursos (por que o SO ia fazer isso por ele), agora ele vai começar a gerar um leak no programa maior cada vez que sua funcionalidade for executada. Muitas horas de depuração vão ser perdidas até identificar a origem do problema, e mais ainda refatorando o código original para se comportar direito.
Comment: Essa é a resposta certa. Não é boa prática, mesmo que o SO te ajude a evitar problemas maiores. Em algum momento, você vai ter que resolver um vazamento de memória por isso.
Comment: @GuilhermeBernal Quando você mais de 4 GB alocados, talvez não ache que a quebra de modularidade seja cara demais.
Comment: Se o preço a pagar pela finalização rápida é a quebra de modularidade, é claramente caro demais. Esse ponto eu não havia levado em consideração.
Answer: Não considero uma boa prática deixar o sistema liberar todos os recursos que foram alocados pelo programa. Devo lembrar que memória é apenas um dos recursos que o sistema deve gerenciar e se, o único recurso que o seu programa usa é somente memória, o que eu acho pouco provável em programas de médio ou grande porte, ainda assim, não considero uma boa prática.
A função exit, conforme resposta dada pelo próprio autor, deve ser utilizada com cautela e deve-se saber de seus efeitos colaterais. Um dos problemas de se utilizá-la é:

Criação de múltiplos pontos de saída de um programa, o qual pode dificultar o debug;
Pode dificultar a leitura de um programa, no fundo, equivale a múltiplos goto para o fim do programa;
Não libera os recursos de forma clara e limpa.

Na verdade, chamo a atenção para o fato que chamar a função exit é diferente do que chamar a instrução return ao final do programa main. Enquanto a instrução return realiza o "desempilhamento do pilha (unwind stack)", o que permite chamar todos os destrutores do objetos locais, a função exit não o faz, o que pode causar erros de lógica, não facilmente detectáveis em um debug.
Chamo a atenção também que a ideia de deixar o SO cuidar de liberar os recursos só acontece em SOs "modernos". Em SOs, como os do tipo do FreeRTOS é de total resposabilidade do programador liberar os recursos alocados.
Novamente, volto a questão de que a memória é apenas uns dos recursos gerenciados. SOs modernos liberam todos os recursos alocados pelo programa, no fechamento do processo, não importando o estado em que se encontram (se tiver que fazer um flush num arquivo, para salvar os dados, isso não acontecerá no encerramento do processo). O autor, em sua resposta, sugere a criação de callbacks ou um sistema de mensagens para auxiliar o processo. Considero que isso apenas complica a lógica do sistema. Acho um preço muito baixo deixar o sistema fazer a destruição automática de todos os objetos de forma clara, limpa e segura, mesmo que isso acarrete retirar a memória do swap. E visualizando os sistemas de hardware atuais, onde memória é um recurso que pode ser considerado abundante, não justifica todas essa lógica a mais.
Comment: Como sempre, tudo tem o seu contexto. `memória é um recurso que pode ser considerado abundante` não é verdade para desenvolvimento embarcado, como em celulares. Ainda assim, concordo com todo o resto de sua resposta.
Answer: Em qualquer sistema operacional moderno é utilizado o recurso de páginas virtuais de memória. Nesse modelo cada processo é dono de todo um espaço de endereçamento e o sistema tem a responsabilidade de mapear o endereço que o processo quer ler para o endereço em que aquela memória realmente está. Isso dá ao sistema diversas oportunidades de otimização úteis, como colocar páginas não usadas no disco (swap), as resgatando quando forem requeridas, ou aplicar o copy-on-write (CoW) em que dois processos compartilham a mesma página.
Dessa forma o sistema já sabe exatamente qual memória pertence a cada processo. E liberar essa memória é tão simples quanto a marcar como uma página lixo que pode ser reaproveitada em outro processo. Ou seja, para qualquer computador moderno, terminar um processo significa liberar toda a sua memória.
Considerando um programa grande, existes diversos problemas quando você aperta em "fechar". O destrutor de todos os objetos serão executados em sequencia, fazendo com que um monte de memória semimorta seja acessada e tenha que ser lida do disco (caso tenha acontecido algum swap) e causando lentidão visível ao usuário final. Está se gastando a vida útil do HD enquanto se desperdiça o tempo do utilizador, tudo errado. Isso apenas para liberar recursos que já serão liberados de qualquer forma pelo sistema, e de forma mais eficiente (libera páginas em vez de liberar objeto por objeto, e não precisa ler dados do disco).
Já se isso é boa prática, é questionável. O design da orientação a objetos espera que tudo que for construído seja, em algum momento, destruído. Então pode acontecer de haver alguma lógica importante acontecendo no destrutor, como salvar configurações no disco. Nesse caso meramente chamar exit(0) pode ser danoso. Outra forma seria ter uma variável global booleana que seja verdadeira quando o processo está prestes a se encerrar e fazer cada destrutor verificar essa variável, pulando liberações desnecessárias de memória. Mas aqui há pouca vantagem porque um monte de memória precisará ser lida de qualquer forma (voltamos ao swap) e a lógica de destruição se complica e fica não trivial.
Uma solução pode ser ter um mecanismo de notificação que envie algum tipo de sinal a todos os objetos que precisem fazer algo mais na terminação do programa. Pode ser uma lista de callbacks por exemplo. Essa é provavelmente a maneira mais eficiente que não quebra completamente a estrutura orientada a objetos.
O grande problema é que ferramentas que detectam leak vão acusar um monte de problemas no seu programa. Daí é interessante ter dois caminhos de terminação, um desalocando tudo (para debug) e outro indo direto ao exit(0). Os dois devem ser igualmente testados, claro. Mas o segundo não precisa passar pelo leak detector.
Mas se lembre que existem outros recursos que não a memória. Os mecanismos de comunicação inter-processual do System V (disponível em alguns *nix, incluindo o linux), por exemplo, são permanentes e sobrevivem a terminação do processo by-design. Para eles é essencial liberar.
Toda essa discussão só é válida para linguagens onde você programador faz o manejo da memória. Para linguagens com coletor de lixo geralmente não haverá muita escolha.