Help with Mellin-Barnes Integral (product of two Hypergeometrics)

Question: I am trying to prove that
$$\int_0^1 \frac{dz}{z^2} z^{h}\cdot {}_{2}F_{1}(h,h;2h;z) \cdot {}_{2}F_{1}\left(\frac{1+2a}{2},\frac{1-2a}{2};1;\frac{z-1}{z}\right) = -\frac{\Gamma(2h)}{\Gamma{(h)}^2} \cdot \left(\frac{1}{a^2-(h-1/2)^2} \right).$$
To begin I first use Mellin-Barnes representation of Hypergeometric representation:
$$ {}_{2}F_{1}(a,b;c;z)=\frac{\Gamma(c)}{\Gamma(a)\Gamma(b)}\int_{-i\infty}^{i\infty}ds\frac{\Gamma(-s)\Gamma(a+s)\Gamma(b+s)}{\Gamma(c+s)}(-z)^s$$
The integral over the z variable is (done in Mathematica):
$$\int_0^1 \frac{z^h(-z)^s(1-z)^t}{z^2z^t}=(-1)^s\frac{\Gamma(-1+h+s-t)\Gamma(1+t)}{\Gamma(h+s)} $$
Plugging this back in I get,
$$\frac{\Gamma(2h)}{\Gamma(h)^2\Gamma(1/2+a)\Gamma(1/2-a)}\int\int ds dt \frac{\Gamma(-1+h+s-t)\Gamma(-s)\Gamma(h+s)\Gamma(-t)\Gamma(1/2+a+t)\Gamma(1/2-a+t)}{\Gamma(2h+s)}(-1)^s$$
where s and t are the Mellin-Barnes variables.
Then I use Barnes lemma to integrate over the t-variable to obtain:
$$\frac{\Gamma(2h)}{\Gamma(h)^2}\int_{-i\infty}^{i\infty}\frac{\Gamma(-s)\Gamma(-1/2+h+s+a)\Gamma(-1/2+h+s-a)}{\Gamma(2h+s)} \, ds$$
I dont see how I will get to the final result from here.
Any help appreciated.
Thanks
Answer: The hypergeometric function in contour form is
$${}_{2}F_{1}(a, b; c; x) = \frac{1}{2 \pi i} \, \int_{-i \infty}^{i \infty} \frac{\Gamma(-s) \Gamma(a+s) \Gamma(b+s)}{\Gamma(c + s)} \, ds.$$
The integral in question becomes:
\begin{align}
I &= \int_{0}^{1} {}_{2}F_{1}(p,p;2p;t) \cdot {}_{2}F_{1}\left(\frac{1+2a}{2},\frac{1-2a}{2};1;\frac{t-1}{t}\right) \, t^{p-2} \, dt \\
&= \left(\frac{1}{2 \pi i}\right)^2 \, \int \int \frac{\Gamma(-u) \Gamma^2(p+u)}{\Gamma(2p + u)}  \cdot \frac{\Gamma(-s) \Gamma(\frac{1}{2} + a + s) \Gamma(\frac{1}{2} - a + s)}{\Gamma(s + 1)} \, J \, du \, ds,
\end{align}
where
\begin{align}
J &=\int_{0}^{1} t^{p-2} \, (-t)^{u} \, \left(-1 + \frac{1}{t}\right)^{s} \, dt = (-i)^{u} \, B(s+1, p+u-s-1) \\
&= (-1)^{u} \, \frac{\Gamma(s+1) \Gamma(p+u-s-1)}{\Gamma(p+u)}.
\end{align}
Now, by use of Barnes' Lemma (first) given by
$$\frac{1}{2 \pi i} \, \int_{-i \infty}^{i \infty} \Gamma(a+s) \Gamma(b+s) \Gamma(c -s) \Gamma(d -s) \, ds = \frac{\Gamma(a+c) \Gamma(a+d) \Gamma(b+c) \Gamma(b+d)}{\Gamma(a+b+c+d)},$$
with $d = 0$, $c = p+u-1$, $a = 1/2 +a$ and $b = 1/2 -a$, then
$$ \frac{1}{2 \pi i} \, \int_{- i \infty}^{i \infty} \Gamma(-s) \Gamma(\frac{1}{2} + a + s) \Gamma(\frac{1}{2} - a + s) \Gamma(p+u-s-1) \, ds = \frac{\Gamma(a + \frac{1}{2}) \Gamma(p+a-\frac{1}{2} + u) \Gamma(p - a - \frac{1}{2} +u)}{\Gamma(p+u)} $$
and
\begin{align}
I &= \left(\frac{1}{2 \pi i}\right) \, \int \frac{(-1)^u \Gamma(-u) \Gamma(p+u)}{\Gamma(2p + u)} \, du  \\
& \hspace{5mm} \cdot \frac{1}{2 \pi i} \, \int_{- i \infty}^{i \infty} \Gamma(-s) \Gamma(\frac{1}{2} + a + s) \Gamma(\frac{1}{2} - a + s) \Gamma(p+u-s-1) \, ds \\
&= \frac{\Gamma(a + \frac{1}{2})}{2 \pi i} \, \int_{- i \infty}^{i \infty} \frac{\Gamma(-u) \Gamma(p-a-\frac{1}{2} + u) \Gamma(p +a-\frac{1}{2} +u)}{\Gamma(2 p + u)} \, (-1)^{u} \, du \\
&= \Gamma\left(a + \frac{1}{2}\right) \, {}_{2}F_{1}\left(p+a-\frac{1}{2}, p-a-\frac{1}{2}; 2p ; 1\right) \\
&= \frac{\Gamma(2p) \Gamma\left(a+\frac{1}{2}\right)}{\Gamma\left(p+a+\frac{1}{2}\right) \Gamma\left(p-a+\frac{1}{2}\right)}.
\end{align}
Answer: I just figured it out.
The last integral can be written in terms of 2F1 Hypergeometric using standard Mellin-Barnes integral.
And then I needed to use the Gauss Hypergeometric formula.
Yay!!


Problema na formatação do site

Question: Bom dia,
estou com um problema com o css do meu site ele apenas funciona a partir do Laptop até ao 4K, alguém me sabe dizer o porquê?

 /*Mobile S*/
@media only screen and (max-width: 320px) {
.content{
margin-left: 35%;
margin-top: 250%;
margin-right: 35%;
background: -webkit-linear-gradient(left, #666666, #333333);
padding-top: 5%;
border-radius:15px;
    height: 320;
}
}

/*Mobile M*/
@media only screen and (min-width:321px) and (max-width: 376px) {
.content{
margin-left: 35%;
margin-top: 128%;
margin-right: 35%;
background: -webkit-linear-gradient(left, #666666, #333333);
padding-top: 5%;
border-radius:15px;
    height: 320;
}
}

/*Mobile L*/
@media only screen and (min-width:377px) and (max-width: 426px) {
.content{
margin-left: 35%;
margin-top: 111%;
margin-right: 35%;
background: -webkit-linear-gradient(left, #666666, #333333);
padding-top: 5%;
border-radius:15px;
    height: 320;
}
}

/*Tablet*/
@media only screen and (min-width:427px) and (max-width: 768px) {
.content{
margin-left: 35%;
margin-top: 53%;
margin-right: 35%;
background: -webkit-linear-gradient(left, #666666, #333333);
padding-top: 5%;
border-radius:15px;
    height: 320;
}
}

/*Laptop*/
@media only screen and (min-width:769px) and (max-width: 1025px) {
.content{
margin-left: 35%;
margin-top: 36%;
margin-right: 35%;
background: -webkit-linear-gradient(left, #666666, #333333);
padding-top: 5%;
border-radius:15px;
    height: 320;
}
}

/* Laptop L*/
@media only screen and (min-width:1025px) and (max-width: 2559px) {
.content{
margin-left: 35%;
margin-top: 25%;
margin-right: 35%;
background: -webkit-linear-gradient(left, #666666, #333333);
padding-top: 5%;
border-radius:15px;
    height: 320;
}
}

/* 4K*/
@media only screen and (min-width:2560px) {
.content{
margin-left: 35%;
margin-top: 13%;
margin-right: 35%;
background: -webkit-linear-gradient(left, #666666, #333333);
padding-top: 5%;
border-radius:15px;
    height: 320;
}
}
Comment: Jovem suas regras de media queries parecem estar na ordem errada... tente começar com as regras de 4k e deixar por último as regras de mobile etc... Faça o teste e veja se da certo, se funcionar me fala que te dou uma resposta com mais detalhes
Comment: Antes de postar já tinha feito isso e não resultou.
Answer: Já consegui resolver!! Vou postar o código para quem precisar. No meu caso bastou colocar device na query.

/* 4K*/
@media only screen and (min-device-width:2560px) {
 .content{
 margin-left: 35%;
    margin-top: 13%;
    margin-right: 35%;
    background: -webkit-linear-gradient(left, #666666, #333333);
    padding-top: 5%;
 border-radius:15px;
     height: 320;
}
}

/* Laptop L*/
@media only screen and (min-device-width:1025px) and (max-device-width: 2559px) {
 .content{
 margin-left: 35%;
    margin-top: 25%;
    margin-right: 35%;
    background: -webkit-linear-gradient(left, #666666, #333333);
    padding-top: 5%;
 border-radius:15px;
     height: 320;
}
}

/*Laptop*/
@media only screen and (max-device-width: 1025px) and (min-device-width: 769px){
 .content{
 margin-left: 35%;
    margin-top: 36%;
    margin-right: 35%;
    background: -webkit-linear-gradient(left, #666666, #333333);
    padding-top: 5%;
 border-radius:15px;
     height: 320;
}
}

/*Tablet*/
@media only screen and (min-device-width:427px) and (max-device-width: 768px) {
 .content{
 margin-left: 35%;
    margin-top: 53%;
    margin-right: 35%;
    background: -webkit-linear-gradient(left, #666666, #333333);
    padding-top: 5%;
 border-radius:15px;
     height: 320;
}
}

/*Mobile L*/
@media only screen and (min-device-width:377px) and (max-device-width: 426px) {
 .content{
 margin-left: 35%;
    margin-top: 111%;
    margin-right: 35%;
    background: -webkit-linear-gradient(left, #666666, #333333);
    padding-top: 5%;
 border-radius:15px;
     height: 320;
}
}

/*Mobile M*/
@media only screen and (min-device-width:321px) and (max-device-width: 376px) {
 .content{
 margin-left: 35%;
    margin-top: 128%;
    margin-right: 35%;
    background: -webkit-linear-gradient(left, #666666, #333333);
    padding-top: 5%;
 border-radius:15px;
     height: 320;
}
}

/*Mobile S*/
@media only screen and (max-device-width: 320px) {
 .content{
 margin-left: 35%;
    margin-top: 90%;
    margin-right: 35%;
    background: -webkit-linear-gradient(left, #666666, #333333);
    padding-top: 5%;
 border-radius:15px;
     height: 320;
}
}
Comment: Cara por der resolvido, mas cuidado com isso, pq quando vc fala `device` é a largura da tela do dispositivo, não a largura da janela... faça testes para garantir que nada esta buggando... https://pt.stackoverflow.com/questions/140997/qual-%C3%A9-a-diferen%C3%A7a-entre-max-width-e-max-device-width

Problema na formatação do site


ReadDocumentAsync always fails claiming Id does not exist

Question: I am querying Azure DocumentDb (cosmos) for a document that is present in the container:
try{
   doc = await client.ReadDocumentAsync(
   GetDocumentUri("tenantString-campaignId"),
       new RequestOptions
       {
          PartitionKey = new PartitionKey(tenantString)
       });
   }
   catch(Exception e)
   {
       Console.WriteLine(e);
   }

 for this document:

tenantString-campaignId is the id you can see here and tenantString alone is the partition key this is under. The tenant itself was passed in as a string and I had that working but now I have changed to passing a Tenant object and parsing the string required from it I am not returning the document.
I have tried a few different variations of tenantString and id and I can generate either a DocumentClientException, Id does not exist, Exception or it fails silently; no exception and returns to the calling method where it causes a NullReferenceException as no document is returned.
As far as I can make out from debugging through this I am constructing all my data correctly and yet no document is returned. Does anyone have any idea what I can try next?
Comment: I'm not quite sure I understand your code: what is `GetDocumentUri()` doing? Is that something you've written? I can't find that method in the SDK.
Comment: Also, please edit your question to contain formatted text for your sample document, instead of an image. Please see [this meta post](https://meta.stackoverflow.com/a/285557/272109) for the many reasons why this is really important.
Comment: One thing you could try to do is trace the request/response through Fiddler and see what's being sent over the wire.
Comment: Does GetDocumentUri use UriFactory.CreateDocumentUri using the correct database and collection names, and the id?
Comment: Sorry all I have been creating the url incorrectly. Not from the db/collection point of view but passing the wrong combination for the id of the record. That is the getdocumenturi call, which is correct I was just passing the wrong thing to it. Thanks all for giving your time to look at this for me but in the end it was just a silly mistake on my part.
Answer: This syntax for the .NET SDK v2 is not correct. ReadDocumentAsync() should look like this.
var response = await client.ReadDocumentAsync(
    UriFactory.CreateDocumentUri(databaseName, collectionName, "SalesOrder1"),
    new RequestOptions { PartitionKey = new PartitionKey("Account1") });

You can see more v2 samples here


Apache Permission issue

Question: How do I resolve an issue of permissions in apache. The initial task that I am trying to get working is to upload a mura plugin the the temp directory of ColdFusion9. However, I have since discovered that this issue isn't a ColdFusion issue.
ColdFusion is running as the apache user:
<code># ps aux | grep coldfusion
apache   31016  0.0  0.0   2104   664 ?    S    Oct27   0:00 /opt/coldfusion9 ...
apache   31017  0.7 24.5 933260 513976 ?   Sl   Oct27  18:02 /opt/coldfusion9 ...
</code>
Apache has access to the directory that I'm attempting to write to:
<code># namei -m /opt/coldfusion9/runtime/servers/coldfusion/SERVER-INF/temp/wwwroot-tmp/
f: /opt/coldfusion9/runtime/servers/coldfusion/SERVER-INF/temp/wwwroot-tmp/
 drwxr-xr-x /
 drwxr-xr-x opt
 drwxrwxrwx coldfusion9
 drwxrwxr-x runtime
 drwxrwxr-x servers
 drwxr-xr-x coldfusion
 drwxr-xr-x SERVER-INF
 drwxr-xr-x temp
 drwxr-xr-x wwwroot-tmp

# ls -la /opt/coldfusion9/runtime/servers/coldfusion/SERVER-INF/temp/wwwroot-tmp/
total 8
drwxr-xr-x 2 apache apache 4096 Oct 28 15:46 .
drwxr-xr-x 3 apache root   4096 Oct 27 21:33 ..
</code>
There are no extended attributes assigned to the directory:
<code>#lsattr /opt/coldfusion9/runtime/servers/coldfusion/SERVER-INF/temp/wwwroot-tmp/
------------- /opt/coldfusion9/runtime/servers/coldfusion/SERVER-INF/temp/wwwroot-tmp/afile
</code>
I changed the shell (temporarily) of the apache user to bash, logged into the shell and was able to write to the directory.
Selinux is disabled.
fixweb has been run.
I created two scripts, tmp.cfm and tmp.php, which simply attempted to write a file in the target directory, browsed to the tmp scripts in the browser and both were unable to write to the directory.
I also created an alias to the directory in apache:
<code>Alias /atemp /target-dir
<Location /atemp>
Order allow,deny
Allow from all
</Location>
</code>
Restarted apache and was still unable to get access to this directory.
I've seen a similar permission issue when working with Wordpress.
I suspect that this is something to do with my apache binary but I haven't heard back from the providers of that binary, so I was hoping to get some assistance from a larger audience.

Edit: I'd be open to other possible problems that would cause this that I haven't considered.
Comment: Do you have any  (or a parent directory thereof) that might be granting or removing access?
Comment: No. Double checked to make sure.
Answer: Turns out it was an Adobe ColdFusion 9 issue after all.

Apache Permission issue


TabLayout embaixo da actionbar

Question: Vou usar um tablouyt mas ela fica embaixo da action bar, como resolver isso?
Xml da tela
<?xml version="1.0" encoding="utf-8"?>

<android.support.design.widget.TabLayout
    android:id="@+id/tab_Solicitacao"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    app:layout_constraintBottom_toTopOf="@+id/pgr_Solicitacao"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

</android.support.design.widget.TabLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/pgr_Solicitacao"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/tab_Solicitacao" />

Answer: Aparentemente você esta usando um ConstraintLayout mas o problema é que você esta colocando todas as constraint do topo do layout como parent.
Solução
Primeiro é recomendável que você use um estilo base sem Action bar como Theme.AppCompat.Light.NoActionBar depois adicione uma toolbar da biblioteca de suporte v7 e em seguida ajuste suas constraints. Em seguida torne a constraint do topo do tablayout como bottom da toolbar, então este devera ser o resultado:
demo.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.Toolbar
        android:id="@+id/tb1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <android.support.design.widget.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tb1">

        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Left" />

        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Center" />

        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Right" />
    </android.support.design.widget.TabLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/vp"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tabLayout" />

</android.support.constraint.ConstraintLayout>

Resultado
Comment: Não posso tirar a action bar de todo projeto só por causa dessa tela.
Comment: então faça o mesmo procedimento acima, porém sem a toolbar v7
Comment: ficou do mesmo jeito
Comment: Poderia mandar o xml do seu layout completo?
Comment: está completo, só tem a definição do constraint layout em cima disso.
Answer: Antes, você tem que definir o tipo de layout em que esses elementos estarão inseridos. Tente colocar eles dentro de um RelativeLayout e indique para o ViewPager que ele deve ficar por baixo do TabLayout usando android:below="@+id/tab_solicitacao" como poderás ver no código abaixo.
Isso sairia mais ou menos assim:
<?xml version="1.0" encoding="utf-8"?>

**<RelativeLayout
     android:layout_height="match_parent"
      android:layout_width="match_parent" >**

    <android.support.design.widget.TabLayout
        android:id="@+id/tab_Solicitacao"
        android:below="@+id/tab_solicitacao"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toTopOf="@+id/pgr_Solicitacao"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
       app:layout_constraintTop_toTopOf="parent">

    </android.support.design.widget.TabLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/pgr_Solicitacao"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
       app:layout_constraintTop_toBottomOf="@+id/tab_Solicitacao" />

**</RelativeLayout>**

Comment: O problema não é o layout, o problema é que ele esta usando o tablayout como top parent do layout e não da toolbar

TabLayout embaixo da actionbar


Changing library path with hook_library_info_alter

Question: I am having difficulties to change the library path defined by another module in *.libraries.yml via hook_library_info_alter
Essentially I have one module defining a library component in its *.libraries.yml like that:
<code># Font Awesome
fontawesome:
  version: 4.7.0
  css:
    component:
      /libraries/fontawesome/css/font-awesome.min.css: {minified: true }
</code>
How has my hook to look like to change to path to:

/libraries/fontawesome/web-fonts-with-css/font-awesome.min.css

Thanks for helping me!
Answer: I pushed my patch for social icons module to add dynamic font awesome css here
https://www.drupal.org/project/social_icons/issues/2984954
This is helpful to you.
<code>if (isset($libraries['font-awesome'])) {
     $library_key = key($libraries['font-awesome']['css']['theme']);
     $library_array = $libraries['font-awesome']['css']['theme'][$library_key];
     unset($libraries['font-awesome']['css']['theme'][$library_key]);
     $libraries['font-awesome']['css']['theme'][$font_awesome_url] = $library_array;
}
</code>


Replace the end of a File Name (SRC)

Question: i'm having a bit of a problem here. I found this script on the web, and changed it around a bit for my needs.
This script shows a preview of the image following the mouse onmouseover.
Originally, there was only one way of doing this. But i have 2 different sections on my website in which i want to display images with different attributes (height, width).
I was able to do that, the problem is that on the second section, the src (file name) is a thumbnail of the actual picture i want to display, so when it dows, it just blows up a very small picture, which looks very bad. But hopefully, this will make things easier: all the thumbnails are named whaterver_small.jpg and the originals, whatever.jpg Now, if i could remove _small or _small.jpg and replace with .jpg from the end of that file, that would display the original picture for me, which would be great. This is how the funcion is called on html:
Original size, no need changing:

Show image2, the one i'm having problems with.

This is the script
    var floatWidth = 150;  // set the width of the floating image
    var floatHeight = 100;  // set its height
    var floatWidth2 = 320;  // set the width of the floating image
    var floatHeight2 = 240;  // set its height

    var midWindow = 0;
    var nContainer = "";
    var IE = false;

    if (navigator.appName == 'Microsoft Internet Explorer'){IE = true}

    function stayHome(m){

            if (IE)
                    {
                    var currX = event.clientX;
                    var currY = event.clientY;
                    }
            else        {
                    var currX = m.pageX;
                    var currY = m.pageY;
                    }
            if (document.documentElement && document.documentElement.scrollLeft || document.documentElement && document.documentElement.scrollTop)
                    {
                    var iL = document.documentElement.scrollLeft;
                    var iV = document.documentElement.scrollTop;
                    }
            else        {
                    var iL = document.body.scrollLeft;
                    var iV = document.body.scrollTop;
                    }
            if (currX > midWindow+80)
                    {
                    var msgWidth = nContainer.clientWidth;
                    if (IE){nContainer.style.left = (currX-msgWidth-10+iL)+'px'}
                    else {nContainer.style.left = (currX-msgWidth-10)+'px'}
                    }
            else        {
                    if (IE){nContainer.style.left = (currX+15+iL)+'px'}
                    else {nContainer.style.left = (currX+15)+'px'}
                    }
            if (IE){nContainer.style.top = (currY+iV-(floatHeight/2)+70)+'px'}
            else {nContainer.style.top = (currY-(floatHeight/2)+70)+'px'}
    }

    function hideImage(){

            while (nContainer.lastChild)
                    {nContainer.removeChild(nContainer.lastChild)}
            document.getElementById('isFloat').style.display = 'none';
    }

    function showImage(isImg,currItem,currCaption){

            document.getElementById('isFloat').style.display = 'inline';
            nIMG  = document.createElement('img');
            nContainer.appendChild(nIMG);
            nIMG.setAttribute('src',isImg);
            nIMG.setAttribute('width',floatWidth);
            nIMG.setAttribute('height',floatHeight);
            nCaption = document.createElement('div');
            nCaption.style.textAlign = "center";
            nCaption.style.backgroundColor = '#EAE3C6';
            nCaption.style.padding = '5px';
            nCaption.style.color = '#000000';
            nCaption.style.fontFamily = 'Sans-serif';
            nCaption.style.fontSize = '10pt';
            nCaption.style.borderTop = "1px solid black";
            nContainer.appendChild(nCaption);
            nCaption.innerHTML = currCaption;
            currItem.onmouseout=hideImage;
    }

    function showImage2(isImg,currItem,currCaption){

            document.getElementById('isFloat').style.display = 'inline';
            nIMG  = document.createElement('img');
            nContainer.appendChild(nIMG);
            nIMG.setAttribute('src',isImg);
            nIMG.setAttribute('width',floatWidth2);
            nIMG.setAttribute('height',floatHeight2);
            nCaption = document.createElement('div');
            nCaption.style.textAlign = "center";
            nCaption.style.backgroundColor = '#EAE3C6';
            nCaption.style.padding = '5px';
            nCaption.style.color = '#000000';
            nCaption.style.fontFamily = 'Sans-serif';
            nCaption.style.fontSize = '10pt';
            nCaption.style.borderTop = "1px solid black";
            nContainer.appendChild(nCaption);
            nCaption.innerHTML = currCaption;
            currItem.onmouseout=hideImage;
    }

    function getMidWindow(){

            if (document.documentElement && document.documentElement.scrollLeft || document.documentElement && document.documentElement.scrollTop)
                    {
                    midWindow = document.documentElement.clientWidth/2;
                    }
            else        {
                    midWindow = document.body.clientWidth/2;
                    }
    }

    function initFloatImg(){

            var nBody = document.getElementsByTagName('body')[0];
            var nDiv = document.createElement('div');
            nDiv.id = "isFloat";
            nDiv.style.position = "absolute";
            nDiv.style.top = "0px";
            nDiv.style.left = "0px";
            nDiv.style.border = "1px solid black";
            nDiv.style.padding = "5px";
            nDiv.style.backgroundColor = "#ffffff"
            nBody.appendChild(nDiv);
            nContainer = document.getElementById('isFloat');
            document.onmousemove = stayHome;
            hideImage();
            if (!IE){document.captureEvents(Event.mousemove)}
            getMidWindow();
    }

    onload=initFloatImg;
    onresize=getMidWindow;

Update:
Ok, so i updated the script in this page, and it works perfectly now.
I ran into another problem, when the picture that has the mouse over, is near the end of the page, the preview is cutoff. I'd like to be able to move the preview up, so there's no scroll bar.
Here's a live example of a functional one: http://www.soccer.com/Navigation.process?Ne=178&N=4294960224+346
Where the picture is never cutoff.
Comment: This script looking like it was lifted from a page in the 1990s. You're far better off looking at jQuery as part of the solution. You could do this in a few lines of code.
Comment: i'd love that, but i'm incredibly newbie when it comes to jquery
Comment: Time to take the leap. Writing separate code blocks for IE is madness.
Comment: Agreed. I got that code online, does the job, but you right, i should get into jquery. I'm trying. =]
Answer: This will remove all _small matches from all of your image sources, if I'm understanding what you want correctly:
$("img").each(function() {
    $(this).attr("src", $(this).attr("src").replace("/_small(?=\.)/", ""));
});

Comment: One suggestion: use `replace` the regex `/_small(?=\.)/` with a lookahead for a period at the end, so it only replaces when `_small` when it comes right before the extension.
Comment: No problem. If this answer was helpful to you, would you mind accepting and possibly upvoting it as well? (via the check-mark and up arrow directly to the left of my answer) Thanks! :)
Comment: as soon as i can, my "reputation" is too low still haha
Answer: Replace following line in the showImage2 function
nIMG.setAttribute('src',isImg);

with
nIMG.setAttribute('src',isImg.replace(/_small\./, '.'));

Comment: If you have a second, think you could take a look at that again? Thanks
Comment: If a question is solved you should accept an answer (no reputation needed, see [here](http://meta.stackexchange.com/a/5235/172024); reputation is only needed for upvotes). If you have an additional question you should create a new question and don't update the old one, because the new question will be sorted at the beginning of the queue, so many people can find it. An updated question only find people, which will see it randomly.
Comment: I have to go now, but I have an idea to solve your new issue. If I have a little time later I will update my answer.
Comment: Thanks, i didn't know how to accept it, and i also didn't know if i should create a new question, so thanks for letting me know.
Thanks again @scessor

Replace the end of a File Name (SRC)


[WARN ][plugins] plugin jdbc- river, failed to invoke custom onModule method

Question: I have installed the Elastic search version 1.7.1. It was working fine. I have installed the JDBC driver also. Check my plugins folder below
Directory of E:\Xampp\htdocs\my-elastic\elasticsearch-1.7.1\plugins\river-jdbc
09-09-2015  19:19            66,891 elasticsearch-river-jdbc-2.3.1.jar
27-07-2015  15:55           959,984 mysql-connector-java-5.1.33.jar

So i have the connector files are in plugins folder. When i start the elasticsearch it shows warning erros as below.
[2015-09-10 14:29:48,728][WARN ][plugins                  ] [Rogue] plugin jdbc-
river, failed to invoke custom onModule method
java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.elasticsearch.plugins.PluginsService.processModule(PluginsService
.java:200)
        at org.elasticsearch.plugins.PluginsModule.processModule(PluginsModule.j
ava:61)
        at org.elasticsearch.common.inject.Modules.processModules(Modules.java:6
4)
        at org.elasticsearch.common.inject.ModulesBuilder.createInjector(Modules
Builder.java:58)
        at org.elasticsearch.node.internal.InternalNode.<init>(InternalNode.java
:210)
        at org.elasticsearch.node.NodeBuilder.build(NodeBuilder.java:159)
        at org.elasticsearch.bootstrap.Bootstrap.setup(Bootstrap.java:77)
        at org.elasticsearch.bootstrap.Bootstrap.main(Bootstrap.java:245)
        at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:32)

Caused by: java.lang.VerifyError: class org.xbib.elasticsearch.rest.action.RestJ
DBCRiverInduceAction overrides final method handleRequest.(Lorg/elasticsearch/re
st/RestRequest;Lorg/elasticsearch/rest/RestChannel;)V
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(Unknown Source)
        at java.security.SecureClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.access$100(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at org.xbib.elasticsearch.plugin.river.jdbc.JDBCRiverPlugin.onModule(JDB
CRiverPlugin.java:53)
        ... 13 more

How can i fix the issue. Please help to fix the issue.
Thanks in Advance
Comment: Can you show how you installed your jdbc river plugin? i.e. `bin/plugin --install ...` or via another way? I'm pretty sure you have an incompatible version of the plugin that doesn't play well with ES 1.7
Comment: Actually i have downloaded the latest version of the jar file in `http://dl.bintray.com/jprante/elasticsearch-plugins/org/xbib/elasticsearch/plugin/elasticsearch-river-jdbc/2.3.1/%elasticsearch-river-jdbc-2.3.1.jar` path and pasted into the plugins folder. because i don't know how can i update the latest version.
Answer: According to the JDBC plugin's documentation, the version that you should use with ES 1.7 is the version 220.127.116.11.
So try again to install your plugin with the 22.214.171.124 package at
http://xbib.org/repository/org/xbib/elasticsearch/importer/elasticsearch-jdbc/22.214.171.124/elasticsearch-jdbc-220.127.116.11-dist.zip
And then follow these installations steps
UPDATE
Actually, I didn't get you were trying to install a river plugin. Since rivers have been deprecated, the JDBC importer does not provide a river plugin anymore since version 1.5. If you absolutely want to use the river plugin, you need at most ES 1.5 (i.e. it won't work with ES 1.6+) and the JDBC plugin v1.5.
If you decide to go down that path, you can install the JDBC river plugin with
./bin/plugin --install jdbc --url http://xbib.org/repository/org/xbib/elasticsearch/plugin/elasticsearch-river-jdbc/220.127.116.11/elasticsearch-river-jdbc-184.108.40.206.zip

In the case you decide to stay with ES 1.7, then you can run the JDBC importer as a standalone tool by running the appropriate script in the bin folder
Comment: I have downloaded the files, installation steps little bit confusing me. I have two directories in that folder `bin, lib`. what is the next step? I have `mysql-connector-java-5.1.33.jar` file in `lib` folder. that is already in my `plugins\river-jdbc` folder. Where i can find the JDBC river jar file?
Comment: I am using the latest version i will choose ES 1.7.  My Elasticsearch and Elasticsearch-River folders are in various path.. How can i import the JDBC to that elasticsearch. Still i am confused with poitns 5,6,7 in Installation steps.


Como contar quantidade de checkbox selecionados

Question: Eu estou tentando fazer um código que verifica quantos checkbox estão marcados ao clicar em um botão, pois estou fazendo um sistema que duplica registros. Tenho uma lista com vários checkbox, e quando a pessoa clicar no botão "duplicar" o jQuery vai verificar quais estão marcados e pegar o value deles. Não tenho ideia de como fazer, pois tentei de várias formas e nada. O último código que tentei foi esse:

Answer: Para pegar os valores dos checkbox selecionados, primeiramente você deverá alterar o seletor de sua função. Não é permitido mais de um elemento com o mesmo id, então sugiro utilizar o nome do checkbox ou um classe para isto, segue exemplo de sugestão de implementação:
HTML
<input type="checkbox" value="1" name="mcheckbox[]" /> 1
<input type="checkbox" value="2" name="mcheckbox[]" /> 2
<input type="checkbox" value="3" name="mcheckbox[]" /> 3
<input type="checkbox" value="4" name="mcheckbox[]" /> 4
<input type="checkbox" value="5" name="mcheckbox[]" /> 5
<button type="button" id="duplicar-registro">Duplicar Registro</button>

jQuery
 $('#duplicar-registro').click(function () {
    //seletor para os checkbox com name mcheckbox selecionados
    var checkbox = $('input:checkbox[name^=mcheckbox]:checked');
    //verifica se existem checkbox selecionados
    if(checkbox.length > 0){
        //array para armazenar os valores
        var val = [];
        //função each para pegar os selecionados
        checkbox.each(function(){
            val.push($(this).val());
        });
        //exibe no console o array com os valores selecionados
        console.log(val);
    }
});

Exemplo: JSFiddle
Comment: Acredito que o exemplo não esteja funcionando!
Comment: @GabrielBorghi acredito que devido atualização do JSFiddle o jQuery não esta sendo incluido, veja aqui http://jsfiddle.net/UtL36/31/
Comment: É pra mim não funciona, mas beleza era só pra ter certeza caso alguém precise, mas o código ja me ajudou valeu.
Answer: Exemplo: Demo
<!DOCTYPE HTML>

<meta charset="utf-8">
<title>CheckBox Selecionados</title>

    <input type="checkbox" value="1" name="check1" id="check1">1

    <input type="checkbox" value="2" name="check2" id="check2">2

    <input type="checkbox" value="3" name="check3" id="check3">3

    <input type="checkbox" value="4" name="check4" id="check4">4

    <input type="button" value="Verificar" id="btnverificar" name="btnverificar">


Forcing Mechanize to use SSLv3

Question: How would you force mechanize to use SSLv3 for HTTPS URLs that require it? If I try to use mechanize with all SSLv3-only URLs, I get the error:
URLError: <urlopen error [Errno 1] _ssl.c:504: error:140773E8:SSL routines:SSL23_GET_SERVER_HELLO:reason(1000)>

Comment: From the following bug report, this may help:
http://bugs.python.org/issue11220

Also I think there should be a ``verify_mode`` option somewhere, but I can't find it in the ``mechanize`` docs :/. and ``def add_client_certificate(self, url, key_file, cert_file):`` in mechanize/_useragent.py  might help, but sorry I can't find anything definite using right now :(
Comment: @EiyrioüvonKauyf, Yeah, I stumbled across that page myself. That's why I'm trying to force it to use SSLv3, "The problem is the server strictly accepts SSLv3 only and urllib and http.client send SSLv23 protocol." They even provide a workaround for urllib in the form of a custom opener, but I don't know how to adapt it to mechanize.
Answer: A dirty answer... not requiring patching.
import ssl
from ssl import PROTOCOL_SSLv23, PROTOCOL_SSLv3, CERT_NONE, SSLSocket

def monkey_wrap_socket(sock, keyfile=None, certfile=None,
                server_side=False, cert_reqs=CERT_NONE,
                ssl_version=PROTOCOL_SSLv23, ca_certs=None,
                do_handshake_on_connect=True,
                suppress_ragged_eofs=True, ciphers=None):
    ssl_version=PROTOCOL_SSLv3
    return SSLSocket(sock, keyfile=keyfile, certfile=certfile,
                     server_side=server_side, cert_reqs=cert_reqs,
                     ssl_version=ssl_version, ca_certs=ca_certs,
                     do_handshake_on_connect=do_handshake_on_connect,
                     suppress_ragged_eofs=suppress_ragged_eofs,
                     ciphers=ciphers)

ssl.wrap_socket = monkey_wrap_socket

... before your code.
Comment: Hrmm, didn't work for me, I still get hostname doesn't match certificateerror
Answer: The last comment on the Python issue Eiyrioü von Kauyf mentions above is the solution I implemented in my forked version of mechanize. The diff of mechanize/_opener.py follows. It fixes mechanize.urlopen(), but not mechanize.Browser()'s open() method:
diff --git a/mechanize/_opener.py b/mechanize/_opener.py
index ad8412d..e6d1ebc 100644
--- a/mechanize/_opener.py
+++ b/mechanize/_opener.py
@@ -25,9 +25,27 @@ import _rfc3986
 import _sockettimeout
 import _urllib2_fork
 from _util import isstringlike
+import ssl, socket

 open_file = open

+class HTTPSConnectionV3(httplib.HTTPSConnection):
+    def __init__(self, *args, **kwargs):
+        httplib.HTTPSConnection.__init__(self, *args, **kwargs)
+
+    def connect(self):
+        sock = socket.create_connection((self.host, self.port), self.timeout)
+        if self._tunnel_host:
+            self.sock = sock
+            self._tunnel()
+        try:
+            self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, ssl_version=ssl.PROTOCOL_SSLv3)
+        except ssl.SSLError, e:
+            self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, ssl_version=ssl.PROTOCOL_SSLv23)
+
+class HTTPSHandlerV3(urllib2.HTTPSHandler):
+    def https_open(self, req):
+        return self.do_open(HTTPSConnectionV3, req)

 class ContentTooShortError(urllib2.URLError):
     def __init__(self, reason, result):
@@ -370,7 +388,7 @@ class OpenerFactory:
         _urllib2_fork.HTTPErrorProcessor,
         ]
     if hasattr(httplib, 'HTTPS'):
-        default_classes.append(_urllib2_fork.HTTPSHandler)
+        default_classes.append(HTTPSHandlerV3)
     handlers = []
     replacement_handlers = []

Answer: You can monkey-patch ssl.wrap_socket() to use TLSv1, which, after the Poodle vulnerability, seems to be the only viable left. This will force all SSL connections to use TLSv1 regardless of the higher level library.
import ssl
from functools import wraps
def sslwrap(func):
    @wraps(func)
    def bar(*args, **kw):
        kw['ssl_version'] = ssl.PROTOCOL_TLSv1
        return func(*args, **kw)
    return bar

ssl.wrap_socket = sslwrap(ssl.wrap_socket)

Forcing Mechanize to use SSLv3


Somar valores numéricos em arquivos de texto com Python

Question: estou escrevendo um pequeno projeto em Python que consiste em um aplicativo que vai adicionando gastos, armazenando o nome e o valor dos gastos em um arquivo de texto e printando na linha de comando, e no final computando a soma do valor dos gastos. A ideia é que a cada vez que abro o aplicativo, eu possa somar novos valores ao valor total de gastos anterior. Por exemplo, o total de gastos deu 100, o programa armazena esse valor e quando eu abrir de novo, posso adicionar um gasto de 20 reais efazer o programa mostrar 120. É possível realizar esse tipo de operação trabalhando somente com python e arquivos?
Segue o código do projeto
while True:
    while True:
        try:
            opc = int(input(f'''=================================================
              MENU PRINCIPAL
=================================================
[1] Visualizar lista de compras
[2] Atualizar gastos
[3] Sair
=================================================

Sua opção: '''))
        except (ValueError, TypeError):
            print('Tipo de dado digitado inválido! Digite novamente')
        else:
            break
    if opc == 1:
        with open("arquivo.txt") as n:
            nome = n.read()
            print('='*49)
            print(nome)
            print('='*49)
    elif opc == 2:
        with open("arquivo.txt",'a') as n:
            while True:
                x = str(input(f'Tipo de gasto: '))
                t = x.strip().capitalize()
                if len(t) < 20:
                    b = 20 - len(t)
                    h = t + (' '*b)
                if x.isalpha() == False:
                    print(f'Digite novamente: ')
                else:
                    break
            while True:
                try:
                    y = float(input(f'Valor do gasto (R$): '))
                except (ValueError, TypeError):
                    print('Tipo de dado digitado inválido! Digite novamente')

                else:
                    valores.append(y)
                    break

            z = str(y)
            n.write(h)
            n.write(f'\t\t R${z}')
            n.write('\n')
            print(f'''
Novo registro de {x} adicionado''')

            soma = 0
            for i in valores:
                soma += i
            print(f'''
Soma                R${soma}''')

    elif opc == 3:
        print(f'Obrigado, volte sempre! ')
        break
    else:
        print(f'Opção inválida! Tente novamente: ')```

Answer: Sim, você pode utilizar o open para abrir um arquivo em formato de leitura, obter o valor, somá-lo dentro do programa e depois escrever o arquivo novamente com o valor atualizado. Exemplo:
def atualizaGastos(valor):
    with open("data.txt") as file:
        gastos = float(file.read())
    with open("data.txt","w") as file:
        file.write(str(gastos+valor))

Caso o arquivo possua mais informação do que um simples número (gastos), você deverá saber a posição exata deste número no arquivo ou então, utilizar o módulo re para obter os gastos em qualquer parte do arquivo. Se você não sabe o que são Expressões Regulares pesquise primeiro por esse assunto e depois utilize o módulo re para obter os valores desejados no arquivo.


Strange question pertaining views as forms?

Question: I am attempting to provide quizzes in Drupal. The Drupal quiz module is out of question as a version for Drupal 7 does not exist. The way to go about doing this then IMHO is using web-forms. I am treating each question that is part of the quiz as a separate node entity.
The idea is to cluster these questions based on taxonomy vocabularies and establish a quiz. Clearly the best way to have nodes together would be VIEWS with some filter criterion. However, this clearly backfires. It establishes the required set of questions as a view. But this does not necessarily establish them a single quiz form, but rather a set of individual forms all present in the single page. Essentially, if my view has 10 questions, then it has 10 SUBMIT buttons.
My aim is to try and create this view as a form, but I think that is not possible anymore. I feel I should just post this here, regardless to get an answer or alternative ways to go about doing this.
Comment: Here is a link to similar question:  http://drupal.stackexchange.com/questions/21990/creating-an-exam-system-with-drupal-7/22024#22024
Comment: I have a little half-finished module for doing this, if you want to wade through it: https://github.com/bbinkovitz/derpl/ It's the one called "webformta".
Answer: I'm not sure Views would be the way I'd go with this. It's for getting data displayed from the database and this just seems like you're stretching the scope of what it's designed to do.
Is there any reason each question has to be on a different node? That seems to be adding even more complexity.
My suggestion would be to use webform to a the form for each different quiz. Especially if site administrators will have to create the quizzes regularly as webform offers the best UI for doing this. The difficult bit then is to write some sort of add on to webform (I don't know how much of an API webform has) that changes how the form is submitted and validated to be more 'quiz like'.


High autocorrelation when taking the L-th order of difference of a sequence of independent random numbers

Question: To explain this question in more detail, I'll first elaborate my approach:

I simulated a sequence of independent random numbers $X = \{x_1,...,x_N\}$.
I then take $L$ times the difference; i.e. I create the variables:
$dX_{1} = \{X(2)-X(1),...,X(N)-X(N-1)\}$
$dX_{2} = \{dX_{1}(2)-dX_{1}(1),...,dX_{1}(N-1)-dX_{1}(N-1-1)\}$
$...$
$dX_{L} = \{dX_{L-1}(2)-dX_{L-1}(1),...,dX_{L-1}(N-L)-dX_{L-1}(N-L-1)\}$

I observe that the (absolute) autocorrelation of $dX_{L}$ increases as $L$ becomes larger; the ac approaches even 0.99 for $L >100$. I.e. when taking the L-th order of difference, we create a series of highly dependent numbers (sequence) out of an initially independent sequence.
Here are some graphs to illustrate my observations:

My questions:

Is there any theory behind this approach, and its implications or applications for it?
Does this indicate that this approach exploits the weaknesses of a pseudo-randomn generator (of the computer). I.e. the generated "random" sequence is not trully random, and this is illustrated/proved from my approach?
Can we exploit the high autocorrelation of the L-th order of differences, in order to predict the next number in the sequence (i.e. $X(N+1)$). I.e. if we can predict the next number of $dX_{L}$ (through e.g. linear regression), we can deduce back the estimated sequence $X(i)$ through taking $L$ times the cumulative sum. Is this a feasible approach?

Objective
Note that I am trying to predict $X(N+1)$, but since the numbers are generated independentaly and random, this is very hard (low ac of $N$).
Comment: The difference of order $L$ is a linear combination of the original values across a window of width $L+1$, so *of course* there will be strong relationships among successive values of the differences. There's no way to exploit this, because you're basically predicting tiny deviations from the values you already know.
Comment: I am sorry.You edited it twice but there is a lot I don't understand.  I doubt that the problem is with the pseudo random number generator.  Are you transforming the uniform random numbers to some other distribution? You are taking differences but why if the variables are suppose to be independent? Why are you trying to predict numbers  in the sequence?  Differencing is usual done to remove polynomial trend.
Comment: @Michael My goal is to predict the next number in the sequence, not to change the distribution. Trying to predict X(N+1) is hard because the numbers of the sequence are independent and random (low autocorr as well). So I differenced the sequence L times amd found that the ac increases when L increases, which led to me wondering what this means and whether it can be exploited.
Comment: I added some graphs for illustration.
Answer: Theory
If the autocorrelation is going to have any meaning, we must suppose the original random variables $X_0, X_1, \ldots, X_N$ have the same variance, which--by a suitable choice of units of measure--we may set to unity.  From the formula for the $L^\text{th}$ finite difference
$$X^{(L)}_i=(\Delta^L(X))_i = \sum_{k=0}^L (-1)^{L-k}\binom{L}{k} X_{i+k}$$
for $0 \le i \le N-L$ and the independence of the $X_i$ we readily compute
$$\operatorname{Var}(X^{(L)}_i) = \sum_{k=0}^L \binom{L}{k}^2 = \binom{2L}{L}\tag{1}$$
and for $0 \lt j \lt L$ and $i \le N-L-j$,
$$\operatorname{Cov}(X^{(L)}_i, X^{(L)}_{i+j}) = (-1)^{j}\sum_{k=0}^{L-j} \binom{L}{k}\binom{L}{k+j} =  (-1)^{j}\frac{4^L \binom{L}{j} j!\Gamma(L+1/2)}{\sqrt{\pi}(L+j)!}.\tag{2}$$
Dividing $(2)$ by $(1)$ gives the lag-$j$ serial correlation $\rho_j$. It is negative for odd $j$ and positive for even $j$.
Stirling's Formula gives a readily interpretable approximation
$$\log(|\rho_j|) \approx -\left(\frac{j^2}{L} - \frac{j^2}{2 L^2} + \frac{j^2 \left(j^2+1\right)}{6L^3}-\frac{j^4}{4 L^4} + O(L^{-5})O(j^6)\right)$$
As a function of $j$ its magnitude is roughly a Gaussian ("bell-shaped") curve, as we would expect of any diffusion-based procedure like successive differences.  Here is a plot of $|\rho_1|$ through $|\rho_5|$ as a function of $L$, showing how rapidly the serial correlation approaches $1$.  In order from top to bottom the dots represent $|\rho_1|$ through $|\rho_5|$.

Conclusions
Because these are purely mathematical relationships, they reveal little about the $X_i$.  In particular, because all finite differences are linear combinations of the original variables, they provide no additional information that could be used to predict $X_{N+1}$ from $X_0, X_1, \ldots, X_N$.
Practical observations
As $L$ grows, the coefficients in the linear combinations grow exponentially.  Notice that each $X^{(L)}_i$ is an alternating sum: specifically, in the middle of that sum appear relatively large coefficients close to $\binom{L}{L/2}$.  Consider actual data subject to a little bit of random noise.  This noise is multiplied by these large binomial coefficients and then those large results are nearly canceled by the alternating addition and subtraction.  As a result, computing such finite differences for large $L$ tends to wipe out all information in the data and merely reflects tiny amounts of noise, including measurement error and floating point roundoff error.  The apparent patterns in the differences shown in the question for $L=100$ and $L=168$ almost surely provide no meaningful information.  (The binomial coefficients for $L=100$ get as large as $10^{29}$ and as small as $1$, implying double-precision floating point error is going to dominate the calculation.)
Comment: Very clear, and after reading this it totally makes sense. On your last point, indeed I tested it out by adding a small number (e.g. 0.00001) for a large $L$, and its astonishing to see that it has such a huge effect on $X_i$, this due to the large coefficients. In other words, one would need a highly accurate forecast in order to predict the next sequence, but since there is no additional info in the sequences for a large $L$, it would seem an impossible task.
Answer: This is more a comment or, at best, maybe a further clue to solve your question, but my reputation doesn't allow me to post comments.
I replicated your experiment in Stata using draws from a standard Normal with the following code:
<code>clear all
set obs 100000

gen t = _n
tsset t

drawnorm x, n(100000)

forvalues i = 1(1)100 {
generate D`i' = D`i'.x
}
</code>
Looking at the correlograms of the differenced variables, I was wondering why the confidence bands are so tiny. I have never seen such small confidence bands in a Stata correlogram. Any ideas?
I was thinking this could be a clue because, with confidence bands so small, even the tiny autocorrelations from the furthest lags are being counted in your absolute autocorrelation, if I'm interpreting "absolute" correctly.
Here is the correlogram for my dX_10...

...and here it is again, zoomed in on the first 10 lags...
Comment: Looking at your graph, are the confidence bands also small for smaller lags? I only use AC(1) of the differenced variables. With absolute I simply mean either negative or positive ac.
Comment: Yes, the bands are also very small for dX_1 through dX_9. And, sorry, I thought by "absolute" you somehow meant the sum of the correlations for all lags.
Comment: AC(1) is indeed higher the more we difference like you said... interesting.
Answer: This is expected because the differences are not independent of each other. For example, $dX_1(1) \equiv X(2) - X(1)$ is directly proportional to $X(2)$ while $dX_1(2) \equiv X(3) - X(2)$ is inversely proportional to $X(2).$ Because the definitions of consecutive elements of $dX_1$ share elements of $X$ in this inverse way, we expect them to be inversely correlated to each other. In fact, as we go to higher order differences $dX_i$, consecutive values share a higher and higher fraction of the elements of $X$ that go into their definition, and their anticorrelation increases. However, if we did not know the shared element ($X(2)$ in my example) we would not be able to calculate any differences that include this element. We therefore cannot use the anticorrelations in the differences to predict unknown elements of $X$ if they are generated independently of the known elements.


Tomato dnsmasq - limit queries to specific name server

Question: Does anyone know if it's possible to limit queries to a specific name server using dnsmasq? As an example:
All queries for anything on 172.16.0.0/12 should only be answered by server A.
All queries for the Internet should only be answered by server B
In this case server A is my ISPs main name server and it handles queries for the Internet and also the customers Intranet (the 172 network) Unless I use their name server I cannot access resources on the Intranet. However, I also wish to use a VPN but the ISPs name server leaks on dns leak test.
I have looked at the server=/ section of the dnsmasq man page but I can't tell whether it will work for the scenario described above.
Thanks
Comment: Are you querying PTR records?
Comment: No, straight forward lookup.
Answer: You just need to state the following in your dnsmasq.conf:
server=/ispdomain.tld/126.96.36.199
Queries to any host in ispdomain.tld would be answered by 220.127.116.11, where 188.8.131.52 is your ISP's main name server.
And "server B"'s IP address should be stated in /etc/resolv.conf as this:
nameserver 220.127.116.11
Comment: Thanks for the reply. I have tried this before but it doesn't prevent the isp name server from answering Internet requests and thus leaking.
Comment: It SHOULD answer Internet requests as well, but it is your right to use it for resolving only several domains while using "server B" for other requests.
Comment: I appreciate it should answer Internet queries but that's what I'm trying to prevent.
Comment: Suggested setup in my answer should work. Using server A or server B depends on domain name queried. What's exactly wrong with it?


Excel file missing reference to Microsoft Windows Common Controls-2

Question: I need to export a .xlsm file to other computers. I'm having trouble with a reference.
For instance: atual_date = Date - is giving error of missing library.
How can I export the file with the references included?
Can I have a individual file that adds the references to the other computers?

How can I work around?
Why is this refence missing?
Can I add VBA code to paste the mscomct2.ocx file when the user opens the file?
Comment: The workbook it is saved with references checked. There are missing references only if on the new computer the referenced library does not exist. Even if it is a matter of diferite version.
Comment: Do you use this reference (Microsoft Windows Common Controls...) in Excel? It usually is used in Access and if I remember well, it is useless now. Try, please uncheck it and see what happens...
Comment: When you have a missing  referenced library, even Left or Right will not work, anymore. The line where the error occurs is not all the time directly related to the missing library... ;)
Comment: I didn't know that. As it was the first time that I was trying the file on a different computer, when appeared the error on the Date, I instantly assumed that should be missing some reference. Luckly it was a lot easier to solve!
Comment: The important issue is that now you know... :)
Comment: What is missing is the mscomct2.ocx file. Can you tell me how I can work arround? Why is missing this refence? Can I add some VBA code to paste the mscomct2.ocx file when the user opens the file?

Thank you for answering!
Comment: Wow, that worked! Many thanks! That happens to lack of knowledge of each reference is related to! What I can't explain is why before on this : atual_date = Date , was giving library missing, and now, I unchecked and work. But that is not so important... @FaneDuru, thank you very much for your help!!
Comment: Yes always learning! ;)
Answer: Do you use this reference (Microsoft Windows Common Controls...) in Excel?
It usually used to be used in Access and if I remember well, it is useless now. Try, please un-checking it and see what happens...
Please, see the next link
And take care to un-check it from the original file, too. Otherwise, it must be removed only after an error will appear...
Comment: @TiagoSantos: Glad I could help! I tried clarifying this issue after your first comment asking for such a clarification. Please, check it...
Comment: It worked! What I don't understand why atual_date = Date was giving "missing library" and now it doesn't. But that doesn't matter anymore. Worked perfectly! Again, thank you very much!!


Minimizing $\int_{-\pi}^{\pi} |x^2 - A|^2dx$ using Fourier Series theory

Question:
Let $f(x) = x^2$ on $[-\pi, \pi]$. Choose the real number $A$ to minimize $\int_{-\pi}^{\pi} |f(x)-A|^2dx$

So I see an integral with an absolute value squared term, so something like Bessel's inequality is jumping out at me. The difficultly is though that A must be a real number, so simply applying Bessel's here doesn't seem to work. My other idea was perhaps to construct a Fourier Series for A, then that should converge to a real number, and then apply Bessel's. However, I am not sure if this logic is correct.
Any help is appreciated, thank you!
Comment: All you need to do is find the constant term in the series expansion, it is guaranteed to minimize the distance in $L^2$
Comment: What you want is to minimize the distance to the subspace of constant functions, spanned by $g_0(x)=1$ or any other non-zero constant. This is always achieved by the orthogonal projection in any Hilbert space. Any partial sum of the Fourier series is the orthogonal projection onto the subspace spanned by $\{1,\sin x,\cos x,\sin 2x,\cos 2x,\dots\sin nx,\cos nx\}$ (this is not a normal basis, but that does not change the span). In your particular case, you need the projection onto the span of $g_0$, which is just the constant term in the series, $a_0/2$. Your $A=a_0/2$, the integral average.
Comment: Right, $a_0=\int_{-\pi}^\pi x^2 \, dx = \frac{2\pi^2}{3},$ and the constant term is $\frac{a_0}{2} = \frac{\pi^2}{3}.$
Comment: @mjw shouldn't $a_0$ also contain $A$? or are we simply looking at the fourier series expansion for $x^2$?
Comment: As @GReyes observed, the "$A$" that minimizes the mean squared value is $A=\frac{a_0}{2}$, the constant term in the Fourier series.
Comment: Why is this the case? And is this for complex or real notation?
Comment: The reason is the orthogonality of the trigonometric system. What you want to do is minimize the distance to the subspace generated by the constant function $g_0(x)=1$. The minimum is given by the orthogonal projection  onto the subspace. But this is precisely the first partial sum of the series.
Comment: In the "answer", there is nothing special about $f(x)=x^2$, it could have been any function.  We minimize $A^2 \int dx - 2A \int f(x) dx$ which leads to $A=\frac{\int f(x) dx}{\int dx} = \frac{1}{2\pi} \int_{-\pi}^\pi f(x) dx.$
Comment: @GReyes So we want to choose $A$ is such a way that $|f-A| = c_n$, where $c_n$ are the Fourier coefficients, since is the closest approximation to $f$ (i.e. the orthogonal projection)?
Comment: @GReyes Also, what is $g_0(x) = 1$ in this case? Is it simply $|f(x) - g_0(x)A|$?
Answer: We want to minimize $$\int_{-\pi}^\pi (x^2-A)^2 dx = \int_{-\pi}^\pi x^4 dx-2A \int_{-\pi}^\pi x^2 dx +  A^2 \int_{-\pi}^\pi dx$$
This is equivalent to minimizing $ A^2 \int_{-\pi}^\pi dx -2A \int_{-\pi}^\pi x^2 dx $ or $$g(A) = \frac{A^2}{2} - \frac{\pi^2 }{3}A.$$
$$g^\prime(A) = A-\frac{\pi^2}{3} = 0.$$
$$A=\frac{\pi^2}{3}.$$
It is obvious that this is at the minimum (and not the maximum).  Nevertheless $g^{\prime\prime}(A) =1 >0.$


How to save current page source in different name & folder

Question: I would like to use the getPageSource() method to save the current page source under a different name in a nominated folder. e.g. save current page source
as Hawai.htm under C:/Holiday folder.
Most reference material including Java doc available have only touched on getPageSource() but nothing specifically not what is needed in this case.
I am using Selenium Webdriver 2 Java (JDK 7) on Windows platform.
Answer: getPageSource() will return a String which contains entire page source.
In WebDriver there is no file operations available. For writing that string (page source) to separate file in required location you should use some programming language.
class FileWrite
{
 public static void main(String args[])
  {
  try{
  // Create file
  FileWriter fstream = new FileWriter("C://Holiday//Hawai.htm");
  BufferedWriter out = new BufferedWriter(fstream);
  out.write(driver.getPageSource());
  //Close the output stream
  out.close();
  }catch (Exception e){//Catch exception if any
  System.err.println("Error: " + e.getMessage());
  }
  }
}

Answer: Based on documentation, the getPageSource() might (depends on browser) not return correct content if page has been modified by JavaScript. If you have jQuery, you could use:
try (FileWriter fstream = new FileWriter("C://Holiday//Hawai.htm");
     BufferedWriter out = new BufferedWriter(fstream)) {
    String content = (String)((JavascriptExecutor)driver).executeScript("return $('html').html();"));
    out.write(content);
}
catch (Exception e) {...}


prove sum of divisors of a square number is odd

Question: Don't know how to prove that sum of all divisors of a square number is always odd.
ex: $27 \vdots 1,3,9,27$; $27^2 = 729 \vdots 1,3,9,27,81,243,729$; $\sigma_1 \text{(divisor
 function)} =  1 + 3 + 9 + 27 + 81 + 243 + 729 = 1093$ is odd;
I think it somehow connected to a thing that every odd divisor gets some kind of a pair when a number is squared and 1 doesn't get it, but i can't formalize it. Need help.
Answer: Yes, you can assign a pair to every odd divisor, except one of them.
So, we have a square number $n^2$. Extract the largest power of $2$ from $n$ to get $n = 2^k m$ where $m$ is odd. Odd divisors of $n^2$ are the same as all divisors of $m^2$. If $d$ is a divisor of $m^2$, then $m^2/d$ is also its divisor. So they all come in pairs, except for $m$ which is paired with itself.
Answer: The divisors $1=d_1<d_2<\cdots <d_k=n^2$ can be partitioned into pairs $(d, \frac {n^2}d)$, except that there is no partner for $n$ itself.
Therefore, the number of divisors is odd.
Thus if $n$ itself is odd (and  so are all its divisors), we have the sum of an odd number of odd numebrs, hence the result is odd.
But if $n$ is even, we can write it as $n=m2^k$ wit $m$ odd. The odd divisors of $n^2$ are precisely the divisors of $m^2$. Their sum is odd and all other (even) divisors do not affect the parity of the sum.
Answer: Sum of divisors =$\prod_{p_i\mid n}(1+p_i+p_i^2+\cdots+p_i^{2P_i})$ where $p_i$s are distinct primes and $p_i^{P_i}\mid\mid n$
Now, $p_i^r+p_i^{2P_i+1-r}$ is even for all the prime divisor $p_i$ of $n$ for $0< r\le 2P_i+1-r\implies 0<r\le P_i$ leaving $p_i^0=1$ unpaired.

Alternatively, $p_i^k\equiv p_i\pmod 2$ for $k\ge 1$
So, $1+p_i+p_i^2+\cdots+p_i^{2P_i}\equiv 1+\sum_{1\le s\le 2P_i}p_i\pmod 2\equiv 1+2P_is\pmod 2\equiv 1$
Answer: The formula for $\sigma_1(n)$ for $\displaystyle{n=\prod_{i=1}^kp_i^{\alpha_i}} $ is $\displaystyle{\sigma_1(n)=\prod_{i=1}^k\frac{p_i^{\alpha_i+1}-1}{p_i-1}}$ (see this).
Therefore $\displaystyle{\sigma_1(n^2)=\prod_{i=1}^k\frac{p_i^{2\alpha_i+1}-1}{p_i-1}}$. But $\frac{p_i^{2\alpha_i+1}-1}{p_i-1}=1+p_i+p_i^2+\ldots+p_i^{2\alpha_i}$ is always odd. Thus $\sigma_1(n^2)$ is odd as product of odd numbers.
Answer: If $n=2^{k_{1}}...p_{m}^{k_{m}}$, then the odd divisors of $n^{2}$ are exactly the divisors of
$f=\frac{n^{2}}{2^{2k_{1}}}$ which, because $f$ is a square, has an odd number of divisors. Since the sum of an odd number odd's is odd, it follows that the sum of the divisors of $n$ is odd.
Answer: $144 = 12^2 = 12 \times 12$ = $2^4 \times 3^2$
so every square number is of the form $a^{2p} \times a^{2q}$
$\therefore$ total number of divisors = $(2p + 1)(2q + 1)$
$\because (2p + 1) \wedge (2q + 1)$ are both odd numbers $\forall(p \wedge q) \in \mathbb{Z}$, then every squared number $n^2$ will have an odd number of divisors.
Comment: why does  the first line prove "every square number is of the form"?  In your example I could choose $a=6, p=2, q=1$ but the number of divisors is not $35$ but $15$ or I could choose $a=1,p=16,q=9$ and the number of divisors is not $170$
Comment: Do not assume something is true and make a statement on it based on one example. This is what makes a "bad" mathematician. You must test all occasions.


How to pause Postgres before taking an LVM/ZFS snapshot?

Question: How can I instruct Postgres to complete all "in-progress" transactions, but to delay starting new ones (without kicking clients off) until I have taken a ZFS or LVM snapshot (which takes less than a second).
e.g.

pause Postgres, waiting for "in-progress" transactions to complete
sync to disk
take ZFS/LVM snapshot
resume Postgres
Comment: And why would you need this. Why not just take a snapshot. Yes, the DB state will be dirty, and some of the transactions will be rolled back, but nothing really harmful usually happens.
Answer: This answer on dba.stackexchange seems to be what you are after.
Comments do not seem to automatically link in the side bar (inside the network), so I need to write some more stuff to prevent auto-conversion to a comment... yeah.
Answer: The post mentioned in @user121391 answer is correct, but in short:

You cannot pause postgresql in any way (force it to continue open transactions and not process new transactions)
If the underlying snapshot is atomic (ZFS snapshots seems to be atomic), It's not necessary to do anything before snapshot, If you run a new  postgres process on the snapshot, the database will start in recovery mode (as when the previous process stopped abnormally).
pg_start_backup will make recovery process a little faster (since a checkpoint is made, and there will be less pending writes in WAL)


How can i adjust the positioning of two html elements?

Question: I am trying to adjust the position of two HTML Elements. I have one HTML element to display the "ASCII" generated text. The other, to display an  tag with a HREF link. I want the  tag to be displayed underneath the printed "ASCII" text. However, it seems to be printing next to it, which isn't what I want.
My HTML code is as follows:

    *, *:before, *:after {
      border: 0;
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }

    body {
      font: 16px "Helvetica Neue", Helvetica, sans-serif;
      line-height: 1;
      background-color: black;
    }

    .container {
      overflow: hidden;
      width: 100%;
      height: 100%;
      position: fixed;
      top: 0;
      left: 0;
      display: flex;
      align-items: center;
      align-content: center;
      justify-content: center;
    }

    .bypass {
      text-align: center;
      color: linear-gradient(to top, #e7343d 50%, #e7343d 50%);
      color:transparent;
      -webkit-background-clip: text;
      background-clip: text;
      align-items: center;
      justify-content: center;
    }

    .rainbow {

      background-image: linear-gradient(to top, #e7343d 50%, #61d6d6 50%);
      color:transparent;
      -webkit-background-clip: text;
      background-clip: text;
    }

    .ascii {
      display: none;
    }
    <!DOCTYPE html>

      <meta charset="UTF-8">
      <title>Brrrrrr</title>
      <link rel="stylesheet" href="./style.css">

           ______            __               _
          / ____/_  ______  / /_  ____  _____(_)___ _
         / __/ / / / / __ \/ __ \/ __ \/ ___/ / __ `/
        / /___/ /_/ / /_/ / / / / /_/ / /  / / /_/ /
       /_____/\__,_/ .___/_/ /_/\____/_/  /_/\__,_/
                  /_/

                  Home

src="script.js">

Comment: Add `flex-direction: column;` to your `.container` styles. Flex direction by default is `row`
Comment: @disinfor I just tried that, whilst it does center it, it posts the text above the ascii art.
Comment: Not sure what you're seeing, but that worked here in this fiddle: https://jsfiddle.net/kotq0w94/
Comment: @disinfor Yes, that works without JavaScript. Please take a look here [link(https://jsfiddle.net/jy9b5etw/1/)
Comment: You need to update your snippet to include your Javascript. How could we possibly know that's what you were working with if it's not in your question and you didn't tag the question with a javascript tag?
Comment: Add `#wrapper {
      order: 3;
    }` to your CSS. That will do what you want.
Comment: Does this answer your question? [Use flexbox order to order item between DOM-ordered items](https://stackoverflow.com/questions/32168052/use-flexbox-order-to-order-item-between-dom-ordered-items)
Comment: I apologize, I forgot to add that in. No, that didn't help in this situation.
Comment: I tested with your fiddle adding that line of CSS and that moved your animated ASCII above the `home` link: https://jsfiddle.net/vrdzLbej/
Answer: you can use the following code to print your text on next line
Remove this code
.ascii {
   display: none;
 }

Add this code
.rainbow { flex-flow: row wrap; }

Add a new div with between two elements

..

..

Add CSS to the new div
.break {
  flex-basis: 100%;
  width: 0px;
  height: 0px;
  overflow: hidden;
}

Update

since I got the js file attached in the project, this can be resolved with following steps
step 1:
move the div with id = text up and add a div with class .break

...

...

...

...

step 2:
Add the .break class and add code to .rainbow class as above.
Do not remove
.ascii { display: none }

Check the Jsfiddle here
Comment: @cosmokid Please click the checkmark button to the left of the question if this resolved the issue and close the question
Comment: This appears to print "Euphoria" twice, unless I miss understood. [link](https://lushy.dev/384e9igjhrito/v3/)
Comment: okay so I didn't know this had js associated with it
can you share the js file in your question?
Comment: Yes! I apologize. [link(https://jsfiddle.net/jy9b5etw/1/)
Comment: I have updated my answer, please check it and also attached my jsfiddle link


what does $\sum\limits_{i=1}^{10} \sum\limits_{j=1}^{10} \min(i,j)$ mean

Question: what does
$$\sum\limits_{i=1}^{10}  \sum\limits_{j=1}^{10} \min(i,j)$$
mean?
I'm aware that $\sum$ represents the summation, and min the minimum value . But when written like $\sum \sum$ , what exactly does it mean?
Comment: Hi. Is it less confusing with parentheses? You can read it as: $$\sum_{i=1}^{10}  \left( \sum_{j=1}^{10} \left( \min(i,j) \right) \right) = \left( \sum_{j=1}^{10} \left( \min(1,j) \right) \right)  +  \left( \sum_{j=1}^{10} \left( \min(2,j) \right) \right)  + ... +  \left( \sum_{j=1}^{10} \left( \min(10,j) \right) \right) $$
Comment: Ah,OK. Thanks a lot!
Answer: Hint
Evaluating the expression $\ \sum_\limits{i=1}^{10}\sum_\limits{j=1}^{10}\min(i,j)\ $ is facilitated by dividing the inner sum into two parts:
\begin{align}
\sum_\limits{j=1}^{10}\min(i,j)&=\sum_{j=1}^ij+\sum_{j=i+1}^{10}i\\
&=\sum_{j=1}^ij+(10-i)i\\
&=\frac{i(i+1)}{2}+(10-i)i\
\end{align}
for $\ 1\le i\le9\ $, because $\ \min(i,j)=j\ $ when $\ j\le i\ $ and  $\ \min(i,j)=i\ $ when $\ j>i\ $, and
\begin{align}
\sum_\limits{j=1}^{10}\min(10,j)&=\sum_\limits{j=1}^{10}j\\
&=45
\end{align}
because $\ \min(10,j)=j\ $ whenever $\ 1\le j\le10\ $.
Answer: This is called a double summation. Since the summations are all finite, you can read it as either
$$\sum_{i=1}^{10}  \left( \sum_{j=1}^{10} \left( \min(i,j) \right) \right)$$
or
$$\sum_{j=1}^{10} \left( \sum_{i=1}^{10} \left( \min(i,j) \right) \right)$$
or even as (if you prefer)
$$\sum_{i,j=0}^{10}\min(i,j)$$
which some people are more accustomed to.
Basically, it is the sum of $\min(i,j)$ for $i,j$ ranging over $[0,10]$.


Need help with a regex that needs to work with php

Question: I need help with this regex, I have to use it with PHP but I keep getting errors while using it with preg_match. I know I am doing something wrong but I can't figure it out. This regex finds/matches html tags in a string. If you have any other regex that can do this, please let me know!
</?(a|abbr|acronym|address|applet|area|b|base|basefont|bdo|big|blockquote|body|br|button|caption|center|cite|code|col|colgroup|dd|del|dir|div|dfn|dl|dt|em|fieldset|font|form|frame|frameset|h[1-6]|head|hr|html|i|iframe|img|input|ins|isindex|kbd|label|legend|li|link|map|menu|meta|noframes|noscript|object|ol|optgroup|option|p|param|pre|q|s|samp|script|select|small|span|strike|strong|style|sub|sup|table|tbody|td|textarea|tfoot|th|thead|title|tr|tt|u|ul|var|xmp)\b((\"[^\"]*\"|\'[^\']*\')*|[^\"\'>])*>

        if (!preg_match("/</?(a|abbr|acronym|address|applet|area|b|base|basefont|bdo|big|blockquote|body|br|button|caption|center|cite|code|col|colgroup|dd|del|dir|div|dfn|dl|dt|em|fieldset|font|form|frame|frameset|h[1-6]|head|hr|html|i|iframe|img|input|ins|isindex|kbd|label|legend|li|link|map|menu|meta|noframes|noscript|object|ol|optgroup|option|p|param|pre|q|s|samp|script|select|small|span|strike|strong|style|sub|sup|table|tbody|td|textarea|tfoot|th|thead|title|tr|tt|u|ul|var|xmp)\b((\"[^\"]*\"|\'[^\']*\')*|[^\"\'>])*>/", $input) && preg_match("/^.{2,$max_width}$/i", $input)) {
            $result = true;
        }

Thank you!
Comment: Please see http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags for more information.
Comment: Welcome to StackOverflow. When asking a question, saying "I keep getting errors" without showing the **exact** error message you're getting is meaningless. So is saying "I need help with this" without explaining what "this" is supposed to do (or supposed to be); "finds/matches html tags in a string" doesn't say much. Please edit your post to make it an actual answerable question, or it will most likely be closed. When doing so, remember that we have no idea of what you're trying to do (or anything else) except what you put in your question. Thanks. :)
Comment: *(related)* [Best Methods to parse HTML](http://stackoverflow.com/questions/3577641/best-methods-to-parse-html/3577662#3577662)
Comment: What is this regex supposed to do?
Answer: Your regex starts with /</?(a|abbr|ac... - the delimiter character (denotes start and end of regex) is a forward slash. When it sees the second forward slash after < it thinks the regex is finished.
Change it to /<\/?(a|abbr|ac (escape the slash with a backslash) and it will work.


Android - Position Views Based on Percentages instead of Pixels

Question: Is it possible to arrange the XML-based position of a TextView or related element based upon percentages of screen width and height rather than pixels? For example, could
android:layout-marginLeft="150dip"

be replaced with something like
android:layout-marginLeft="25%"?

If not, is it possible to do so programmatically?
Comment: and then you have weights in linearlayouts
Answer: The layout_margin attributes do not accept a percentage value.
You are looking for the LinearLayout attribute android:layout_weight which allows you to use percentages to define your layout:
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight=".25" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight=".75" />

</LinearLayout>

In this example, the left TextView uses 25% of the screen and the right TextView 75%.
Answer: Use the PercentRelativeLayout (http://developer.android.com/reference/android/support/percent/PercentRelativeLayout.html)
<android.support.percent.PercentRelativeLayout
         xmlns:android="http://schemas.android.com/apk/res/android"
         xmlns:app="http://schemas.android.com/apk/res-auto"
         android:layout_width="match_parent"
         android:layout_height="match_parent">
     <ImageView
         app:layout_widthPercent="50%"
         app:layout_heightPercent="50%"
         app:layout_marginTopPercent="25%"
         app:layout_marginLeftPercent="25%"/>
 </android.support.percent.PercentFrameLayout>


Ubuntu 14.04 Server GUI Installation and RDp Acess through windows 10

Question: How to install GUI for Ubuntu 14.04 and get RDP Access over windows ??
I have a laptop running on windows 10. I want to acess the linux machine running in Hyper V Enviornment with GUI .
This Linux machine is going to be used for web development ,specifically angular JS ./
What are the best practices that can be used to do this . I want a virtual Setup that has to run in a Hyper V Environment and can be accessed from Client Machine using Putty or RDP
Answer: xrdp is tool that you can install on Ubuntu 14.04 and access ubuntu remotely with RDP from any windows machine. First you need to install any desktop environment. I suggest you to go with LXDE the lightest one.


MySql Packets Out of Order

Question: Forgive me if this is a simple issue, I've been struggling for days with this.
I am migrating a client's WP site to MAMP in order to make some changes for her. I imported the DB to phpMyAdmin, and copied the site root to the folder that I have set up as the document root.
My Apache Port is 8888 and my PHP Port is 8889.
In my browser, I navigate to - http://localhost:8889/.
I keep getting this in the browser window:

J���
  5.5.33����}k~Z(VX7�ÿ÷�€����������HE`5%YpHW\J>�mysql_native_password�!��ÿ"#08S01Got
  packets out of order
Comment: That's your *MySQL connection port*, PHP "runs as part of" the web-server (Apache).
Answer: that's a mysql service not a web-server, where you expecting phpmyadmin?
Answer: PHP do not uses any ports
Mysql use ports, and looks like 8889 in your case
To check web-site you need to http://localhost:8888/

MySql Packets Out of Order


AngularJS $http get request is not correctly encoding dates inside object

Question: Please look at this issue.
When I'm trying to send object (which contains dates as properties) via $http (type GET) - I'm getting URL which contains ":".
For example object:
var a = {date:"15:36", name:"Test"}

I'm expecting, that I will recieve something like "site.com?date=15%3A36&name=test"
But in actual I get: "site.com?date=15:36&name=test"
If I understand correctly - the reason is in: https://github.com/angular/angular.js/blob/master/src/ng/http.js
Line 50:
parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
In my example - it is object, not array. First of all - it is serializeing value. (serializeValue(value))

Line 13-18
function serializeValue(v) {
  if (isObject(v)) {
    return isDate(v) ? v.toISOString() : toJson(v);
  }
  return v;
}

It is object, but it is not date (it contains date as property). So we get json string.
After it - it is encoding data to URI query.
I found it here: github.com/angular/angular.js/blob/720012eab6fef5e075a1d6876dd2e508c8e95b73/src/ngResource/resource.js
(Lines 405-411) (could not add 2 links, sorry me).
 function encodeUriQuery(val, pctEncodeSpaces) {
    return encodeURIComponent(val).
      replace(/%40/gi, '@').
      replace(/%3A/gi, ':').
      replace(/%24/g, '$').
      replace(/%2C/gi, ',').
      replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  }

It encodes with encodeURIComponent input data, but after it is returning values @, :, $, ,.
Is it AngularJS' bug, or did I do something wrong? I use AngularJS version 1.5.6. Please let me know your thougths, or ideas.
Comment: which back-end you use ? for get request ?
Comment: @31piy thank you a lot for editing grammar errors. My english is not so good as I want :-)
I'm using ASP.NET WEB API server as backend.
Answer: Use $httpParamSerializerJQLike Link
Example :
$http({
    url: URL,
      method: 'GET',
      params:  { date:"140:30", number:"10" },
      paramSerializer: '$httpParamSerializerJQLike',
      headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
      }
})

Comment: I tried to use it. But seems, that heart of this logic is also encodeUriQuery function. parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));  It is in "jQueryLikeParamSerializer.serialize()".


Which preprocess hook do I use to fire some HTML altering PHP?

Question: I have some PHP that ultimately says 'If this class is present in the HTML, add this string to the $additional_classes array'. Eg, something similar to:
$leftcol_empty = empty($content['leftcol']);
$additional_classes = !$leftcol_empty ? 'medium-8 medium-pull-4' : '';

Currently, I've put this at the top of my .tpl file and it works fine. However, I've been told I should move it to the 'theme preprocess function'.
I looked through my theme's template.php file and tried adding it to my_theme_preprocess_page, my_theme_theme and my_theme_process_html but it stopped working.
I've tried Googling for theme preprocesses but haven't found anything that works.
Would anyone know what preprocesses function I can use here?
Comment: You need to leverage the variables being passed and or add your own variable on ex. `$variables['additional_classes']` then output that in the template with `print $additional_classes;`. The preprocess hook you are using depends on which template you want to add it to.
Answer: you can use theme_preprocess_html(&$variables) OR my_module_preprocess_html(&$variables)
in $variables you will see $variables['classes_array']
if(in_array('class_name', $variables['classes_array'])) {

  //Do your changes

}

Hope this will help.


Classe Build-in do PHP não funciona no CakePHP 3.0

Question: Estou tentando usar uma classe Built-in do PHP dentro do CakePHP porém é retornado um:

Error: Class 'App\Controller\Component\DateTime' not found

Onde esta sendo usado:
public function listNewBanners($newBannersQuantity)
{
    $newBanners = TableRegistry::get('new_banners');
    $query = $newBanners->find();
    $query->select(['path_banner', 'date_start', 'date_end'])
        ->where(['date_start <' => new DateTime('today')])
        ->limit($newBannersQuantity);
    return $query;
}

Link da documentação oficial onde vi esta classe sendo usada: Documentação
Comment: Tente colocar uma barra antes, `new \DateTime('today')`
Comment: @rray Bruxo.... submeta uma resposta, sempre que quiser usar uma classe built-in devo usar esta \ ?
Comment: É o mesmo problema de [Namespace e PDO = Erro](http://pt.stackoverflow.com/q/67773/91)
Answer: Para chamar classes nativas do php dentro de um namespace é necessário adicionar uma barra(\) antes do nome, dessa forma o php sabe que precisa chamar um classe/função do core e não uma com o mesmo nome que pode estar dentro do namespace atual.
Mude:
new DateTime('today')

Para:
new \DateTime('today')

Exemplo, sem a barra ou seja vai tentar chamar a classe do namespace atual se ela existir ou retornará nome da classe not found
<?php

namespace teste;

class Teste{
    public function __construct(){
         echo '
';
         var_dump(new DateTime());
    }
}

class DateTime{
    public function __construct(){
        echo 'minha DateTime personalizada';
    }
}

new Teste();

Saída:
minha classe personalizada
object(teste\DateTime)[2]

Exemplo com a barra que indica que essa classe é do core
Alteração:
class Teste{
    public function __construct(){
         echo '
';
         var_dump(new \DateTime());
    }
}

Saída:
object(DateTime)[2]
  public 'date' => string '2015-07-30 20:02:00.000000' (length=26)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Europe/Berlin' (length=13)

Comment: Também pode declarar `use DateTime` logo após `namespace teste`. Uso essa alternativa como convenção para o uso de classes nativas.


Determine the values of $p$ for which the integral of $\sup_n f_n(x)$ converges to $0$.

Question: Consider $f_n(x)=n^px^n(1-x)$ on $[0,1]$. Then $\lim_{n\to \infty}f_n(x)=0$ for $x\in [0,1]$. I already know that if and only if $p<2$,
 we have$\int_{[0,1]} f_n(x)\mathrm{d}x\to 0$. I am asked for which values of $p$,  $\sup_nf_n(x)$ is integrable on $[0,1]$.
I tried to take derivative of $f_n(x)=n^px^n(1-x)$ with respect to $n$, and look for the expression of $\sup_nf_n(x)$. But it seems this does not help me much doing this way. I already see that, when $p\leq 1$, $\sup_nf_n(x)$ is integrable. But I still have difficulty when considering $p>1$. Any hint for this? Thank you for your help!
Comment: We can easily show that if $p>2$ then for sure $\sup_n f_n(x)$ is not integrable. Observe that
$$0\leq  f_n(x) \leq \sup_{n} f_n(x) \qquad \Longrightarrow \qquad \int_0^1 |f_n(x)|\;dx \leq \int_0^1 \sup_{n} f_n(x)\;dx$$
Which implies that
$$ \frac{n^p}{(n+1)(n+2)} = \int_0^1 |f_n(x)|\;dx \leq \int_0^1 \sup_{n} f_n(x)\;dx$$
for all $n\in \mathbb{N}$. You can see that if $p>2$ then the left hand side tends to infinity as $n\longrightarrow \infty$, thus $\sup_n f_n(x)$ cannot be integrable if $p>2$.
Comment: Oh thank you. But the difficulty is the part $1<p\leq2$. I don't know how to get good estimation here.
Answer: Differentiation with respect to $n$ might work. Assuming $n$ to be a continuous variable we get
$$
\frac{\partial}{\partial n}n^px^n=pn^{p-1}x^n+n^px^n\ln x=0\quad\Leftrightarrow\quad p+n\ln x=0\quad\Leftrightarrow\quad n=\frac{p}{\ln(1/x)}=\log_{1/x}e^p.
$$
It is easy to see that it is maximum. Hence,
$$
x^n=\frac{1}{(1/x)^n}=\frac{1}{e^p}=e^{-p}
$$
and
$$
\sup_n f_n=p^pe^{-p}\frac{1-x}{\ln^p(1/x)}.
$$
The integral has singularity at $x=1$. Change the variable to e.g. $1/x=1+t$ to see the asymtotics of this singularity to be
$$
\frac{t}{\ln^p(1+t)}\sim \frac{t}{t^p}=\frac{1}{t^{p-1}}
$$
as $t\to 0$. The RHS function is integrable at $(0,\epsilon)$ iff $p<2$.


Find the spectrum of a given operator

Question: Let operator $A:L^2[0, 1]\to L^2[0,1]$ be so that:
$$Ax(t)=
\begin{cases}
x(2t), & t\in[0, 1/2]\\\
x(2t-1), & t\in(1/2, 1]
\end{cases}$$
The problem is to find the spectrum of $A$.
The operator contracts the graphic of $x(t)$ on $[0,1]$ and inserts it into ranges $[0, 1/2]$ and $[1/2, 1]$. I've already got that as for eigenvalues (the discrete part of spectrum), they include $\lambda=1$ and not $0$, because if $Ax(t)-\lambda x(t)=0$ than $\forall t\in[0, 1/2]: x(2t)=\lambda x(t)=\lambda x(t+1/2)$ and if $t=0$ than $\lambda x(0)=x(0)$.
If $\lambda=0$ than the kernel of $A-\lambda I$ consists of only $x\equiv 0$ so it is not an eigenvalue.
If $\lambda=1$ than any constant function is the solution of $Ax(t)=x(t)$ and it is really an eigenvalue.
Could anyone help me with the rest part? Thank you in forward!
Answer: Recall that the set of functions $\{e^{2\pi int} : n \in \mathbb{Z}\}$ is an orthonormal basis for $L^2[0,1]$. Denote $e_n(t) = e^{2\pi int}$ and calculate:
$$(Ae_n)(t) = \begin{cases}
e_n(2t), & t\in[0, 1/2]\\\
e_{n}(2t-1), & t\in(1/2, 1]
\end{cases} = \begin{cases}
e^{4\pi int}, & t\in[0, 1/2]\\\
e^{4\pi int - 2\pi in}, & t\in(1/2, 1]
\end{cases}  = e^{4\pi int} = e_{2n}(t)$$
Therefore $A$ acts on the othornormal basis as $Ae_n = e_{2n}$ for all $n \in \mathbb{Z}$.
Note that $A$ is isometric:
$$\|Af\|^2 = \left\|\sum_{n\in\mathbb{Z}} \langle f, e_n\rangle e_{2n}\right\|^2 = \sum_{n\in\mathbb{Z}}\left| \langle f, e_n\rangle \right|^2 = \|f\|^2$$
so $\|A\| = 1$ and hence $\sigma(A) \subseteq \overline{B}(0,1)$.
You have already established that $0$ is not an eigenvalue so let $\lambda \in \sigma_p(A)$, $\lambda \ne 0$ and let $f \ne 0$ be an eigenvector. We have
$$0 = (A - \lambda I)f = \sum_{n\in\mathbb{Z}}\langle f, e_n\rangle e_{2n} - \lambda \sum_{n\in\mathbb{Z}}\langle f, e_n\rangle e_{n} = \sum_{n\in\mathbb{Z}}\left(\langle f, e_n\rangle - \lambda\langle f, e_{2n}
\rangle\right)e_{2n} + \lambda\sum_{\substack{n\in\mathbb{Z}\\n \text{ odd}}}\langle f, e_n\rangle e_n$$
Hence $\langle f, e_n\rangle = 0$ for all odd $n\in\mathbb{Z}$ and $\langle f, e_n\rangle = \lambda\langle f, e_{2n}\rangle$ for all $n\in\mathbb{Z}$. Consequently $\langle f, e_n\rangle = 0$ when $n$ is not a power of $2$, and $\langle f, e_{\pm e_{2^k}}\rangle = \frac1{\lambda^k}\langle f, e_{\pm 1}\rangle$ for all $k \in \mathbb{N}$.
We have
$$\|f\|^2 = \sum_{n\in\mathbb{Z}}\left| \langle f, e_n\rangle \right|^2 = \left(\left|\langle f, e_1\right\rangle|^2 + \left|\langle f, e_{-1}\right\rangle|^2\right)\sum_{n\in\mathbb{N}}\frac1{|\lambda|^{2n}} + \left|\langle f, e_0\right\rangle|^2$$
The sum $\frac1{|\lambda|^{2n}}$ cannot converge because $|\lambda| \le 1$ so $\left\langle f, e_1\right\rangle = \left\langle f, e_{-1}\right\rangle = 0$ and hence $\langle f, e_n\rangle = 0$ for all $n \in \mathbb{Z} \setminus \{0\}$. Therefore $f = \langle f, e_0\rangle e_0$ so $f$ is a constant function. $Af = \lambda f$ now gives $\lambda = 1$.
Therefore $\sigma_p(A) = \{1\}$.
Now let $\lambda \in S(0,1)\setminus\{1\}$. Assume $f \perp \operatorname{Im}(A - \lambda I)$. We have $f \perp (A - \lambda I) e_n = e_{2n} - \lambda e_{n}$ which implies $\langle f, e_{2n}\rangle = \lambda\langle f, e_n\rangle$ for all $n \in \mathbb{Z}$.
This yields $\langle f, e_{\pm 2^k}\rangle = \lambda^k \langle f, e_{\pm 1}\rangle$ for all $k \in \mathbb{N}$. Left side converges to $0$ when $n\to\infty$ so $\lambda^k \langle f, e_{\pm 1}\rangle \xrightarrow{k\to\infty} 0$ also. If $|\lambda| = 1$, we conclude $\langle f, e_{\pm 1}\rangle  = 0, \forall k \in \mathbb{N}$ and also $(1-\lambda)\langle f, e_0\rangle = 0$ so $\langle f, e_0\rangle = 0$. Therefore $\langle f, e_n\rangle = 0$ for all $n\in\mathbb{Z}$ so $f = 0$.
We conclude that $\overline{\operatorname{Im}(A - \lambda I)} = L^{2}[0,1]$ when $|\lambda| = 1$.
On the other hand, if $|\lambda| < 1$ then check that $f = \sum_{n=1}^\infty \lambda^k e_{2^k} \perp \operatorname{Im}(A - \lambda I)$ so $\overline{\operatorname{Im}(A - \lambda I)} \ne L^{2}[0,1]$. We conclude that $\sigma_r(A) = B(0,1)$.
The spectrum is a closed set so we conclude $\sigma(A) = \overline{B}(0,1)$. Finally, $\sigma_c(A) = S(0,1) \setminus \{1\}$.
To conclude:
$$\sigma(A) = \overline{B}(0,1)$$
$$\sigma_p(A) = \{1\}$$
$$\sigma_r(A) = B(0,1)$$
$$\sigma_c(A) = S(0,1)\setminus \{1\}$$

Find the spectrum of a given operator


Modal ao acessar o site

Question: Alguém poderia me passar um código simples de jquery?
Só preciso que um modal ( div ) apareça quando o site for acessado e contenha um botão "fechar".
Answer: Com jquery

$("#myModal").modal('show');
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

                 <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Modal

Bla bla bla

blablabla

                 <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

Basicamente criada com CSS.

$(document).ready(function(){
    $(".close").click(function(){
        $("#openModal").hide();
    });
});
 .modalDialog > div {
  width: 400px;
  position: relative;
  margin: 10% auto;
  padding: 5px 20px 13px 20px;
  border-radius: 10px;
  background: #fff;
  background: -moz-linear-gradient(#fff, #999);
  background: -webkit-linear-gradient(#fff, #999);
  background: -o-linear-gradient(#fff, #999);
 }

 .close {
  background: #606061;
  color: #FFFFFF;
  line-height: 25px;
  position: absolute;
  right: -12px;
  text-align: center;
  top: -10px;
  width: 24px;
  text-decoration: none;
  font-weight: bold;
  -webkit-border-radius: 12px;
  -moz-border-radius: 12px;
  border-radius: 12px;
  -moz-box-shadow: 1px 1px 3px #000;
  -webkit-box-shadow: 1px 1px 3px #000;
  box-shadow: 1px 1px 3px #000;
 }

 .close:hover { background: #00d9ff; }

  X

Janela Modal

Esta é uma simples janela de modal.

Você pode fazer qualquer coisa aqui, página de Login, pop-ups, ou formulários

Modal ao acessar o site