Joint probability function $f(x,y)$

Question: I got this question on an exam and was thrown off by the $x$ variable.
\begin{equation*}
f(x,y) =
\begin{cases}
\frac{cy}{x^{2}},\quad &x\geq 1,\ 0<y<1\\
0,\quad &\text{otherwise}.
\end{cases}
\end{equation*}
I understand you derive the double integral and set it equal to one but the $x$ variable is throwing me off.
Thanks for any help!
Answer: You are solving
$$
c\int_0^1\int_1^\infty\frac{y}{x^2}dxdy=1\implies
c\int_0^1ydy\int_1^\infty\frac{1}{x^2}dx=1
$$
does that help?
Answer: You didn't state it, but I assume you seek to find the value of $c$. Recall that a PDF must integrate to $1$ (that's a requirement). So we simply impose that condition:
$$\iint_{\mathbb R^2} f(x, y)\,\mathrm dx\mathrm dy = 1$$
We are integrating over the whole $\mathbb R^2$ plane, but using the fact that the PDF is zero on some subset of it, we can rewrite the above as
$$\int_0^1\int_1^\infty \frac{cy}{x^2}\mathrm dx\mathrm dy = 1$$
Now, can you finish this?
Comment: why are you doing $x^3$?
Comment: @Heavenly96 Typo, thanks for pointing it out.

Joint probability function $f(x,y)$


¿Why this returns 0?

Question: Thats return me 0. Why? i need som like this 1/8 + 1/7 + 1/6....1/m
Srry for my code, im learning sql.
<code>delimiter //

drop function if exists divide;

create function divide(m int) returns decimal(30,3) deterministic
begin
    declare m int;
    declare n decimal(30,3) default 0;
    declare x decimal(30,3) default 0;

    while m>=1 do
        set n=n+x;
        select 1/m into x;
        set m=m-1;
    end while;

    return n;
end;//

delimiter ;

select divide(8);
</code>
Comment: Hint: you have two `m int`s..
Comment: `1/m` is likely to give 0 for m with a magnitude greater than 2. Perhaps you meant `1.0/m`.
Comment: [Why should I "tag my RDBMS"?](https://meta.stackoverflow.com/q/388759/11683)
Comment: 1/m is integer division and returns 0, i suppose
Comment: Ok, its solved, thx all.
Answer: Thanks you all, the solution was that i declared two times m.

¿Why this returns 0?


MIPS R4000 Latency and Initiation Intervals

Question: Why MIPS R4000 has latency of 112 cycles and initiation interval of 111 cycles for square root functional unit  ?
Answer: The MIPS R4000 Microprocessor User's Manual provides a somewhat detailed description of the R4000 floating point pipeline (see section 6.7). For floating point operations, the R4000 FPU provides eight operation stages (mantissa add, divide pipeline, exception test, first multiplier, second multiplier, rounding, operand shift, unpack FP numbers). Double precision square root uses the unpack FP numbers for the first cycle, the exception test for the second, both mantissa add and rounding for the next 108 cycles, mantissa add for the next cycle, and rounding for the last cycle.
Since the unpack FP numbers and exception test (the first two cycles) are not used in later cycles, a following square root operation can start two cycles earlier than if square root was completely unpipelined. This can be diagrammed as follows:

         1    2    3   4  ... 110  111  112  114  115
SQRT.D   U    E   A+R A+R     A+R   A    R
SQRT.D        110 stall cycles for second SQRT.D
                                    U    E   A+R  A+R

(You can see that the initiation interval counts the cycle when the first SQRT.D is issued, i.e., an initiation interval of zero would mean parallel issue and an initiation interval of one would support back-to-back issue.)


Adding !one! entity to my game adds !two! entities

Question: My question is:
Why does adding an entity to my game (entityManager.addEntity(new Tree(handler, 19 * 64, 7 * 64));) add 2 entities at once?
I added 8 new trees, and got 12, so I was confused.
On top of that, I have a world.txt file that has my whole world's tiles in it.
The world class is here:
public class World {

    private Handler handler;
    private int width, height;
    private int spawnX, spawnY;
    private int[][] tiles;
    //Entities
    private EntityManager entityManager;

    public World(Handler handler, String path){
        this.handler = handler;
        entityManager = new EntityManager(handler, new Player(handler, 100, 100));
        entityManager.addEntity(new Tree(handler, 16 * 64, 7 * 64));
        entityManager.addEntity(new Tree(handler, 17 * 64, 7 * 64));
        entityManager.addEntity(new Tree(handler, 18 * 64, 7 * 64));
        entityManager.addEntity(new Tree(handler, 19 * 64, 7 * 64));
        entityManager.addEntity(new Tree(handler, 16 * 64, 6 * 64));
        entityManager.addEntity(new Tree(handler, 17 * 64, 6 * 64));
        entityManager.addEntity(new Tree(handler, 18 * 64, 6 * 64));
        entityManager.addEntity(new Tree(handler, 19 * 64, 6 * 64));
        entityManager.addEntity(new Rock(handler, 100, 450));

        loadWorld(path);

        entityManager.getPlayer().setX(spawnX);
        entityManager.getPlayer().setY(spawnY);
    }

    public void tick(){
        entityManager.tick();
    }

    public void render(Graphics g){
        int xStart = (int) Math.max(0, handler.getGameCamera().getxOffset() / Tile.TILEWIDTH);
        int xEnd = (int) Math.min(width, (handler.getGameCamera().getxOffset() + handler.getWidth()) / Tile.TILEWIDTH + 1);
        int yStart = (int) Math.max(0, handler.getGameCamera().getyOffset() / Tile.TILEHEIGHT);
        int yEnd = (int) Math.min(height, (handler.getGameCamera().getyOffset() + handler.getHeight()) / Tile.TILEHEIGHT + 1);

        for(int y = yStart;y < yEnd;y++){
            for(int x = xStart;x < xEnd;x++){
                getTile(x, y).render(g, (int) (x * Tile.TILEWIDTH - handler.getGameCamera().getxOffset()),
                        (int) (y * Tile.TILEHEIGHT - handler.getGameCamera().getyOffset()));
            }
        }
        //Entities
        entityManager.render(g);
    }

    public Tile getTile(int x, int y){
        if(x < 0 || y < 0 || x >= width || y >= height)
            return Tile.grassTile;

        Tile t = Tile.tiles[tiles[x][y]];
        if(t == null)
            return Tile.dirtTile;
        return t;
    }

    private void loadWorld(String path){
        String file = Utils.loadFileAsString(path);
        String[] tokens = file.split("\\s+");
        width = Utils.parseInt(tokens[0]);
        height = Utils.parseInt(tokens[1]);
        spawnX = Utils.parseInt(tokens[2]);
        spawnY = Utils.parseInt(tokens[3]);

        tiles = new int[width][height];
        for(int y = 0;y < height;y++){
            for(int x = 0;x < width;x++){
                tiles[x][y] = Utils.parseInt(tokens[(x + y * width) + 4]);
            }
        }
    }

    public int getWidth(){
        return width;
    }

    public int getHeight(){
        return height;
    }

    public EntityManager getEntityManager() {
        return entityManager;
    }

}

My EntityManager class is here:
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.Comparator;

import dev.blaze.tilegame.Handler;
import dev.blaze.tilegame.entity.creatures.*;

public class EntityManager {

    private Handler handler;
    private Player player;
    private ArrayList<Entity> entities;
    private Comparator<Entity> renderSorter = new Comparator<Entity>(){
        @Override
        public int compare(Entity a, Entity b) {
            if(a.getY() + a.getHeight() < b.getY() + b.getHeight())
                return -1;
            return 1;
        }
    };

    public EntityManager(Handler handler, Player player){
        this.handler = handler;
        this.player = player;
        entities = new ArrayList<Entity>();
        addEntity(player);
    }

    public void tick(){
        for(int i = 0;i < entities.size();i++){
            Entity e = entities.get(i);
            e.tick();
            if(!e.isActive())
                entities.remove(e);
        }
        entities.sort(renderSorter);
    }

    public void render(Graphics g){
        for(Entity e : entities){
            e.render(g);
        }
    }

    public void addEntity(Entity e){
        entities.add(e);
    }

    //GETTERS SETTERS

    public Handler getHandler() {
        return handler;
    }

    public void setHandler(Handler handler) {
        this.handler = handler;
    }

    public Player getPlayer() {
        return player;
    }

    public void setPlayer(Player player) {
        this.player = player;
    }

    public ArrayList<Entity> getEntities() {
        return entities;
    }

    public void setEntities(ArrayList<Entity> entities) {
        this.entities = entities;
    }

}

I don't think the error is in the EntityManager class, it might be where I made the Tree class, or just eclipse's error.
The tree class is here:
    public class Tree extends StaticEntity {

    public Tree(Handler handler, float x, float y) {
        super(handler, x, y, Tile.TILEWIDTH, Tile.TILEHEIGHT * 2);

        bounds.x = 0;
        bounds.y = 0;
        bounds.width = width;
        bounds.height = height;
    }

    @Override
    public void tick() {

    }

    @Override
    public void die(){

    }

    @Override
    public void render(Graphics g) {
        g.drawImage(Assets.log, (int) (x - handler.getGameCamera().getxOffset()), (int) (y - handler.getGameCamera().getyOffset()), width, height, null);
    }

}

If you need to know any other classes, tell me in the comments.
Comment: well let's see that EntityManager class too at least. Also what exactly is giving you the hint that this method adds too many items. Debugger view of memory? output of some function?
Comment: The hint that I'm getting is that when I mine the block, it mines two blocks and it covers three tiles and not two. All the tiles are a size of two tiles, they're just overlapping, giving three and not four. @BrunoDelor
Comment: I don't see anything that would result in duplication of entities. Use the debug feature of your IDE to check the state of your program when it runs. if your list only contains the entities you need this means that the mistake is more toward the code managing mining
Comment: @BrunoDelor could it be in the Tree class where I set tree to draw itself? I added the tree class so you could have a look, and debug isn't helping since I have like 20 classes
Comment: it could indeed. It's a bit of a prediction exercice for me right now but my bets are either on the code that calculate what is getting interracted with in the world or the code drawing a single entity. Maybe try with one tree and see if a second one appears if yes then initialize it elsewhere and see if the other one move in the same way
Comment: Debug always help, you just need to think more about where to put your breakpoints :3
Comment: @BrunoDelor It's with the `entityManager.addEntity(new Tree(handler, 19 * 64, 7 * 64));`.
Comment: I know, just add only one tree or one rock and check if you see multiple ones instead. if yes then it is a strong indicator that it is drawing wrong. if not then it's a stong indicator that it is your interaction algorithm that is not doing it's job
Comment: @BrunoDelor I did, that's how I knew it was duplicating.
Comment: My bad, would you mind uploading your project so I can attempt replicating your results?
Comment: @BrunoDelor one sec, let me get all of the classes into a github repo
Comment: Here it is: https://github.com/CodeNMore/New-Beginner-Java-Game-Programming-Src/tree/master/Episode%2031/TileGame, every class is in it, though a few need spritesheets made in paint.net. Just warning you: this isn't my code, it's a youtuber's code that I used to make my own game, the codes are very similar, though.
Comment: is that your code? it looks like a tutorial repository; if you have changed anything from this code I cannot really rely on it. on the other hand if it is the base code itself that have problem I might notice somthing; but it will not be as easy as using directly your version
Comment: @BrunoDelor it is, I customized it to be what I want, but that is the code.
Comment: you meant the code from episode 32 right? I've been checking episode 31 but no code to kill a tree or a rock. Unless you coded these parts yourself?
Comment: you really should put all your code online somewhere it will be easier
Comment: @BrunoDelor no, 31, look in the tree, rock, and player classes. Ep 31 is the episode where you attack entities.
Comment: yeah, and the code in githhub for episode 31 doesn't contain any code to handle death of an entity. I have the code under my eyes. All of the episodes' code. Also seeing your answer it indeed was a problem I couldn't find without your project as the problem relied in how the code was interacted with your assets. In any cases I'm glad you figured it out :)
Answer: In the tree class, instead of putting width and height, I replaced both with 64 and got only one tree / log instead of two.
Instead of:
g.drawImage(Assets.log, (int) (x - handler.getGameCamera().getxOffset()), (int) (y - handler.getGameCamera().getyOffset()), width, height, null);

it was:
g.drawImage(Assets.log, (int) (x - handler.getGameCamera().getxOffset()), (int) (y - handler.getGameCamera().getyOffset()), 64, 64, null);


How to write generic IEnumerable extension method

Question: I'm fairly new (ok, REALLy new) to generics but I love the idea of them.  I am going to be having a few drop-down lists on a view and I'd like a generic way to take a list of objects and convert it to a list of SelectListItems
What I have now:
public static IEnumerable<SelectListItem> ToSelectListItems(
     this IEnumerable<SpecificObject> items, long selectedId)
    {
        return
            items.OrderBy(item => item.Name)
            .Select(item =>
                    new SelectListItem
                    {
                        Selected = (item.Id == selectedId),
                        Text = item.Name,
                        Value = item.Id.ToString()
                    });
    }

Trouble is, I'd need to repeat that code for each drop-down as the objects have different fields that represent the Text property of the SelectListItem
Here is what I'd like to accomplish:
public static IEnumerable<SelectListItem> ToSelectListItem<T>(this IEnumerable<T> items, string key, string value, int SelectedId) {
    // I really have no idea how to proceed from here :(
}

Answer: Well, you could do something like this:
public static IEnumerable<SelectListItem> ToSelectListItems(
     this IEnumerable<T> items,
     Func<T,string> nameSelector,
     Func<T,string> valueSelector,
     Func<T,bool> selected)
{
     return items.OrderBy(item => nameSelector(item))
            .Select(item =>
                    new SelectListItem
                    {
                        Selected = selected(item),
                        Text = nameSelector(item),
                        Value = valueSelector(item)
                    });
}

Comment: How would I call this and, particularly use the 'selected' delegate?
Comment: Cancel that, had to do ToSelectListItems :)
Answer: You could pass in delegates to do the comparisons, and property retrieval.  Something like this:
public static IEnumerable<SelectListItem> ToSelectListItem<T>(this IEnumerable<T> items,
    int selectedId, Func<T,int> getId, Func<T, string> getName,
    Func<T, string> getText, Func<T, string> getValue)
{
    return
        items.OrderBy(item => getName(item))
        .Select(item =>
                new SelectListItem
                {
                    Selected = (getId(item) == selectedId),
                    Text = getText(item),
                    Value = getValue(item)
                });
}

Then you would use it like so:
var selected = specificObjects.ToSelectListItem(10, s => s.Id, s=> s.Name, s => s.Name, s => s.Id.ToString());

Comment: You'd also need a getName delegate (per Bruno's answer) -- the item.Name reference in the OrderBy clause currently won't compile.
Comment: Hmm, I want to mark both this and the next questions as answers :). Both are exactly what I'm looking for!
Answer: In order for this to work as written, your type T will need to implement some interface which provides Name and Id properties:
 public interface ISelectable
 {
     string Name { get; }
     int Id { get; }
 }

With this in place, you can do:
public static IEnumerable<SelectListItem> ToSelectListItems<T>(this IEnumerable<T> items, long selectedId)
     where T : ISelectable
{
    return
        items.OrderBy(item => item.Name)
        .Select(item =>
                new SelectListItem
                {
                    Selected = (item.Id == selectedId),
                    Text = item.Name,
                    Value = item.Id.ToString()
                });
}

This is required in order to use the Name and Id properties within your extension method...  You could, instead, provide a different means of receiving these (ie: passing delegates), but that may or may not increase the maintenance cost in your scenario.
Comment: Friend, with this method, how I would use it ? Looks cleaner than other answers. Thanks !
Answer: //You need to use reflection to get the value of
   public static IEnumerable<SelectListItem> GetListItems<T>
     (this IEnumerable<T> items, int selectedVal)
    {
        return from item in items
               select new SelectListItem
               {
                   Text =item.GetPropValue("Name"),
                    Value = item.GetPropValue("Id"),
                     Selected =
                item.GetPropValue("Id").Equals(selectedVal.ToString())
               };
    }

    public static string GetPropValue<T> (this T item,string refName)
    {

        return
           item.GetType().GetProperty(refName).GetValue(item).ToString();
    }


Find all real values of $x$ which satisfy $\sqrt{x^2 + 1} + x^2 + 1 = 90$.

Question: Find all real values of $x$ which satisfy $\sqrt{x^2 + 1} + x^2 + 1 = 90$.
\begin{align*}
\sqrt{x^2+1} + x^2 &=  89 \\
{(\sqrt{x^2+1} + x^2)}^2 &=  89^2 \\
x^2+2x^2\sqrt{x^2+1}+x^4 &=89^2
\end{align*}
Letting $y = x^2$, so $y^2 = x^4$. This gives us
\begin{equation}
y^2+2y\sqrt{y+1}+y=7920
\end{equation}
I not sure how to proceed to eliminate the radical. I shouldn't square quantities that aren't both positive or else I'll lose the equivalency in the new equation right?
Comment: You could have started with $\sqrt{x^2+1}=89-x^2$ and squared both sides.  Squaring both sides may introduce extraneous solutions, but you'll never lose a solution.
Comment: move the $x^2$ to the right side and do the square...
Answer: Let me point out couple of substitutions that simplifies this equation:

$T=\sqrt{x^2+1},$ then we have a quadratic equation $$T^2+T-90=0$$ which has two solution s $T=9$ and $T=-10.$ Then you continue from here (with the condition that $T\ge 1$).

$x=\tan\theta,$ then $x^2+1=\sec^2\theta$ and we get a trigonometric equation $$\sec^2\theta+\sec\theta-90=0.$$ Similarly $x=\cot\theta$ is also a possible trigonometric substitution for this equation.

$x=\sinh\theta$ has the property that $x^2+1=\cosh^2\theta$ and hence we get $$\cosh^2\theta+\cosh\theta-90=0.$$

In last two substitutions both $\sec$ and $\cosh$ are even functions, therefore we don't need to consider the negative square root as a separate case.
Answer: Hint
Begin by putting
$$y=\sqrt{x^2+1}$$
with
$$y+y^2=90$$
or
$$y^2+y-90=0$$
$$y=\frac{-1\pm 19}{2}$$
and $ y>0$.
You should find that $$x=\pm \sqrt{80}$$
Comment: Or you can factorize viz, $(y-9)(y+10)=0$.
Comment: shouldn't it be $x=\pm\sqrt{80}$?
Comment: @Bumblebee Yes of course. Thank you very much
Answer: Hint to solve
$x^2+1=(89-x^2)^2$
Second hint
Turn the $x^4$ to a variable like $z=x^2$ so you can solve the exercise using discriminant.


Delete all files with *.zip except latest 5(recent) files under windows server

Question: I have filenames called
abc_1.zip
abc_2.zip
abc_3.zip
abc_4.zip
abc_5.zip(below_latest)
abc_6.zip(latest)

under windows server 2012 r2. Now I need a single command to delete all files except the latest and below_latest one.
Note: The above names are just for example. So I can say I want to keep the only recent file(latest and below_latest) and remove all.
Also, I need a single line command, not a PowerShell script.
Thanks in advance.
Answer: Single Line PowerShell:
Get-ChildItem -file | Sort-Object LastWriteTime -Descending | Select-Object -Skip 2 | Remove-Item

or using some aliases:
ls -file | sort LastWriteTime -d | Select -Skip 2 | rm

if you are not in the directory with the files to delete use:
Get-ChildItem -Path C:\test ...


$f_n \in H(G)$ converges uniformly on every compact subset of $G$ to a function $f$. Prove $f$ is holomorphic on $G$

Question: Let $G \subset \mathbb{C}$ be a connected open set and $f_n$ be a sequence of holomorphic functions on $G$, which converges uniformly on every compact subset of $G$ to a function $f$. Prove $f$ is holomorphic on $G$
I tried to prove $f$ can be expressed a series of power series
$$ f(z)=\lim_{m\rightarrow \infty}\sum_{n=0}^{\infty}\frac{1}{2\pi i}\int_{\gamma}\frac{f_m(w)}{{(w-z_0)}^{n+1}}dw \ (z-z_0)^n$$
But I need to put the limit to $f_m$ to finish proof. Can I switch the lim and summation here? Why? Thank you!
Comment: How about using Cauchy's integral formula?
Comment: seems I get it! Thank you!
Answer: You can also use Morera theorem to prove it.
Since $f_n\to f$ uniformly on every compact subset of $G$ and $G$ is connected open set, for any $z\in G$ we can find a closed curve $\gamma$ in $G$ containing $z$ such that $f_n\to f$ uniformly ($\gamma$ is compact). Since $f_n$ are holomorphic in $\gamma$
$$
\oint_\gamma f_n(z)dz=0
$$
And so
$$
0=\lim_{n\to\infty}\oint_\gamma f_n(z)dz=\oint_\gamma\lim_{n\to\infty} f_n(z)dz=\oint_\gamma f(z)dz
$$
(limit and integral can be switched for $f_n\to f$ uniformly). By Morera theorem, this means that $f$ is holomorphic in $G$.


Por que usar o AngularJS?

Question: Eu tenho pesquisado bastante, mas não consigo entender o porquê de usar o AngularJS, sendo que utilizo paginas .php então os retornos do banco, CRUD e etc. Eu trato diretamente nas paginas .php, listas de registros do banco, inserção e essas coisas.
Onde e como o AngularJS pode me ajudar? Em que aplicações as pessoas mais usam?
Comment: Por que tá na moda, hehehe
Comment: Você pode dividir responsabilidades com AngularJS, o Front e Back-end são independentes. Você pode utilizar o mesmo back-end que no caso será uma API REST pra outros fins, como mobile.
Comment: Não tenho experiência com angular, mas eu ACHO que ele seja mais indicado quando você trabalha com API. Onde tudo que o back end faz é disponibilizar dados brutos (JSON).
Answer: Há muita opinião sobre o assunto, resolvi responder para tentar uma resposta que não caia muito nisto, por isso ela não é muito extensiva. Não ficarei afirmando sobre o que há controvérsias se é uma vantagem mesmo ou não.
O principal motivo das pessoas usarem AngularJS (ou Angular que é o que todo mundo usa hoje em dia) quando resolvem trabalhar com Single Page Application. Ou seja, quando se produz uma aplicação baseada em tecnologia web onde uma única página (não é tão rígido assim) faz todas as operações.
Então lembre-se que o cliente (a página) acaba trabalhando de forma independente e toda renderização da visualização ocorre no navegador (ou eventualmente outro host do cliente). Em geral o acesso ao servidor é feito através de um acesso que forneça uma API ao invés de páginas pré-renderizadas lá (ainda que isto possa ocorrer também em algumas situações, pelo menos o primeiro acesso costuma mandar a página-aplicação).
Outro motivo já foi dito em comentário: moda. Muitos não percebem que esse tipo de aplicação estraga o tão perseguido SEO. E que existem outras desvantagens em optar por isso. Mas moda tem a ver com as pessoas usarem porque os outros estarem usando. Pode ser que algumas pessoas saibam porque estão usando, as outras usam porque elas não sabem, mas leem algum blog e acham que tem o mesmo problema, ela só quer fazer o mesmo na esperança que aquilo lhe ajude.
Claro que há vantagens também, que se for uma aplicação de fato, e não um website, pode fazer sentido o seu uso para facilitar certas operações, tais como:

manipulação do DOM (de forma mais ampla que o jQuery, que por sinal nem faz sentido mais)
fazer data binding
adotar o MVC ou MVVM de forma "simples"
usar um mecanismo de templating
entre outras operações comuns feitas de forma correta pronta para uso.

Em tese pode ser usado para qualquer coisa, até mesmo websites se puder conviver com as dificuldades, mas a maioria adota sem ter consciência das dificuldades neste caso.
Coloquei no GitHub para referência futura.
Comment: Relacionada: [O que é SPA e no que se diferencia de uma página não SPA?](https://pt.stackoverflow.com/q/212952/66203)
Answer: O texto abaixo é o resultado de um recente período de imersão nesse mundo de Angular para aprendizado. Peço que a comunidade me auxilie a melhorar meu entendimento caso exista algo incorreto ou ausente.
O AngularJS é um framework para desenvolvimento de Single Page Applications (SPA).
Um Single Page Application é, de forma simples, uma aplicação web composta de uma única página. Todos os assets necessário (HTML, CSS e JS) são carregados em um único load (o inicial) e os componentes da página construidos dinamicamente utilizando JS de acordo com as ações do usuário.
A maior vantagem de um SPA é que a página torna-se muito mais responsiva e ágil, tornando a experiência mais próxima de uma aplicação desktop. Na necessidade da criação de uma página que exija extrema responsividade, pode ser o caso para um SPA.
As aplicações de um SPA são as mais variadas e, principalmente, com a grande quantidade de frameworks que utilizam este conceito (AngularJS, React, EmberJS, Meteor ...) a tendência é que cada vez mais páginas neste modelo surjam.
Certamente você já visitou alguma página que funciona neste formato como a página do Angular2, a do Protractor ou o próprio Gmail. Ao clicar nos links disponíveis na página, não há outro load: os componentes são atualizados na mesma página. Qualquer dado adicional necessário é obtido utilizando AJAX.
Diferente do PHP onde sua lógica está sendo executada do lado do servidor um SPA usa JS de forma pesada, ou seja, demanda mais processamento da estação do usuário (para processar o JS) e comunica-se com um Back-End conforme necessário.
Um bom 'efeito colateral' de um SPA, na minha opinião, é desacoplamento da lógica de Front-End e Back-End. Analise algum código Angular e você verá que as tarefas de renderização de páginas estarão no Front End.
As demais tarefas referentes à persistência (crud, como você citou), computações pesadas de dados e outros estarão em uma segunda aplicação que será o Back-End, geralmente, oferecendo uma API Rest para consumo dos dados.
Outras vantagens geralmente citadas são:

O Back-End não precisar guardar o estado da navegação do usuário, ficando isto à encargo do Front-End, onde geralmente a tarefa é feito utilizando recursos locais da estação do usuário (usando Web Storage, por exemplo)
Possibilidade de uma aplicação funcionar Offline, uma vez que após o download dos assets para a estação do usuário a aplicação precisará de um Back-End apenas para sincronizar dados e outras operações (Nota: isto traz algumas implicações que estão fora do âmbito desta resposta)

Note que isto não é uma solução universal e sim um 'caso'. Muitos estão construindo sites neste modelo por, como você disse, moda.
Comment: Uma sugestão de leitura para te ajudar na decisão de usar um SPA ou não é o tópico http://stackoverflow.com/questions/21862054/single-page-application-advantages-and-disadvantages, e a leitura deste artigo (http://adamsilver.io/articles/the-disadvantages-of-single-page-applications/). Note que algumas coisas mudaram de 2014 para cá mas os pontos ainda são relevantes. Em minha opinião, SPAs brilham em aplicações que dependam fortemente de dados externos (de um backend) às custas de um front end com complexidade elevada.
Comment: Então seria vantajoso, sempre que possível, utilizar um SPA no desenvolvimento de um sistema? Ate criei um tópico sobre o assunto: http://pt.stackoverflow.com/questions/154739/web-moderna-spa-rest?noredirect=1#comment319468_154739

Por que usar o AngularJS?


Adding react component to contenteditable or innerhtml

Question: I am working with content editors (medium-editor specifically) that use contentEditable but are not in React. I have a use-case where someone can drag and drop images, or I can insert images. My question is instead of adding the following to the html of the editor:
editorHtml += ''

I would ideally like to add a React component.
editorHtml += '<CoverImage src="something" />'

In other words, can React Components be added to contentEditable or innerHtml of html elements outside of React Components?
Answer: You have to render React Component to string.
To achieve this, use ReactDOMServer. To be precise, use its renderToString method. This outputs string with all fancy element attributes React needs (e.g. data-react-id). If you are after cleaner output, use renderToStaticMarkup instead.
Comment: Yes, this is one way road. From React world out. I cannot image what is reason behind this use case. Instead, OP should consider wrapping `contentEditable` into React component and control what happens.
Comment: In React ecosystem, there is concept of portals. Portals render components to "other" container - whichever you pick. In this case, it could be contentEditable div (or any other element). E.g. Modals are perfect candidate for portals here - they are rendered to document.body. Not giving guarantees, give it a chance.

Take a look at this https://www.npmjs.com/package/react-portal repo (or any similar one).  Little theory here: http://joecritchley.svbtle.com/portals-in-reactjs
Comment: It should be noted that this will hand the markup to the editor, which will exit the React world again. The editor can do what it wants with it. That seems likely to cause lots of problems
Comment: thanks for the answer! The use-case is that I am using an editor that wasn't built in or for react, but inside of a react app. The intent was (1) not duplicate markup that has been setup in a component. (2) and more importantly, have that act as a React component and not just html markup.

So instead of rendering the markup of a component via renderToString, is it possible to actually render the component and have it not exit the React world? (to @JoshDavidMiller's point). In other word, have it behave as a React component rather than just share its markup?
Comment: @geoboy I am not aware of any way to accomplish that, no. The two systems (React and `medium-editor`) have their own lifecycles and, more importantly, `medium-editor` is driven the DOM while React is driven by a *virtual* DOM. There would inevitably be clashing.


Model convergence problem; non-positive-definite Hessian matrix with glmmTMB in R

Question: I'm trying to fit a GLMM using the package glmmTMB in R. The model has a negative binomial distribution. The fixed effect "Treatment" has two levels (low or high), "Sampling" is the number of consecutive times a colony has been sampled (14 levels). "Size" is a covariate that account for the size of the individuals, and the colony and individual ID are included as random effects. I have 6 replicates per treatment.
Model <- glmmTMB(cell_con ~ treatment * sampling + size +(1|colony/ind_ID), family = "nbinom2", data=countI)
The model fits when I only include the main effects, but when I include interactions between terms I get the following warning. I'm actually mainly interested in the interaction between treatment and sampling.
"Warning message: In fitTMB(TMBStruc) : Model convergence problem; non-positive-definite Hessian matrix. See vignette('troubleshooting')"
I already check the Troubleshooting page for glmmTMB, but unfortunately I'm not that well versed in statistics to solve the problem with that information
Thanks
PD: this is the first time I post a questions here. Let me know if I should post more information about the experiment. I can also send the complete code and data.
Comment: Your model is having problems converging, 1) are your variables highly correlated? 2) Do you have enough observations to estimate all the terms? 3) Try a different optimizer.
Comment: Perhaps you don't need the nested random effects.
Comment: see troubleshooting with glmmTMB - https://cran.r-project.org/web/packages/glmmTMB/vignettes/troubleshooting.html
Comment: @user2974951 What were you referring to when you said to try a different optimizer? I don't see an optimizer specified in the original model.
Comment: @SusieDerkins Admittedly I don't know this specific package so there may well not be such an option, but I know that other more standard packages do have this option. So maybe the answer is try a different package.
Answer: the following site reports the troubleshooting you are mentioning: https://cran.r-project.org/web/packages/glmmTMB/vignettes/troubleshooting.html
the following point can be the problem when you are getting the message.These problems are most likely:

when a model is overparameterized (i.e. the data does not contain enough information to estimate the parameters reliably)
when a random-effect variance is estimated to be zero, or random-effect terms are estimated to be perfectly correlated ("singular fit": often caused by having too few levels of the random-effect grouping variable)
when zero-inflation is estimated to be near zero (a strongly negative zero-inflation parameter)
When dispersion is estimated to be near zero
When complete separation occurs in a binomial model: some categories in the model contain proportions that are either all 0 or all 1


Why isn't Drupal object oriented?

Question: I just started to peek into the docs and source (Drupal 6 at the moment) and noticed that there are no classes to be seen, only vast number of prefixed functions. Is this handy? Does such decision have a background? Why?
Comment: Why are you using Drupal 6?  Drupal *8* is on the way!
Answer: This is pretty well explained on Drupal programming from an object-oriented perspective.
In short, Drupal has existed for much longer than you could properly use OOP in PHP. Which means, PHP5.
Drupal 7 already uses classes internally in a lot of places and it will probably continue so with Drupal 8.
But this is a step by step process and not everything needs to be a class. For example, it does not make any sense to make modules into a single class.
Comment: Drupal 8 will be very OOP, pulling in many of the components of Symfony2. But the APIs for developers will still be the backward-compatible hooks, FTMP.
Comment: It will be a lot more OOP yet, and the point about the API's is not correct. That's just because things aren't completely converted yet. hook_block_*() just got replaced by the plugin system, for example, routing will change, configuration will change, the entity system has changed, ...
Comment: @Berdir I am very interested in how to leverage OOP PHP in Drupal 7 as I will probably not make the move to Drupal 8 right now. Are there some examples?
Answer: Drupal was created before oo became better in php5. Objects are being used more in drupal in each release but you need to balance a complete rewrite and adding new features.

Why isn't Drupal object oriented?


Compile a C# solution with multiple projects without producing .dlls

Question: I'm very new to C#, my background is mainly in C w/ some OOP in C++. I'm sure I'm phrasing this incorrectly which is why google isn't helping me but here goes.
I have two programs which use the same class library, when I add the class library to a solution containing one of the programs the class library is compiled as a .dll and then linked to the main solution. Is it possible to compile the library code directly into the solution code?
I can do this by importing the class library code into the the main projects hierarchy but I don't want to do this as I must update any changes to the library in two places..
Should I define my class library as a different entity, is there an option in the solution settings of Visual Studio 2010 to do what I want?
Comment: Is there any specific reason why you do not what to create dlls?
Comment: Because I don't want to bundle .dll's with the release .exe
Answer: Just add the files containing your class library to your project by reference rather than adding as a copy.
Comment: How do I do this? The only way the library shows up under references is to add it to the solution and after I add it as a reference it's linked by .dll.
Comment: Right click on the project in solution explorer, Add Existing Files. Select the files, and instead of clicking the Add button, add as a reference (the add as reference UI changes between VS2005/2008/2010).
Answer: EDIT:
You can use ILMerge to combine the .dll and .exe.  You can't staticly link things in C#.  It has to be done dynamically.

If you compile your code as a DLL, and add the project to the references of another project, the compiler will automatically copy the class library to the respective build folder.
C# can automatically find classes, namespaces and functions an application needs when you've specified the reference.   There's no need to import any headers, etc, because all of the data is stored in metadata in the DLL, and the .net runtime will look for it automagically.  I am also assuming you are working with a C# library.
Comment: Yes, I'm using a C# library but I want to be able to modify the library code while working on either program so I think compiling a .dll would prohibit me from doing that.   The idea is that I don't want to bundle a .dll with my .exe file.  I want the .dll code compiled with the .exe.
Comment: @user642559: *Why* don't you want to bundle a DLL with your EXE? That's the normal way libraries work in .NET, and moving away from that model is likely to cause you more work in the long term.
Answer: You are talking about static linking.
There is a tool ILMerge which allows you to do this. In general in C# this is less of an issue than in C++ because C# Assemblies/dlls offer version information in the assembly header (which you can control in Visual Studio), thus there is no risk of a dll hell.
Answer: As the other answerers already said, it is normal .net behaviour that referenced assemblies are just copied into the output folder and NOT compiled into the executable.
There are ways to merge them into the .exe after compiling, but that's not the default, you need additional tools for that.
If you are interested in this, you might want to look at ILMerge or NETZ.


Access to Proxy Protocol address within HAProxy

Question: I am running HAProxy that is receiving layer 4 proxy protocol from an upstream source. I have a need to create a custom HTTP header with the address contained there. I can't seem to find how I can reference that TCP header.
Below is a sample of what I am trying to do:
frontend http_in
    bind *:1025 accept-proxy
    mode http
    default_backend http_out

backend http_out
    mode http
    http-request set-header X-Custom-Header %[<ip from proxy protocol header>]
    server some-server some-server:80

How can I make sure I am populating the new header with the address from the L4 header and not some spoofable http header?
Answer: Based on the docs of the accept-proxy bind option, and more generically the usage of the PROXY protocol, all the fields contained in the PROXY protocol header (source IP & port, destination IP & port) replace those from the real connection:

...
  The PROXY protocol dictates the layer 3/4 addresses of the incoming
  connection to be used everywhere an address is used, with the only
  exception of "tcp-request connection" rules which will only see the
  real connection address. Logs will reflect the addresses indicated in
  the protocol, unless it is violated, in which case the real address
  will still be used.
  ...

Meaning that your backend would look like
backend http_out
    mode http
    http-request set-header X-Custom-Header %[src]
    server some-server some-server:80

This works because the src sample field will contain the source IP as defined in the PROXY header, and not the actual source IP.


$T^2=S$ implies $\text{rank}T=\text{rank}S$?

Question: Is it true, that if $T$ and $S$ are selfadjoint and positive operators in a finite-dimensional Hilbert space, such that $T^2=S$, that then $\text{rank}T=\text{rank}S$ ?
Answer: This is true more generally if $T$ is diagonalizable (recall that if $T$ is self-adjoint, it is diagonalizable).
If $T$ is diagonalisable, there is an invertible matrix $P$ and a diagonal matrix $D$ such that $T=PDP^{-1}$, the rank of $T$ is the number (counted with multiplicities) of the non-zero eigenvalues of $T$. Now since $T^2=PDP^{-1}PDP^{-1}=PD^2P^{-1}$, the rank of $T^2$ is the number of the non-zero eigenvalues of $D^2$, which is the same as the number of non-zero eigenvalues of $D$.
The ranks of $T$ and $T^2$ are thus equal.
Answer: Since we are in a finite dimensional vector space, we can diagonalize $T$: there is a hermitian matrix $P$ and a diagonal matrix $D$ such that $T=P^*DP$. The rank of $T$ is the same as the rank of $D$, which is the same as the rank of $D^2$ (the number of non-zero elements of the diagonal), and $S=P^*D^2P$, which proves that $S$ and $T$ have the same rank.
The fact that the operators are self-adjoint is necessary here: if $T^2=0$, $T\neq 0$ and $S=0$, it won't work. Positiveness is not necessary here.
Comment: Whenever $T$ is a matrix which has the same rank as its square, $\mathrm{i}T$ also is. However it is not possible that $T$ and $\mathrm{i}T$ are both self-adjoined unless $T=0$. Thus your claim that self-adjointness is necessary for this property is disproven.


Customizing the Alert dialog in Android

Question: I want to show text in dark color on a light background on alert dialog. But I can't figure out how to do this. Please help me.
Thanks.
Comment: Take a look at [this post][1], very helpful for me

  [1]: http://stackoverflow.com/a/10599154/599993
Answer: You can create your own layout in an XML View just like you would for an Activity:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/layout_root"
              android:orientation="horizontal"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:padding="10dp"
              >
    <ImageView android:id="@+id/image"
               android:layout_width="wrap_content"
               android:layout_height="fill_parent"
               android:layout_marginRight="10dp"
               />
    <TextView android:id="@+id/text"
              android:layout_width="wrap_content"
              android:layout_height="fill_parent"
              android:textColor="#FFF"
              />
</LinearLayout>

Then you can use this View in the Dialog by calling setContentView(View) on the Dialog:
Context mContext = getApplicationContext();
Dialog dialog = new Dialog(mContext);

dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("Custom Dialog");

TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Hello, this is a custom dialog!");
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageResource(R.drawable.android);

As the example shows, you'll have to set some of the values after you declare the content view.
Example provided from http://developer.android.com/guide/topics/ui/dialogs.html#CustomDialog
Comment: According to google's Documentation you should avoid instantiating the `Dialog` class directly. Better to use `DialogFragment`
Answer: see this example,It will help you:http://www.helloandroid.com/tutorials/how-display-custom-dialog-your-android-application

as in this example layout defined in file for alert dialog.You can set your style for alert dialog.
Comment: Thats a custom dialog. Can't we modify the alert dialog itself?

Customizing the Alert dialog in Android


Como fazer com que todos os checkbox sejam desmarcados e que o valor seja vazio dentro do if?

Question: Meu precisa permitir que: Com a seleção do radio ele possa escolher ou não o checkbox correspondente ao ID do radio. E caso o usuário selecione um checkbox além  (>1) eu envio um alert informando que houve uma segunda seleção de check e limpo os campos. Porém não estou conseguindo limpar os checkbox após o segundo click.
function testaCheck(idMaster) {
    var inputs, i, checados = 0;
    inputs = document.getElementsByTagName("input");
    for (i = 0; i < inputs.length; i++) {
        if (inputs[i].type == "checkbox") {
            if (inputs[i].checked == true) {
                checados++;
                document.getElementsByName('DS_MD' + idMaster).value = idMaster;
                $("#formSelectMAWB").find("#masterDireto").val(idMaster);
            }
            if (checados > 1) {
                alert("Só pode haver um item selecionado.");
                inputs[i].checked = false;
            }
        }
    }
};

    <input type="radio" name="idMAWB" id="idMAWB" value="<%=ID_CD_MAWB%>" onClick="selecionaMAWB(this.value)">
    <%=DS_MAWB%>

<label for="DS_MD<%=ID_CD_MAWB%>">
    <input type="checkbox" name="DS_MD<%=ID_CD_MAWB%>" id="masterDireto<%=ID_CD_MAWB%>" onClick="testaCheck(<%=ID_CD_MAWB%>)">
     <%=ID_CD_MAWB%>

Comment: Qual a relação do ASP  no problema?
Comment: Deixei o ASP pois não sei se há diferença entre o JS que é utilizado com ASP para utilização com outras linguagens. Estou aprendendo sobre ASP e JS no estágio onde estou.
Comment: Bom, me parece que seu problema é exclusivamente de JavaScript, portanto não vejo razão de utilizar a tag [tag:asp]
Comment: Entendi, sendo assim retirei a tag asp. Obrigado pela dica Sam.
Comment: Essa função `selecionaMAWB()` é o que? Não tem ela no código.
Comment: O `selecionaMAWB()` é o para trazer o valor que corresponde ao ID_CD_MAWB é algo que já existia no sistema desde a criação. Ex: ID_CD_MAWB - 17 ; MAWB - 417 2541 5571
Answer: Você consegue deschecar todos os checkbox com:
$("input:checkbox")     // seleciona todos os checkbox
.prop("checked", false) // desmarca todos
.val('');               // esvazia o value de todos

Já que você está usando jQuery, aproveita e usa ele que é mais fácil de fazer o que deseja. É só trocar a linha inputs[i].checked = false; pelo código acima.
Agora, há um problema no seu código, aqui:
document.getElementsByName('DS_MD' + idMaster).value = idMaster;

Falta colocar o índice [0], se não não vai fazer efeito, porque o getElementsByName cria uma lista de nós, e não seleciona um elemento. Então deveria ficar assim:
document.getElementsByName('DS_MD' + idMaster)[0].value = idMaster;

Outro problema:

Me parece que está repetindo este id:
id="idMAWB"

Saiba que repetir id é errado no HTML. Faça como você fez nos outros id's, para que não fique repetido:
id="idMAWB<%=ID_CD_MAWB%>"

Comment: Fiz os testes com o que me explicou porém o valor que o check passa ao ser marcado não foi limpado.
Com relação ao `id="idMAWB"`, acredito que não posso fazer uma alteração assim pois esse campo é chamado em outro arquivo `.asp` e parece estar vinculado ao SQL Server.
Comment: É esse aqui: `$("#formSelectMAWB").find("#masterDireto").val(idMaster)`?
Comment: o `id="idMAWB` é o ID_CD_MAWB dentro do SQL Server, o `$("#formSelectMAWB").find("#masterDireto").val(idMaster)` é o valor a ser passado para o banco para informar se a operação é um masterDireto (box checked sinaliza que é masterDireto e assim o código do ID do Master retorna pro banco na coluna 'DS_MS')
Answer: Muito obrigado pela ajuda Sam, graças a sua resposta consegui deixar o código conforme a necessidade da empresa aonde faço estágio. Segue o código final para que possa servir de ajuda para alguém.
function testaCheck(idMaster) {
    var inputs, i, checados = 0;
    inputs = document.getElementsByTagName("input");
    for (i = 0; i < inputs.length; i++) {
        if (inputs[i].type == "checkbox") {
            if (inputs[i].checked == true) {
                checados++;
                document.getElementsByName('DS_MD' + idMaster).value = idMaster;
                $("#formSelectMAWB").find("#masterDireto").val(idMaster);
            }

        }

    }
    if (checados > 1) {
                uncheckAll(inputs);
                document.getElementsByName('DS_MD' + idMaster).value = null;
                $("#formSelectMAWB").find("#masterDireto").val(null);
            }
};

function uncheckAll(inputItems){
    alert("Só pode haver um item selecionado. Favor refazer a seleção");
    for (i = 0; i < inputItems.length; i++) {
        inputItems[i].checked = false;
    }
}


"Multiple definition of node a" error in Winbugs

Question: okay i just rewrite my code. Now the problem is when i compile it, I get an error of "multiple definition of node a". Do anyone know what wrong in my code. I create the variable a,b and c for the model not to have many constants.
<code>  model{

  for(i in 1:n){

            a <- (k[1] + step(s1[i]-.9)*k[2] + step(s1[i]*.5-.9)*k[3])
            b <- (r[1] + step(s2[i]-.9)*r[2] + step(s2[i]*.5-.9)*r[3])
            c <- (s[1] + step(s3[i]-.9)*s[2] + step(s3[i]*.5-.9)*s[3])

    dummy[i] <- 0

      dummy[i] ~ dloglik(logLike[i])

      # This is the log transformation of the 3-variate poisson

      logLike[i] <- -theta12[i] + a*log(theta12[i]) - logfact(a) -theta13[i] - b*log(theta13[i]) - logfact(b)-theta23[i] - c*log(theta23[i]) - logfact(c)-theta1[i] + (y1[i]-a-b)*log(theta1[i]) + logfact(y1[i]-a-b)-theta2[i] + (y2[i]-a-c)*log(theta2[i]) + logfact(y2[i]-a-c)-theta3[i] + (y3[i]-b-c)*log(theta3[i]) + logfact(y3[i]-b-c)

            log(theta1[i]) <- alpha1 + beta1*log(L[i])
            log(theta2[i]) <- alpha2 + beta2*log(L[i])
            log(theta3[i]) <- alpha3 + beta3*log(L[i])
            log(theta12[i]) <- alpha4 + beta4*log(L[i])
            log(theta23[i]) <- alpha5 + beta5*log(L[i])
            log(theta13[i]) <- alpha6 + beta6*log(L[i])
    }

            alpha1 ~ dgamma(.001, .001)
            alpha2 ~ dgamma(.001, .001)
            alpha3 ~ dgamma(.001, .001)
            alpha4 ~ dgamma(.001, .001)
            alpha5 ~ dgamma(.001, .001)
            alpha6 ~ dgamma(.001, .001)
            beta1 ~ dgamma(.001, .001)
            beta2 ~ dgamma(.001, .001)
            beta3 ~ dgamma(.001, .001)
            beta4 ~ dgamma(.001, .001)
            beta5 ~ dgamma(.001, .001)
            beta6 ~ dgamma(.001, .001)

    }

    data
    list(y1 =c(0,1,2,3,2),
    y2 = c(1,2,3,0,2),
    y3 = c(1,3,2,3,2),
    k =   c(0,1,2,3,4),
    s =   c(0,1,2,3,4),
    r =    c(0,1,2,3,4),
    L =   c(1,2,3,4,5),
    s1= c(0,1,2,0,2),
    s2= c(0,0,0,0,0),
    s3=  c(1,1,0,0,0),n=5)

    inits
    list(beta1=0,beta2=0,beta3=0,beta4=0,beta5=0,beta6=0,alpha1=0,alpha2=0,alpha3=0,
    alpha4=0,alpha5=0,alpha6=0)
</code>
Comment: I rolled back your edit because it is impossible for anyone to help you if you delete your code and replace it with a rant.
Answer: You get this error because you've defined a, b, c within a for() loop.  In other words you've defined a constant node multiple times (n times).  You should replace a, b, c with a[i], b[i], c[i].  Think of BUGS as a model description language, not a programming language.  Every quantity in your model has to have one single definition as a fixed or random function of other quantities.


Is statement "PEDs compensate the genetic disadvantages" valid?

Question: I heard the hypothesis that PEDs (Performance Enhancing Drugs) compensate for genetic disadvantages in athletes, thus the PEDs make the sport more "fair".
I do not really care about the philosophic aspect (the second part of the hypothesis). I am interested in the first part.
I talk about this hypothesis with a few people in the mid/top-level sport (I guess some of them actually used PEDs) and they somehow agree with this statement. However, no one sounds 100% confident.
Is the statement the PEDs compensate for genetic disadvantages in athletes correct? I understand that such issues are not black or white so the question is maybe more like to what level is this statement valid?
The problem could be also formulated in a following example:
Consider an athlete in some specific sport. This athlete is not genetically suitable for the given sport in a terms of weight, strength, speed and/or endurance (nor height or similar hardcoded parameters).
Can this athlete match the more genetically suitable athletes for the given sport via the usage of the suitable PEDs? Can this athlete beat them? Or the PEDs will not be enough to match them? Would the disadvantaged athlete benefit more from PEDs than the more "gifted" athletes? Is ability to benefit from PEDs more limited for athletes who already has good genetic dispositions?
Note that I am talking about PEDs usage protocol that is "viable" for a professional sport where it is illegal (also I know there is quite a difference in how the given sport/country/league interprets the "illegal" issue).
I am not much interested in opinions or cool stories. I am asking about some large sample research or long time observation summary that seems to be valid.
Answer: From a basic perspective of function, the majority of (if not all) performance-enhancing drugs do not target innate deficiencies that are due to genetics, they merely affect some bodily system in a way that improves athletic performance (hence the obvious name) regardless of whether the need for such improvement is of genetic, environmental, developmental or other origin.
It is possible that the bodily system so affected has an innate deficiency which is partly or wholly based on genetic determination - for example, an athlete may have a nerve disorder that requires beta blockers as regular treatment, even though this would be doping when done by someone else to improve their fine motor control. There are processes to manage the case where someone is in both groups, but in these cases it is clear that the PED is designed to provide functionality up to the extent of what might be called "normal" performance, not to provide capability of going beyond this into athletic competition.
The PED is not compensating for genetic disadvantage, any more than eating a better diet is compensating for the "genetic disadvantage" of a less effective digestive system or that studying tactics every day is compensating for the "genetic disadvantage" of a less effective memory (or a brain structure or nervous system less suitable for high performance sport than some equivalent athlete). It may coincidentally have that effect, but in practice, doping is used to provide a competitive advantage relative to normal capability, not to bring such performance up to that point in the first place.
Answer: This simply is the opposite.   Think if everyone took PEDs...
Understand -

Genetically some bodies are more apt to have a higher muscle density.
Some bodies can carry more muscle.
Some bodies have stronger ligaments and cartilage.

So everyone takes PEDs, everyone works out the same, and let's take skill out of the equation (for the sports that require skill).   Then you will simply have the tallest, most genetically available people that are the best athletes.
Out of this "supreme" group, they will lift, run, whatever.   Their body will hit a building limit based on activity.   This limit has probably been hit by some current athletes who have taken PEDs.   Then out of this "supreme" group their knees will start to blow out, their hip abductors will not be able to handle the torque, their elbows will blow...
And then you are left with the people whose bodies whether genetically or luck don't crumble with the extra muscle, speed, and tension.   This is pure genetics and the exact opposite of a level playing field.   If everyone does PEDs someone under 5'8" just never runs track or plays most sports.
There is no research for things like this.   Your research is the baseball players that have had hip issues after PEDs, the football players that tear their knees up, and some golfers (who have mysterious hip injuries and go from best player in the world to dud).   Your research is in the news everyday.


Atributos nulos em um objeto é Ruim?

Question: Tenho um objeto que possui 7 atributos:

2 atributos estão sempre com algum valor atribuído.
3 valores estão sempre setados caso seja necessário fazer uma consulta com filtros (os 3 atributos são filtros).
Os últimos 2 atributos são exclusivos (se um está setado com algum valor os outros 5 atributos são dispensados (null).

Então eis a minha duvida: é ruim ter um objeto com múltiplos campos com valor null? Todos os atributos fazem parte do escopo do objeto e o objeto em si já é especializado. Há gasto de memória mesmo que os atributos estejam como null?
Comment: Obs: Estou utilizando PHP
Comment: "Há gasto de memória mesmo que os atributos estejam como `null`?" Há a memória gasta pela referência em si (4 ou 8 bytes por campo, dependendo se a arquitetura é de 32 ou 64 bits). Para um único objeto, não é nada de mais, se forem muitos (muitos *mesmo*) aí começa a pesar... Pode ou não ser vantajoso usar um objeto separado, mas aí já estamos caindo no campo da micro-otimização (i.e. dificilmente valerá a pena se preocupar com isso).
Comment: @mgibsonbr Interessante, não me recordava que gastavam-se até 8 `bytes` por referencia.
Answer: Em modelagem de objetos não existe uma resposta certa para todos os casos, mas há princípios que podem ser aplicados em qualquer situação.
O cenário exposto na pergunta dá a entender que o objeto está carregando mais responsabilidades do que deveria. Vamos analisar isso com calma.
Um cenário possível: pesquisa
O que você me descreveu parece muito com um objeto que carrega dados de uma consulta/pesquisa.
Por exemplo, um gerente de um banco pode estar fazendo a pesquisa por um contrato de um de seus clientes. Os dois campos sempre preenchidos poderiam ser número da agência e código do gerente. Os três campos opcionais poderiam ser nome do cliente e um intervalo de datas para delimitar os resultados. Os dois últimos exclusivos poderiam ser filtros exclusivos como contratos com pendências ou contratos com atraso de pagamento.
Dentro desse exemplo, o objeto carregaria as informações de consulta da tela. Em muitos casos isso é usado com frameworks MVC para fazer o mapeamento automático dos campos da tela para um objeto no servidor.
Nessa situação não há problema algum em ter um objeto assim, representando um formulário web.
O que eu não recomendaria é enviar um objeto desses diretamente para os métodos de pesquisa do seu model.
Seguindo com o exemplo, seria melhor ter um objeto para identificação do gerente com os dois primeiros campos e ter três métodos de pesquisa. O primeiro receberia o objeto que identifica o gerente e os três campos opcionais. O segundo faria a busca por contratos pendentes recebendo apenas a identificação do cliente. O terceiro também receberia a identificação do gerente e faria a busca por contratos com atraso.
A lógica para chamar o método adequado com os parâmetros adequados é responsabilidade do seu Controlador (Controller).
Outro cenário possível: dados de domínio
Outra cenário que vejo é que esse objeto seria um objeto ou classe de domínio, representando informações importantes e fundamentais do sistema.
Por exemplo, o objeto poderia representar uma Pessoa. Os dois campos obrigatórios poderiam ser um código e o tipo de pessoa (Física e Jurídica). Os três campos opcionais poderiam ser dados como nome, endereço e telefone. Os dois campos exclusivos poderiam algum tipo de Pessoa especial que não necessita o preenchimento dos dados mencionados acima.
Dentro desse exemplo específico, já existem algumas discussões aqui no SO sobre qual é a melhor abordagem:

O que fazer se cliente pode ser tanto PF quanto PJ?
Pode ser considerada uma má prática de modelagem armazenar todas as pessoas (clientes, funcionários, fornecedores) em uma mesma tabela?

Considerações
A lógica contida em sua entidade diz que não é uma simples questão de adotar um conjunto de campos ou outro. Existe um conjunto de regras que pode gerar complexidades futuras.
Para resolver isso, polimorfismo ou composição poderiam ser alternativas interessantes, mas a aplicação dessas técnicas varia de caso para caso.
Quanto ao desempenho ou uso de memória, dividir os dados entre diferentes objetos irá utilizar mais memória e consumir mais processamento. Entretanto, a perda ou ganho de uma abordagem é ínfimo para a grande maioria das aplicações.
Portanto, a não ser que o desempenho seja crítico para seu programa (o que é bem difícil já que PHP não está entre as linguagens mais eficientes), é melhor focar em deixar o seu código mais limpo e bem organizados do que se preocupar com esse aspecto em um nível de detalhes como este.
Comment: @utuluiz sê verdadeiro: Tinhas essa resposta em clipboard, não era? :P (fora de brincadeiras: boa resposta!)
Comment: O meu cenário é o de pesquisa: o usuario pode pesquisar livros pela letra de inicio ou pela quantidade de membros que compraram ou ainda uma pesquisa com filtros: autor, dt de lançamento, editora e pais de origem.
Comment: @MoshMage Obrigado! Na verdade foram uns 20 minutos para elaborar :D
Answer:
Então eis a minha duvida: é ruim ter um objeto com múltiplos campos
  com valor null? Todos os atributos fazem parte do escopo do objeto e o
  objeto em si já é especializado.

Respondendo objetivamente, no seu caso sim. Não por motivos de desempenho mas por motivos de facilidade de compreensão do código.
Se esse objeto representa o objeto persistido no banco não é uma boa pratica que tenha atributos não relacionados ao próprio objeto, nesse caso os filtros não fazem parte do escopo do objeto persistido, e se for somente uma classe de busca não vejo necessidade de instanciar a mesma, poderia utilizar uma classe estática ou Singleton.
Perceba que o exemplo fica estranho como Objeto e mas nem tanto como classe estática.
Objeto Instanciado:
carro = new Carro();
carro.filtroCor = "azul";
carro.filtroMarca = "Suzuki";
carro.busca();

Classe Estática:
carro = new Carro();
PesquisaCarro.filtroCor = "azul";
PesquisaCarro.filtroMarca = "Suzuki";
PesquisaCarro.busca(carro);

Eu separaria o objeto persistido da classe responsavél pela busca. Independente de como vai implementar a lógica de busca.
Sugestão:
carro = new Carro();
carroControler = new CarroControler();
carroControler.busca(carro, "azul","Suzuki"); //Chama lógica de persistência passando parâmetros.

Há gasto de memória mesmo que os atributos estejam como null?

Pelo meu ponto de vista, três ponteiros a mais na memoria a principio não vão matar ninguém.

Atributos nulos em um objeto é Ruim?


Varnish cache objects for as long as possible

Question: According to the book, Varnish automatically invalidates expired objects. By invalidates, I understand that it removes these objects from the data store, as soon as they're expired.
Is there a way to instruct Varnish to keep these expired objects forever, to only invalidate the oldest ones when a new object needs to be stored?
Keeping expired objects is important because they can still be revalidated on the origin server, that can return a 304 response if they are still valid (thus avoiding a new transfer).
I read about the grace mode that allows to keep objects beyond their TTL:
sub vcl_fetch {
  set beresp.grace = 30m;
}

If I set the grace mode to something like 1 year, will it work as I want?

will it revalidate the expired objects with the origin server?
will it automatically delete the oldest object when it needs to make room for a new one?
Comment: which version of varnish are you running?
Comment: Let's say the latest. Just considering Varnish for now.
Comment: Then I think a huge grace time tackles your issue. What it means is : If a request hits varnish during an object grace time and the object is still stored in varnish, then the object is returned to the client and then it is refresh with an "If Modified Since" request to the backend, renewing the cache.
Comment: Actually I don't want it to return a stale object, I want Varnish to query the backend server in real time, and only reply to the client once it got the `304` or `200` response from the backend.
Comment: In other words, you want varnish to store an object beyond it's ttl just to revalidate them using a IMS request saving you some bandwith between backend and varnish. Is that it ? If so, then I don't know how you can achieve that. During its ttl, the object will not be revalidated by Varnish, and after it is expired the grace time will let you serve it but it will be revalidated asynchronously.
Comment: I'm actually surprised that the behaviour I'm after is not the default, though: why evict an object from the cache as soon as it's expired, when you can revalidate it later on? As long as you've got space left in the storage, this can only be beneficial.
Comment: It's not physically evicted. Purging an object is resource consuming. It's just marked as staled (or banned). One cause, I could think about is when varnish revalidate an object against the backend it needs to be sure that the object is still stored in its cache. That's true during its ttl and grace time, but that's not 100% sure afterwards
Comment: It'd be cheaper to check whether the object is stored in the cache, than going straight to the origin server, though?
Answer: Summary from what have been told in the comments :
If I set the grace mode to something like 1 year, will it work as I want?
will it revalidate the expired objects with the origin server?

Not quite. It will revalidate the expired objects but asynchronously. When a requests hits varnish and the object is expired but in its grace time, the stale object is immediatly returned and the object is then refreshed using an "If Modified Since" request to the backend. That seems to be what you want, except for serving a stale object.
will it automatically delete the oldest object when it needs to make room for a new one?

Varnish purges objects when it needs space, but even if the object is still stored somewhere, if it is expired then it won't be served to the client (unless if in grace mode)
Is there a way to instruct Varnish to keep these expired objects forever, to only invalidate the oldest ones when a new object needs to be stored?

I don't think there is a way to let Varnish keep a stale object other than the grace period.
I checked my varnish production (v4.1) logs and I only see IMS backend requests in case of bgfetch (async refresh during grace time) and pass. Whenever Varnish MISS the object in cache, the fetch was done without the IMS headers.
Answer: are you actively invalidating your cached objects via ban? Than a grace of one year is what you are looking for ;).
Greetings,
Bastian
Comment: I don't want to invalidate anything via `ban`, all the objects must be cached according to their Cache-Control directive, but I want them to be kept after their max-age has been reached, to be revalidated and be reused if `304`.


Como tirar 6 fotos Seguidas apenas usando o Kivy?

Question: Queria um exemplo de como tirar 6 fotos Seguidas usando kivy.uix.camera.
Observação: Sem mandar consultar o site de exemplos da Kivy, todos os exemplos que eu vi tinham comentários falando para ler o documento do Kivy, mas eu não achei ainda essa função para foto.
Answer: E não é só chamar 6 vezes a função?
camera = Camera(play=False)

camera.export_to_png('c:/fotos/1.png')
camera.export_to_png('c:/fotos/2.png')
camera.export_to_png('c:/fotos/3.png')
camera.export_to_png('c:/fotos/4.png')
camera.export_to_png('c:/fotos/5.png')
camera.export_to_png('c:/fotos/6.png')

Ou com for:
for i in range(1, 6):
    camera.export_to_png('c:/fotos/' + str(i) + '.png')

E se quiser de meio em meio segundo não seria apenas aplicar um simples sleep?
import time

camera = Camera(play=False)

for i in range(1, 6):
    camera.export_to_png('c:/fotos/' + str(i) + '.png')
    time.sleep(0.5)

Se sabe usar Python e conhece o time.sleep então sabe que dá pra trabalhar com segundos ou valores menores, no exemplo foi meio segundo com 0.5, se for intervalo de um segundo:
time.sleep(1)

Não creio que haja complexidade, acho que talvez você esteja esperando que a API faça algo que deveria fazer parte do seu algoritmo, é uma critica construtiva, não adianta querer fazer o avançado se você pular o básico da linguagem de programação e me parece que sua falta de entendimento é no básico do Python e não no uso do Kivy


Histograma em Java

Question: Olá,
Necessito transformar uma imagem em uma matriz de pixels.
Por exemplo: Dada a imagem "netuno.jpeg", de 256 x 256 pixels, preciso alocar o valor dos pixels nessa Matriz e imprimir a quantidade que esses pixel aparecem em outro vetor:
Matriz[0][0] = 2 (sendo 2 o valor do pixel),
Matriz[0][1] = 12, ... , Matriz[255][255] = 23
Qtd de pixels 0 = 34 (sendo 34 a quantide de vezes em que o pixel de valor 0 apareceu) ,
Qtd de pixels 1 = 21, ... , Qtd de pixels 255 = 120
Até agora eu li a imagem usando BufferedImage, mas não sei como acessar os pixels da imagem.
import xxx;

public class Histograma {

public static void main(String[] args) throws IOException {

    //Atributos

    //Métodos

    //Leitura da Imagem - Planeta Netuno

    BufferedImage img = ImageIO.read(new File("/home/patch/netuno.jpeg"));
    int altura = img.getHeight();
    int largura = img.getWidth();
    int[][] matrix = new int[largura][altura];

    for(int i = 0; i < img.getWidth(); i++) {
        for(int j = 0; j < img.getHeight(); j++) {

        }
    }
}

Obrigado!
Answer: Lendo a documentação da classe BufferedImage, me parece que você pode ler o valor RGB de cada pixel na posição (x, y), valor este que é retornado como um int. O nome do método é getRGB(int x, int y). Obtido o valor RGB, pode-se quebrá-lo nos componentes vermelho, verde e azul aplicando um pouco de escovação de bits, se isso for necessário. Ou apenas use como índice para seu histograma.

Histograma em Java


How to sum total div text

Question: How to sum div text? I need comma xx,xxx for sum but the result with the script below is 7

var sum = 0;
$(".price").each(function () {
    var val = $.trim($(this).text());
    if (val) {
        val = parseInt(val.replace(/^\$/, ""));
        sum += !isNaN(val) ? val : 0;
    }
});
alert(sum);

2,000

1,000

3,200

1,000

Comment: you're using parseInt, so the result is 7. That should get you thinking.
Comment: just do: `var sum = 0.0;`
Comment: sorry... did not see you used comma's.
Answer: Try with split and join in javascript
var sum = 0;
$(".price").each(function() {
var val = parseInt($(this).text().split(",").join(""));
 sum = sum + val;
});

sum= sum.toString();
var lastThree = sum.substring(sum.length-3);
var otherNumbers = sum.substring(0,sum.length-3);
if(otherNumbers != '')
    lastThree = ',' + lastThree;
var res = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree;

alert(res);

DEMO
Answer: If more than 100000 -> 1,00,000
var sum = 0;
$(".price").each(function() {
var val = parseInt($(this).text().split(",").join(""));
 sum = sum + val;
});

sum= sum.toString();
var lastThree = sum.substring(sum.length-3);
var otherNumbers = sum.substring(0,sum.length-3);
if(otherNumbers != '')
    lastThree = ',' + lastThree;
var res = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree;

alert(res);

Answer: You are leaving a comma in there and parseInt doesn't like it.
Try this:
var sum = 0;
$(".price").each(function() {
var val = $.trim( $(this).text() );
if ( val ) {
val = parseInt( val.replace( /^\$/, "" ).replace(",","") );
sum += !isNaN( val ) ? val : 0;
}
});
alert(sum);

How to sum total div text


minifying css in drupal and getting the original source css

Question: We have inherited a drupal 7 installation.  We have the source code. When we look on the front end there are series a of minified css files named like below. We are interested in getting the original source css files. I have no experience in drupal css minification. Does this kind of output look like out the box drupal minification. If so is there a location that specified the exact css that was used?
<code> <link type="text/css" rel="stylesheet" href="http://www.mydomain.com/sites/default/files/css/css_pbm0lsQQJ7A7WCCIMgxLho6mI_kBNgznNUWmTWcnfoE.css" media="all" />
<link type="text/css" rel="stylesheet" href="http://www.mydomain.com/sites/default/files/css/css_hYCLW089C9S9sP3ZYkuG6R-Q5ZHbEhblZBFjwZ_bE_I.css" media="all" />
<link type="text/css" rel="stylesheet" href="http://www.mydomain.com/sites/default/files/css/css_YYoEBheeHSoZ5EBVRncs-cuvNClW-5FNm_tmYaEdRwM.css" media="all" />
<link type="text/css" rel="stylesheet" href="http://www.mydomain.com/sites/default/files/css/css_5-5L742ZPRdlG5Jq9Yz3AIRJ3MBxYr6H_bolFIoqd68.css" media="all" />
</code>
Each css file that we see on the front end is collection of multiple css files.
Answer: Yes that looks like Drupal's built in CSS aggregation.
The easiest solution would be to turn aggregation off temporarily. Then you'll see the original sources in the markup.
You can turn it off at the admin/config/development/performance page.
Answer: In addition to what Clive said. The default location of the css file would be in the theme directory. Navigate to:
root/sites/all/themes/[select your theme that is listed as the active theme in the appearance admin page]/style.css
If you do not see the style.css go the themes ".info" in that directory and in that file it will tell you where the .css file(s) are located.


RAID 1+0 drives upgrade

Question: My server has two 72GB drives. I want to upgrade them to higher capacity drives without losing the data. Can I simply replace the hard drives one at a time and wait till rebuilding is done?
Comment: Vote to close. THis is product specific, is not professional level (the answer is in the documentation for the raid controller, which is not even mentioned in the question). 2 reasons per the FAQ the question should not be here.
Comment: Two drives can't be in a RAID 1+0 configuration, that requires at least four drives. Make sure you're really mirroring and not striping before doing anything, and take a backup.
Comment: You should add more context to your question, as the answer depends entirely upon the hardware and software configuration of your system.
Answer: Since you mentioned that you were using an HP ProLiant server and a Smart Array P400i RAID controller, I can give an answer specific to your configuration.
You can replace the disks one at a time with larger drives. This will result in "unallocated space" in your drive array once the drives rebuild. You can either extend the existing logical disk to fill this space, or create a second logical drive.
See: What are the good ways to migrate a RAID array to bigger disks?
Answer: Yes, you can do this and you won't lose any data (unless there is a disk failure while doing it).  However, once it is done, you will have to somehow resize the array; hopefully your controller supports this.  Then, you will have to resize the partition and the filesystem, which is usually possible but depends on your filesystem and whether the volume is a boot volume.
Comment: Thank you for your quick response. The controller is Smart P400i, not sure if it supports resize the array... It has 2 partitions in a volume, one boot partition and the data. Can I do the resizing using Disk Management in Windows?
Comment: You will be able to resize if you are using NTFS, if I recall, using the MMC.

RAID 1+0 drives upgrade


How to detect if a server is using SPDY

Question: Any way to detect if a remote website supports SPDY and what version it is?
Something I can use from the command line like a bash script.
Tried sending custom User-Agent headers with curl but can't get any kind of response headers that would help me.
The idea is to be able to get SPDY:true/false Version:3.1/3.0... for any domain.
Comment: Are you going to write a program to do this, or do you want this program to be written for you?
Comment: I was hoping there was something ready out there that I could use in a bash script.
Answer: openssl s_client -connect google.com:443 -nextprotoneg ''
CONNECTED(00000003)
Protocols advertised by server: spdy/3.1, spdy/3, http/1.1

Comment: This command won't work if you are using openssl 0.9.8. If you are on a Mac you can update openssl with brew: http://apple.stackexchange.com/a/126832/78754
Comment: My server using openssl v1.0.1 and this command helped. Thank a lot!
Answer: The SPDY protocol negotiation happens during the initial TLS handshake.
There are currently two ways to negotiate the protocol: the older one is called NPN (https://datatracker.ietf.org/doc/html/draft-agl-tls-nextprotoneg-04).
In the ClientHello TLS message the client sends the NPN extension with ID 0x3374. The server replies with a ServerHello TLS message that also contains the list of protocols supported by the server also in a NPN extension.
The client then chooses the protocol and sends its choice, encrypted, to the server.
The newer method has been designed for HTTP 2.0 and is called ALPN (https://datatracker.ietf.org/doc/html/draft-ietf-tls-applayerprotoneg-05).
The ClientHello TLS message contains the ALPN extension with ID 0x10.
The client, this time, sends the list of protocols supported and the server replies with a ServerHello TLS message that contains the protocol chosen by the server, also in a ALPN extension.
In both the NPN and ALPN extension the list of protocols is sent as strings such as http/1.1 or spdy/3.
Once the protocol has been chosen, the TLS handshake continues and then both parties will start to speak immediately the protocol that they have chosen.
The only way to be aware of negotiation of the protocol is therefore to use TLS and to have a client that exposes the protocol negotiation extensions.
Each client does that in a specific way, but there is not yet support for bash scripts, as far as I know.
HAProxy for example has support for both NPN and ALPN (http://cbonte.github.io/haproxy-dconv/configuration-1.5.html) and Jetty 9.2 too has support for both NPN and ALPN (both for clients and servers).
Other servers like Nginx or Apache have support for NPN with patches for ALPN (since it will be needed by HTTP 2.0 anyway).
NPN will eventually fade away; Google's Adam Langley has stated that NPN will be deprecated in favour of ALPN.
Comment: So you recommend using  wireshark to check for SPDY? Any way to automate this process?
Comment: Wireshark is certainly an option. The programmable option is to find an API that allows you to set/inspect TLS extensions. I know that Java does not provide one (yet), but other languages/platforms may. The Jetty project has API for both NPN and ALPN in Java, but they cannot be used together. By using the Jetty APIs it would be fairly easy to detect SPDY support (that's what the Jetty SPDY client does).
Comment: I think this wrongly downvoted answer is better than the accepted one. +1

How to detect if a server is using SPDY


Theoretical motivation for using log-likelihood vs likelihood

Question: I'm trying to understand at a deeper level the ubiquity of log-likelihood (and perhaps more generally log-probability) in statistics and probability theory.  Log-probabilities show up all over the place: we usually work with the log-likelihood for analysis (e.g. for maximization), the Fisher information is defined in terms of the second derivative of the log-likelihood, entropy is an expected log-probability, Kullback-Liebler divergence involves log-probabilities, the expected diviance is an expected log-likelihood, etc.
Now I appreciate the many practical and convenient reasons.  Many common and useful pdfs are from exponential families, which leads to elegantly simplified terms when log-transformed.  Sums are easier to work with than products (esp for differentiating).  Log-probs have a great floating point advantage over straight probs.  Log-transforming a pdf often converts a non-concave function into a concave function.  But what is the theoretical reason/justification/motivation for log-probs?
As an example of my perplexity, consider the Fisher information (FI).  The usual explanation for intuiting the FI is that the second derivative of the log-likelihood tells us how "peaked" the log-likehood is:  a highly peaked log-likelihood means the MLE is well-specified and we are relatively sure of its value, while a nearly flat log-likehood (low curvature) means many different parameter values are nearly as good (in terms of the log-likelihood) as the MLE, so our MLE is more uncertain.
This is all well-and-good, but isn't it more natural to just find the curvature of the likelihood function itself (NOT log-transformed)?  At first glance the emphasis on the log-transform seems arbitrary and wrong.  Surely we are more interested in the curvature of the actual likelihood function.  What was Fisher's motivation for working with the score function and the Hessian of the log-likelihood instead?
Is the answer simply that, in the end, we have nice results from the log-likelihood asymptotically? E.g., Cramer-Rao and normality of the MLE/posterior.  Or is there a deeper reason?
Comment: I asked a similar question [here](https://stats.stackexchange.com/questions/229831/why-apply-log-to-likelihood)
Answer: It's really just a convenience for loglikelihood, nothing more.
I mean the convenience of the sums vs. products: $\ln (\prod_i x_i) =\sum_i\ln x_i$, the sums are easier to deal with in many respects, such as differentialtion or integration. It's not a convenience for only exponential families, I'm trying to say.
When you deal with a random sample, the likelihoods are of the form: $\mathrm{L}=\prod_ip_i$, so the loglikelihood would break this product into the sum instead, which is easier to manipulate and analyze. It helps that all we care is the point of the maximum, the value at the maximum is not important, se we can apply any monotonous transformation such as the logarithm.
On the curvature intuition. It's basically the same thing in the end as the second derivative of loglikelihood.
UPDATE:
This is what I meant on the curvature. If you have a function $y=f(x)$, then it's curvature would be (see (14) on Wolfram):
$$\kappa=\frac{f''(x)}{(1+f'(x)^2)^{3/2}}$$
The second derivative of the log likelihood:
$$A=(\ln f(x))''=\frac{f''(x)}{f(x)}-\left(\frac{f'(x)}{f(x)}\right)^2$$
At the point of the maximum, the first derivative is obviously zero, so we get:
$$\kappa_{max}=f''(x_{max})=Af(x_{max})$$
Hence, my quip that the curvature of the likelihood and the second derivative of loglikelihood are the same thing, sort of.
On the other hand, if the first derivative of likelihood is small not only at but around the point of maximum, i.e. the likelihood function is flat then we get:
$$\kappa\approx f''(x)\approx A f(x)$$
Now the flat likelihood is not a good thing for us, because it makes finding the maximum more difficult numerically, and the maximum likelihood is not that better than other points around it, i.e. the parameter estimation errors are high.
And again, we still have the curvature and second derivative relationship. So why didn't Fisher look at the curvature of the likelihood function? I think it's for the same reason of convenience. It's easier to manipulate the loglikelihood because of sums instead of the product. So, he could study the curvature of the likelihood by analyzing the second derivative of the loglikelihood. Although the equation looks very simple for the curvature $\kappa_{max}=f''(x_{max})$, in actuality you're taking a second derivative of the product, which is messier than the sum of second derivatives.
UPDATE 2:
Here's a demonstration. I draw a (completely made up) likelihood function, its a) curvature and b) the 2nd derivative of its log. On the left side you see the narrow likelihood and on the right side it's wide. You see how at the point of the max likelihood a) and b) converge, as they should. More importantly though, you can study the width (or flatness) of the likelihood function by examining the 2nd derivative of its log-likelihood. As I wrote earlier the latter is technically simpler than the former to analyze.
Not surprisingly deeper 2nd derivative of loglikelihood signals flatter likelihood function around its max, which is not desired for it causes bigger parameter estimation error.

MATLAB code in case you want to reproduce the plots:
<code>f=@(x,a)a.^2./(a.^2+x.^2);
c = @(x,a)(-2*a.^2.*(a.^2-3*x.^2)./(a.^2+x.^2).^3/(4*a.^4.*x.^2/(a.^2+x.^2).^4+1).^(3/2));
ll2d = @(x,a)(2*(x.^2-a.^2)./(a.^2+x.^2).^2);

h = 0.1;
x=-10:h:10;

% narrow peak
figure
subplot(1,2,1)
a = 1;
y = f(x,a);
plot(x,y,'LineWidth',2)
%dy = diff(y)/h;
hold on
%plot(x(2:end),dy)
plot(x,c(x,a),'LineWidth',2)
plot(x,ll2d(x,a),'LineWidth',2)
title 'Narrow Likelihood'
ylim([-2 1])

% wide peak
subplot(1,2,2)
a=2;
y = f(x,a);
plot(x,y,'LineWidth',2)
%dy = diff(y)/h;
hold on
%plot(x(2:end),dy)
plot(x,c(x,a),'LineWidth',2)
plot(x,ll2d(x,a),'LineWidth',2)
title 'Wide Likelihood'
legend('likelihood','curvature','2nd derivative LogL','location','best')
ylim([-2 1])
</code>
UPDATE 3:
In the code above I plugged some arbitrary bell shaped function into the curvature equation, then calculated the second derivative of its log. I didn't re-scale anything, the values are straight from equations to show the equivalence that I mentioned earlier.
Here's the very first paper on likelihood that Fisher published while still in the university, "On an Absolute Criterion for Fitting Frequency Curves", Messenger of Mathmatics, 41: 155-160 (1912)
As I was insisting all along he doesn't mention any "deeper" connections of log probabilities to entropy and other fancy subjects, neither does he offer his information criterion yet. He simply puts the equation $\log P'=\sum_1^n\log p$ on p.54 then proceeds to talk about maximizing the probabilities. In my opinion, this shows that he was using the logarithm just as a convenient method of analyzing the joint probabilities themselves. It is especially useful in the continuous curve fitting, for which he gives an obvious formula on p.55:
$$\log P=\int_{-\infty}^\infty\log fdx$$
Good luck analyzing this likelihood (or probability $P$ as per Fisher) without the log!
One thing to note when reading the paper he was only starting with maximum likelihood estimation work, and did more work in subsequent 10 years, so even the term MLE wasn't coined yet, as far as I know.
Comment: Your final sentence (about curvature) intimates there truly is something fundamental about the log likelihood and that taking logs is not just a mere "convenience."  I believe there's much more going on here than you are letting on.
Comment: Your discussion of curvature does not appear relevant, because it doesn't distinguish an analysis of log likelihood from an analysis of the likelihood itself.  This answer seems to come down to "logs are convenient," but there's much more to the issue than that, as other answers are beginning to suggest.
Comment: @Aksakal  OK, thanks, I think I see this now.  The likelihood function is specified up to an arbitrary multiplicative constant.  Therefore, the value of the likelihood at the maximum, $ f(x_{max}) $, is also arbitrary.  For instance, it is common to use a unit normalized likelihood function, where $ f(x_{max}) = 1 $.  In that case, the second derivatives of the likelihood and the log-likelihood are equivalent at the maximum.
Comment: So using the log-likelihood for the Fisher information apparently serves two practical purposes: (1) log-likelihoods are easier to work with, and (2) it naturally ignores the arbitrary scaling factor.  And, it gives the same answer as the 2nd deriv of the straight likelihood.  This seems an important point to me, one that was not obvious and that I've never seen stated in any statistics text.  Presumably it was known to Fisher.
Comment: $$f(x_{max})''= (\ln f(x))'' f(x_{max})$$

and if the arbitrary multiplicative constant is taken as $f(x_{max}) = 1$

$$f(x_{max})''= (\ln f(x))''$$
Comment: I added UPDATE 3 to my answer with a link to the original Fisher's paper and comments.
Comment: @Aksakal Note that your chosen example only worked serendipitously, since $L(a_{max}|x)=1$. This is not true of all likelihood functions. E.g., try $L(b|x)=b^2 x e^{−b x}$ .
In general the equivalence is only up to the arbitrary scaling constant of the likelihood function.
Comment: @whuber I totally agree with you. I believe it has to do something with "combinations". This is one of the reasons I posted two questions on taking the log transformation in both Shannon and Fisher Inf.
Comment: @whuber Shannon's information axioms seem to be a clue that the logarithm is required in defining information content:  https://en.m.wikipedia.org/wiki/Information_content
Comment: @Aaron There's a huge logical gap involved in that statement, because there's no direct connection between the meaning of Shannon's "information" and the term "information" in the information matrix of maximum likelihood theory.
Comment: @whuber Can't Fisher's information be written as the second derivative of the expected value of Shannon's information?  Maybe I am wrong.
Answer: Additional point. Some of the commonly used probability distributions (including the normal distribution, the exponential distribution, the Laplace distribution, just to name a few) are log-concave. This means that their logarithm is concave. This makes maximising the log-probability much easier than maximising the original probability (which is particularly handy in maximum likelihood or maximum a-posteriori methods). To give an example, using Newton's method to maximise a multivariate Gaussian distribution directly may take a large number of steps while maximising a paraboloid (the log of the multivariate Gaussian distribution) takes exactly one step.
Comment: Not so fast. See exercise 7.4 on pp. 393-394 of http://web.stanford.edu/~boyd/cvxbook/bv_cvxbook.pdf
Comment: Exactly this. All the talk about how logs are more convenient is nice, but convexity (or concavity, depending on perspective) is what really distinguishes log-likelihood as the "correct" thing to work with.
Comment: Note that I already mentioned log-concavity in the OP.  But this is still just a "convenience", there is no theoretical justification here for log-concavity, and in any case log-likelihoods are not log-concave in general.
Comment: @ratsalad, yes, you are right, it's convenience. I think log-probabilities are an additional way to look at a probability function. I can't say for sure which one is better. If you look at [https://en.wikipedia.org/wiki/Statistical_distance](probability-distance measures), some effectively work on the log-probability (e.g. KL divergence which is effectively the expected value of the difference of log-probabilities), some on the probability directly (e.g. KS distance).
Comment: That's not log-concave. The Gaussian is log-concave wrt to its argument or to the mean parameter, not wrt the variance too. If you also want to determine the scale, you can use a normal-gamma distribution, which is also log-concave (using the precision instead of the variance).
Comment: The log may also a more natural way to look at odds ratios or Bayes factors, i.e whenever you consider how many times A is more likely than B (being a ratio, it lends itself to being treated in a logarithmic scale).
Answer: Log-likelihood's theoretical importance can be seen from (at least) two perspectives: asymptotic likelihood theory and information theory.
The earlier of these (I believe) is the asymptotic theory of log-likelihood. I think information theory got underway well after Fisher set maximum likelihood on its course towards 20th century dominance.
In likelihood theory, a parabolic log-likelihood has a central place in inference. Lucien Le Cam has played an important role in elucidating the importance of the quadratic log-likelihood in asymptotic theory.
When you have a quadratic log-likelihood, not only does the curvature about the MLE tell you qualitatively how precisely you can estimate the parameter, but we also know the error is normally distributed with a variance equal to the reciprocal of the curvature. When the log-likelihood is approximately quadratic, then we say these results hold approximately, or asymptotically.
A second reason is the prominence of the log-likelihood (or log-probability) in information theory, where it is the main quantity used to measure the information content.
There is a variant of Entropy called the Kullback-Liebler Divergence  that is minimized by the maximum likelihood estimate. In particular, if the true data distribution is $g$ then the "closest" distribution (as measured by the Kullback-Liebler divergence) to $g$ in parametric family $f(\theta)$ is given by $f(\hat{\theta})$, where $
\hat{\theta}$ is the maximum likelihood estimate.
Finally, log-likelihood is the quantity used in various model selection criteria such as AIC and BIC. Essentially, each of these criteria equates an extra parameter/degree of freedom with some multiple of $\ln \hat{L}$.
So, log likelihood, apart from being a useful numerical transformation, has deep ties to inference and information theory.
Comment: @ratsalad thanks for expanding on this...as you can see, getting beyond simple "logs are easier" explanations of log-likelihood can take one pretty far afield. I use log-likelihood for the reasons Aksakal gives...however, your OP asked for something deeper. I gave two examples that show connections to other areas that have influenced statistics and likelihood theory. I think the asymptotic explanations are more direct, but entropy and probability are linked in ways that makes log-probabilities things we are interested in beyond mere numerical convenience.
Comment: Your reference to information theory's use of log-likelihoods is circular. Why do **they** use log? Probably for the same reason, especially, if you consider that information theory's a relatively newer field compared to statistics.
Comment: @Aksakal however, on a more fundamental level additivity turns entropy/information into something like a measure ...  akin to mass. If you combine two statistically independent systems, then the entropy of the combined system is the sum of the entropy of each system. Here's a nice explainer: https://physics.stackexchange.com/questions/240636/why-is-entropy-additive
Comment: @Bey Thermodynamic statistical entropy actually follows directly from the Boltzmann distribution of microstates and classical macroscopic thermo (the form of stat mech entropy was not a "choice").  The Boltzmann distribution itself is a consequence of two premises: (1) the physical property that energies are specified only up to an arbitrary additive constant and (2) the fundamental stat mech assumption that all microstates with the same energy have the same probability.  So, at the deepest level thermo entropy involves log-probs because energy is additive and proportional to log-prob.
Comment: @Aksakal yes and no. Information theory got its foundations partially from statistical mechanics and entropy: https://en.wikipedia.org/wiki/Entropy. Boltzmann defined the entropy of a system using the log of the number of microstates. Why logs? Because it makes entropy/information additive (as your answer points out)? So what? At a numerical level, linearity/additivity opens up the use of the powerful methods of linear algebra.
Comment: @ratsalad also, you may want to check out Shannon's original paper on information theory...he spells out some "desiderata" that a measure of informations should have and these lead to quantities involving log-probabilities (see also the more general Renyi Entropies)
Answer: TLDR: It is much easier to derive sums than products, because the derivative operator is linear with summation but with product u have to do the product rule. It is linear complexity versus some higher order polynomial complexity
Comment: This is what the question means by "convenient and practical."  It is far from the only, or even the main, reason why analysis focuses on the log likelihood.  Consider, for instance, what the expression for the [Fisher Information](https://en.wikipedia.org/wiki/Fisher_information) would look like in terms of the likelihood rather than the log likelihood.
Comment: yeah for sure; I think when he said its "easier" to find it directly, I thought he meant the opposite of this, because it certainly is easier to find it after we apply the log transformation.