Any source code to load the head tag fast

Question: Usually in a web page the  tag and  loads together in a webpage, Because of this often the webpage looks dull because sometimes the style sheets and java script load slowly and even several times it didn't load. So I am searching for a loader which will load the content which are in the head tag first and then after loading the content in the head tag then it will load the body content.
Is there such kind of script or any other trick to let the  tag load first
Comment: minify your CSS and JS files which will reduce file size and `gzip` it. Try to reduce CSS and JS file to one single files each.
Answer: Pages load linearly from top to bottom. It will retrieve additional linked assets as it encounters them in the source. The order those assets are returned to the browser will depend on the path it takes and size of the files.
Your JS should not be linked from the HEAD section due to the fact that JS files can block concurrent loading of other assets. Instead, place your JS file links immediately before the  tag.
As for the CSS files, you COULD write a script that waits for the CSS to fully load before 'displaying' the rest of the page, but I'd strongly recommend AGAINST that, as this is simply how the internet works. The 'dull look' you are concerned about is really of no concern to anyone else that uses the internet.


Using two group-by in xslt

Question: Hi,
I need to group values twice based on some attribute and populate it.
below the xml and I want a group-by on UITVOERINGSNIVEAU and Enveloppe
<rows>
  <row Enveloppe="ACOS" POST_NUM="1000" UITVOERINGSNIVEAU="BnComd" CSTAMNUMMER="1" />
  <row Enveloppe="ACOS" POST_NUM="5000" UITVOERINGSNIVEAU="BnComd" CSTAMNUMMER="2" />
  <row Enveloppe="DG" POST_NUM="1001" UITVOERINGSNIVEAU="BdeComd" CSTAMNUMMER="4" />
</rows>

I want the result as below:
<rows>
      <row>
        <cell image="folder.gif">BnComd</cell>
        <row>
           <cell image="folder.gif">ACOS</cell>
              <row>
                 <cell>1000</cell>
                 <cell>1</cell>
              </row>
              <row>
                 <cell>5000</cell>
                 <cell>2</cell>
              <row>
        </row>
     </row>
     <row>
        <cell image="folder.gif">BdeComd</cell>
          <row>
            <cell image="folder.gif">DG</cell>
              <row>
                 <cell>1001</cell>
                 <cell>4</cell>
              </row>
        </row>
      </row>
    </rows>

I Find this to do a group-by on only UITVOERINGSNIVEAU, but I don't know how to integrate my second group-by:
<xsl:template match="/*">
  <rows>
    <xsl:for-each-group select="//rows/row" group-by="@UITVOERINGSNIVEAU">
      <row>
        <cell image="folder.gif"><xsl:value-of select="current-grouping-key()"/></cell>
        <xsl:apply-templates select="current-group()"/>
      </row>
    </xsl:for-each-group>
  </rows>
</xsl:template>

<xsl:template match="row">
  <row>
    <xsl:apply-templates select="@* except @UITVOERINGSNIVEAU"/>
  </row>
</xsl:template>

<xsl:template match="row/@*">
  <cell><xsl:value-of select="."/></cell>
</xsl:template>

can someone help me please?
thanks
Answer: If you want to group the second time it is possible to do it like this:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

    <xsl:template match="/*">
        <rows>
            <xsl:for-each-group select="//rows/row" group-by="@UITVOERINGSNIVEAU">
                <row>
                    <cell image="folder.gif">
                        <xsl:value-of select="current-grouping-key()"/>
                    </cell>
                    <xsl:for-each-group select="current-group()" group-by="@Enveloppe">
                        <row>
                            <cell image="folder.gif">
                                <xsl:value-of select="current-grouping-key()"/>
                            </cell>
                            <xsl:apply-templates select="current-group()"/>
                        </row>
                    </xsl:for-each-group>
                </row>
            </xsl:for-each-group>
        </rows>
    </xsl:template>

    <xsl:template match="row">
        <row>
            <xsl:apply-templates select="@* except (@UITVOERINGSNIVEAU | @Enveloppe)"/>
        </row>
    </xsl:template>

    <xsl:template match="row/@*">
        <cell>
            <xsl:value-of select="."/>
        </cell>
    </xsl:template>
</xsl:stylesheet>

Using two group-by in xslt


Forcing encryption for outgoing SMTP with Postfix

Question: Does anyone know how to tell Postfix to encrypt outgoing mail?
I have configured it to use encryption on reception, but I'm unable to do it with the outgoing mail. This is my main.cf file:
smtpd_recipient_restrictions = permit_sasl_authenticated, permit_mynetworks, reject_unauth_destination
smtpd_sasl_auth_enable = yes
smtpd_sasl_path = smtpd
transport_maps = hash:/etc/postfix/transport

# tls config
smtp_use_tls = yes
smtpd_use_tls = yes
smtp_tls_note_starttls_offer = yes
smtpd_tls_key_file = /etc/postfix/ssl/smtpd.pem
smtpd_tls_cert_file = /etc/postfix/ssl/smtpd.pem
smtpd_tls_CAfile = /etc/postfix/ssl/smtpd.pem
smtpd_tls_loglevel = 1
smtpd_tls_received_header = yes
smtpd_tls_session_cache_timeout = 3600s
tls_random_source = dev:/dev/urandom

Answer: smtp_tls_security_level = encrypt or smtp_enforce_tls=yes
For specific destinations you could use smtp_tls_policy_maps
smtp_use_tls = yes and smtp_enforce_tls=yes are deprecated. With Postfix 2.3 and later use smtp_tls_security_level instead.
Remember: Enforcing TLS encryption could cause mail delivery problems for SMTP host, that doesn't have TLS configured. If server is used to deliver mails to only your internal server with configured TLS, it's not a problem in that case. But if server is used to deliver mail to public servers, you cannot assume, that all servers has TLS support. In that case use
smtp_tls_security_level = may
Comment: I think he only wants to enforce it from the software mailclient to the sending mailserver. Not from mailserver to mailserver (see his comment posted at Mar 7 '10 at 23:26)
Comment: I think that whole community is adopting to a couple lazy administrators who don't support TLS. Most of the email servers have TLS configured. If they don't screw them... Just enable TLS and ignore those suckers.
Comment: Yeah, this does not work. Still unencrypted upon sending.
Answer:
The idea is to force users to
configure their email clients with
encrypted outgoing smtp server. With
the current conf, Thunderbird leave
them the option to communicate with
the smtp server in plain text...

You cannot disable option in Thunderbird without recompiling source code, but you can configure postfix stmpd daemon (which receives mail from your clients) to enforce encryption. To do that, use smtpd_tls_security_level=encrypt,
which is equivalent of obsolete options smtpd_use_tls=yes and smtp_enforce_tls=yes. smtpd_tls_security_level=encrypt and smtp_enforce_tls=yes implies smtpd_tls_auth_only=yes
From postfix documentation about smtpd_tls_security_level=encrypt

Mandatory TLS encryption: announce
STARTTLS support to SMTP clients, and
require that clients use TLS
encryption. According to RFC 2487 this
MUST NOT be applied in case of a
publicly-referenced SMTP server.
Instead, this option should be used
only on dedicated servers.

If you use public server, you cannot enforce email encryption on port 25/tcp. Better solution is disable mail delivery on by postfix smtpd daemon port 25/tcp from your clients and enable postfix submission daemon (which is special postfix smtpd daemon used only for receiving mail from your local clients described in RFC 4409 running on port 587/tcp).  To do that, set smtpd_tls_security_level=may and remove permit_sasl_authenticated from smtpd_recipient_restrictions. In master.cf uncomment line about submission daemon:
submission inet n       -       n       -       -   submission
  -o smtpd_tls_security_level=encrypt
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_recipient_resrictions=permit_sasl_authenticated,reject

Answer: Just curious, how are you telling that it isn't using TLS? The default value for smtp_tls_loglevel (which is different from smtpd_tls_loglevel) is 0, so by default you won't see anything about TLS negotiation for outbound mail in Postfix's logs.
If you set smtp_tls_loglevel = 1 or higher, you should see a line like this in the log when a message is sent:
Mar  7 22:28:10 rack postfix/smtp[27400]: initializing the client-side TLS engine
I admit I'm being lazy, but aside from that (and ms' notes above) the config looks fine to me at a glance.
Comment: I've understood, that Simon wants to enforce all mail to be encrypted using TLS. smtp_use_tls = yes allows postfix use of TLS, if remote server supports it (smtp_use_tls = yes is equivalent for smtp_tls_security_level = may). Appropriate message should be placed in maillog, if outgoing mail was encrypted using TLS.
You're right that smtp_* options are for different postfix daemon than smtpd_* (smtpd_* is for receiving mails from remote servers, smtp_* is for delivery mails to remote servers).
Comment: Thanks for your words, I probably didn´t explain me well.

The idea is to force users to configure their email clients with encrypted outgoing smtp server.

With the current conf, Thunderbird leave them the option to communicate with the smtp server in plain text... is it possible to avoid this?

Thanks in advance, Simon.
Comment: Actually I think the question might be a little ambiguous. At least I can't tell whether Simon wants Postfix to require TLS or just use it if the recipient's server supports it.
Comment: Easy way to identify whether TLS is active is to look at raw message on receiving side and look for Authentication-Results:  domainkeys=neutral (no sig);  Which indicates its not using TLS


Force rebuild of aggregated css/js

Question: I have manually removed all aggregated css and js files from sites/default/files.
I would like Drupal to regenerate these, but it does not. Drupal is still looking for the old files, the ones I have deleted.
Clearing the cache does nothing.
How do I force Drupal to recognize that the files are missing and need to be recreated?
Comment: Double check that Drupal is able/has permission and has the correct folder owner/group to write to your folder.
Comment: It definitely does.
Comment: You sure about the `owner/group` part? because you could have the correct
write `permissions` but if `owner/group` is wrong then you  cannot write. In addition, you could also try unchecking, saving, and then rechecking, saving the [settings](https://i.stack.imgur.com/7bRRP.jpg)
Comment: This has nothing to do with file or folder permissions. The files were created before by Drupal so it should be able to create them again, but it simply doesn't. Only "drush cr" seems to work, but that refreshes all other caches, which will temporary slow down the whole site.
Comment: With "Clearing the cache does nothing" you mean the browser cache or the Drupal cache. Clearing the latter should definitely work!
Answer: In D7 you might want to clear also the variables drupal_js_cache_files and drupal_css_cache_files:
<code>drush vdel drupal_js_cache_files && drush vdel drupal_css_cache_files
</code>
Other than that, do you have any other cache on top of drupal (varnish?). Your pages could be cached with the reference to the old JS files. Is your site broken (404 on CSS/JS files) or is it just referencing the old ones? Usually drupal regenerates aggregated files if it can't find it.
Comment: This is a D8 question.

Force rebuild of aggregated css/js


Quantum degree of Khovanov Complex

Question: Reading Turner's 5 Lectures on Khovanov Homology (here) , I am trying to understand how to do computations using the long exact sequence defined on Lecture $3$.
I have realized that I cannot understand what the star parametrizes when we right $C^{i,*}$
I would be glad if , along with an explanation, someone could give an example on Example 3.7, Lecture 1 the Hopf Link: Is it true that $C^{-2,j}=\mathbb{Q}$ for $j=-4,-6$ and $0$ otherwise ?
Also, If I understand correctly, the Khovanov Homology of the Unknot should be $C^{0,1}=C^{0,-1}=\mathbb{Q}$ and $0$ otherwise. Is this true ?
Answer: The term $C^{i,*}$ means $\bigoplus_{j\in\mathbb{Z}}C^{i,j}$. In other words, $C^{i,*}$ is the summand of the chain complex $C$ in homological grading $i$ and in any quantum/Jones/polynomial grading.
In Example 3.7, Turner chooses an orientation on the Hopf link so that both crossings are negative. Thus $n_+=0$ and $n_-=2$. The homological grading $i=-2$ corresponds to the all-$0$ state on the far left of the cube. Since there are two components in that state, there are four possible ways to label that state with $1$'s and $x$'s: $1\otimes 1$, $1\otimes x$, $x\otimes 1$ and $x\otimes x$. The degrees of those four states are $2, 0, 0,$ and $-2$ respectively. Therefore, the $j$-gradings of those states are $-2, -4, -4$ and $-6$ respectively. So
$$C^{-2,*} = C^{-2,-2}\oplus C^{-2,-4}\oplus C^{-2,-6}$$
where
\begin{align*}
C^{-2,-2} \cong &\; \mathbb{Q},\\
C^{-2,-4} \cong & \; \mathbb{Q}^2,~\text{and}\\
C^{-2,-6} \cong & \; \mathbb{Q}.
\end{align*}
The differential sends $1\otimes 1$ to $(1,1)$ (meaning a $1$ on the top middle state and a $1$ on the bottom middle state), sends both $1\otimes x$ and $x\otimes 1$ to $(x,x)$, and sends $x\otimes x$ to $0$. Thus $1\otimes x - x \otimes 1$ generates homology in the summand $H^{-2,-4}$ and $x\otimes x$ generates homology in the summand $H^{-2,-6}.$
You are correct about the Khovanov homology of the unknot.

Quantum degree of Khovanov Complex


What is this rhythm?

Question: I think I've heard this rhythm before, what is it called? Where does it come from?
Comment: I'm sure we all know it, but, yes, where's it from..? 1st bar is cha-cha!
Comment: That's the rhythm country western dancers use for cha-cha. The Latin dancers have the eighth notes on weak beats (2 and 4).  There's a similar difference in steps between East Coast and West Coast salsa or mambo dancers.  Geographic differences seem common among dancers in the US. Western Swing has the Push and Whip versions in Dallas and Houston respectively.
Answer: As Laurence shows, it's prevalent in pop culture as a crowd-participation chant. I'm used to it with the last two notes spoken as "Let's Go." It looks like it originated with a 1962 song by The Routers:

It looks like the opening clap/call material spread to cheerleading rather than the other way around. You can see more about its creation in the book Superstar in a Masquerade by William Sargent
Answer: I've heard it at football matches, the first 9 notes stomped or clapped, the last two being a shouted team name.
Comment: i'm no football fan, but I first heard this in the early/mid 70's as M. I. - M.I.C. - M.I.C.K.-  Mick Jones. (Leeds Utd, back when they were good;)
Comment: Makes it hard for Wolverhampton Wanderers and others of such ilk!!!
Comment: Duh, duh. Duh, duh, duh. Duh, duh, duh, duh: Inverness Caledonian Thistle!!
Comment: Huh-huh-huh, ARSE-nal, huh-huh-huh

What is this rhythm?


Inserção MySql com com "Ligação" entre inserções

Question: estou com um problemão aqui.
Preciso fazer um upload de multiplos arquivos e inseri-los em tabelas diferentes.
A tabela produtos contem os detalhes dos produtos e a tabela fotos os arquivos para acessar as imagens, só que preciso relaciona-las de acordo com o ID, como faço para inserir as fotos em outra tabela com o id do produto da primeira tabela?
<?php
if(isset($_POST['submitProduto'])){

//Caminho para salvar
$caminho = "uploads/";

$produto = trim($_POST["produto"]);
$informacao = trim($_POST["informacao"]);
$categoria = trim($_POST['categoria']);
$subCategoria = $_POST['subCategoria'];

// Verifica Checkbox
if (isset($_POST['destaque'])) {
    $destaque = 1;
}
else {
    $destaque = 0;
}

//Inseri imagem
for ($i = 0; $i < count($_FILES["fotos"]["name"]); $i++) {

    $nomeArquivo = $_FILES["fotos"]["name"][$i];
    $tamanhoArquivo = $_FILES["fotos"]["size"][$i];
    $nomeTemporario = $_FILES["fotos"]["tmp_name"][$i];

    if (!empty($nomeArquivo)) {

        $arquivoArray= explode(".", $nomeArquivo);
        $extensao = end($arquivoArray);

        $arquivo = $caminho.md5(time().rand(3212, 12043)).'.'.$extensao;

        move_uploaded_file($nomeTemporario, $arquivo);

        // lastInserId
        $last = $database::insert_id();

        $database::query("INSERT INTO produtos (nome,descricao,categoria,destaque, sub_categoria) VALUES ('".$produto."', '".$informacao."','".$categoria."','".$destaque."', '".$subCategoria."')");
        $database::query("INSERT INTO produtos_fotos (id_produto, imagem) VALUES ('".$last."', '".$arquivo."')");

        }
    }

$message = '
Produtos cadastrados com sucesso!
';

}
?>

Comment: Posta o código fonte também
Comment: pronto @rray já adicionei, o que eu quero é inserir os detalhes na tabela produto e que o id_produto da tabela produtos_fotos seja o mesmo.
Comment: Depois do primeiro insert, chama a função [mysql_insert_id](http://php.net/manual/en/function.mysql-insert-id.php) ela vai retornar o id do registro inserido, depois pegue ele e grave no segundo insert.
Comment: mysql_inser_id não funciona mais e caso eu use isso ele vai pegar o ultimo id inserido na tabela produtos_fotos e não na tabela produtos.
Answer: Você precisa deixar de fora o primeiro insert, e dentro do for sim colocar o insert das imagens... se não ele vai repetir vários inserts dos produtos.
if(isset($_POST['submitProduto'])){

    //Caminho para salvar
    $caminho = "uploads/";

    $produto = trim($_POST["produto"]);
    $informacao = trim($_POST["informacao"]);
    $categoria = trim($_POST['categoria']);
    $subCategoria = $_POST['subCategoria'];

    // Verifica Checkbox
    if (isset($_POST['destaque'])) {
        $destaque = 1;
    }
    else {
        $destaque = 0;
    }

    //Inseri imagem
    $sqlInsere = $database::query("INSERT INTO produtos (nome,descricao,categoria,destaque, sub_categoria) VALUES ('".$produto."', '".$informacao."','".$categoria."','".$destaque."', '".$subCategoria."')");

    $sqlUltimoID = $database::query("SELECT * FROM produtos ORDER BY id LIMIT 0 , 1");
    $rowUltimoID = $database::row($sqlUltimoID);

    // lastInserId
    $last = $rowUltimoID['id'];

    for ($i = 0; $i < count($_FILES["fotos"]["name"]); $i++) {

        $nomeArquivo = $_FILES["fotos"]["name"][$i];
        $tamanhoArquivo = $_FILES["fotos"]["size"][$i];
        $nomeTemporario = $_FILES["fotos"]["tmp_name"][$i];

        if (!empty($nomeArquivo)) {

            $arquivoArray= explode(".", $nomeArquivo);
            $extensao = end($arquivoArray);

            $arquivo = $caminho.md5(time().rand(3212, 12043)).'.'.$extensao;

                if(move_uploaded_file($nomeTemporario, $arquivo)){
                    $database::query("INSERT INTO produtos_fotos (id_produto, imagem) VALUES ('".$last."', '".$arquivo."')");
                } else {
                    echo "Não foi possível enviar a imagem";
                }
        }
    }

$message = '
Produtos cadastrados com sucesso!
';

}


AS3 - The supplied DisplayObject must be a child of the caller error while removing swf

Question: please help i am getting this error and could not solve with any of the other methods described in all previous posts with similar topic.
Actually here i am loading a swf myMap onto another swf.
The swf loading works fine, but when try to remove this from stage i get the above said error...
ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
    at flash.display::DisplayObjectContainer/removeChild()
    at actions.classes::MapInteractionManager/unloadSWF()
    at flash.events::EventDispatcher/dispatchEventFunction()
    at flash.events::EventDispatcher/dispatchEvent()

Here's my as3 code...
 var _swfLoader:Loader;
    var _swfContent:MovieClip;

    loadSWF("myMap.swf");  //loading the swf file here

    function loadSWF(path:String):void {
       var _req:URLRequest = new URLRequest();
       _req.url = path;

       _swfLoader = new Loader();
       setupListeners(_swfLoader.contentLoaderInfo);

       _swfLoader.load(_req);
    }

    function setupListeners(dispatcher:IEventDispatcher):void {
       dispatcher.addEventListener(Event.COMPLETE, addSWF);
       dispatcher.addEventListener(ProgressEvent.PROGRESS, preloadSWF);
    }

    function preloadSWF(event:ProgressEvent):void {
       var _perc:int = (event.bytesLoaded / event.bytesTotal) * 100;
       // swfPreloader.percentTF.text = _perc + "%";
    }

    function addSWF(event:Event):void {
       event.target.removeEventListener(Event.COMPLETE, addSWF);
       event.target.removeEventListener(ProgressEvent.PROGRESS, preloadSWF);

       _swfContent = event.target.content;
       _swfContent.addEventListener("close", unloadSWF);

       main.stage.addChild(_swfContent);
    }

    function unloadSWF(event:Event):void {
       _swfLoader.unloadAndStop();

    main.stage.removeChild(_swfContent);  //getting error when trying to remove swf
       _swfContent = null;
    }

    and close event is as,
    _swfContent.dispatchEvent(new Event("close"));

Please help, I'm stuck.
here with some update,
i updated code as,
function unloadSWF(event:Event):void
{
     if(main.stage.contains(_swfContent))
           main.stage.removeChild(_swfContent);
}

Now the error is gone as it is not entering the if loop!!!???
But still i can see that swf on stage:(  plz help
GOT SOLVED...
Thanks everyone for helping...
ToddBFisher did solve it:)
Simply added the _swfLoader to the stage, loaded it, and attached the close listener to it instead of even having a _swfContent. Cut out the middle man and it worked.... Hope this helps...
Comment: hey Vesper, both traces resulted 'true'!!!   Anyhow thanks for help, now got it working by removing the middle man _swfContent and directly adding _swfLoader onto stage as guided by ToddBFisher...
Comment: Place a `trace(_swfContent, _swfContent.parent)` statement after your call to `unloadAndStop()`, perhaps this method also clears your loaded SWF from your stage's display list, so the statement that throws the error is useless. The manual does not say anything like that, though.
Comment: hey Vesper, thanks for reply... here the problem persists even if i dont use unloadAndStop()
Comment: Okay, if you still see the SWF on the stage, do trace _swfContent.parent somewhere, and its type (`trace(_swfContent.parent is Loader);` will return true if it's Loader, then you can find out if that Loader's parent is your stage).
Comment: thanx again Vesper,                                                             trace(_swfContent.parent); gives [object Stage]
trace(_swfContent.parent is Loader); gives false                                    !!!???
Comment: `trace(main.stage==_swfContent.parent); trace(main.stage==_swfContent.stage);` Sorry, didn't yet work with multiple SWFs, there can be hidden issues about more than a single stage. (Most likely both will return false, but _swfContent.stage will be equal to _swfContent.parent, but this needs to be checked.)
Answer: As I recall .unloadAndStop(); does a bunch of cleanup type things, which you are calling right before. It is possible part of the cleanup is removing it from the display list.
Try calling the removeChild() before calling unlodaAndStop()
function unloadSWF(event:Event):void {
    stage.removeChild(_swfContent);  //getting error when trying to remove swf
    _swfLoader.unloadAndStop();
    _swfContent = null;
}

EDIT
Try simply adding the _swfLoader to the stage, load it, and attach the close listener to it instead of even having a _swfContent. Cut out the middle man and see what happens.
Comment: hey ToddBFisher, thanks for reply.. but doesnt work in my case. i tried dis, if(main.stage.contains(_swfContent)) main.stage.removeChild(_swfContent) the error disappears but i can still see the swf on stage
Answer: The error means the child is already removed (or never added)
try to comment out
_swfLoader.unloadAndStop();
to see if it works.
Answer: main.stage.removeChild is already setting  _swfContent to null because removeChild was fired so  removing the line _swfContent = null might solve it.
Comment: hey tariq, thanks for reply...even                              function unloadSWF(event:Event):void {
    main.stage.removeChild(_swfContent);
} didnt work!!!
Comment: Try this link,it should help you better understand your problem- http://senocular.com/flash/tutorials/runtimeerrors/#2025


Calculating Kurtosis with Beta distribution in R

Question: I am working on an assignment question in R. The problem I am having is to calculate the Kurtosis using Beta distribution.
So far I am able to get the kurtosis value of alpha = 3  beta = 2 using this code:
> kurtosis=(3*alpha^3*beta+3*alpha*beta^3+6*alpha^2*beta^2+alpha^3+beta^3+13*alpha^2*beta+13*alpha*beta^2+alpha^2+beta^2+14*alpha*beta)/((alpha*beta*(alpha+beta+2)*(alpha+beta+3)))

kurtosis
  [1] 2.892857

The question asks me to generate 1 000 000 independent identically distributed random variables following a Beta distribution. That is easy:
n=100 (I am using 100 for now as 1 000 000 pretty much just hangs my machine up for hours)
p<-rbeta(n, shape1=alpha, shape2=beta)
p

[1] 0.6264632 0.8556988 0.8947960 0.2508657 0.2478296 0.3652293 0.4058185 0.9133942 0.2521895 0.3846150 0.7311879 0.6123567 0.5687362 0.5272337 0.7321268 0.5167320 0.2628915
 [18] 0.6827633 0.4034805 0.7767011 0.9246785 0.5946597 0.7077071 0.4014387 0.5738073 0.7225824 0.2736515 0.2674327 0.3449036 0.8527233 0.9142692 0.8225190 0.8081674 0.7760414
 [35] 0.5947241 0.8211220 0.6825275 0.1994827 0.3839823 0.8674370 0.4383073 0.6895321 0.6948742 0.4175201 0.4870160 0.4839224 0.5868314 0.6400326 0.5956450 0.7255520 0.4290051
 [52] 0.8997959 0.8925137 0.7729661 0.6168284 0.5989350 0.6112734 0.1849604 0.5710712 0.5314022 0.8364838 0.7888875 0.8285151 0.5491049 0.9450382 0.6302862 0.6035714 0.4513216
 [69] 0.1588688 0.6744496 0.6010260 0.6908575 0.5219169 0.6897020 0.1486987 0.6108051 0.5032918 0.8729911 0.8216785 0.4243647 0.6615128 0.5479400 0.6326745 0.7449108 0.7917081
 [86] 0.3582359 0.7631012 0.6198699 0.4402614 0.5099704 0.3586977 0.4702083 0.5465371 0.7308831 0.3773918 0.5209375 0.2836313 0.6724058 0.7975775 0.6507358

Now I am using this formula to calculate Kurtosis:
(sum(Xi-Xbar)^4/n)/(sum(Xi-Xbar)^2/n)^2

Putting this into R
for (i in 1:n) {
value[i] <- ((p[i]-mean(p))^4/n)/(((p[i]-mean(p))^2/n)^2)}

When I call value I get this return:
 value

 [1] 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100
 [44] 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100
 [87] 100 100 100 100 100 100 100 100 100 100 100 100 100 100

I tried to do the first value of (p[1]-mean(p))^4/n)/(((p[1]-mean(p))^2/n)^2) in mathematica and i get value of 7.389056099
I found that the problem is when I try to divide numerator by denominator, is there another way to do division other than / ? Or am I approaching the problem wrong?
Comment: Did I understand you correctly: You want to calculate the empirical kurtosis of the random variables generated by rbeta, right? So there will be finally one calculated number, which is the kurtosis? Why should there result an array of values? I am not getting this?
Comment: see my answer, maybe this helps you.
Answer: I am not sure, if I got you right, but you want to calculate the kurtosis of the numbers generated by rbeta which you saved into the variable p?
You can use the e1071 library, and NOTICE: THE COMMAND KURTOSIS GIVES YOU THE EXCESS KURTOSIS, so you have to add 3:
library(e1071)
kurtosis(p)+3

Or you calculate it manually:
First of all, you do not need a loop.
Second, your loop is wrong, because it is not considering the sums correctly.
You can calculate the kurtosis manually with:
m4 <- mean((p-mean(p))^4)
kurt <- m4/(sd(p)^4)
kurt

in this simple case you do not need a loop.
I give you a more simple example (not from a beta distribution):
testvector<-c(1,2,1,2,1,2)
kurtosis(testvector)+3
m4 <- mean((testvector-mean(testvector))^4)
kurt <- m4/(sd(testvector)^4)
kurt

In both cases, the result is
[1] 0.6944444

Comment: @netuser01 you can accept my anwer, by clicking on the button to the left of my post (the hook).
Comment: Thank you for your reply, that makes much more sense.

The actual question is to use a monte-carlo technique to approach skewness and kurtosis using the sample p created.

I was under the impression that I should have used the manual calculation for kurtosis from p and then compare it with the kurtosis value from the alpha, beta values.

Your explanation is much better! I think that it may be on the right track for my original question, time for me to think more :)

Thank you


Documentation of Hydra Config

Question: Hydra provides a way to dynamically create a hierarchical configuration by composition and override it through config files and the command line, leveraging OmegaConf. I look for a recommended way to document the parameters but I could not find (a documented) one. What are best practices for that? Coming from argparse, I like the way of documenting the parameter inline, i.e. close to the code.
Answer: Excellent question! The answer is: parameter-by-parameter documentation is not yet implemented (as of Hydra v1.1, OmegaConf v2.1).
The future plans are:

in OmegaConf, expose an API allowing users to attach documentation (and other metadata) to each field of a structured config. See this open OmegaConf issue.
Once the above is complete, implement a Hydra feature allowing a parameter-specific help messages to be printed based on the parameter's metadata. See this open Hydra issue.

For now, the best we can do is to customize the general application help message (i.e. the <code>--help</code> command line flag).

Documentation of Hydra Config


Is $\limsup_{\epsilon \to 0^+}\frac{1}{\epsilon}\sup_{y \in B(x; \epsilon)}|f(y)-f(x)|$ related to any standard notion of gradient?

Question: Let $f:\mathbb R^d \to \mathbb R$ be a function and fix scalar $\epsilon > 0$. Given a pint $x \in \mathbb R^d$, define
$$
\Delta_f(x;\epsilon) := \sup_{y \in B(x; \epsilon)}|f(y)-f(x)|,
$$
where $B(x;\epsilon):=\{y \in \mathbb R^d \mid \|y-x\| \le \epsilon\}$.
Finally, define $\partial^{-} f(x) := \liminf_{\epsilon \to 0^+}\frac{\Delta_f(x;\epsilon)}{\epsilon}$ and $\partial^+ f(x) :=\limsup_{\epsilon \to 0^+}\frac{\Delta_f(x;\epsilon)}{\epsilon}$

Question 1. Is there a way to link the quantities $\partial^{\pm} f(x)$ with any known notion of derivative ?

The strong slope of $f$ at $x$, denoted $|\partial^+ | f(x)$ is defined by
$$
|\partial^+| f(x) := \limsup_{y \to x}\frac{(f(y)-f(x))_+}{\|y-x\|},
$$
where $(t)_+ := \max(t,0)$. This notion of gradient is common in gradient-flow literature, and can be defined for functions on arbitrary metric spaces (e.g spaces of probability measures).

Question 2. Is $|\partial^+| f(x)$ related in any way to $\partial^{\pm} f(x)$ ?
Comment: It seems somewhat related to the metric derivative (https://en.wikipedia.org/wiki/Metric_derivative) (indeed the wiki page cites Ambrosio-Gigli-Savaré!).
Comment: Yes, that's what they call *strong slope*.
Answer: Q1: Assume $f$ is differentiable at $x$, then $ \partial^+f(x)=\partial^-f(x)=\|f'(x)\|$, where $f'(x)=\nabla f(x) = (\frac{\partial f}{\partial x_1}(x), \cdots, \frac{\partial f}{\partial x_d}(x))$ is the gradient (a row vector).
Proof. As $f$ is differentiable, $f(y) = f(x) + f'(x) (y-x) + o(\|y-x\|)$ around $x$. Therefore for suffciently small $\epsilon$ (all the sups are taken over $B(x;\epsilon)$), $$\begin{align}\Delta_f(x;\epsilon) &=\sup\mid f'(x)(y-x)+o(\|y-x\|)\mid \\ &\le \sup|f'(x)(y-x)| + \sup o(\|y-x\|) \\ &=\|f'(x)\|\epsilon + \sup o(\|y-x\|) \\ \frac{\Delta_f(x;\epsilon)}{\epsilon}&\le\|f'(x)\|+ \sup \frac{ o(\|y-x\|)}{\epsilon}\end{align}$$
Here $\sup|f'(x)(y-x)|=\|f'(x)\|\epsilon$ follows from Cauchy-Schwarz. Note that $\sup \frac{ o(\|y-x\|)}{\epsilon}\le\sup \frac{ o(\|y-x\|)}{\|y-x\|}\rightarrow 0$, We have shown that $\partial^+f(x)\le \|f'(x)\|$. Similarly $$\begin{align} \Delta_f(x;\epsilon) &=\sup\mid f'(x)(y-x)+o(\|y-x\|)\mid \\ &\ge\|f'(x)\|\epsilon - o(\epsilon) \end{align}$$
Hence $\partial^-f(x)\ge \|f'(x)\|$.
Q2: From Q1, it's easy to show that $|\partial^+|f(x)=\|f'(x)\|$ as well.
Comment: I haven't checked the paper yet. The argument I had in mind: Clearly $(f(y)-f(x))_+\le|f(y)-f(x)|\le \|f'(x)\|\|y-x\|+o(\|y-x\|)$ hence $|\partial^+|\le \|f'(x)\|$. If $\|f'(x)\|=0$, we are done. Otherwise, we can let $y$ approaches $x$ following $f'(x)$, and $f'(x)(y-x)=\|f'(x)\|\|y-x\|>0$ dominates $o(\|y-x\|)$, hence $+$ can be dropped, $()_+ = \|f'(x)\|\|y-x\|+o(\|y-x\|)$
Comment: Indeed, you're write. Ignore previous comment.


Reading a file from the filesystem

Question: I am trying to read a file from /data partition in Android. I wrote a test App and then started it on the emulator. Then I used "adb push local_path_to_file /data/mydir/file1" to copy file1 under /data/mydir/.
Now I tried the following in my App and nothing happens :(
How to read a file saved in the /data? What is wrong with my code?
Here is the snippet code:
            try {

            File source = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/data/pu/file1");
            InputStream is = new FileInputStream(source);
            String fileStr = new String(ReadBytesOfFile(is).toString);
            System.out.println("file out ="+ fileStr);
            is.close();
            }
            catch(IOException e){
                Log.d("file","NOT FOUND");
            }

         public byte [] ReadBytesOfFile (InputStream input) throws IOException {
            long length = input.available();
            byte[] rbuffer = new byte[(int) length];
            input.read(rbuffer);
            return rbuffer;
         }

Comment: I also tried just: Environment.getExternalStorageDirectory()+"/data/pu/file1"
Answer: First, you cannot store files in /data in production, except in the location returned to you by getFilesDir(), so you really need to rethink your approach.
Second, you are not trying to read from /data. Your code reads from a /data directory inside of Environment.getExternalStorageDirectory(). The precise location of Environment.getExternalStorageDirectory() varies by device and OS version, but /mnt/sdcard is the most common spot. Hence, you are presently trying to read from something like /mnt/sdcard/data, not /data.
Here is the documentation on data storage in Android.
Comment: @user489152: `getFilesDir()` is the directory for private data.
Comment: Thanks CommonWare. Just another question, sdcard dir seems to be mounted as READ ONLY. So how do I push/copy my files to this partition and then read from them? I actualy thought I was reading from the sdcard!
Comment: @user489152: Your emulator probably does not have an emulated SD card. You need to define one using the AVD Manager. And if you do not know what "inside" means with respect to a directory, there is little I can do to help you.
Comment: Oops well, deleting that comment. I wanted to know if it was the directory for private data of Apps not visible to other Apps. Anyway got it now.

Reading a file from the filesystem


Dúvida sobre indexes para campos booleanos - MongoDB

Question: Tenho documentos com campos booleanos numa coleção do Mongo. Para indexar esses campos, é melhor que seus valores sejam Number (0 ou 1) ou não faz diferença se forem do tipo booleano? Tenho recebido alguns alertas de "slow query" na busca por usando esses campos booleanos.
Answer: No final das contas o índice vai ficar com duas entradas (0 e 1 ou true e false) creio que não faça diferença. Sem dúvida os valores booleanos vão ocupar menos espaço em disco, o que vai te deixar com um índice menor e dados menores.
Os avisos de consulta lenta devem ser por outro motivo. Você tem mais filtros na consulta além desse campo booleano? em que ordem você criou os campos do índice? tem ordenação na consulta? Adiciona um exemplo de consulta que ficou como lenta, e mostra a estrutura do teu documento que fica mais fácil de ajudar.


Horisontal scrollbar not working for JScrollPane

Question: This is my plugin to the application with Miglayout:

This is MigLayout initialistion code, layout occupies 100% space of main panel:
resPanel.setLayout(new BoxLayout(resPanel, BoxLayout.Y_AXIS));
mainPanel.setLayout(new MigLayout("", "[][grow][grow][]", "[][][][grow]"));
mainPanel.add(new JLabel("Class expression"), "wrap");
mainPanel.add(owlDescriptionEditor, "growx,span 3");
mainPanel.add(calcButton, "wrap");
mainPanel.add(new JLabel("Definitions found"), "span 2");
mainPanel.add(new JLabel("Target signature"), "span 2,wrap");
JScrollPane jsp = new JScrollPane(resPanel);
mainPanel.add(jsp, "growy, growx, span 2");
jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
mainPanel.add(new JScrollPane(deltaList), "growx,growy,span 2");

The problem is not working horizontal scrollbar of the left list, which is JPanel with BoxLayout, even though I call setVerticalScrollBarPolicy for it. JPanel is populated dynamically with this loop:
static void updateList(JPanel panel, Collection<OWLClassExpression> list) {
    panel.removeAll();
    for (int i = 0; i < 3; i++) {
        for (OWLClassExpression p : list) {
            String name = ((OWLNamedObject) p).getIRI().getShortForm();
            JEditorPane jep = new JEditorPane("text/html", name+"QWQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ");
            jep.setPreferredSize(new Dimension(200,20));
            jep.setEditable(false);
            jep.setOpaque(false);
            panel.add(jep);
        }
    }
    panel.add( Box.createVerticalStrut(400) );
}

I had to add last line to get vertical scrollbar working. If I don't add it, then its also missing, even though it has side effect of extra empty space in the bottom. How can I make scrollbars work properly?
Comment: For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). It'd help if the MCVE / SSCCE used only J2SE layouts.
Answer: jep.setPreferredSize(new Dimension(200,20));

Don't hardcode preferred sizes.
Each component will dynamcially determine its own preferred size based on the properties of the component (text, font etc.).
The layout manager can then dynamically determine the size of the panel based on the preferred size of each component and scrollbars will appear when required.
Also after you are finished adding all the components to the panel you need to use:
panel.revalidate();

To invoke the layout manager so the new size of the panel can be calculated.


Como percorrer um enum?

Question: Preciso fazer o seguinte: Passar uma string e ir percorrendo ela e pegar cada letra encontrada e somar com seu valor correspondente, tipo: a = 1, s = 19 e etc.
Bem, fiz um enum com todos os valores da string, começando por a = 1 até z = 26 (inclui K,W e Y). Estou com dificuldade de pegar a letra no for e acumular seu valor em relação ao enum.
public enum triaguloLetra
{
    a = 1,
    b = 2,
    c = 3,
    d = 4,
    e = 5,
    f = 6,
    g = 7,
    h = 8,
    i = 9,
    j = 10,
    k = 11,
    l = 12,
    m = 13,
    n = 14,
    o = 15,
    p = 16,
    q = 17,
    r = 18,
    s = 19,
    t = 20,
    u = 21,
    v = 22,
    w = 23,
    x = 24,
    y = 25,
    z = 26
}
string teste = "Stackoverflow";
for (int i = 0; i <= teste.Length - 1; i++)
{
    //Como eu digo que teste[i] = ao enum.s?? e assim por diante
}

Answer: Em vez de um enum use um Dictionary:
Dictionary<string, int> valorLetra = new Dictionary<string, int>();

valorLetra.Add("a",1);
.....
....
valorLetra.Add("z",26);

string teste = "Stackoverflow";
int soma = 0;
for (int i = 0; i <= teste.Length - 1; i++)
{
    string letra = teste[i].ToString().ToLower();
    soma = soma + valorLetra[letra];
}

No entanto, neste caso, não precisa de enum nem de Dictionary:
string teste = "Stackoverflow";
int soma = 0;
for (int i = 0; i <= teste.Length - 1; i++)
{
    soma = soma + Char.ToLower(teste[i]) - 'a' + 1;
}

Usando LINQ:
string teste = "Stackoverflow";
int soma = teste.Select(c => Char.ToLower(c) - 'a' + 1).Sum();

Comment: `char` não é mais que uma instância da estrutura *System.Char* que é usada para representar os caracteres *Unicode* e cujo valor é um inteiro. O valor de 'a' é 97, 'b' é 98 e assim sucessivamente. Com você quer que a sequência comece em 1 teremos que subtrair ao valor de cada letra o valor de 'a' mais 1. Exemplo para a letra 'b' => 98 - 'a'(97) + 1 = 2.
Comment: Acho que seria melhor usar um `Dictionary` em vez de `Dictionary`
Comment: @dcastro Sim, evitaria a chamada a `ToString()`.
Comment: @ramaral, desculpe-me minha ignorância, mas não entendi o 'a' + 1 na lambda acima. Deu certo sem Dictionary<>, mas não entendi o porque de 'a' + 1.
Comment: @ramaral Entendi, ainda que meio estranho. Então "c" seria: => 99 - 'a'(97) + 1 = 3. É isso, certo?
Comment: Exacto. Cada caractere tem um [código](https://en.wikipedia.org/wiki/List_of_Unicode_characters) associado, é esse código que `char` representa.
Answer: Mais uma solução:
foreach (var elemento in Enum.GetValues(typeof(TrianguloLetra))) {
    //faz o que você quiser aqui
}

Exemplo:
using System;
using static System.Console;

var soma = 0;
foreach (var elemento in Enum.GetValues(typeof(TrianguloLetra))) soma += (int)elemento;
WriteLine(soma);

public enum TrianguloLetra {
    a = 1, b, c, d,  e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Answer: Usando estritamente os pontos da sua pergunta original (Lookup em um Enum), seu teste deveria ser o seguinte:
var valorEnum = (triaguloLetra)Enum.Parse(typeof(triaguloLetra), letra);

O método Enum.Parse realiza um lookup na coleção de valores do Enum, de maneira similar ao key lookup de um Dictionary, mantendo assim a estrutura original da sua pergunta.
Comment: A minha dúvida crucial, pela sua resposta, foi em não usar e/ou conhecer o Enum.Parse. Aí estava meu quebra-cabeça. Vou refazer dessa forma e ver a resposta e assim, já posso seguir em dois caminhos distintos: O Dictionary<> e o Enum. Valeu.
Comment: @pnet Pois é, os métodos de manipulação de Enum ficam escondidos na classe estática - acho que seria melhor se eles fossem expostos diretamente na instância. De qualquer maneira, mais uma ferramenta pro seu cinto de utilidades. =)
Answer: Você pode fazer assim:
public enum triaguloLetra
{
    a = 'a', b = 'b', c = 'c', d = 'd', e = 'e', f = 'f', g = 'g', h = 'h', i = 'i', j = 'j', l = 'l', m = 'm', n = 'n', o = 'o', p = 'p', q = 'q', r = 'r', s = 's', t = 't', u = 'u', v = 'v', x = 'x', z = 'z'
}

var texto = "Stackoverflow";
foreach (var item in texto.ToLower())
{
    var charEnum = (triaguloLetra)item;
}

Comment: Entendi Felipe, pegar a letra e transformá-la em um char e como os char são indexados, o valor dos chars já estão implícito. Também seria uma outra forma. Valeu.
Answer: Pegando no conselho do @ramaral, uma forma mais funcional de expressar o comportamento do codigo seria:
var valores = new Dictionary<char, int>
{
    {'a', 1},
    {'b', 2}
};

int soma = teste.Select(c => Char.ToLower(c))
                .Select(c => valores[c])
                .Sum();

Aproveitei para melhorar a sugestao usando um dicionario de char em vez de string, e usando collection initializer.
Comment: Ainda esqueço que existe o LINQ. Só falta passar a minúsculas: `c => valores[Char.ToLower(c)]`
Comment: @ramaral Done ;)
Answer: Você pode fazer usando LINQ
Func<string, int> Contador =
    x =>
    x.Select(c => Char.ToLower(c) - 98).Where(c => c > 0 && c < 27).Sum();

Exemplo no DotNetFiddle

Como percorrer um enum?


Can $\sigma(n)-n$ be a proper divisor of $n$?

Question: Let $n\ge 2$ be a natural number, $\sigma(n)$ the sum of its divisors.

Can $\sigma(n)-n$ be a PROPER divisor of $n$ ?

If $\sigma(n)-n=n$ , $n$ is a perfect number.
If $\sigma(n)-n=1$ , $n$ is a prime number.
I checked the numbers upto $n=10^9$ and did not find a number $n$ with
the desired property. My conjecture is that there is no such number.
Can anyone prove or disprove this conjecture ?
Comment: Put $n=12$. $\sigma(12)=16$. Hence $\sigma(n)-n=4$, which is a proper divisor of $12$.
Comment: @AyushKhaitan No, $\sigma(12)=28$
Comment: @user26486- yes I'm sorry I forgot to add $12$ itself! Haha
Answer: There is no such $n$ such that $\sigma(n)-n$ is a proper divisor of $n$, except for prime numbers, for which it is trivial (as you stated).
Assume $n$ is not prime, and let $m$ be its biggest divisor (not necessarily a prime). Then $n=m\cdot p$ for some prime $p$. If $m=p$, then $n=p^2$ and $\sigma(n)-n=p+1\nmid p^2$. If $m\neq p$, then $\sigma(n)-n> m+p> m$, so $\sigma(n)-n$ is larger than any proper divisor of $n$, and can't be any of them.
Comment: One little detail is missing, the case $p=q$, but this implies $n=p^2$, with a prime $p$, for which we have $\sigma(n)-n=p+1$, which is not a divisor of $p^2$.
Comment: But beside this, an impressive proof!
Comment: I have greatly edited your answer to make it more clear and more rigorous and shorter. If you don't like it, then tell me.
Comment: @Peter: Does this question (and the corresponding answer) have a bearing on the [Descartes-Frenicle-Sorli Conjecture](http://nntdm.net/papers/nntdm-24/NNTDM-24-3-062-067.pdf) on odd perfect numbers?


I get this error with my custom module, Any advice on tracking down the problem?

Question: I get this error when i select an option form a select list.
https://i.stack.imgur.com/ACmDg.png
Drupal Watchdog log Error Details
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'examplesite.field_data_field_for_date' doesn't exist: SELECT r.entity_id AS entity_id FROM {field_data_field_for_date} r WHERE (field_for_date_target_id = :db_condition_placeholder_0) ; Array ( [:db_condition_placeholder_0] => 0 ) in stopsale_getcurrentsale() (line 249 of /nfs/c05/h02/mnt/examplesite.com/html/sites/all/modules/custom_apps/stopsale/stopsale.module).
https://i.stack.imgur.com/ACmDg.png
Answer: You need to create a custom field called for_date which will be represented in the database as field_data_field_for_date or remove field_data_field_for_date from the SQL query.
Comment: @Jerry You can find that list at /admin/reports/fields
Comment: Ah that makes sense, is there a way to list all fields in drupal 7?


Django development server showing Error 61 Connection Refused with Redis

Question: I am trying to follow the tutorial on read the docs for Django Channels. In the settings.py file I am trying to change the inmemory BACKEND to the redis backend with the following code:
CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "asgi_redis.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("localhost", 6379)],
        },
        "ROUTING": "chan.routing.channel_routing",
    },
}

However, the moment I do this, the console which is running the runserver command shows the following error:
ConnectionError: Error 61 connecting to localhost:6379. Connection refused.

How can I fix this?
Comment: All that's doing is installing the redis client library. The server is not Python and can't be installed via pip. Get it [here](http://redis.io/download).
Comment: If you type `redis-cli` in your terminal, does it allows you to establish connection? `ping` command, maybe? And if it's 0k, try using 127.0.0.1 instead of `localhost`.
Comment: No. It says command not found. But in the shell I can do `import redis`, `print redis.Redis("localhost")` which gives me `Redis>>`.
Comment: You should reinstall redis from guide posted in answer than. It's abnormal behavior, that `redis-cli ` is not found, 'cause it's a part of a standard dist.
Comment: It seems likely that you haven't actually installed the redis server.
Comment: I did `pip install asgi_redis`. I think it installs redis for me because I've tried doing `pip install redis` later but it says that the requirement is already installed. I am doing all this within a virtualenv. Am I missing something?
Answer: Please make sure if redis is installed on your system and it is running.
To check if redis is running use
 redis-cli

then it will take you to redis console, then if you type ping it will return PONG if redis is running or not.
If you don't have redis in your system, please visit Redis Quick Start.
For Mac OS X: Go to terminal and type brew install redis.
Comment: I did `pip install asgi_redis` and it installed Redis inside my virtualenv. Should I install from source like it says in the Redis official website?
Comment: It is not to be installed in virtualenv, it is to be installed over as root, try
`wget http://download.redis.io/redis-stable.tar.gz`

`tar xvzf redis-stable.tar.gz`

`cd redis-stable`

`make`

`redis-server`
Answer: This is worked for me:
redis-server

That's simple
Comment: ... but why does it work? it worked for me as well


Animating View - compatible for iPad 3.2 and 4.2 version

Question: Two views need to be resized when a button is clicked in iPad .
I Tried it with following code
[UIView animateWithDuration:1.0 animations:^{
    //Target Rect of the View will be given here
}];

It works fine with iPad4.2 ,but Crashes with 3.2 version(Incompatible).
On Googling found that 3.2 version supports only Animating Views (W/O Blocks)
Source:
http://developer.apple.com/library/iOS/#documentation/UIKit/Reference/UIView_Class/UIView/UIView.html#//apple_ref/occ/clm/UIView/beginAnimations:context:
They have mentioned its not advisable to use it for 4.0 and later
How can I achieve animating the views for both 3.2 and 4.2.
Answer: I you really need to support versions below 4.0, you can use this:
[UIView beginAnimations:@"animation" context:nil];
[UIView setAnimationCurve:UIViewAnimationCurveLinear];
[UIView setAnimationDuration:1.0]; //In seconds
//Here do your stuff
int newPosY = myImage.frame.origin.y - 10;
[myImage setFrame:CGRectMake(self.frame.origin.x, newPosY, myImage.frame.size.width,     myImage.frame.size.height)];

[UIView commitAnimations];

That moves an UIImageView 10 pixels up.
Also check UIView reference to see all the possibilities.
Comment: This method is not advisable for 4.0 and above . I am in need of a thing which runs in both the versions
Comment: I'm using it in a bunch of iOS 4.3 projects and also submitted apps to the App Store, what's the problem with it?


Adding new text field to drupal 8 menu

Question: I am trying to add a new text field to the menu in Drupal 8, and I have done it using the instruction in the following post:
Add field(s) to menu link?
function my_module_entity_base_field_info(\Drupal\Core\Entity\EntityTypeInterface
$entity_type) {
  if ($entity_type->id() === 'menu_link_content') {
    $fields['location'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Location'))
      ->setDisplayOptions('view', ['label' => 'hidden', 'type' => 'string', 'weight' => 0, ])
      ->setDisplayOptions('form', array('type' => 'string', 'weight' => 0));

    return $fields;
  }
}

But I am not sure how to go about using hook_update_n to update the schema to reflect this change.
function menu_link_content_update_8201() { 'what do I put here to add the new field that I created'? }

I was able to workaround this issue by manually adding the location column in the mysql db and I can see the field showing up in the menu link editor and able to load and save it just fine in the cms UI.
But then I am not sure how to access this field in the twig file.
Any help would be grateful.  Thanks!
Answer: You only need an update hook if you want that your module can be updated on production sites already using the module. If you write a new module or the module is still in development you can simply reinstall the module. If you have data you want to keep during development use drush entity-updates after changing the code of the installed module.

Adding new text field to drupal 8 menu


How to find MLE of this piecewise pdf?

Question: Suppose $X_1,\ldots, X_n$ are i.i.d. random variables having pdf
$$
f_{\theta}(x)=\left\{\begin{array}{ll}{\theta,} & {0 \leqslant x \leqslant 1} \\ {1-\theta,} & {1<x \leqslant 2}\end{array}\right.
$$
Give the maximum likelihood estimate of $\theta$.
I know the likelihood function of $(X_1,\ldots, X_n)$ is
$$\ell(\theta;x)=\prod_{i=1}^{n}\left[\theta I(0<x_i<1)+(1-\theta)I(1<x_i<2)\right]$$
But I don't know how to compute $\frac{\partial \log \ell(\theta)}{\partial \theta}=0$ to get $\hat{\theta}$.
Is there anyone can tell me?
Answer: What you have written for the likelihood function is technically correct but you cannot reasonably derive an MLE in this setup because of the additive nature of the function. In this case, you can suppose that $n_1$ observations in the sample are in $[0,1]$ and $n_2$ observations are in $[1,2]$, with $n_1+n_2=n$.
Given the sample, rewrite the likelihood function as $$L(\theta)=\left(\prod_{i:0\le x_i\le 1}\theta\right)\left(\prod_{i:1<x_i\le 2}(1-\theta)\right)\quad,\,\theta\in(0,1)$$
This is the same as saying $$L(\theta)=\theta^{n_1}(1-\theta)^{n_2}\quad,\,\theta\in(0,1)$$
Differentiating the log-likelihood wrt $\theta$ yields
$$\frac{\partial}{\partial\theta}\ln L(\theta)=\frac{n_1}{\theta}-\frac{n_2}{1-\theta}$$
So a critical point of the likelihood is $$\hat\theta=\frac{n_1}{n_1+n_2}=\frac{n_1}{n}$$
Comment: I understand. Thank you very much.
Answer: Your expression of the p.d.f. is not very convenient for the estimation.
It's better to use
$$ f_\theta(x) = \theta^{I(0 \leq  x  \leq 1)}(1-\theta)^{I( 1 < x \leq 2)}.$$
If you spend two minutes on it you'll see it's the same.
Then,
$$L(\theta) = \prod_{i=1}^N f_\theta(x_i) = \theta ^{\#[0,1]}(1-\theta)^{\#(1,2]},$$
where $\#[0,1]$ and $\#(1,2]$ are the number of $x_1$ that fall in each interval. Then, by taking the derivative, you find that the maximum likelihood estimate of $\theta$ is given by
$$ \frac{\#[0,1]}{\hat\theta} + \frac{\#(1,2]}{1-\hat\theta} = 0;$$
so
$$\hat \theta = \frac{\#[0,1]}{\#[0,1] + \#(1,2]} = \frac{\#[0,1]}{N}.$$
Comment: I understand. Thank you very much.

How to find MLE of this piecewise pdf?


Unable to get google graphs to display when trying to implement MVC pattern

Question: Hoping someone can find a solution to my problem.  I am trying to create a dashboard using google maps and PHP.  I was able to display the graphs before I tried putting it into the MVC pattern and now all I get is errors. (the code is separated into their respective folders Model, View, and Controller with an index file in the root directory). Here is a the code I have so far
Index
<?php

include_once ("Design/includes.php");

$controller = new Controller();
$controller->invoke();
?>

Controller
<?php

class Controller {
public $model;

public function __construct()
{
    $this->model = new tableModel();

}

public function invoke()
{
    $this->model -> tableData();
    include 'view/homeScreen.php';
}

}

?>

Model (this is for the table, another model is in the same folder but it is exactly the same)
<?php

class tableModel {

public function tableData(){
    global $con;

$result = mysqli_query ( $con, "SELECT fk_EXECUTION_LAB_MACHINE as LAB_MACHINE,    COUNT(fk_EXECUTION_LAB_MACHINE) as TOTAL
                            FROM EXECUTION_QUEUE
                            WHERE fk_EXECUTION_LAB_MACHINE IS NOT NULL and WEEK (TEST_START_TIME) = WEEK( current_date ) -1 AND YEAR( TEST_START_TIME) = YEAR( current_date )
                            GROUP BY fk_EXECUTION_LAB_MACHINE order by count(fk_EXECUTION_LAB_MACHINE) desc;");

$rows = array();

$table = array();

$table['cols'] = array(

    // Labels for chart/column titles
    array('label' => 'LAB_MACHINE', 'type' => 'string'),
    array('label' => 'TOTAL', 'type' => 'number')

);

//Getting results array and populating table
$rows = array();
while($r = mysqli_fetch_array($result)) {
    $temp = array();
    $temp[] = array('v' => (string) $r['LAB_MACHINE']);
    $temp[] = array('v' => (int) $r['TOTAL']);
    $rows[] = array('c' => $temp);
}

//Get table in JSON format
$table['rows'] = $rows;

$jsonTable = json_encode($table);
echo $jsonTable;
return $jsonTable;

mysqli_close ( $con );

    }
}
?>

and here is the view

As I said earlier, the graphs worked fine when I had it just with the view and the table data in one folder but now I have put it into MVC style it no longer works. here is the errors I am getting
{"cols":[{"label":"LAB_MACHINE","type":"string"},{"label":"TOTAL","type":"number"}],"rows":[{"c":[{"v":"LIT-QAVIST-20"},{"v":1}]},{"c":[{"v":"LIT-QAVIST-25"},{"v":1}]}]}Warning: mysqli_query(): Couldn't fetch mysqli in C:\Users\n0237569\workspace\Dashboard MVC\Design\model\tableModel.php on line 11
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in C:\Users\n0237569\workspace\Dashboard MVC\Design\model\tableModel.php on line 28
{"cols":[{"label":"LAB_MACHINE","type":"string"},{"label":"TOTAL","type":"number"}],"rows":[]}
Warning: include(view/homeScreen.php): failed to open stream: No such file or directory in C:\Users\n0237569\workspace\Dashboard MVC\Design\controller\Controller.php on line 17
Warning: include(): Failed opening 'view/homeScreen.php' for inclusion (include_path='.;C:\php\pear') in C:\Users\n0237569\workspace\Dashboard MVC\Design\controller\Controller.php on line 17
As you can see from the first error it is returning the data in json but then im not sure what is going on next.
Here is the contents of the include folder as the last two errors make reference to it
includes
<?php
require_once "Design/config.php";
require_once "Design/connection.php";
require_once "Design/model/pieModel.php";
require_once "Design/model/tableModel.php";
require_once "Design/controller/Controller.php";

?>

Any help would be greatly appreciated
Thanks
Answer: Warning: include(view/homeScreen.php): failed to open stream: No such file or directory in C:\Users\n0237569\workspace\Dashboard MVC\Design\controller\Controller.php on line 17

Warning: include(): Failed opening 'view/homeScreen.php' for inclusion     (include_path='.;C:\php\pear') in C:\Users\n0237569\workspace\Dashboard     MVC\Design\controller\Controller.php on line 17

These errors are being caused by this line in your controller
include 'view/homeScreen.php';

because inside your controller you are in the Controller folder so you need to look up a level, i.e.
include '../view/homeScreen.php';

In your tableModel
return $jsonTable;

mysqli_close ( $con );

The mysqli_close( $con ); part in the bottom of your tableModel is useless as you are already returning just above it. PHP will automagically close the connection when the request is finished, but it might be worth closing it yourself if it is no longer needed.
You should wrap some logic around your MySQL functions to debug the query.
You can try something like
if( !$result ) { die(mysqli_error($con));

You should consider using PDO, and taking a look at some existing MVC frameworks to get a better idea about the MVC pattern, and how they handle routing and autoloading classes etc.
Comment: you were correct about the two errors, I added the folder to the controller and now the errors are gone (just displays the JSON now but still will not display the view with the graphs) Im pretty new to this so will have a look at PDO and see what I can do.


Generative vs. discriminative

Question: I know that generative means "based on $P(x,y)$" and discriminative means "based on $P(y|x)$," but I'm confused on several points:

Wikipedia (+ many other hits on the web) classify things like SVMs and decision trees as being discriminative. But these don't even have probabilistic interpretations. What does discriminative mean here? Has discriminative just come to mean anything that isn't generative?
Naive Bayes (NB) is generative because it captures $P(x|y)$ and $P(y)$, and thus you have $P(x,y)$ (as well as $P(y|x)$). Isn't it trivial to make, say, logistic regression (the poster boy of discriminative models) "generative" by simply computing $P(x)$ in a similar fashion (same independence assumption as NB, such that $P(x) = P(x_0) P(x_1) ... P(x_d)$, where the MLE for $P(x_i)$ are just frequencies)?
I know that discriminative models tend to outperform generative ones. What's the practical use of working with generative models? Being able to generate/simulate data is cited, but when does this come up? I personally only have experience with regression, classification, collab. filtering over structured data, so are the uses irrelevant to me here? The "missing data" argument ($P(x_i|y)$ for missing $x_i$) seems to only give you an edge with training data (when you actually know $y$ and don't need to marginalize over $P(y)$ to get the relatively dumb $P(x_i)$ which you could've estimated directly anyway), and even then imputation is much more flexible (can predict based not just on $y$ but other $x_i$'s as well).
What's with the completely contradictory quotes from Wikipedia? "generative models are typically more flexible than discriminative models in expressing dependencies in complex learning tasks" vs. "discriminative models can generally express more complex relationships between the observed and target variables"

Related question that got me thinking about this.
Comment: (+1) I think the terminology is confusing, and I think of a model of $P(y|x)$ as being generative for the conditional distribution in contrast to SVM, say, that only models aspects of this conditional distribution for a purely discriminative purpose. As your second bullet point shows, a model of $P(y|x)$ can be augmented to become a fully generative model. The distinction is relevant from a learning point of view because we can either model $P(x,y)$ and compute $P(y|x)$ or we can model $P(y|x)$.
Comment: I don't think that your statement about SVMs is true: "But these don't even have probabilistic interpretations." Anything with a loss function can clearly be interpreted in a probabilistic sense by finding the MAP configuration of a suitable PDF.
Answer: The fundamental difference between discriminative models and generative models is:

Discriminative models learn the (hard or soft) boundary between classes
Generative models model the distribution of individual classes

To answer your direct questions:

SVMs (Support Vector Machines) and DTs (Decision Trees) are discriminative because they learn explicit boundaries between classes.  SVM is a maximal margin classifier, meaning that it learns a decision boundary that maximizes the distance between samples of the two classes, given a kernel.  The distance between a sample and the learned decision boundary can be used to make the SVM a "soft" classifier.  DTs learn the decision boundary by recursively partitioning the space in a manner that maximizes the information gain (or another criterion).

It is possible to make a generative form of logistic regression in this manner.  Note that you are not using the full generative model to make classification decisions, though.

There are a number of advantages generative models may offer, depending on the application.  Say you are dealing with non-stationary distributions, where the online test data may be generated by different underlying distributions than the training data.  It is typically more straightforward to detect distribution changes and update a generative model accordingly than do this for a decision boundary in an SVM, especially if the online updates need to be unsupervised.  Discriminative models also do not generally function for outlier detection, though generative models generally do.  What's best for a specific application should, of course, be evaluated based on the application.

(This quote is convoluted, but this is what I think it's trying to say) Generative models are typically specified as probabilistic graphical models, which offer rich representations of the independence relations in the dataset.  Discriminative models do not offer such clear representations of relations between features and classes in the dataset.  Instead of using resources to fully model each class, they focus on richly modeling the boundary between classes.  Given the same amount of capacity (say, bits in a computer program executing the model), a discriminative model thus may yield more complex representations of this boundary than a generative model.
Comment: A trivial comment: $\binom{k}{2}$ boundaries between $k$ clusters get harder and harder to plot / understand / measure as $k$ increases. Thus e.g. k-clustering, viewed as a discriminative model, gets noisier and ad hoc. (Example: compare politics in 2-party systems vs. 5-party in Germany).
Comment: I've seen the terms, generative and discriminative models, used in contexts outside of classification models, for example, Fb's Prophet library, which is for time series modeling. Decision boundaries aren't applicable in the regression world, as far as I can imagine. Any thoughts?
Answer: (hamner's answer is great, so just cross-posting my answer from MetaOptimize for completeness.)
I think of generative algorithms as providing a model of how the data is actually generated (I think of them as giving you a model of both $P(X|Y)$ and $P(Y)$, rather than of $P(X, Y)$, though I guess it's equivalent), and discriminative algorithms as simply providing classification splits (and not necessarily in a probabilistic manner).
Compare, for instance, Gaussian mixture models and k-mean clustering. In the former, we have a nice probabilistic model for how points are generated (pick a component with some probability, and then emit a point by sampling from the component's Gaussian distribution), but there's nothing we can really say about the latter.
Note that generative algorithms have discriminative properties, since you can get $P(Y|X)$ once you have $P(X|Y)$ and $P(Y)$ (by Bayes' Theorem), though discriminative algorithms don't really have generative properties.
1: Discriminative algorithms allow you to classify points, without providing a model of how the points are actually generated. So these could be either:

probabilistic algorithms try to learn $P(Y|X)$ (e.g., logistic regression);
or non-probabilistic algorithms that try to learn the mappings directly from the points to the classes (e.g., perceptron and SVMs simply give you a separating hyperplane, but no model of generating new points).

So yes, discriminative classifiers are any classifiers that aren't generative.
Another way of thinking about this is that generative algorithms make some kind of structure assumptions on your model, but discriminative algorithms make fewer assumptions. For example, Naive Bayes assumes conditional independence of your features, while logistic regression (the discriminative "counterpart" of Naive Bayes) does not.
2: Yes, Naive Bayes is generative because it captures $P(X|Y)$ and $P(Y)$. For example, if we know that $P(Y = English) = 0.7$ and $P(Y = French) = 0.3$, along with English and French word probabilities, then we can now generate a new document by first choosing the language of the document (English with probability 0.7, French with probability 0.3), and then generating words according to the chosen language's word probabilities.
Yes, I guess you could make logistic regression generative in that fashion, but it's only because you're adding something to logistic regression that's not already there. That is, when you're performing a Naive Bayes classification, you're directly computing $P(Y|X) \propto P(X|Y) P(Y)$ (the terms on the right, $P(X|Y)$ and $P(Y)$, are what allow you to generate a new document); but when you're computing $P(Y|X)$ in logistic regression, you're not computing these two things, you're just applying a logistic function to a dot product.
3: Generative models often outperform discriminative models on smaller datasets because their generative assumptions place some structure on your model that prevent overfitting. For example, let's consider Naive Bayes vs. Logistic Regression. The Naive Bayes assumption is of course rarely satisfied, so logistic regression will tend to outperform Naive Bayes as your dataset grows (since it can capture dependencies that Naive Bayes can't). But when you only have a small data set, logistic regression might pick up on spurious patterns that don't really exist, so the Naive Bayes acts as a kind of regularizer on your model that prevents overfitting. There's a paper by Andrew Ng and Michael Jordan on discriminative vs. generative classifiers that talks about this more.
4: I think what it means is that generative models can actually learn the underlying structure of the data if you specify your model correctly and the model actually holds, but discriminative models can outperform in case your generative assumptions are not satisfied (since discriminative algorithms are less tied to a particular structure, and the real world is messy and assumptions are rarely perfectly satisfied anyways). (I'd probably just ignore these quotes if they're confusing.)
Comment: Is there any reason for calling Logistic Regression a counterpart of Naive Bayes besides the two being well-known representatives of the respective types of models? (just curious)
Answer: As an additional point to the above answers, when the aim of algorithm is only to classify, then discriminative approach may be better and less expensive than generative approach, as following the generative approach to model input distribution can result in requiring too much training data to model complexities in distribution which are unimportant for computing the posteriors required for decision making.

Generative vs. discriminative


R - generate deviate using probability based on known occurrence of event

Question: In R, I want to simulate an event using a probability $p$ based on a known occurrence $k$ of the event.
If I have a population of $n = 100$ individuals in a given area, and I know over a period of time $t$ (e.g. 365-days) that 5 of these individuals will move away from that area, what is the best way to simulate this?
Each day, for each individual, a binomial deviate is drawn indicating whether or not the individual will move on that day. An individual can only move away from the area once, and once moved cannot move back - therefore, the population will decrease over time. At the end of the time period (e.g. 365-days), there should be approximately 95 individuals remaining.
At first, I thought the daily probability* of an event such as this should be derived as $ p = 1 - (1 - \frac{k}{n})^{1/t} $, where $k = 5, n = 100, t = 365$, and simulated in R using a binomial draw rbinom() with $p$ probability. But I'm not sure that this is best way and would appreciate some guidance.
Edit
*unconditional probability - as clarified by @whuber
Comment: It's not clear if you want the number of individuals moving to be exactly 5 or not. If you do want exactly 5, then couldn't you just choose 5 randomly and then randomize their move times however you want?
Comment: @soakley no, it should be probability-based, so at the end of the time period, approximately 95 individuals remain
Comment: I would still divide the processes. Simulate 100 realizations from a Bernoulli random variable with success probability 0.05 - that gives you who moves away and will average 5 people. Then, if you need a time when they move away (I don't know if you need that or not), you can simulate that for those that have been selected as movers.
Answer: Assume the actions of these individuals are independent.  (If you don't, you need to specify--mathematically--how they are interdependent.)
Assume that the chance any individual leaves during any time period does not change over time.  (This can be modified, but then you will have to specify how these chances vary over time.)
These assumptions imply that the time $T_i$ when individual $i$ leaves is a random variable with an exponential distribution.  You can make progress towards a solution by supposing every individual has the same propensity to leave: that is, the rate parameters of these exponential distributions are all the same.  (If you don't want to assume that, you must make some assumption about the distribution of rate parameters in the population.)  Let this common rate be $\kappa.$
These assumptions imply that when there are $n$ people, the time until the next person leaves (the smallest of the $T_i$) has an exponential distribution with rate $n\kappa.$  Its expectation is $1/(n\kappa).$  After that $n-1$ people remain, so the time until the second person leaves has an exponential distribution with rate $(n-1)\kappa.$  And so on.  Consequently, the distribution of the time taken until the fifth person leaves is the sum of (independent) exponential distributions of rates $n\kappa,$ $(n-1)\kappa,$ and on on down to $(n-4)\kappa.$
The expectation of the sum is the sum of the expectations of the terms, equal to
$$\mu = \frac{1}{n\kappa} + \frac{1}{(n-1)\kappa} + \cdots + \frac{1}{(n-4)\kappa}.$$
Solving for $\kappa$ gives
$$\kappa = \frac{H(n) - H(n-5)}{\mu}$$
where $H(n)$ is the Harmonic Number.
In your problem you stipulate $\mu=5$ people per year and $n=100.$ The corresponding value of $\kappa$ is $0.01020621.$
In general (depending on $n$ and $\mu$) two simulation approaches look feasible.  One is to simulate the sequence of exponential variates and add them.  The other is to compute the distribution once and for all.  According to the solution at https://stats.stackexchange.com/a/72486/919, the distribution (of the time until the fifth person leaves) is a mixture of exponential distributions.  This isn't any simpler or more efficient to compute, so let's go with the first method.
In R, for instance, the time until d people out of n will leave can be simulated in two lines: one to compute $\kappa$ and the other to generate the exponential variates and sum them:
kappa <- sum(1/seq(n, n-d+1, by=-1))
x <- colSums(matrix(rexp(1e6 * d, rate=seq(n, n-d+1, by=-1)*kappa), d))

(The cumulative column sums in this matrix would indicate the specific times at which the first, second, ..., through the $d^\text{th}$ person leaves.)
This example generates a dataset of 1e6 values.  Here is their histogram:
hist(x, freq=FALSE, breaks=200, xlim=c(0, 3.5), border="Gray",
     main=paste("Histogram of Time for", d, "People to Leave"))

The red curve was computed using the partial fractions formula previously quoted.  Clearly it agrees with the simulation, confirming the correctness of both approaches.
Comment: Thanks for the detailed answer. Is it not possible to estimate a daily probability of moving for each individual then? Maybe I've misunderstood, but it seems like your method estimates the time when `d` individuals move, not the probability that any individual will move on a given day
Comment: This analysis produces the answers to all such questions of probabilities.  Indeed, at the outset it states the probability per day in terms of the rate, which is a function of how many people are left.  There is no estimation involved: given your assumptions, the calculations are exact.  Now, some questions do require a calculation based on this formulation.  For instance, if you want to compute an *unconditional* probability per day, then you will need to compute that integral. But as far as I can tell, that's not what you asked: your question asks about *simulation.*
Comment: Thanks for clarifying. It is an unconditional probability per day that I'm after. Could you expand your response to include this?


How to create a custom payment page attached to a user account's form

Question: I am on Drupal 7 and I am building an ads website in which people can buy credits via their account form. I am not using Commerce or Ubercart for very complex reasons that would be a bit long to explain.
So lets move forward.
Users will use the credit that they buy to make payable actions on their content, such as making a content sticky.
1. What I already did :
Now a user who is connected to his account can select the number of credits to add to his balance. And the balance will be added that amount of credits.
And all the payable action on the ads decrease the balance of the concerned user.
So to say that the system works fine.
2. What I need to do now :
I set up field to let the user choose the type of payment his wants : PayPal or Credit Card.

How can I create a payment page without programming ?
How can I make people really see a payment page ?
How can I make that payment page appear before the users saves the
account forms ?

These are the things that I really need to know.
Anybody know how to ?
Answer: I think that this site will tell you what to do:
Setting up payment methods
You shall download one of the modules to get a list of services.
Comment: I am studying carefully from your answer @Jonathan Dalgaard.
Comment: Thanks I really hope that you will find a quick solution.
Comment: I think that you shall download the payment module.
Answer: First of all I advice you the two modules its very helpful and I used the before to achieve similar scenario as you asked.
1- commerce node checkout:
allow you to charge users to create nodes. It is possible to have multiple different product offerings for each node type, so the user can pick the product they want to purchase when creating the node. An example use-case would be a classifieds site that charges people to post listings
2- commerce account balance:
enables a -per user- account balance to which you can deposit money and which you can use for purchasing things on your website.
You could use any payment method like paypal to charge balance.
I think both two modules will do most of the job for you, if you don't need to use commerce which is required by the two modules try to patch them and customize or even get the main ideas and build your own solution.
Edit: payment forms may help if none of the above fits your needs.
Comment: I am studying carefully from your answer @Mohammed Gomma.
Comment: If the answer helps you, then up vote and accept.


Sencha Touch 2 Panel w/ Template include Data and an Object

Question: I'm wondering if it's possible to include both data and make a new object in a template in Sencha Touch 2?
I have the following code:
Ext.define('MyApp.view.VideosDetail', {
extend: 'Ext.Panel',
xtype: 'videosdetail',

config: {
    title: 'Details',
    styleHtmlContent: true,
    scrollable: 'vertical',
    tpl: [
        '{content}',
        {
            xtype: 'video',
            width: 400,
            height: 400,
            url: '{link}'
        }
    ]
}
});

I see [object Object] instead of a video object with the link url.
The {content} works correctly via a store and such.
Answer: Ok, two things you have to remember

You cannot use a complicated object inside of the tpl in the manner you just did. In Sencha Touch, adding a "," followed by a "{ . . . }" after the tpl strings implies adding member functions or configurations to your XTemplate. In this case, ST misunderstood your object to be a member function of sorts, and didn't display anything since you didnt call any function.

Example of member functions ::
var tpl = new Ext.XTemplate(
'
Name: {name}
',
'
Kids: ',
'<tpl for="kids">',
    '<tpl if="this.isGirl(name)">',
        '
Girl: {name} - {age}
',
    '<tpl else>',
        '
Boy: {name} - {age}
',
    '</tpl>',
    '<tpl if="this.isBaby(age)">',
        '
{name} is a baby!
',
    '</tpl>',
'</tpl>
',
{
    // XTemplate configuration:
    disableFormats: true,
    // member functions:
    isGirl: function(name){
       return name == 'Sara Grace';
    },
    isBaby: function(age){
       return age < 1;
    }
}
);

If you have a complex tpl object, always try to create a separate XTemplate object instead, that will make your code simple and beautiful (ie easy to read)
I have done something similar and added videos to my XTemplate before. But I haven't used the video object. Instead, my tpl that I created looks as follows ::

In my scenario, the url of my video was composed of two parts, vurl1 was something common like "www.youtube.com/watch?" and the vcode1 was the dynamic code that followed.


How to show a number is irrational with this approach?

Question: I read on MathOverflow the following:
"The number of proofs that we have of showing some numbers are irrational are very limited. We either show a number $α$ is irrational because it is algebraic of degree greater than one (by exhibiting an irreducible polynomial $f$ of degree greater than one $f(α)=0$)."
An algebraic number is a number that is a root for a polynomial with integers coefficients. What is an algebraic number of degree greater than one?
How do we show an "irreducible polynomial $f$ of degree greater than one $f(α)=0$" (a non-constant polynomial such that $\alpha$ is a root for it?)
Is there some literature that show that some number is irrational with this approach? Maybe a link on the internet or a book that show exactly this?
Comment: For example, let $f(x)=x^2-2$ then $f$ is an irreducible polynomial of degree greater than one and $f(\pm\sqrt{2})=0$ hence $\pm\sqrt{2}$ are irrational numbers.
Comment: I thought that the definition of an algebraic number was any number that  *is* a root of a polynomial with integer coefficients.   Why did you write "can't be?"
Comment: @MichaelTuchman I've fixed. Thanks!
Comment: Normally, I'm not such a nitpicker, but in this case the entire meaning was changed to its opposite.
Answer: An algebraic number is a number that is a root of a polynomial with integer coefficients (and not all coefficients $0$).
If it is a root of such a polynomial that has degree $d$ and is irreducible over the rationals, then it can't be the root of any polynomial with integer coefficients (not all $0$) and degree less than $d$.  This is because if $z$ is a root of two polynomials $f$ and $g$, then it is a root of $\gcd(f,g)$, which is a polynomial that divides both $f$ and $g$.
In that case we say the number is algebraic of degree $d$.
In particular, $z$ is rational if and only if it is the root of a polynomial of degree $1$ with integer coefficients (namely $z = a/b$ is a root of $b z - a$).
So if it is algebraic of degree $>1$, it can't be rational.
Answer: When you say a number $z$ is algebraic, all you know is that there is some polynomial $P$ with rational coefficients such that $P(z)=0$. The notion of "degree" tells you more: An algebraic number of degree $d$ is an algebraic number such that there is some polynomial of degree $d$ such that $P(z)=0$ and no polynomial of lesser degree having $z$ as a root. This polynomial $P$ is called the minimal polynomial and has the property that if $Q(z)=0$ then $P$ divides $Q$ evenly.
"Algebraic of degree one" therefore means that $z$ satisfies $az+b=0$ for some rational $a,b$ or, otherwise put, $z=-b/a$. This is synonymous with the statement that $z$ is rational.
"Algebraic of degree two" turns out to mean - if you examine the quadratic formula - that the number is of the form $a\pm \sqrt{b}$ where $a,b$ are rational and $b$ is not a perfect square. If you want to prove, for instance, that $\sqrt{2}$ is an algebraic of degree two, you first note that it is a root of $x^2-2$ and then, by whatever machinery you have, show that $x^2-2$ is not divisible by any polynomials of lesser degree - so must be the minimal polynomial of $\sqrt{2}$. While you could probably show that $x^2-2$ is irreducible without any special machinery, in general, it can be fairly difficult to decide if a polynomial is irreducible, though algorithms to do that do exist. Note that since all the rationals have degree one, this implies that $\sqrt{2}$ is irrational.
I don't think there's many references to this method of proof in particular, because it's usually taken as a corollary of the theory of field extensions - the comment you refer to is pointing out that algebraic numbers are quite well understood and once we can write a polynomial that a number satisfies, we can situate it inside of a well-developed theory to immediately see that it is irrational.


Is the Splitting Field necessarily a subset of a field where the polynomial splits?

Question: Just a very basic theoretical question that has been puzzling me.
Let $f(x)$ be a polynomial with coefficients in a field $F$. Let $K$ be the splitting field of $f$ over $F$.
Say $f$ splits in a field extension $L$ of $F$.
Can we conclude that $K\subseteq L$?
Intuitively, I know that $K$ is supposed to be the 'smallest' field over which $f$ splits. However, I am worried that there are some elements in $K$ that are not in $L$. Can that be the case?
Thanks for enlightenment!
Comment: We can say that $K$ is a isomorphic to a subfield of $L$, but that isomorphism is not usually unique.
Comment: @ThomasAndrews ... which is the reason Galois theory is a thing. It measures how many of these isomorphisms there are and how they relate to one another.
Answer: If $L_1$, $L_2$ are two extensions of $k$ such that $f$  splits in both $L_1$ and $L_2$, and if $K_i$ are the subfields of $L_i$ generated by the roots of $f$ in $L_i$, then there exist an isomorphisms taking $K_1$ to $K_2$ and fixing $k$. So any such $K$ can be called "the" splitting field of $f$.
$\bf{Added:}$ Inspired by  reading the exhaustive answer of @Thomas Andrews: I want to add here the following: if $k \subset L$ and $f$ splits completely in $L$, $K$ is the field generated by the roots, then $K$ is the unique subfield of $L$ that contains $k$ and is isomorphic to $L$ ( this follows from the uniqueness of the decomposition of a polynomial in linear factors). Therefore, if in an extension the polynomial splits completely, the splitting field "is in there", and is unique.
Answer: Let $p(x)\in F[x]$ be your polynomial.
if $K$ and $L$ are subfields of the same field, so $F\subseteq K,L\subseteq F_2$, then yes, $K$ is a subfield of $L$. This is true because the polynomial cannot have more than $\deg p$ roots, so all roots in $F_2$ have to be in $K$, and therefore $K$ must be in $L$. (You have to deal with repeated roots here, but it is not hard to fix that argument. The splitting field for $p$ is the same as the splitting field for a $q$ which does not have repeated roots.)
You might take $F_2=\overline{F},$ the algebraic closure of $F$, for example. Then given a field $L$ with $F\subseteq L\subseteq \overline{F}$ in which your polynomial splits, we know $L$ contains the splitting field.
However, depending on how splitting fields are defined, you might not have such an $F_2$. Then all you know is that $K$ is isomorphic to a subfield of $L$. The image of $K$ in $L$ is always the same, but the isomorphism is usually not unique.