Iterating substitution question (Matlab)

Question: I have four relations between A and B as below.
A(i)= B(i) + B(i-1)
B(i)= A(i) + A(i-2)
A(i)= B(i-1) + A(i-2)
B(i)= B(i-1) + A(i-2)
Assume i is 7 and A(7),A(0),B(7),B(0) are known. (Just for easier calculation here, so that my iteration will be from 7 to 0) And I will need to determine A(4),B(4). I will need to solve this in Matlab as I will need to change i to a much bigger number.
Now what I got is as below.
A(7) = B(6) + A(5)
<code>=B(5)+A(4) + B(4)+A(3) (using equation 3 and 4)
=B(4)+A(3) + B(3)+A(2) + B(3)+A(2) + B(2)+A(1) (using equation 3 and 4)
=B(3)+A(2) + B(2)+A(1) + B(2)+A(1) + B(1)+A(0) + B(2)+A(1) + B(1)+A(0)
 + B(1)+A(0) + B(1)+B(0)  (using equation 1,3,4. When it comes to A(1),
 we have to switch to equation 1 to prevent A(-1))
=B(2)+A(1) + B(1)+A(0) + B(1)+A(0) + B(1)+B(0) + B(1)+A(0) + B(1)+B(0)
 + B(1) + A(0) + B(1)+A(0) + B(1)+B(0) + B(1) + A(0) + B(1) + A(0) +B(1)
 + B(0)
= 12B(1)+7A(0)+5B(0)
</code>
Using the same way,
A(6)=8B(1)+4A(0)+3B(0)
A(5)=3B(1)+3A(0)+2B(0)
A(4)=3B(1)+2A(0)+B(0)
A(3)=2B(1)+A(0)+B(0)
A(2)=B(1)+A(0)
Originally my idea was trying to iterate in the way that when i of A(i) or B(i) is bigger than 1, then it will substitute in equation 3 and 4. While i is equal to 1, then it will substitute in equation 1 and 2. This process will keep iterating until the equation is left with one unknown.
Thank you so much.
Comment: [Here's a MathJax tutorial](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) :)
Answer: A(i)= B(i) + B(i-1)
B(i)= A(i) + A(i-2)
A(i)= B(i-1) + A(i-2)
B(i)= B(i-1) + A(i-2)
From your first and third equations, $B(i)=A(i-2)$.  Then from your second equation, $A(i)=0$.
Comment: Thanks for the answer, I think I made some mistakes here. From the original problem, there is only equation 3 and 4, and using substitution, I formed equation 1 and 2 and I just ignored the coefficients just for easier calculation. Is it possible to solve just using the last two equation?
Comment: A(i)=B(i), then both are Fibonacci-type numbers.


Best pratice to free allocated memory on SIGINT

Question: I have a simple program which uses select and stuff like that for multiplexing IO.
To interrupt the "server" process, I integrated a sig_handler which reacts on SIGINT.
Each time when memory is allocated, the containing method does the free itself or the calling method.
Using valgrind shows up, that there are some allocation aren't freed up.
Perhaps there is no need for it, but I want to learn what would be the best way to handle the signal.
It seems that the free calls aren't invoked when pressing STRG + C.
So it would be senseless to quit loops with a break condition, which was my first approach.
Is there any possibility to clean every thing up, before closing the whole program?
Thanks for any hints and advices.
Comment: There is no need to do this if you plan to exit. Only if you plan to continue then there is a need to ensure there is no leak.
Answer: Valgrind is just a tool for finding memory leaks, not an oracle whose advice must be heeded.  Making a program "Valgrind-clean" is a worthy goal but don't let it get out of hand.  Ask yourself some questions about the program.

Does the program need to do anything when it receives a SIGINT or SIGQUIT or whatever?  Does it need to do some kind of clean shutdown?  For example, a server might decide to finish handling all open requests, or at least send a shutdown message to connected clients.
Does a sudden termination always leave behind certain blocks?  Then you can just quash those reports from Valgrind, without having to spend extra time freeing memory that's already going to be freed.

In simple terms, there are only two reasons to call free in a program that is about to exit.

If it's the easiest way to quash Valgrind messages (that is, without reading the Valgrind manual)
If it makes your code simpler.

Otherwise, just don't call free during program exit, since all it will do is burn CPU cycles.
Handling SIGINT: I can think of four common ways to handle a SIGINT:

Use the default handler.  Highly recommended, this requires the least amount of code and is unlikely to result in any abnormal program behavior.  Your program will simply exit.
Use longjmp to exit immediately.  This is for folk who like to ride fast motorcycles without helmets.  It's like playing Russian roulette with library calls.  Not recommended.
Set a flag, and interrupt the main loop's pselect/ppoll.  This is a pain to get right, since you have to twiddle with signal masks.  You want to interrupt pselect/ppoll only, and not non-reentrant functions like malloc or free, so you have to be very careful with things like signal masks.  Not recommended.  You have to use pselect/ppoll instead of select/poll, because the "p" versions can set the signal mask atomically.  If you use select or poll, a signal can arrive after you check the flag but before you call select/poll, this is bad.
Create a pipe to communicate between the main thread and the signal handler.  Always include this pipe in the call to select/poll.  The signal handler simply writes one byte to the pipe, and if the main loop successfully reads one byte from the other end, then it exits cleanly.  Highly recommended.  You can also have the signal handler uninstall itself, so an impatient user can hit CTRL+C twice to get an immediate exit.

The two simplest and most fool-proof methods are #1 and #4.
A program that exits does not have any leaks.  Only a running program can have leaks.  Once the program exits, all memory is freed (so there is no leak any more).
Comment: +1 for "A program that exits does not have any leaks." Love it.
Comment: With that said, I think your answer could be even better if it addressed async-signal-safety and the dangers of trying to free memory from an async signal handler.
Answer: Here's my simple and slightly dirty solution.
#include <signal.h>

volatile bool gContinue;

void handleCtrlC(int ) {
    gContinue = false;
}

int main () {
    gContinue = true;

    signal(SIGINT, handleCtrlC);

   ... allocate memory ...

    sigset_t sigmask;
    sigemptyset (&sigmask);

    while (gContinue) {

        /*...*/
        ready = pselect(nfds, &readfds, &writefds, &exceptfds,
            timeout, &sigmask);
        /*...*/
    }

    ... free memory ...

    return 0;
}

Edit: Added pselect to the loop.
Comment: I think `gContinue` has to be `volatile`.  I don't know who told you global variables are "bad", but you should stop listening to them.  This is exactly the kind of problem global variables are good for.
Comment: Thanks.  I'll add volatile and remove the comment.
Comment: BTW, I don't have the ability to comment on the other answer, but I think you don't need sigprocmask when using pselect.  This is new information to me, but I think sigprocmask is used with select like this. sigprocmask(SIG_SETMASK, &sigmask, &origmask);
 ready = select(nfds, &readfds, &writefds, &exceptfds, timeout);
 sigprocmask(SIG_SETMASK, &origmask, NULL);
Comment: The idea behind `pselect` is that you can block signals, check the flag, then unblock them during the `pselect` call.  If you block signals during the `pselect` call, as in your current example, the call won't be interrupted.  But you *want* to interrupt the call.  So you'll typically pass `pselect` a relatively empty signal mask.
Answer: Adam Hunt's suggestion will work, provided that you add a check for the flag just before your call to select. It must be immediately before because your normal EINTR handling would likely skip over the check otherwise, so the exiting would be delayed until your next select returned a real event.
while (gContinue) {
    /*set up some stuff for next select call*/
    do {
        if (gContinue == 0) break;
        nfds = select(...);
    } while (nfds == -1 && errno == EINTR);
    /*handle select return*/
}

Edit: Dietrich Epp points out there is a race condition between the flag check and the select call that can only be closed by a call to pselect. pselect is very similar to select, with the primary difference being the last parameter is used as a mask to determine which signals to block. So the code sample below closes the race between the flag check and the pselect call:
sigset_t emptyset, blockset, origset;
sigemptyset(&emptyset);
sigemptyset(&blockset);
sigaddset(&blockset, SIGINT);

while (gContinue) {
    /*...*/
    sigprocmask(SIG_BLOCK, &blockset, &origset);
    do {
        if (gContinue == 0) break;
        nfds = pselect(..., &emptyset);
    } while (nfds == -1 && errno == EINTR);
    sigprocmask(SIG_SETMASK, &origset, NULL);
    /*...*/
};

Another approach is to register all your allocated elements to a global data structure, so that they can be freed by an atexit handler that you install. If you end up in code that will deallocate it, unregister it from the global data structure first;
m = malloc(sz);
register_allocation(m);
/*...*/
unregister_allocation(m);
free(m);

And using atexit:
void cleanup_allocations () {
    /*...*/
}

atexit(cleanup_allocations);

Comment: Note that this kind of situation is exactly why we have `pselect`.  You can't avoid a race between checking the flag and calling `select`, so you **must** use `pselect` unless you want to lose some of your SIGINT.
Comment: The `atexit` thing is just silly though, since all you're doing is quashing Valgrind messages without figuring out if they're real leaks or not.  You might as well just disable Valgrind's leak checking, since that's what you're doing.
Comment: @DietrichEpp: I'll edit my answer for `pselect`, thanks for the info. The `atexit` usage just depends on the goals of the OP. It could be used as an independent memory manager with its own leak detection that is always on and queryable, even in deployed code.


What is the D7 equivalent of CCK "content_instance_tablename" in db_query?

Question: I am porting a D6 module to D7 which deals with controlling field access of CCK fields. I can now successfully enable my port without any errors but receive a fatal error when trying to create new content.
The issue is the the "content_table_instance" in db_query which as far as I understand no longer exists in D7 due to the CCK --> Fields move. I am having a lot of trouble finding exactly what the alternative of "content_table_instance" is in D7. Any suggestions?
Here is the section of the code:
$result = db_query("SELECT nfi.field_name, nfi.label
  FROM {" . content_instance_tablename() . "} nfi
    INNER JOIN {" . content_field_tablename() . "} nf ON nfi.field_name = nf.field_name
  WHERE nfi.type_name = '%s' AND nf.active = 1 AND nf.locked = 0", $type_name);

Answer: Both functions in your code (content_field_tablename() and content_instance_tablename()) just return a string based on the version number of the CCK module.
The Drupal 7 equivalents would be the field_config and field_config_instance tables respectively, as defined in field_schema.
Remember fields can be attached to any entity in Drupal 7 (not just nodes) so you'll need to change your code accordingly.
If you're using this query to get information about the field metadata you might want to use one of the Field Info API functions instead, e.g.
$all_field_instance_data = field_info_instances();

or
$single_field_instance_data = field_info_instance('node', 'field_some_field', 'article');

Comment: That's ok, thank you anyway. Hopefully, if I manage to get this together I can make it available for everyone else also :)
Comment: Thank you for your answer, really helpful. I am starting to wonder whether porting this module is actually beyond me. Unfortunately there is no other alternative available in any current D7 module and I really need this functionality. I'm not a programmer but since there is no other option at this point I've decided to bite the bullet and give this a try. There are over 20 people subscribed for the D7 version of this module but little progress has yet been made by anyone. Thanks again
Comment: Are you porting a module that deals with permissions for CCK fields? If so, there's already one out there for the D7 field system: [Field Permissions](http://drupal.org/project/field_permissions/)
Comment: Thanks again. Yes I do know about Field Permissions, unfortunately though it does not integrate with User Relationships module which is the functionality I need: to be able to hide/show user fields based a user's relationship to another or lack there of. I have also tried doing this functionality via Rules module but couldn't achieve it to this level. This is why I am trying to port CCK Private Fields, but if there are better options out there I am all ears.
Comment: Ah I see. I don't know of any I'm afraid


JavaScript mechanism for holding onto a value from a user action

Question: I've created a JavaScript object to hold onto a value set by a user checking a checbox in a ColorBox.
I am relatively new to jQuery and programming JavaScript "the right way" and wanted to be sure that the below mechanism for capturing the users check action was a best practice for JavaScript in general. Further, since I am employing jQuery is there a simpler method to hold onto their action that I should be utilizing?
function Check() {
    this.Checked = false;
}

obj = new Check;

$(document).ready(function() {
    $('.cboxelement').colorbox({ html: '<input id="inactivate" type="checkbox" name="inactivatemachine"> Inactivate Machine' });

    $(document).bind('cbox_cleanup', function() {
        obj.Checked = $.fn.colorbox.getContent().children('#inactivate').is(':checked');
    });

    $(document).bind('cbox_closed', function() {
        if ($($.fn.colorbox.element()).attr('id').match('Remove') && obj.Checked) {
            var row = $($.fn.colorbox.element()).parents('tr');
            row.fadeOut(1000, function() {
                row.remove();
            });
        }
    });
});

Answer: Personally, I would attach the value(s) to an object directly using jQuery's built-in data() method. I'm not really entirely sure what you are trying to do but, you can, for instance, attach values to a "namespace" in the DOM for use later one.
$('body').data('colorbox.checked',true);

Then you would retrieve the value later by:
var isChecked = $('body').data('colorbox.checked');

You run the data() method on any jquery object. I would say this is best-practice as far as jQuery goes.
Comment: I didn't know about jQuery's `data()` method. Given the nature of ColorBox that seems the best fit for my particular use. Is there any guidance when attaching values to a "namespace"?
Comment: @ahsteele: Well, the "namespace" is really string based (hence the quotes around the word in my answer). Basically you are adding a a key->value pair to an object. Something like (for demo purposes only): `document.body.data['colorbox.checked'] = true`. This is so that some other plugin doesn't accidentally overwrite your key->value pair (which is quite possible with a generic variable like 'checked'). You could just as legitimately do: `$('body').data('colorbox_checked',true)`. instead of the dot-notation. Like I said it's "namespaced". Good luck!
Answer: You could capture the reference in a closure, which avoids global data and makes it easier to have multiple Checks.  However, in this case it appears to be binding to the single colorbox, so I don't know that you could usefully have multiple instances.
function Check() {
    this.Checked = false;

    var obj = this; // 'this' doesn't get preserved in closures

    $(document).ready(function() {
       ... as before
    )};
}

var check = new Check; // Still need to store a reference somewhere.

Comment: ColorBox dynamically renders its content so there is only on per page. I need to read up more on closures but this seems much cleaner than having a *global* variable running around.
Answer:
$($.fn.colorbox.element()) is redundant. $.fn.colorbox.element() is already a jquery element.
It's common use (in the examples i watched, at least) to prepend a $ to variables referencing jquery elements.
So, var $rows = $.fn.colorbox.element().parents('tr'); gives instantly the idea that it is referencing jquery element(s).
I am afraid fadeOut won't work on rows in IE6 (if i recall correctly). You should be able to hide all the content inside the
 before removing it.

Can't help on the "simplify" thing because i don't know the colorbox's best uses.
Comment: Unfortunately, $.fn.colorbox.element() doesn't return a jQuery element but will in the next release. I'll check out the fadeout stuff in IE6, thanks for the heads up. My largest concern is the use of my custom Check() object for the purpose of capturing the user's action.
Comment: Technically, that would be "prepend a `$`"


Show that the estimator $ \delta_n(X)=\Phi(\sqrt{\frac{n}{n-1}}(a-\bar{X}_n)) $ is an unbiased estimator

Question: Suppose that $X_1,\dots,X_n$ are iid from the normal location model $N(\theta,1)$ and we wish to estimate the critical or cutoff value $g_{a}(\theta)=P(X_1\le a)$, where $a\in R$ is some fixed number.
(a) Let $\Phi$ denote the CDF of the standard normal distribution. Show that the estimator
$$
\delta_n(X)=\Phi(\sqrt{\frac{n}{n-1}}(a-\bar{X}_n))
$$
is an unbiased estimator of $g_a(\theta)$. Prove that $\sqrt{n}(\delta_n-g_a(\theta))\to^d N(0,\phi^2(a-\theta))$ where $\phi$ is the PDF of the standard normal.

For (a), we want to show that $E\delta_n(X)=g_a(\theta)$, then it is enough to show that
$$
E\delta_n(X)=E\left[P(Z\le \sqrt{\frac{n}{n-1}}(a-\bar{X}_n)|X_1,\dots, X_n)\right]
$$
where $Z$ is standard normal and independent of $X_i$. But how to go the next step?
For the second part,
$$\sqrt{n}(\delta_n-g_a(\theta))=\sqrt{n}(\Phi(\sqrt{\frac{n}{n-1}}(a-\bar{X}_n))-\Phi(a-\theta))$$
Note that
$$
\sqrt{n}(\sqrt{\frac{n}{n-1}}(a-\bar{X}_n)-(a-\theta))\to N(0,1)
$$
Then from the Delta method
$$
\sqrt{n}(\delta_n-g_a(\theta))\to^d \Phi'(a-\theta) N(0,1)
$$
Comment: The second part follows straightforwardly from the delta method, but I am genuinely surprised that the first part is even true -- that there's such a simple exact bias correction applied *inside* the nonlinear function $\Phi(\cdot)$.
Comment: First part is answered at https://stats.stackexchange.com/q/413264/119261.
Comment: @ThomasLumley For the second part, which function do we choose for Delta-Method?
Answer:

Sometimes the iterated expectation is easier to solve, but in this case, it is not.
\begin{align*}
E\delta_n
&= E_{\bar{X}_n}\left[P(Z\le \sqrt{\frac{n}{n-1}}(a-\bar{x}_n)|\bar{X}_n =\bar{x}_n)\right]\\
&= P(Z \le \sqrt{\frac{n}{n-1}}(a-\bar{X}_n)) \\
&= P(Z - \sqrt{\frac{n}{n-1}}(a-\bar{X}_n) \le 0)
\end{align*}
2.
Use the (first-order) Delta-Method.
Comment: But why this is $P(X_a\le a)$?
Comment: For the second part, which function do we choose for  Delta-Method? $\sqrt{n}(\delta_n-g_a(\theta))$ is like a distribution?


Javascript how to change page title with user input

Question: The thing i wanna do is when user writes something to input and sumbits it, the page will change to the input.
Example:
If user writes "Web" to the input, the page title should change to "Web"
Here's the code:
JS:
document.getElementById("titleSumbitBtn").onclick = function (){
    var newTitle = document.getElementById("newTitle").textContent;
    document.getElementById("title").innerHTML = newTitle;
}

HTML:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title id="title">Web Editor</title>
    <link rel="stylesheet" href="style.css">

    Welcome to Web Editor!

Change the title of Web:

    <input type="text" id="newTitle">

    <button type="button" id="titleSumbitBtn">Change</button>

Comment: So _where_ does the JS code actually get embedded into the HTML document? I don't see a single `script` element anywhere.
Comment: Does this answer your question? [How to dynamically change a web page's title?](https://stackoverflow.com/questions/413439/how-to-dynamically-change-a-web-pages-title)
Answer: You can assign new title to the document like this:
document.getElementById("titleSumbitBtn").onclick = function (){
    var newTitle = document.getElementById("newTitle").value;
    document.title = newTitle;
}

This is actual implementation but keep in mind that it must run after the DOM element with id newTitle.
If you put your


Problemas com cache no google chrome

Question: Estou fazendo umas alterações num site e essas alterações envolvem páginas em ASP Clássico e Javascript. O que está passando é que sempre altero o javascript, salvo e jogo ele no meu servidor ele não atualiza. Ele sobrescreve o antigo, porém quando vou utilizar as alterações realizadas ele continua referenciando a versão anterior. Para resolver isso tenho sempre que reiniciar a máquina, aí sim, as alterações feitas são utilizadas. Como eu sempre trabalho com o Dev Tools do Chrome aberto, eu marquei a opção Cache Disabled, mas mesmo assim não funcionou, só reiniciando a máquina. Alguém sabe o que tenho que fazer para resolver esse problema que me incomoda? Reiniciar um máquina hoje, demando pelo menos entre 5 a 20 min, fazendo isso umas 10 a 15 vezes por dia, isso é um tempo perdido muito grande.
Comment: Não sei te ajudar quanto ao cache, mas uma pequena gambiarra para você não ter que ficar reiniciando toda hora é toda vez que atualizar o seu js trocá-lo de nome, e na página que o referencia também.
Comment: @JoaoPaulo, nem pensar. Você não tem noção do tamanho disso aqui e vários sites, que estão à minha disposição o utiliza esse e outros arquivos. É muito grande. Só para ter uma idéia, mexemos num módulo em ASP, mas tem Java, Asp.Net. É um ninho de cobras isso aqui. Temos algumas vezes que duplicar arquivos, pois não temos como alterar uma página, pois muitas delas são chamadas em vários lugares. Isso não tem nem como cogitar.
Comment: Eu também não aconselho. Mas já fiz isso e depois voltei pro nome original porque de jeito nenhum o código atualizava.
Answer: Se o Cache disabled não funcionou vou orientar a limpar o cache manualmente ou mesmo usar uma extensão para limpar o cache sempre como o Cache Killer.
Comment: @pnet Vi que postou limpar manualmente, tenta o control + R
Comment: Ok, tenho problemas aqui na empresa para instalar o cache killer. Já falei com os caras que administram, pois o chrome aqui na empresa tem muitas restrições, diferente do IE. Mas assim que os caras que derem permissão para instalar, farei os testes e se der certo, posto o resultado e encerro o post.
Comment: Não sei se isso tem a ver com tudo, mas sempre que eu reinicio a máquina, quando testo não funciona. Porém após uns minutos, depois de reiniciada, aí funciona. Observei isso pela segunda vez, coincidência ou não, coloco isso como subsídio para tentar solucionar o problema que eu tenho aqui. Parece bizarro, mas é a segunda vez que observo em duas vezes que reiniciei a máquina.
Comment: Pode então limpar manualmente a cada vez como indiquei.
Comment: Como limpar manualmente? Com Ctrl+F5? Dessa forma não funciona. Só funciona reiniciando.
Answer: o problema está resolvido, mas uma coisa não conseguir entender. Possivelmente já estivesse assim e só agora notei. O seguinte: Eu dou Ctrl+R, Ctrl+F5, Recarregar e nada. Bem, fiz isso ontem e nada dava certo, continuava com o arquivo .js não atualizado. Bem, depois de uns 20min observei que funcionou. Fiz outra atualização no arquivo e fiz todo esse processo e não atualizou. Aí lembrei dessa espera, deixei lá e depois de uns 30min, fui testar e funcionou. Hoje a mesma coisa aconteceu, logo alguma coisa que eu não sei o que é está tipo, "travando" a atualização e depois, sei lá o que, funciona. Talvez seja possível que nem precise descarregar cache, ou seja, depois de um tempo o próprio browser reconhece as alterações. Parece estranho, mas é isso que está acontecendo aqui. É só esperar que volta a funcionar. Tudo isso sem reiniciar a máquina. Closed case.
Comment: Isso pode ser cache do lado do servidor, ou também cache do proxy caso a sua rede use algum tipo de proxy.

Problemas com cache no google chrome


filter clause syntax for mysql

Question: Using MySQL 8.0
I've recent read a blog https://medium.com/swlh/three-useful-yet-neglected-sql-statements-9406d9316e10 that talks about creating pivot table using FILTER function, I followed exact step and tried it out on my database however it keeps on giving me syntax error.
What is the correct syntax for using filter clause in MySQL?
My current query:
  select date(time) as dt
      , count(*) FILTER (where type= 'A') as 'B'
      , count(*) filter (where type = 'B') as 'B'
      , count(*) filter (where type = 'C') as 'C'
  from table
group by dt;

not sure why this is giving me an error.
It works when I use Case When to create pivot table
 select date(start_time) as dt
      , sum(case when type = 'A' then 1 else 0 end) as 'A'
      , sum(case when type = 'B' then 1 else 0 end) as 'B'
      , sum(case when type = 'C' then 1 else 0 end) as 'C'
  from table
group by dt;

How can I do this using Filter clause in mysql or is there Filter function in MySql?
Comment: Ensure - FILTER function is **NOT** listed in [MySQL SQL Function and Operator Reference](https://dev.mysql.com/doc/refman/8.0/en/sql-function-reference.html). I think that the article author tells about PostgreSQL or some another DBMS.
Comment: Are you sure MySQL has `FILTER` function? Even though the article is talking about `SQL`, it doesn't necessarily meant for `MySQL`. It could be for `MSSQL` or `PostgreSQL`.
Comment: I am unsure... but when I type `filter` it is marked as a function
Comment: i donot think mysql supports it yet
Comment: Do u know why it is marked as a function though? in workbench it turns blue when I type `filter` is it used in different way? I'm curious to know
Comment: Not sure why but I'm using SQLyog tool and it doesn't recognize filter as a function.
Comment: Yes, I've read throught MySQL doc and couldn't find filter function however since `filter` was marked blue like any other function in MySQL I thought it does something.
Answer: MySql doesn't support filter clause - you can try the below -
select date(start_time) as dt
      , sum(type = 'A') as 'A'
      , sum(type = 'B') as 'B'
      , sum(type = 'C') as 'C'
  from table
group by dt

Comment: One downside is that this isn't portable, while `case` is ANSI SQL and portable.
Comment: Maybe `SUM(IFNULL(type  = 'A',0))` to take care of the `NULL`?
Comment: Thanks! this seems more cleaner than using case when. Is there any downside of this? Why would someone use case when over this
Comment: @Ambleu If there is no value with any condition it will return null instead of 0

filter clause syntax for mysql


jQuery's Autocomplete dropdown is not showing after upgrade to jQuery UI 1.10.3

Question: In my Ruby on Rails app I was using jQuery UI 1.9.2 (through jquery-ui-rails). I had an Autocomplete field in a Modal Dialog form that was populating it's dropdown suggestion box using Ajax and Json. It worked correctly, showing me the correct suggestions.
I subsequently upgraded to jQuery UI 1.10.3 (using bundle update) and now the Autocomplete dropdown suggestion box is no longer working. It shows no error in the JavaScript console. In fact it shows that the Json that is returned is correct.
I have tried rewriting the autocomplete function in JS to perform the call manually (using the Autocomplete's source: $.ajax {} call and still nothing.
It was suggested to me that the problem might be that jQuery changed something that caused the jquery-ui-rails gem to stop working, but after submitting a bug ticket to them, it turns out that that is not the problem.
Any help would be appreciated.
NOTE to Answers:
mhu's answer is correct, and you should avoid tampering with the z-Indexes where possible (which is why I marked it as correct). However in my case (where the Autocomplete text box is in a Modal Dialog) the drop down will only be displayed within the width of the dialog box (if the text is wider than that, it is hidden and you cannot use the scrollbar). As I did not want that, I did what I described in my answer below and it works. I did make various comments and notes to myself to make sure it still works after any jQueryUI update.
Answer: After searching everywhere for this issue, I found that nobody had a solution to my problem as I could not produce any error messages and the code I showed was sound. After someone suggested I read the jQuery changelogs (which admittedly I hadn't), I found the bug in the jQuery as well as workaround:
In the jQuery UI 1.10.1 changelog, under the Autocomplete section it read:
Added: Use .ui-front instead of .zIndex() for the suggestions menu. (7d5fe02)

Following the link provided and looking through the jQuery code fix, gave me an idea: I performed my Autocomplete search, and then I moved the Modal Dialog to the side! That's when I noticed the Autocoplete dropdown suggestion menu was behind the Modal Dialog.
I fixed this by adding the following CSS rule:
ul.ui-autocomplete.ui-menu {
  z-index: 1000;
}

I have submitted a Bug ticket to jQuery, so I'm hoping it will be dealt with by 1.10.4 so that the workaround is no longer needed.
I hope this helps others too.
Answer: When using jQuery UI 1.10, you should not mess around with z-indexes (http://jqueryui.com/upgrade-guide/1.10/#removed-stack-option). Just make sure the autocomplete element is in the correct DOM order with: autocomplete.insertAfter(dialog.parent())
Example
 var autoComplete,
     dlg = $("#dialog"),
     input = $("#input");

 // initialize autocomplete
 input.autocomplete({
     ...
 });

 // get reference to autocomplete element
 autoComplete = input.autocomplete("widget");

 // init the dialog containing the input field
 dlg.dialog({
      ...
 });

 // move the autocomplete element after the dialog in the DOM
 autoComplete.insertAfter(dlg.parent());

Comment: It's really just one statement: `autoComplete.insertAfter(dlg.parent());`. The rest is just the standard stuff you always need to setup the autocomplete.
Comment: You could also use `$(".ui-autocomplete")`, but that would target all autocomplete-elements on the page, instead of the just the one attached to `input`.
Comment: and in case you came here having a similar problem with autocomplete inside a colorbox:
`autoComplete.insertAfter($('#cboxLoadedContent').parent());`
Comment: But this is so much more complicated than before... I know you might not know the reason, but this seems like I suddenly have to perform 2 more steps than before
Comment: OK That makes sense. But why did you reference the autocomplete("widget") like that? I have never needed to do that


Perturbing integer roots

Question: The polynomial
$$(x-a_1)(x-a_2)\cdots(x-a_n) - x^{n-1} = 0$$
for arbitrary integers $a_i$ has come up in a project.  Is the root with the greatest modulus always real?  Evidence from several choices of the $a_i$ for small $n$ suggests that the answer is yes...
I titled this perturbing the roots since, without the $x^{n-1}$ term, the zeros would simply be the $a_i$. This feels like the sort of thing that was better known when "theory of equations" classes were a mainstay of mathematics training.

Edit: As per Chris Sanders below, the $a_i$ should be positive integers.
Comment: Shift $ x^{n-1}$ to LHS and then try making graphs depending on cases when n is even or odd
Comment: I can imagine that comparing the graphs $f(x) = (x-a_i)\cdots(x-a_n)$ and $g(x) = x^{n-1}$ could show that there is always at least one real root, but the key part of the question is about the root *with the greatest modulus* being real.
Answer: $(x+1)^2-x$ has no real roots.
$(x+1)^3-x^2$ has exactly one real root with modulus smaller than the modulus of either of the other roots.
https://www.wolframalpha.com/input?i=%28x%2B1%29%5E3-x%5E2
EDIT:
I think you might want to require that all $a_i$ be positive integers.
In that case, have a look at my other answer.
Answer: Let $p(z)=(z-a_1)\ldots(z-a_n)$,
where $a_1,...,a_n$ are all positive integers.
Without loss of generality, $a_1\leq a_2\leq\ldots\leq a_n$.
$\\$
Denote by $r$ the largest real root of $p(x)-x^{n-1}$.
Now, because $p$ is of degree $n$, you get $\displaystyle\lim_{x\to\infty}p(x)-x^{n-1}=\infty$,
but $p(a_n)-a_n^{n-1}=-a_n^{n-1}<0$.
Therefore, there must be a real root of $p(x)-x^{n-1}$ to the right of $a_n$. Hence, $r>a_n$.
Let's compare $p(rw)$ and $(rw)^{n-1}$, where $w$ is on the unit complex circle $S^1$; in other words $|w|=1$.
Now $|(rw)^{n-1}|=r^{n-1}$, but what about $p(rw)=(rw-a_1)\ldots(rw-a_n)$?
For $w\in S^1\setminus\{1\}$, you find that $|rw-a_j|>r-a_j$. This follows from the "equality conditions" of the triangle inequality. So actually, $|p(rw)|=|rw-a_1|\ldots|rw-a_n|>(r-a_1)\ldots(r-a_n)=r^{n-1}$.
This means that of the roots of $p(z)-z^{n-1}$, there is only one of the form $rw$ for $w\in S^1$, and that root is $r$ itself.
$\\$
Let $t$ be a real number greater than $r$.
Then, because $r$ is the largest real root of $p(x)-x^{n-1}$,
it follows that $p(t)>t^{n-1}$.
Again, for $w\in S^1$, you get
$|p(wt)|=|wt-a_1|\ldots|wt-a_n|\geq(t-a_1)\ldots(t-a_n)>t^{n-1}=|(tw)^{n-1}|$.
We conclude that $p(z)-z^{n-1}$ has no complex roots with modulus greater than $r$.

Perturbing integer roots


Why do the p-value and confidence intervals not always match in logistf?

Question: I have recently started using logistf in R and find that I am getting strange results. Namely, sometimes the confidence intervals for the coefficient cross 0, despite having a strongly significant p-value, and vice versa.
For example
outcome <- as.factor(c(0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1))
predictor <- c(0,5,5,5,5,5,5,5,5,5,5,5,1,0,0,0,0)
logistf(outcome ~ predictor)

In my output, I discover the coefficient for my predictor to be -0.4 (95% confidence interval -2 to 7). However, the p-value is 0.00000352.
Can anyone explain how I am using this penalised logistic regression method incorrectly as this result seems to be inconsistent?
Comment: Something fishy is that using `glm(..., family = binomial)` and `logistf(..., firth = FALSE)` give quite radically different coefficient estimates even though they're both using maximum likelihood to estimate the coefficients. Maybe this package has a bug in it. You can perform the same analysis using the `brglm2` package, which has results more in line with what you get using `glm()`.
Comment: You can set pl=FALSE, so that you get wald c.i, I think the penalized loglikelihood estimation doesn't quite work in this case
Comment: I don't understand the meaning of your "however:" the p-value and confidence interval are perfectly consistent.  Maybe you should review our posts on what p-values mean: start with https://stats.stackexchange.com/questions/31.
Comment: Thank you all. @StupidWolf if you input your response as an answer I'll accept it.
Answer: The default logistf is to return estimates based on profile penalized log likelihood. Most likely you are looking for something similar to a Wald confidence interval:
library(logistf)

outcome <- as.factor(c(0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1))
predictor <- c(0,5,5,5,5,5,5,5,5,5,5,5,1,0,0,0,0)

logistf(outcome ~ predictor,pl=FALSE)

logistf(formula = outcome ~ predictor, pl = FALSE)
Model fitted by Penalized ML
Confidence intervals and p-values by Wald

                  coef  se(coef) lower 0.95 upper 0.95     Chisq         p
(Intercept)  3.9062500 3.1794521  -2.325362 10.1378616 1.5094387 0.2192248
predictor   -0.3853818 0.6646985  -1.688167  0.9174034 0.3361499 0.5620600

Likelihood ratio test=21.50504 on 1 df, p=3.528995e-06, n=17


Execute code before cache is cleared

Question: I want to execute code before cache is cleared, for example for the menu cache:
<code>// Clear menu cache
$cache = \Drupal::cache('menu');
$cache->deleteAll();
</code>
I want to intervene when the cache clear is called, right before it is deleted. I've read the documentation on Drupal::cache and the Cache API but didn't find a solution. Do note that I want to do this using core code only, no contributed modules.
Comment: I think you'll need to provide your own cache classes to do that; none of the core classes invoke events or hooks in `::deleteAll` or `::deleteMultiple` which is where it would need to happen
Comment: Exactly, thanks for your input. Could you provide a code sample to get me started?
Comment: Why do you need this? It is a *cache*, caches are not persistent. Whatever you try to do there will not be reliable, especially with alternative cache backends like redis/memcache which will just drop your cache entries if the memory is used up
Comment: It's for the following core isse: [Standard profile: make "Home" menu link to  editable/deletable](https://www.drupal.org/node/2838106). We're removing a link from `standard.links.menu.yml` and adding it with `MenuLinkContent::create()` instead. And now we need an upgrade path.
Comment: Ah of course, just saw the update there. Yeah, forgot about the update path, alex pott saving us again :) I don't think that will work, adding a new hook won't exist yet in the cache either. So it won't be called..
Comment: @Berdir I'm working on this during the Drupal core #SprintWeekend so feel free to jump in today!
Answer: It isn't clean but I'm able to do this with hook_cache_flush. It's called when a cache clear has been called, before the cache has been cleared.

Execute code before cache is cleared


how to loop string or button in python?

Question: i'm new with python.
I have a problem:
I would like you to click a button to infinity. how to do?
random_int = randint(15, 30)
print('Sleeping for {} seconds'.format(random_int))
time.sleep(random_int)
driver.find_element_by_xpath("//button[@class='control-button']").click()

Answer: You can use a forever running while loop.
import time
from numpy.random import randint

while True:
    driver.find_element_by_xpath("//button[@class='control-button']").click()
    time.sleep(randint(15, 30))

Comment: thx for reply,
I tried but it gives me this error:
IndentationError: expected an indented block
Comment: all I need is a button to be clicked x times every 15-30 seconds

how to loop string or button in python?


Copiar uma faixa de células do Excel para um objeto "image" pelo VBA

Question: Preciso copiar uma faixa de uma planilha do Excel que contém um esquema gráfico feito com bordas em torno de algumas células, com algumas cores de fundo e textos, e visualizar este esquema em um objeto "image" do VBA.
Com o código abaixo a faixa de células que compõe a figura é copiada da planilha atual para outra de nome "Imagem", e é copiada como imagem (como preciso), porém não consegui uma forma de colocá-la no objeto "image", ou ainda, de colá-la diretamente no objeto "image" (assim a planilha "Imagem" seria desnecessária).
Range("D19:H25").Select

Application.CutCopyMode = False

Selection.CopyPicture Appearance:=xlScreen, Format:=xlBitmap

Sheets("Imagem").Activate

Range("A1").Select

ActiveSheet.Paste

Na tentativa de encontrar uma solução, ao fazer manualmente selecionando as células que contêm a imagem, e em "Página Inicial", "Copiar como imagem" (aparência: como mostrada na tela, e formato: Bitmap); ao clicar em propriedades do objeto "image" no campo "Picture" onde está descrito "nenhum" e dar "colar" neste campo, surge a palavra "Bitmap" e no objeto "image" surge a imagem como desejado.
Tentei e pesquisei automatizar este mesmo procedimento no VBA, inclusive fazendo-o por meio de macro e analisando o código, mas evidentemente o código da parte que o desvio é feito para o VBA para "colar" a faixa selecionada na propriedade do objeto (Picture) não é registrado na macro.
Como o esquema gráfico é alterado dinamicamente pelo usuário (via VBA), sempre que o usuário entrar em determinado formulário este objeto "image" precisa apresentar a imagem atual, quantas vezes o usuário desejar refinar esta imagem.
Como resolver isso da forma que preciso?
Comment: Possível duplicata de [Salvar uma imagem colada em planilha Excel por meio do VBA](http://pt.stackoverflow.com/questions/111185/salvar-uma-imagem-colada-em-planilha-excel-por-meio-do-vba)
Comment: A outra pergunta trata de "como salvar a imagem em arquivo", enquanto esta pergunta trata de "como pegar uma imagem e colocá-la em um objeto image do VBA", são dois problemas diferentes para tratamento de uma mesma imagem
Comment: Ok, vi a edição que vc fez. Retirei meu voto de fechar como duplicada.
Answer: Basta deletar a imagem anterior (guardando antes a posição em que ela se encontra) e atualizar a nova colada com o mesmo nome e na mesma posição. Eis o código:
Set oImage = ActiveSheet.Shapes.Item("Imagem 1")
x = oImage.Left
y = oImage.Top
oImage.Delete

' Seu código
' -------------
Range("e7:E9").Select

Application.CutCopyMode = False

Selection.CopyPicture Appearance:=xlScreen, Format:=xlBitmap

ActiveSheet.Paste Destination:=ActiveSheet.Range("J19:N25")
' -------------

ActiveSheet.Shapes.Item(ActiveSheet.Shapes.Count).Name = "Imagem 1"
Set oImage = ActiveSheet.Shapes.Item("Imagem 1")
oImage.Left = x
oImage.Top = y

IMPORTANTE: Note que nesta resposta eu apenas demonstro como atualizar
  uma imagem já existente com uma nova imagem gerada a partir dos dados
  de um range selecionado. Na sua outra pergunta, a minha resposta
  demonstra como gravar essa imagem (e não o range!) em um arquivo. No
  final as perguntas não estão duplicadas, mas foi totalmente
  desnecessário ter duas para resolver o seu problema. Se você tivesse
  sido mais organizado ao perguntar, teria evitado todas as pequenas
  confusões e tido a sua resposta mais rapidamente. Fica a dica pro
  futuro. :)
Comment: Ok, grato, a sua resposta a outra pergunta complementa essa!


minha página html fica com ? (mas estou enviando coisas via post). http://localhost/SistemaAline/formulario.html?

Question: Minha página carrega assim (abaixo)
http://localhost/SistemaAline/formulario.html
depois que envio dados para o php e retorno eles pra mesma página usando jquery, ela volta com ?
http://localhost/SistemaAline/formulario.html? e aí uns updates não funcionam direito, apenas quando recarrego a página sem o ?
Comment: Sem o código só podemos partir da especulação e isso não agregará em nada. Poderia [edit] e construir um [mcve] do problema?
Answer: Isso acontece porque muito provavelmente o método de envio do seu <form> está como GET, ou nem foi configurado. sugiro que adicione a seguinte tag method='POST', ao seu formulário.
Exemplo:
<form method="POST" action="página">
</form>


Data preparation and machine algo for ad click prediction

Question: I am an ml noob. I have a task at hand of predicting click probability given user information like city, state, os version, os family, device, browser family browser version, city, etc. I have been recommended to try logit since logit seems to be what MS and Google are using too. I have some questions regarding logistic regression like:
Click and non click is a very very unbalanced class and the simple glm predictions do not look good. How to make the data work through this?
All variables I have are categorical and things like device and city can be numerous. Also the frequency of occurrence of some devices or some cities can be very very low. So how to deal with what I can say is a very random variety of categorical variables?
One of the variables that we get is device id also. This is a very unique feature that can be translated to a user's identity. How to make use of it in logit, or should it be used in a completely different model based on a user identity?
Answer: The number of different values in your categorical variables is only important relative to your sample size.  If you only have 10,000 observations, 40,000 dummy variables for each zipcode in the US is probably too much, but if you have 10,000,000 observations 40,000 dummy variables is fine.
You're probably going to have the best results by gathering all the data you can get your hands on and modeling it with a tool like vowpal wabbit that can handle 100's of millions of observations and all of the variables you can throw into it.
As far as the unique identifier goes, if you get more than one observation per user, you probably want to use it in some fashion.  A person who clicked 10 times out of 10 impressions is very likely to click again, regardless of what the other variables are.  A dummy variable for every user is probably not the best approach, but a set of variables like "user's prior impressions", "user's prior clicks" and "user's prior click-through-rate" are probably really valuable.
This trick can also be used to convert your other categorical variables to continuous variables, e.g. "zip code's prior impressions", "zip code's prior clicks", and "zip code's prior click-through-rate."
There's a recently-completed kaggle competition for predicting ad click-through-rates, and there's some great stuff in the forums.  There are also 2 very good blog posts (here and here) on fitting logistic regressions models to this dataset using scikit-learn and vowpal wabbit.
Answer:
Click and non click is a very very unbalanced class and the simple glm
  predictions do not look good. How to make the data work through this?

Have a look at here: Does an unbalanced sample matter when doing logistic regression?

So how to deal with what I can say is a very random variety of
  categorical variables?

This is an age-old problem in Stats / Machine learning, called 'the curse of dimensionality'. I can't think of any immediate solutions. I would google and search this website for some valuable gems but at the end of the day the higher the dimensions you want to build a model / train an algorithm on, the more data you need.

One of the variables that we get is device id also. This is a very
  unique feature that can be translated to a user's identity. How to
  make use of it in logit, or should it be used in a completely
  different model based on a user identity?

As you say, this would be the unique identifier of an observation (user) in your dataset. You should not include this as a predictor variable (unless it has some speific meaning, e.g. id's that are closer to each other tend to behave similarly..)
Comment: Hi this answer adds no additional information - it just sort of repeats some the problems mentioned - so I decided to downvote it.


Are these two definitions of the natural numbers equivalent?

Question: If we consider two definitions of the natural numbers:
Definition 1
$N$ is the set that satisfies all of:

There is an element $0$ in $N$.
For each element $n$ in $N$, there is the successor of $n$, $Sn$.
There is no element in $N$ whose successor is 0.
For each $m$ and $n$ in $N$, $Sm=Sn$ implies $m=n$.
For any subset $A$ of $N$, if $A$ contains $0$ and, for each $n$ in $A$, it holds that if $A$ contains $n$ then $A$ contains $Sn$, then $A=N$.

Definition 2
$N$ is the smallest set that satisfies all of:

There is an element $0$ in $N$.
For each element $n$ in $N$, there is the successor of $n$, $Sn$.
There is no element in $N$ whose successor is 0.
For each $m$ and $n$ in $N$, $Sm=Sn$ implies $m=n$.

Are these exactly equivalent? Does this get around the need for the induction axiom?
Comment: Note that neither definition can define the natural numbers on its own; they only make sense in the context of set theory.
Answer: With just a bit of tweaking, Definition 2 can be shown to be equivalent to Definition 1:
Let $X$ be a set such that

There is an element $0$ in $X$.
For each element $n$ in $X$, there is the successor of $n$, $Sn$ in $X$.
There is no element in $X$ whose successor is $0$.
For each $m$ and $n$ in $X$, $Sm=Sn$ implies $m=n$.

Let $N$ be the smallest subset of $X$ such that

$0$ is in $N$.
For each element $n$ in $N$, $Sn$ is also in $N$.

Then this subset $N$ will be identical in structure to that given by Definition 1.
By "the smallest subset" I mean the intersection of all subsets of $X$ that meet these two requirements.
For a formal development of this idea, see "Daddy, where do numbers come from?" (February 19, 2013) and "What is a number again?" (Janunary 22, 2014) at my math blog.
Answer: Axioms 1-4 say that you have a set $X$, an element $0 \in X$, and an injective function $S: X \to X$ such that $0$ is not in the image of $S$. This is enough to imply that $X$ is infinite (since if $X$ is finite then any injection $S:X\to X$ is a bijection and so $0$ must be in the image of $S$). But there are many, many other examples. A few that come to mind:

Let $X = N$ but with $S(n) = n^2+1$, say. More generally, $S$ could be any injection which doesn't map anything to 0. Here you have the right set, but the wrong successor operation.
Let $X = N \times N$ be the set of pairs $(m,n)$ where $m \in N$ and $n \in N$, and let $S(m,n) = (m,n+1)$ (again, lots of other functions work).
Let $X = \mathbb{R}_{\geq 0}$ be the set of nonnegative reals with $S(x) = x+1$ (or whatever). Now we actually have a set of different cardinality.

So to characterize the natural numbers, there are a lot of non-examples to rule out, and we need some kind of powerful principle encoding the information the induction principle.
One way to express this formally is to follow Dan Christensen and extract a copy of $N$ from any setup satisfying 1-4.
Here's a slightly different perspective, due to Lawvere, which generalizes somewhat more readily to other settings.  Let's say that an "iteration system" (I just made up that term) is a triple $(X,x_0,s)$ where $X$ is a set, $x_0$ an element $x_0 \in X$ and $s$ is a function $s: X \to X$ (this is weaker than axioms 1-4: we don't require $S$ to be injective, nor that $x_0$ be disjoint from its image). Then the natural numbers $(N,0,S)$ can be characterized by the following two properties:

$(N,0,S)$ is an iteration system, and
if $(X,x_0,s)$ is any other iteration system, there exists a unique function $f: N \to X$ such that $f(0) = x_0$ and for every $n \in N$, $f(S(n)) = s(f(n))$.

This can be expressed by saying that the natural numbers are a "universal iteration system".


Dimension of the dual space of an infinite dimensional vector space using Hahn-Banach

Question: I have to prove that if $\dim(X)=\infty$ then $\dim(X^*)=\infty$. But this question is from the section of excercise of Hahn-Banach extension theorem of my professor. I really don't know how to start this, please if you can give me a couple of tips it would be very helpfull. Thanks.
Comment: Just because it appears in that section it doesn't mean that you have to use H-B Theorem. This result is very elementary. Prove it by contradiction.
Comment: @KaviRamaMurthy ... in ZF it cannot be proved that an infinite-dimensional vector space has any linear functional at all.  So I do not understand why you say that you do not need to use Hahn-Banach.
Answer: Lemma 1:
If $F \in X^{*}$ is nonzero and $\mathcal{N}=\{x \in X: F(x)=0\},$ then there exists a one-dimensional subspace $\mathcal{M}$ of $X$ such that
$$
X=\mathcal{N}\oplus\mathcal{M}=\{x+y: \quad x \in \mathcal{N} \quad \text { and } \quad y \in \mathcal{M}\} \quad \text { and } \quad \mathcal{N} \cap \mathcal{M}=\{0\}.
$$
Lemma 2:
Given $x\neq 0$, then there is an $F \in X^*$ such that
$$||F||=1 \qquad \text{ and } \qquad F(x)=||x||_X $$
Both lemmas are direct consequences from Hahn-Banach Theorem and can be easily verified.
Now, let's suppose (by contradiction) that $\dim (X^*)=n\leq \infty$, then we can consider a base $\mathcal{B}=\{F_1,\dots,F_n \}$ of $X^*$ and apply the lemma 1 for each $F_i$, this gaves the one dimentional subspaces $\mathcal{M}_i$ and the $\mathcal{N}_i$ with the above mentioned properties. Note that by the definition of the $\mathcal{M}_i$, $X=\mathcal{M}_1\oplus \mathcal{M}_2\oplus \dots \oplus \mathcal{M}_n \oplus X_0$, where $X_0$ is the infinitely dimensional space given by $\bigoplus \mathcal{N}_i/\bigoplus M_i$.
So, consider $x$ an arbitrary element of $X_0$, and $F\in X^*$, note that: $$ F(x)=F_1(x)+F_2(x)+\dots+F_n(x)=0,$$ where the first equality is due to the fact that $F_i$ is a base for $X^*$, and the second come from the fact that $X_0\cap M_i = \{0 \}$, note that is for any linear functional and any $x\in X_0$. In particular given an $x\in X_0$ we can consider the $F$ given by lemma 2, as $F(x)=0=||x||$, we can conclude that $||x||=0$ for all $x\in X_0$, therefore $x=0$ and hence $X_0=\{0\}$ which is a contradiction to the fact that $X_0$ is infinitely dimensional.
With this we have that $\dim X^* = \infty$.


Cannot force absolutely positioned elements to fill 100% of viewport/site

Question: I am unable to force a couple of my elements to be 100% height of the browser window. I want .blank and .sidebar to fill 100% height regardless of how much content they hold (any overflow should be taken care of by using overflow-y: scroll;
Thanks!
JSFiddle
HTML

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Header

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Footer

CSS
html,
body {
    height: 100%;
    margin: 0;
    padding: 0;
    position: relative;
    background: grey;
    color: white;
}

.sidebar {
  width: 50%;
    height: 100%;
  position: absolute;
  top: 76px;
    right: 0;
    margin: 0;
  padding: 30px 80px 60px;
    z-index: 3;
    overflow-y: scroll;
    background: black;
}

.blank {
    background: linear-gradient(to left, transparent 0%, cyan 75%);
  width: 100%;
    height: 100%;
  opacity: 0.7;
  position: absolute;
  top: 0;
    left: 0;
    z-index: 2;
}

header {
    width: 100%;
    height: 28px;
    position: absolute;
  left: 0;
  top: 0;
  background: red;
  padding: 24px 0px;
    z-index: 4;
}

main {
    margin: 76px 0 150px 0;
}

footer {
    width: 100%;
  height: 175px;
  left: 0;
  bottom: 0;
    z-index: 1;
  background: yellow;
}

Comment: I've copied your code to http://codepen.io/jaycrisp/pen/OMoEaM and the 2 divs are taller than 100% of the browser height, so I'm not sure what your problem is. However,using absolute positioning for layout like this isn't a great idea. It's not going to be responsive and will break easily if/when the content changes.
Comment: Hi. I'm trying to get the .blank and .sidebar elements (which are both absolutely positioned) to always be 100% height of the browser (even when scrolled, not just based on the initial viewport. Even if there is just one word in a sidebar I still want the black background to extend to the full height. If there is too much content I want it to scroll.
Comment: Here is a live example that might help to explain, please activate .blank and .sidebar by clicking the menu at top (artists, about, history) - my fiddle was simplified. workshop.oakdesignstudio.com/dwl/artists/anna-pancaldi
Comment: Did you ask the same question here: http://stackoverflow.com/questions/35202155/html-body-100-height-not-filling-100-of-viewport ?
Comment: Do you want the sidebar to stay in the same position when the browser is scrolled? if so, you need to use position: fixed instead of absolute
Comment: Hi @JamieC, that is my question but it resolved one of the issues which was the positioning of the footer. The code has changed and the problem different.
Comment: @JamieC yes the sidebar should remain constant but the content within it may or may not be scrollable. Either way the height should always be 100%
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/102611/discussion-between-jamiec-and-dungey-140).
Answer: use vh its for viewport height.
so instead of
height: 100%;

use
height: 100vh;

and set fix heights for mediaqueries below ~768px height because especially ios and some other browsers cannot handle it.
see browser which can viewport units
another solution would be with jquery but i dont recommend using jquery for this case.
cannot show you the updated fiddle cause there the rendered page is not the whole viewport..

update:
you need to set the sidebar this css:
.sidebar {
    width: calc(50% - 160px);
    height: 100vh;
    position: absolute;
    margin-top: 76px;
    right: 0;
    margin: 0;
    top: 0;
    margin-right: -100%;
    box-sizing: border-box;
    padding: 30px 80px 60px;
    z-index: 3;
    overflow-y: scroll;
    background: black;
    -webkit-transition: margin-right 1.2s ease;
    transition: margin-right 1.2s ease;
}

greetings timotheus
Comment: Hi. This doesn't seem to work for me, when I begin to scroll down the page the .blank and .sidebar elements are still not 100% of
Comment: Here is a live example that might help to explain, please activate .blank and .sidebar by clicking the menu at top (artists, about, history) - my fiddle was simplified.

http://workshop.oakdesignstudio.com/dwl/artists/anna-pancaldi/
Comment: ya, its because you have a padding-top and bottom and also set a top value... in your case you could set "box-sizing: border-box;" for letting the padding expand inside not outside and set the height to to less vh because of the top value
Comment: Thanks! Any ideas regarding .blank?
Comment: you want that the page isnt scrollable when menu is open?


ant task for debugging not working: Cause: the name is undefined

Question: I'd like to attach NetBeans to a Java program I'm writing to help with debugging. I've added a "debug" target to my ant file with the expectation that this will launch the debugger on port 54322 where NetBeans could then attach. This has worked at some point in the past, but meanwhile I must have messed something up. Can anyone try and help find my error in the syntax?
ant debug

will simply start the program, no debugger starts. After the program ends, this is printed in the terminal:
build.xml:55: Problem: failed to create task or type jvmarg
Cause: The name is undefined.

In the compile task, I've included the debug options:
<javac srcdir="${src.dir}" destdir="${classes.dir}" includeantruntime="false" debug="true" debuglevel="lines,vars,source">

Here's the "debug" task (including line numbers). You see line 55 is where ant complains about an undefined name.
53 <target name="debug" depends="jar">
54    <java jar="${jar.dir}/${ant.project.name}_ClearText.jar" fork="true"/>
55    <jvmarg line="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=54322" />
56 </target>

Answer: jvmarg must be nested inside the java task call:
<target name="debug" depends="jar">
   <java jar="${jar.dir}/${ant.project.name}_ClearText.jar" fork="true">
       <jvmarg line="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=54322" />
   </java>
</target>


JavaScript form validation 2 letters 1 number

Question: I'm trying to make a validation for my form with JavaScript. This is what I have done so far, and it works, but in the input "klassekode"  needs to start with two letters and then one number.
My html code
<form class="form1" method="POST" id="registrerFagSkjema" action="registrerklasse.php" name="registrerFagSkjema"  onSubmit="return validerRegistrerFag()">

        Registrer klasse

        Klassekode

        <input value="" type="text" name="fagkode" id="fagkode"  onFocus="fokus(this)"
                onBlur="mistetFokus(this)" onMouseOver="musInn(this)" onMouseOut="musUt()"
                onChange="endreTilStoreBokstaver(this)"/ />

        Klassenavn

        <input value="" type="text" name="klassenavn" id="klassenavn"   onFocus="fokus(this)"
                onBlur="mistetFokus(this)" onMouseOver="musInn(this)" onMouseOut="musUt()"  />

        <input value="Registrer Klasse" type="submit" name="submit" id="submit" >
        <input type="reset" value="Nullstill" id="reset" name="reset" onClick="fjernMelding()">

</form>

My JavaScript code
function validate()

{
  var klassekode = document.getElementById("klassekode");
  var klassenavn = document.getElementById("klassenavn");
  var feilmelding="";
  //var firstTwoLetters = document.getElementById("klassekode").substring(0,2);

  if(klassekode.value.trim()=="")
  {

    //alert("blank");
    feilmelding="Fyll ut Klassekode";
    document.getElementById("melding").style.color="red";
    document.getElementById("melding").innerHTML=feilmelding;

    klassekode.style.border = "solid 1px red";
    return false;
  }
  else if ( klassekode.value.trim().length!=3)
  {
    //alert("klassekode for lang");
    feilmelding="Klassekode må kun være 3 bokstaver";
    document.getElementById("melding").style.color="red";
    document.getElementById("melding").innerHTML=feilmelding;
    klassenavn.style.border = "solid 1px red";
    return false;
  }
  else if (klassenavn.value.trim()=="" )
  {
    //alert("blank");
    feilmelding="Fyll ut Klassenavn";
    document.getElementById("melding").style.color="red";
    document.getElementById("melding").innerHTML=feilmelding;
    klassenavn.style.border = "solid 1px red";
    return false;
  }
  else { return true;}
}

Answer: You got the hang of substring, and you can use that the newer method isNaN (Not a Number) and divide your third character with 1. If it's a letter, isNaN will return "true" and if it's a number, it will return "false".

I would, however, recommend you to learn regular expressions, as it will benefit you tremendously in the future.
You basically create a pattern and then test a string against that pattern. If you find a match, then it's  correct. I made a snippet below to demonstrate:

function validateInput() {
  let inputElement = document.getElementById("namn");
  let divElement = document.getElementById("comment");

  var message = "not true";
  let inputValue = inputElement.value.trim();

  let pattern = new RegExp(/^[a-zøæ]{2}\d{1}/, "i");

  if (isValid(inputValue, pattern)) {
    message = "true"
  }

  divElement.innerHTML = message;
}

function isValid(str, pattern) {
  return str.match(pattern);
}
<input id="namn" type="input" value="">

<input type="button" onclick="validateInput()" value="Validate" />

This row needs explanation:
let pattern = new RegExp(/^\d{1}[a-zøæ]{2}/, "i");
The regular expression contains expressions that can be stringed together:
^: start at the beginning of the string.
[a-zøæ]{2}: 2 characters must be between a-z or contain ø or æ.
\d{1}: next following 1 character must be a digit.
The flag "i" makes the a-z case insensitive. Another way would be to don't add a flag, and instead write [a-zA-ZøØæÆ]
Answer: Regex to the rescue. You can add another else if statement as per the following:
else if (klassekode.value.trim().length !== 3) {
    // after checking whether the string length is 3 characters...
} else if (!klassekode.value.trim().match(/^[a-z]{2}\d/i)) {
    // apply validation warning styles
    return false;
}

An explanation of the Regex:
^ - asserts position at the start of the string
[a-z] - matches an alphabetic character
{2} - matches exactly twice
\d - matches a digit (0-9) once
i - case insensitive match
I am not checking the string length again because your previous condition accounts for it.
Ensure to trim() the value before using it (e.g. before sending it to the backend for processing, etc.), because otherwise the leading/trailing spaces will be retained.


Múltiplas transações com FireDAC?

Question: Gostaria de trabalhar com múltiplas transações simultâneas no FireDAC, tomando decisões (rollbacks e commits) diferentes para cada uma. É possível?
Atualmente, trabalho da seguinte forma:
<code>try
  obj_TFDConnection.StartTransaction();
  ...
  obj_TFDConnection.Commit();
except
  obj_TFDConnection.Rollback();
end;
</code>
Porém, assim só consigo gerenciar uma transação de cada vez.
Comment: Documentação oficial com a soluação: http://docwiki.embarcadero.com/RADStudio/Berlin/en/Managing_Transactions_(FireDAC)
Answer: Amigo a transação do FireDAC é conceitualmente diferente da transação do DBX. Acontece que ambos trabalham com multi transações; O que quero dizer que na pratica você pode abrir uma transação, executar algum tipo de alteração no banco, abrir outra transação efetuar novas mudanças e assim por diante. A questão central é que temos uma grande diferença entre o FireDAC e o DBX na maneira como é visto isso. Então implica diretamente em como vc trabalhar. Vejamos:
Tomamos como exemplo duas tabelas, e teremos que fazer uma ação, que consiste em fazer um insert em cada tabela, se ambos forem executados sem problemas é commit e retornamos "OK" para a função principal.
No DBX iremo perceber que a segunda transação não tem relacionado com a primeira. Sou seja se der commit na primeira e rollback na segunda vai ser ao final teremos somente uma inserção;
Já no FireDAC a mesma situação. Se tivermos commit na primeira e rollback na segunda, ambas as transações sofrerão rollback; É como se a primeira manda em tudo.
Isso é uma enorme diferença se vc estiver pensando em migrar;
Answer: Quando venderam o PODER do FireDAC vendo a imagem de conseguir reconectar ao banco de dados (sem perder os dados) foi um milagre...
Mas não contaram os Pós que iriamos enfrentar para quem vem do DBX...
Foi barra, mas consegue resolver assim;
Transaction1 := TFDTransaction.Create(nil);
Transaction1.Connection := TDtMdl(DtMdl).SQLCnctnBancoDados;
Transaction1.Options.AutoCommit := False;
Transaction1.Options.DisconnectAction := xdRollback;
Transaction2 := TFDTransaction.Create(nil);
Transaction2.Connection := TDtMdl(DtMdl).SQLCnctnBancoDados;
Transaction2.Options.AutoCommit := False;
Transaction2.Options.DisconnectAction := xdRollback;
SQL1 := TFDQuery.Create(nil);
SQL1.Connection := TDtMdl(DtMdl).SQLCnctnBancoDados;
SQL1.Connection.TxOptions.AutoCommit := False;
SQL1.Transaction := Transaction1;
SQL2 := TFDQuery.Create(nil);
SQL2.Connection := TDtMdl(DtMdl).SQLCnctnBancoDados;
SQL2.Connection.TxOptions.AutoCommit := False;
SQL2.Transaction := Transaction2;
try
if Transaction1.Active = False then
Transaction1.StartTransaction;
if Transaction2.Active = False then
Transaction2.StartTransaction;
Transaction1.commit;
Transaction2.commit;
except
Transaction1.rollback;
Transaction2.rollback;
end;
obs.
Todos os SQL rodados no SQL1, será tratado na transaction1
Todos os SQL rodados no SQL2, será tratado na teansaction2
Espero ter ajudado;
[]´s

Múltiplas transações com FireDAC?


Edit htaccess file in apache

Question: I would like to deny all IP addresses but allow one specific IP address in .htaccess.
How I should configure my .htaccess or is it a different file?
I have CentOS 5 and Apache.
Answer: <Directory /directory_name>
    Order Deny,Allow
    Deny from all
    Allow from 18.104.22.168
</Directory>

Comment: Small note: This won't work in an `.htaccess` file but only in the main Apache httpd configuration. If you want to use the snipper in an `.htaccess` file you'll have to drop the `` tags.

Edit htaccess file in apache


Kubernetes readiness probe warning has no details

Question: I've made a deployment in GKE with a readiness probe. My container is coming up but it seems the readiness probe is having some difficulty. When I try to describe the pod I see that there are many probe warnings but it's not clear what the warning is.
Events:
  Type     Reason                   Age                   From                     Message
  ----     ------                   ----                  ----                     -------
  Normal   Scheduled                43m                   default-scheduler        Successfully assigned default/tripvector-7996675758-7vjxf to gke-tripvector2-default-pool-78cf58d9-5dgs
  Normal   LoadBalancerNegNotReady  43m                   neg-readiness-reflector  Waiting for pod to become healthy in at least one of the NEG(s): [k8s1-07274a01-default-tripvector-np-60000-a912870e]
  Normal   Pulling                  43m                   kubelet                  Pulling image "us-west1-docker.pkg.dev/triptastic-1542412229773/tripvector/tripvector"
  Normal   Pulled                   43m                   kubelet                  Successfully pulled image "us-west1-docker.pkg.dev/triptastic-1542412229773/tripvector/tripvector" in 888.583654ms
  Normal   Created                  43m                   kubelet                  Created container tripvector
  Normal   Started                  43m                   kubelet                  Started container tripvector
  Normal   LoadBalancerNegTimeout   32m                   neg-readiness-reflector  Timeout waiting for pod to become healthy in at least one of the NEG(s): [k8s1-07274a01-default-tripvector-np-60000-a912870e]. Marking condition "cloud.google.com/load-balancer-neg-ready" to True.
  Warning  ProbeWarning             3m1s (x238 over 42m)  kubelet                  Readiness probe warning:

I've tried examining events with kubectl get events but that also doesn't provide extra details on the probe warning:
 ❯❯❯ k get events
LAST SEEN   TYPE      REASON                    OBJECT                             MESSAGE
43m         Normal    LoadBalancerNegNotReady   pod/tripvector-7996675758-7vjxf    Waiting for pod to become healthy in at least one of the NEG(s): [k8s1-07274a01-default-tripvector-np-60000-a912870e]
43m         Normal    Scheduled                 pod/tripvector-7996675758-7vjxf    Successfully assigned default/tripvector-7996675758-7vjxf to gke-tripvector2-default-pool-78cf58d9-5dgs
43m         Normal    Pulling                   pod/tripvector-7996675758-7vjxf    Pulling image "us-west1-docker.pkg.dev/triptastic-1542412229773/tripvector/tripvector"
43m         Normal    Pulled                    pod/tripvector-7996675758-7vjxf    Successfully pulled image "us-west1-docker.pkg.dev/triptastic-1542412229773/tripvector/tripvector" in 888.583654ms
43m         Normal    Created                   pod/tripvector-7996675758-7vjxf    Created container tripvector
43m         Normal    Started                   pod/tripvector-7996675758-7vjxf    Started container tripvector
3m38s       Warning   ProbeWarning              pod/tripvector-7996675758-7vjxf    Readiness probe warning:

How can I get more details on how/why this readiness probe is giving off warnings?
EDIT: the logs of the pod are mostly empty as well (klf is an alias I have to kubectl logs):
 ❯❯❯ klf tripvector-6f4d4c86c5-dn55c
(node:1) [DEP0131] DeprecationWarning: The legacy HTTP parser is deprecated.
{"line":"87","file":"percolate_synced-cron.js","message":"SyncedCron: Scheduled \"Refetch expired Google Places\" next run @Tue Mar 22 2022 17:47:53 GMT+0000 (Coordinated Universal Time)","time":{"$date":1647971273653},"level":"info"}

Comment: what did the `kubectl log ` show ?
Comment: The logs are more or less empty. I'll update the post with the answer.
Answer: Regarding the error in the logs "DeprecationWarning: The legacy HTTP parser is deprecated.", it is due to the legacy HTTP parser being deprecated with the pending End-of-Life of Node.js 10.x. It will now warn on use, but otherwise continue to function and may be removed in a future Node.js 12.x release. Use this URL for more reference Node v12.22.0 (LTS).
On the other hand, about the kubelet's "ProbeWarning" reason in the warning events on your container, Health check (liveness & readiness) probes using an HTTPGetAction will no longer follow redirects to different host-names from the original probe request. Instead, these non-local redirects will be treated as a Success (the documented behavior). In this case an event with reason "ProbeWarning" will be generated, indicating that the redirect was ignored. If you were previously relying on the redirect to run health checks against different endpoints, you will need to perform the healthcheck logic outside the Kubelet, for instance by proxying the external endpoint rather than redirecting to it. You can verify the detailed root cause of this in the following Kubernetes 1.14 release notes. There is no way to see more detailed information about the  "ProbeWarning" in the Events' table. Use the following URLs as a reference too Kubernetes emitting ProbeWarning, Confusing/incomplete readiness probe warning and Add probe warning message body.
Comment: ah interesting, I don't think I have any redirects set up in my application. The `/heatlhz` endpoint I exposed directly by the server.
Comment: Hmm, I wonder if this could be an issue with https. I currently have the app deployed on heroku and when I execute `curl http://app.tripvector.io/healthz` I get an empty response but when I execute `curl https://app.tripvector.io/healthz` (with https) I get the full response. I wonder if that is affecting how the healthcheck works on k8s?
Comment: and I see something similar when I run the app through docker locally. If I build a production image, and run the container with `-p 3000:3000`, none of the `curl` requests to `localhost:3000/healthz` get the full response object
Comment: Ah yup, my application has `force-ssl` installed which is probably why this is breaking. However, when I change my readiness probe to use HTTPS as the scheme, it has it's connection refused. That's probably some quirk of the package with kubernetes.
Comment: Another option you can try is the command `kubectl describe pod liveness-exec`, please do, use this [URL](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/#define-a-liveness-command) as a deeper reference, and let us know the result. Regarding **https** theory, yes, that may affect the way **Healthcheck** behaves, or if you have **HTTPGetAction** set up, do you have it?


dplyr summarize grouped data with another column

Question: I have a data frame pop.subset <-:
state  location   pop
WA     Seattle    100
WA     Kent       20
OR     foo        30
CA     foo2       80

I need the city in each state with the lowest population stored in a data.frame.
I have:
result <- pop.subset %>%
          group_by(state) %>%
          summarise(min = min(pop))

This returns the data.frame:
state   min
WA      20
...    .... etc

But I need the city too. I tried including location in the group_by function like so: group_by(state, location), but then this gives the min each city paired with a state instead of the state with the city like so:
state location pop
WA    Seattle  100
WA    Kent     20
foo   foo      foo

Is there is a simple solution I missing? I want my result to be like so:
state location pop
WA    Kent     20
...   ...      ... etc.

Comment: Can you edit this question so as the code and data match. Currently you have `State`, `Location` and `Pop` in the data frame, but `state` (lower-case 's'), `location` (lower-case 'l') and `both_sexes_2012` (how does that relate to `Pop`?) in the code.
Comment: Oh sorry I copied some old code, fixed it!
Answer: I think you want to group by state, then filter for min(pop):
pop.subset %>%
  group_by(state) %>%
  filter(pop == min(pop)) %>%
  ungroup()

# A tibble: 3 x 3
  state location   pop
  <chr>    <chr> <int>
1    WA     Kent    20
2    OR      foo    30
3    CA     foo2    80

Comment: you're totally right! thanks I am not sure why I didn't see that. Tried to over complicate it with the summarise function.
Comment: It would seem intuitive to use `summarise`, the key thing is the grouping. If you group on A + B then the summary is for A + B, not for B.
Answer: Did you try something like this?
result <- pop.subset %>%
              group_by(state, location) %>%
              summarise(min = min(both_sexes_2012))

Comment: I tried that but then it pairs states and cities together instead of the minimum city within each state. state location pop. E.g. returns WA, Seattle 100 and WA, Kent, 20 instead of just WA, Kent, 20
Answer: I understand, this solves it:
library(tibble)

data<-tribble(~state,  ~location,   ~pop,
       "WA",     "Seattle",    100,
       "WA",    "Kent",       20,
       "OR",     "foo" ,       30,
       "CA",     "foo2" ,      80

)

library(dplyr)

data%>%group_by(state)%>%summarise(location=location[which.min(pop)]
                                   ,min=min(pop))

# A tibble: 3 x 3
  state location   min
  <chr>    <chr> <dbl>
1    CA     foo2    80
2    OR      foo    30
3    WA     Kent    20

Comment: This is great too!


How to center align everything in JPanels having GridLayout

Question: Recently,I had asked a question about how to make JPanels align from top to bottom in a JFrame. Users told me to use GridLayout(). I got everything working,but I forgot to mention that I wanted to center align all the components in the JPanels.
My first JPanel has a JLabel.
My second JPanel has 5 JRadioButtons.
My third JPanel has a JLabel.
My fourth JPanel has a JButton.
Selecting any JRadioButton would change the text of the JLabel in the third JPanel.When the program starts,the JLabel has no text.
My JFrame has GridLayout. All 4 JPanels which have BoxLayout(BoxLayout.X_Axis) are added into this JFrame.Here is a snippet of my code:
class GUI extends JFrame implements ActionListener {

  JPanel pan1,pan2,pan3,pan4;                   //4 JPanels
  JRadioButton rad1,rad2,rad3,rad4,rad5;   //5 RadioButtons
  JButton button;                          //A JButton
  JLabel label;                            //A JLabel
   public GUI(String header)
   {
      super(header);

      setLayout(new GridLayout(0,1,0,6));  //set GridLayout to JFrame
      setBounds(350,325,600,125);
      setResizable(false);

      creator();
      adder();
      commander();

      add(pan1);
      add(pan2);
      add(pan3);
      add(pan4)  //Add all 4 panels to JFrame

  }

  private void adder()
  {
    pan1.setLayout(new BoxLayout(pan1,BoxLayout.X_AXIS));
    pan2.setLayout(new BoxLayout(pan2,BoxLayout.X_AXIS));
    pan3.setLayout(new BoxLayout(pan3,BoxLayout.X_AXIS));
    pan4.setLayout(new BoxLayout(pan4,BoxLayout.X_AXIS)); //Layout for all 4 JPanels

    pan1.add(new JLabel("Choose a Security Level"));

    ButtonGroup group=new ButtonGroup();

    group.add(rad1);
    group.add(rad2);
    group.add(rad3);
    group.add(rad4);
    group.add(rad5);

    pan2.add(rad1);
    pan2.add(rad2);
    pan2.add(rad3);
    pan2.add(rad4);
    pan2.add(rad5);

    pan3.add(label);

    pan4.add(button);
  }

   private void creator()
   {
      pan1=new JPanel();
      pan2=new JPanel();
      pan3=new JPanel();
      pan4=new JPanel();

      rad1=new JRadioButton("Security Level 1");
      rad2=new JRadioButton("Security Level 2");
      rad3=new JRadioButton("Security Level 3");
      rad4=new JRadioButton("Security Level 4");
      rad5=new JRadioButton("Security Level 5");

      button=new JButton("Move On");

      label=new JLabel();
   }

   private void commander()
   {
    rad1.addActionListener(this);
    rad2.addActionListener(this);
    rad3.addActionListener(this);
    rad4.addActionListener(this);
    rad5.addActionListener(this);

    rad1.setActionCommand("radio1");
    rad2.setActionCommand("radio2");
    rad3.setActionCommand("radio3");
    rad4.setActionCommand("radio4");
    rad5.setActionCommand("radio5");

    button.addActionListener(this);
   }

   public void actionPerformed(ActionEvent evt)
   {
   //When button is pressed,the text in label changes

   if(evt.getActionCommand().equals("radio1"))
      label.setText("Very Easy to bypass");
    else if(evt.getActionCommand().equals("radio2"))
      label.setText("Easy to bypass");
    else if(evt.getActionCommand().equals("radio3"))
      label.setText("Can bypass Sometimes");
    else if(evt.getActionCommand().equals("radio4"))
      label.setText("Hard to bypass");
    else if(evt.getActionCommand().equals("radio5"))
      label.setText("Very Hard to bypass");
    else
    { //Code here
    }

    repaint();
    //More code here....
   }

}

And this is the output that I get(Ignore the green lines):

I want everything to be aligned in the center rather than in the left. What should I do in order to align it?
Comment: BTW - `setBounds(350,325,600,125);` should be changed to `setLocationByPlatform(true); pack();` and those should be called after all content is added but before `setVisible(true);`
Comment: @AndrewThompson ,In my original code,I call `setBounds` and `setVisible` after I do `GUI prog=new GUI();`
Answer: Change:
pan1.setLayout(new BoxLayout(pan1,BoxLayout.X_AXIS));

To something like:
pan1.setLayout(new FlowLayout(FlowLayout.CENTER));

..And the same with the rest of the box layouts.
Comment: Now I think:Why hadn't I thought of that earlier? BTW,`FlowLayout.CENTER` isn't needed,is it?
Comment: *"..isn't needed,is it?"*  I've been leery of accepting defaults ever since Sun change the default layout of a frame from `FlowLayout` to `BorderLayout` (a long time ago).
Comment: For a "row" with one element (such as the area containing the "Move On" button at the bottom of the screen), the `FlowLayout.Center` parameter is absolutely needed


Windows Service Interactions

Question: I´m new to write windows services and I was searching around collecting necessery info and howtos. What I´m missing is the interaction between my webapp and the service. The servicecontroller helps me sending messages to the service and gives me the main status of the service.
Is there a way to get custom messages, set custom properties and get properties?
If there are not, should I use a file for both the service and the web app where both can read and write on, like a settings file in xml or are there better methods?
Is there a way to get the messages in the corresponding eventlog, how do i access them?
Comment: Why do you use windows service? What kind of task does it do and why does it need to be controlled by website? By answering these questions you'll give us a better understanding of your task and you'll receive better architecture recommendations.
Comment: Because there are tasks I need it for. I will get back with other questions when it´s time. Now I´m just interessted how to comunicate with a windows service. I´m now just collection some information to decide the best practice, I think there will be more question for my need, I just want them to be written, so that other people can get some good info about. It´s not all about my task, i think it is usefull for people to know the basic question "how to interact with a windows service", doesnt matter why... But thanks for you tip!
Answer: You may want to look into Windows Communication Foundation.  This would allow your service to "serve" information to your WebApp.
Comment: +1. I normally use WCF to communicate between Windows Services and ASP.NET. Usually, controlling the service and reading its log (`ServiceController` and `EventLog`) is not necessary from ASP.NET.
Comment: Yes, if you use WCF it´s not necessary. I just watched those videos and it is exactly what I need for now. Thanks a lot Reed!

Windows Service Interactions


Closed Range Convolution Operator

Question: Does there exists a nontrivial $f \in L^1(\mathbb{R})\cap L^\infty(\mathbb{R})$ such that $f\ast L^\infty(\mathbb{R})$ is a closed subspace of $L^\infty(\mathbb{R})$?
I couldn't find any good reference on closed range convolution operators.
Comment: Ops. It should have read nontrivial $f$.
Comment: I'm good at the trivial problems...
Answer: I am assuming that $f$ is a nonnegative function in $L^1(\mathbb R)$. Then the range of the operator $Tg:=f\ast g$ is closed only in the trivial case $f=0$. Here $T\colon L^\infty(\mathbb R)\to L^\infty(\mathbb R)$.
Proof. Letting $g_n(x):=\mathbf{1}_{\left[-\tfrac1n, \tfrac1n\right]}(x)$, we have
$$
\lVert g_n \rVert_{\infty}=1,\quad \lVert Tg_n\rVert_\infty \to 0,\quad Tg_n\ne 0;$$
the last of the three being a consequence of $f\ge 0$, while the second is a consequence of $f\in L^1(\mathbb R)$.
Now, the existence of such a sequence $g_n$ implies that the range of $T$ is not closed. Indeed, $T$ is injective (here I use again that $f\ge 0$). If it had a closed range, its inverse would be bounded. And this is precisely what the sequence $g_n$ above disproves.

Closed Range Convolution Operator


What is the reason of this Segmentation fault for PRIME1 on Spoj?

Question: I'm trying to solve the PRIME1 problem on Spoj. I implemented this code using segmented sieve of Eratosthenes
    #include <stdio.h>

    long int primes[100000];

    int main(void) {

       long int t, m, n, i, j, p;
       scanf("%ld",&t);

       while(t--) {
          scanf("%ld",&m);
          scanf("%ld",&n);

          for(i=2; i*i<=n; i++) {
            p=m/i;
            p=p*i;

            for(j=p; j<=n; j+=i)    {
                if(j!=i)
                    primes[j-m] = 1;
            }
          }

          for(i=0; i<(n-m+1); i++)  {
             if(primes[i] == 0)
                 printf("%ld ",i+m);
             else
                 continue;
          }

          printf("\n");
       }
       return 0;
    }

Its works fine when value of n-m is not very high. But if the value of n-m gets very high (i.e. near about 100000), it gives Segmentation fault. Why there is such kind of behaviour?
Also, when I declared the primes array inside main, the code works correctly.
    #include <stdio.h>

    int main(void) {

       long int t, m, n, i, j, p;
       scanf("%ld",&t);

       while(t--) {
          scanf("%ld",&m);
          scanf("%ld",&n);
          if(m==1)  m=2;

          long int primes[n-m+1];
          for(i=0;i<n-m+1;i++)
            primes[i]=0;

          for(i=2; i*i<=n; i++) {
            p=m/i;
            p=p*i;

            for(j=p; j<=n; j+=i)    {
                if(j!=i)
                    primes[j-m] = 1;
            }
          }

          for(i=0; i<(n-m+1); i++)  {
             if(primes[i] == 0)
                 printf("%ld ",i+m);
             else
                 continue;
          }

          printf("\n");
       }
       return 0;
    }

Why the program gives Segmentation fault when I declare the primes array globally?
Comment: Maybe you're going out of bounds of the array? Or maybe you need `unsigned long long` (`long` may be just 32 bits and you're overflowing)?
Comment: `n-m` max  = 100000, `i<(n-m+1)` : `i` max = `n-m` but `primes[100000];` So `primes[i]=0;` (`primes[100000] = 1`) is out of bounds.
Comment: when a user runs the program, they are left with a blinking cursor and no idea about what they are expected to enter.   Suggest: prompt the user for each of the three input values.  Always check the returned value from scanf() to assure the operation was successful
Comment: @user3629249 This program for SPOJ.
Answer: In the first you are declaring primes to have a fixed size of 100000 so if you ever try to access an element outside that range you'll be accessing memory you should not, thus a seg fault.
In the second example you declare it to be size n-m+1 which will make sure it's always big enough to do what you want.
Comment: No. Even if the value of n-m is within and near about 100000, for example 99999, it shows a Segmentation fault.
Comment: I can't repoduce the failure if `n-m` is < 100000, I only get a seg fault if it's greater than that


How to parametrize setUpClass() in Python (2.7) unittests

Question: I am currently implementing a kind of table with interpolation between the values, boundary handling, etc. and want to write unit tests for it.
There is quite a set of possible scenarios e.g. the tables could have only one/multiple row(s)/column(s) and different boundary conditions. The tables in all of these scenarios should all pass the same set of unittests.
For now I am writing a base class for one of the cases and derive from it overriding the setUpClass() method. This is however tedious for testing all combinations.
Is there to generate the TestCase classes dynamically run them with different parameters.
When googling for the problem the best thing I found was overloading load_tests() and add all test methods one by one (which means setting up the objects prior to running each test method instead of once per scenario).
Comment: Why not write a class factory that creates subclasses of your main test class with a `setUpClass` based on the specific requirements of the scenario?
Comment: You can create paramterized test series using either [nose test generators](http://nose.readthedocs.org/en/latest/writing_tests.html#test-generators) or [pytest parametrize method](https://pytest.org/latest/parametrize.html).
Comment: @jonrsharpe This worked. The main reason I did not think about it, was that I did not know how to make PyCharm (or `unittest discover`) aware of the created classes. I now managed to do it using `load_tests()`.
Comment: @Tim if you've cracked it, you can write an answer to your own question
Answer: Thanks to the hint from @jonrsharpe I managed to do it.
My solution is to create the classes dynamically and then add them to the TestSuite using load_tests:
def create_test_case(testcase_name, scenario_data):
    class ScenarioTestCase(BaseTestCase):
        @classmethod
        def setUpClass(cls):
            cls.fillClassVariables(scenario_data)
    return_class = ScenarioTestCase
    return_class.__name__ = testcase_name #for separating the results
    return return_class

def load_tests(loader, tests, pattern):
    list_scenario_names = [...]
    list_scenario_data = [...]

    loader = unittest.TestLoader()
    tests = TestSuite()
    for scenario_name, scenario_data in zip(list_scenario_names, list_scenario_data):
        tests.addTests(loader.loadTestsFromTestCase(
            create_test_case(scenario_name, scenario_data)))
    return tests

This way the TestCases are created dynamically with different parameters and listed separately in PyCharm's Test Runner Tab.
Comment: I might be inclined to have a list of tuples `[(scenario_name, scenario_data), ...]`, to keep the name and data together, but otherwise good job!
Answer: Though this has an accepted answer, I want to document how to do this with subclassing, since it took me a long time to find the details of such a solution. In my case, the goal is for a TestCase class with several methods to have a class fixture (setting up files on the filesystem to test a cli tool), and vary this slightly in the parametrization.
# Inherit from object to not run this abstract class
class TemporaryFolderClassSetup(object):

    @classmethod
    def setUpClass(cls):
        try:
            cls._root = tempfile.mkdtemp()
            # .. create some files here ...
            # allow subclasses to manipulate file tre
            cls.prepare_directory(cls._root)
        except Exception as e:
            cls.tearDownClass()
            raise

    @classmethod
    def tearDownClass(cls):
        shutil.rmtree(cls._root)

    @classmethod
    def prepare_directory(cls, root):
        pass

    # test methods that will run in each subclass
    def testX():
        pass

# scenariotest, must inherit from superclass first, before unittest.TestCase)
class ScenarioTests(TemporaryFolderClassSetup, unittest.TestCase):

    # ... called by parent class
    @classmethod
    def prepare_directory(cls, root):
        pass

    # test only for this scenario
    def testY(self):
        pass


Somando e ordenando linha de matrizes em python

Question: O programa abaixo gera uma matriz aleatória, conforme a quantidade de linhas desejadas.
def gerar(nLins, nCols, min, max):
    from random import randint
    vals = [None] * nLins
    for i in range(nLins):
        vals[i] = [0] * nCols
        for j in range(nCols):
            vals[i][j] = randint(min, max)
    return vals

def mostrar(vals, linMin, linMax, colMin, colMax):
    for i in range(linMin, linMax):
        for j in range(colMin, colMax):
            print(vals[i][j], end=" ")
        print()
    print()
    return None

qtd = input().split()
qtdLinhas = int(qtd[0])
qtdColunas = int(qtd[1])
valores = gerar(qtdLinhas, qtdColunas, 10, 99)
mostrar(valores, 0, qtdLinhas, 0, qtdColunas)

No caso, gostaria de saber como eu poderia fazer a soma de cada linha da matriz e gerar uma nova matriz com as linhas da matriz em ordem crescente da soma de seus valores?
Exemplo:
Quero uma matriz 5 x 6
É gerada a matriz:
13 28 45 50 26 10
27 24 22 33 88 11
90 25 85 23 76 55
77 15 31 29 13 14
66 41 50 20 47 11

Com ela, é gerada se segunda matriz com as linhas ordenadas conforme a sua soma, na ordem crescente:
13 28 45 50 26 10
77 15 31 29 13 14
27 24 22 33 88 11
66 41 50 20 47 11
90 25 85 23 76 55

Visto que suas somas, em ordem crescente dão 172 na primeira linha, 179 na segunda linha, 205 na terceira linha, e assim sucessivamente...
Answer: Use o método sort.
Você pode passar no parâmetro key uma função de callback para gerar o valor que será utilizado para comparar e organizar os itens da matriz. Para esse caso basta usa a função sum para somar todos os itens de cada lista. O resultados das somas serão comparados internamente e a matriz será organizada em ordem crescente pelos resultados das somas:
valores = [
    [13, 28, 45, 50, 26, 10],
    [27, 24, 22, 33, 88, 11],
    [90, 25, 85, 23, 76, 55],
    [77, 15, 31, 29, 13, 14],
    [66, 41, 50, 20, 47, 11]
]

valores.sort(key=sum)

Comment: Poderia me dar um exemplo? Não consegui aplicar gerando a matriz como mencionei acima e aplicando esse conceito que você passou.
Comment: [Aqui](https://ideone.com/YdwsVQ) tem o código funcionando. Não entendi a dificuldade, visto que você pode usar o código literalmente como está na resposta.


Tuples as Dictionary value

Question: My problem is: I have a dictionary with a enum type as key and a named tuple as value.
private let positionDictionary:[Position:(shortG: String, longG: String, shortE: String, longE: String)] =
[   .Goalkeeper:("TW","Torwart","GK","Goalkeeper"),
    .CentralDefender:("IV","Innenverteidiger","CD","Central Defender"),
    .LeftBack:("LV","Linker Verteidiger","LB","Left Back"),
    .LeftWingBack:("LAV","Linker Außenverteidiger","LWB","Left Wing Back"),
    .RightBack:("RV","Rechter Verteidiger","RB","Right Back"),
    .RightWingBack:("RAV","Rechter Außenverteidiger","RWB","Right Wing Back")]

This is part of class where I want to do this:
self.positionDictionary[.Goalkeeper].shortE

But the compiler tells me that he "could not find the member 'shortE'". What am I missing? I would really much appreciate any help :]
Answer: Dictionary key subscript returns optional values. You need to unwrap it or use optional bidding:
if let goalkeepersShortE = self.positionDictionary[.Goalkeeper]?.shortE {
    // ...
}

Comment: or `self.positionDictionary[.Goalkeeper]!.shortE`
Comment: do not use previous comment. if the dictionary containts no value for key .Goalkeeper it will crash at runtime. always check your optionals.

Tuples as Dictionary value