How do I deny all requests not from cloudflare?

Question: I've recently gotten denial of service attacks from multiple proxy ips, so I installed cloudflare to prevent this. Then I started noticing that they're bypassing cloudflare by connecting directly to the server's ip address and forging the host header.
What is the most performant way to return 403 on connections that aren't from the 18 ip addresses used by cloudflare?
I tried denying all then explicitly allowing the cloudflare ips but this doesn't work since I've set it up so that CF-Connecting-IP sets the ip allow tests for.
I'm using nginx 1.6.0.
Comment: Might be easier to do it with `iptables` rules by allowing traffic from the CloudFlare IPs + your own IPs (so you can check if your site is up without going through CloudFlare) and drop everything else sent to port 80. This way the traffic never reaches your web server.
Comment: Not sure if I understand your question. When they DoS me from cloudflare they just get locked out by cloudflare's captcha page. Now they're bypassing cloudflare by going straight to my actual IP.
Comment: Hmm. The iptables solution seems to work fine. Thanks!
I used the longer script here: http://rietta.com/blog/2012/09/10/using-iptables-to-require-cloudflare/ for anyone wondering.

I'm going to leave this question open in case someone comes up with a nginx-config-file solution so people googling this problem can see it.
Comment: What if they DoS you from Cloudflare?
Comment: https://blog.cloudflare.com/ddos-prevention-protecting-the-origin/
Answer: As described here, you can only allow ip addresses from cloudflare.
https://erichelgeson.github.io/blog/2014/01/18/whitelisting-cloudflare-in-nginx/
# https://www.cloudflare.com/ips
# IPv4
allow 18.104.22.168/22;
allow 220.127.116.11/22;
allow 22.214.171.124/22;
allow 22.214.171.124/12;
allow 126.96.36.199/18;
allow 188.8.131.52/22;
allow 22.214.171.124/18;
allow 184.108.40.206/15;
allow 126.96.36.199/13;
allow 220.127.116.11/20;
allow 22.214.171.124/20;
allow 22.214.171.124/20;
allow 184.108.40.206/22;
allow 126.96.36.199/17;

# IPv6
allow 2400:cb00::/32;
allow 2405:b500::/32;
allow 2606:4700::/32;
allow 2803:f800::/32;
allow 2c0f:f248::/32;
allow 2a06:98c0::/29;

deny all; # deny all remaining ips

Note that you will have to update this configuration every one in a while as Cloudflare's IP address ranges might change. To autogenerate this configuration you can use this script
Comment: This also works `(curl -s https://www.cloudflare.com/ips-v{4,6} | sed "s|^|allow |g" | sed "s|\$|;|g" && echo "deny all;")>cloudflare-only.conf`
Comment: It's not working with `set_real_ip_from ` together :(
Comment: @a55 awesome, I've created a .sh command with that, then on my nginx.conf I included the generated file and works perfectly ! Thank you !
Answer: The only solution I came up with that can be done with nginx by itself requires nginx version 1.9.7 or higher.
You can use the ngx_http_geo_module to identify and return a 403 response for any ip's that aren't cloudflare ip's.
Using this geo block.
geo $realip_remote_addr $cloudflare_ip {
    default          0;
    188.8.131.52/22  1;
    188.8.131.52/22  1;
    188.8.131.52/22    1;
    18.104.22.168/12    1;
    22.214.171.124/18 1;
    188.8.131.52/22    1;
    220.127.116.11/18  1;
    188.8.131.52/15   1;
    18.104.22.168/13    1;
    220.127.116.11/20  1;
    22.214.171.124/20  1;
    220.127.116.11/20  1;
    18.104.22.168/22 1;
    22.214.171.124/17  1;
    188.8.131.52/21  1;
    2400:cb00::/32   1;
    2405:8100::/32   1;
    2405:b500::/32   1;
    2606:4700::/32   1;
    2803:f800::/32   1;
    2c0f:f248::/32   1;
    2a06:98c0::/29   1;
}

You can then add this to your server block.
if ($cloudflare_ip != 1) {
    return 403;
}

Which will return a 403 for any connections not originating from a $cloudflare_ip.
This works because I'm using $realip_remote_addr in the geo block which keeps the original client address when using real_ip_header CF-Connecting-IP.
Comment: It works great, I'd like to mention that the geo module works on http level (so no server or location blocks), the 403 part works everywhere.
Answer: The most performant way is a hardware firewall in front of the server.  Or asking your datacenter/upstream provider for help mitigating attack.
Block things it in the webserver or iptables may help, but still uses bandwidth and system resources so DoS attacks are still possible.  What you want is to block the traffic as far upstream as possible - so the traffic never reaches your server, and doesn't flood your link to the rest of the world.  A hardware firewall can filter traffic much, much faster than your webserver, and uses no server resources.  You will want them to allow traffic from cloudflare as well as your office or other servers for when you need to connect directly.
Changing the IP of the server may help as well - only cloudflare should need to know the new IP, don't publish it in public DNS records.
Answer: I have merged the answers from jhilliar and from user6327 to get something OK to me. When using Cloudflare, you usually wish getting the origin client IP in your logs thanks to "set_real_ip_from".
But mixing set_real_ip_from and the solution given by user6327 does not work (as pointed by Sky). That's why Jhilliar solution with geo module should be used (and it seems to be more flexible by the way).
But it would be better to use a script to update cloudlfare IP list as user6327 has suggested. So here's the script.
Answer: Here's a one-liner that generate the geo mapping from Cloudflare's IPs.
Not necessarily the cutest one, perhaps a pro can correct me. I'm unable to fetch and parse v4 & v6 in one command because the files lack a carriage return at the end and the first v6 address is concatenated to the last v4.
(echo -e "geo \$realip_remote_addr \$cloudflare_ip {\n\tdefault\t0;" && curl -s https://www.cloudflare.com/ips-v4 | sed "s|^|\t|g" | sed "s|\$|\t1;|g" && echo -e  && curl -s https://www.cloudflare.com/ips-v6 | sed "s|^|\t|g" | sed "s|\$|\t1;|g" && echo -e "\n}")>cloudflare-only.conf

Inspired by a55 script above


jQuery UI Autocomplete, How to enable autocomplete only if user type in a special charactor?

Question: I have Autocomplete attached to different types of input box. It loads items whenever user start type in anything which is fine. But,in one of the textarea, I want to disable autocomplete by default, and enable it if user type in "@". How to do this?
Answer: This will do the trick:
$('textarea').autocomplete({
    source: availableTags
})
    .autocomplete('disable')
    .on('keypress', function(event) {
        //Detect whether '@' was keyed.
        if (event.shiftKey && event.keyCode === 64) {
            $(this).autocomplete('enable');
            return false;
        }
    });

Live Example - http://jsfiddle.net/tj_vantoll/rRu4A/3
Comment: I typed in @A in the Live Example, it doesn't start loading
Comment: How about something like this - http://jsfiddle.net/tj_vantoll/rRu4A/4/?  You might also want to look into this plugin - http://imankulov.github.com/asuggest/.
Comment: That's because "@" isn't in any of the options.  I altered my example so that the "@" never actually appears in the `textarea`, it just turns on the functionality.  Try it again.
Comment: @Jenny Type "@a".  "@" will activate the autocomplete and "a" will show you some options.
Comment: I typed in "@a" , it doesn't trigger anything.
Comment: I just tried IE, it works. But Firefox does't. Firefox still shows "@" and no response. But I need to show "@", just like this site, when there's "@", user will receive message of notice. Can we use another way to do this?
Comment: Perfectly working! Thanks for your helping! I will study the plugin you recommended.
Answer: I found the accepted answer worked well enough if you started off your input with '@' but not so well when the '@' was embedded deeper down in the middle of a paragraph.  I am still working on a better solution, but this is what I have so far.

$(document).ready(function() {
        function getCurrentWord(el) {
            var $t = $(el),
                v = $t.val(),
                minLength = $t.data('uiAutocomplete').options.minLength,
                start = $t.prop('selectionStart'),
                end = $t.prop('selectionEnd'),
                re = /(\@[^\s]+)/g,
                matches = [], m;

            if (start !== end) // user has text highlighted
                return false;

            while((m = re.exec(v)) != null) {
                var endIndex = m.index + m[1].length;
                if (start >= m.index && start <= endIndex) {
                    var result = {
                        start: m.index,
                        end: endIndex,
                        value: m[1]
                    };
                    return result.value.length >= minLength && result;
                }
            }
            return false;
        }

        $('textarea').autocomplete({
            minLength: 2,
        focus: function() {
          //  Don't let navigating the menu overwrite textarea value
          return false;
        },
            search: function(event, ui) {
                var word = getCurrentWord(this);
                if (word) return word.value;
                return false;
            },
        select: function(event, ui) {
          var fullValue = ui.item.value;
          var target = getCurrentWord(this);
          var value = $(this).val();
          if (target)
            $(this).val(
                value.slice(0, target.start)
                + fullValue
                + value.slice(target.end)
              );

                  return false;
        },
        source: function(req, response) {
          var word = getCurrentWord(this.element);
          response([
            'Adam',
            'Alice',
            'Bjorn',
            'Cathryn',
            'Chris',
            'David',
            'Edward',
            'Francis',
            'George',
            'Hermen',
            'Heidi',
            'Issac',
            'Jennifer',
            'Katie',
            'Kristen',
            'Larry',
            'Melinda',
            'Nina',
            'Oliver',
            'Peter',
            'Quagmire',
            'Rodger',
            'Stacey',
            'Trevor',
            'Ulysses',
            'Victor',
            'William'
            ].map(function(s) { return '@' + s; })
             .filter(function(s) {
                if (!word) return true;
                else return s.toLowerCase().startsWith(word.value.toLowerCase());
             }));
        }
      });
});

<textarea></textarea>


Migrating sha1 user passwords into drupal 7

Question: I have an old zend 1.8 cms site and I wish to import users into a drupal 7 site so that a user can login with their sha1 password without having to changing it. Once verified convert the submitted password to drupal 7 password in the users table. I would guess I would need to import users without their passwords into the users table and create a separate table to store their sha1 passwords in the database. I would be very grateful if someone can point me in the right direction to achieve this.
<code><?php
$str = 'password';//Users password

if (sha1($str) === '5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8') {//from imported users table
    echo "Your password is valid";
    //let user into the site
    //insert into user.pass table password $str $S$DUygh2WJWU3caajVD3mgjIHShYgOTbaZnt9uC8lf6fMNo9lX50nr
}
?>
</code>
Answer: You can use the Migrate framework and easily import accounts into Drupal 7 and it will take care of this for you. Don't bother with separate tables and password lookups and all that.
https://www.drupal.org/project/migrate
https://www.jeffgeerling.com/blogs/jeff-geerling/migrating-drupal-7-users-site
I can't find an actual example of a class that handles users into Drupal 7,
but the Migrate docs are very thorough.
Edit - here is an example: https://cgit.drupalcode.org/migrate/tree/migrate_example/beer.inc#n212
But in your case you will want to define another database connection in settings.php and define that as the source of the migration.


onNewIntent() not called after onResume()

Question: Flow:

Open app (MainActivity)
Press home button ( calling onPause() in activity )
Starting same activity, with different intent
Intent intent = Utils.createIntent(....., this, MainActivity.class); // this will add some extra to our intent
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);

Nothing happens.
onCreate() gets called. (onDestroy wasn't called)
onResume() is called

My activity in xml
<activity
            android:name=".ui.activities.MainActivity"
            android:launchMode="singleTop"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="adjustPan" />

NOte: if I don't press home button (app doesn't pause), onNewIntent will be called correctly.
Comment: Where is your onRsume code?
Comment: @NiravRanpara I do nothing on onResume. I just set a breakpoint to see if is called.
Comment: i thing android:launchMode="singleTop" is the problem. Try to remove this and check
Comment: Try to set this Flags: `intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);`
Comment: @VladimirKulyk this fixed my problem. Thank you.
Answer: Try to set this Flags:
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

You are welcome!


Ukulele: how to avoid hurting my hand on the nut?

Question: I recently started playing the ukulele, but after some time practicing, my left hand starts to hurt from rubbing against the nut. It only starts to hurt after playing for some time, but it still is keeping me from playing as much as I would like to.
The edge of the nut is hurting my hand:

The part of my hand that hurts is in the red circle:

Me, playing a G7 chord. When I switch chord, my hand is going to brush against the edge of the nut.

When I play a D or an Eb6 chord, my hand is even directly against the (pointy-ish) edge of the nut, and if my hand is already irritated from before it hurts a bit too.
What can I do to avoid this pain? Am I holding my left hand wrong? Should I file down the edge of the nut (or have a professional file it down for me)?
Comment: Sandpaper it, but also adjust your hand position so the thumb is pointing straight up the neck and is right in the middle of the back of it. This brings your fingers parallel to the frets and makes everything easier, as well as not abrading with the hardware..
Comment: Your fingers look like they're more "collapsed" towards that neck than John Belzaguy's. Like  Marquis of Lorne said, thumb position, and try moving it so it's closer to the fretting fingers.
Comment: Your first finger in particular looks as though it is bending backwards at the first joint. The other fingers have a better curve. I suspect if you fix that, the problem will go away.
Answer: I agree with the other two answers, knocking that corner down a bit with either sandpaper or a fine file will help but I would like to also offer two tips on your technique.
There isn't a reason for your hand to make contact with the neck in that spot. It looks like your thumb is in a pretty good spot but try placing it just a hair lower, more towards the center of the neck. This will add a little bit of inward curve to your palm and wrist which will in turn will move the base of the index finger away from the neck.
It is hard to see in the photo but it looks like the first joint of your index finger (closest to the tip) might be flat and the first joint on the other fingers have a curve. Unless you're playing a barre it should also have a little curve to it. This will help add a bit of distance from the nut too.
Here are a few pics that show my suggestions. This is a soprano Ukelele so it's very small but I think you can get the idea.
Comment: Yes; press with your fingertips, not with the pad.
Answer: Sandpaper. It sounds like a joke, but the nut is there to hold the string, and the sharp edges are not necessary. Round it down for comfort.
Answer: You could round off that edge of the nut, preferrably with a file. As long as the slot for the top string is still integral, there's no problem. And/or, you could try a fingerless glove. You won't be the first to play fretted instruments using a gloved hand - even a full glove.
EDIT: it also might help if you moved your elbow away from your body.That in itself will have two results: using the thumb as a fulcrum, there's no need to press as hard with your hand itself, and, it'll move the hurty bit away from thee nut.
Answer: Please don't think about sandpapering or chiseling your instrument. This is simply a technique issue that you need to work on. You problem is with your first knuckle of the first finger in your left hand. You need to keep your fingers in a rounded configuration, similar to what it would be if you were holding something with your left hand. At the present time, your first finger is flattened against the neck and this is affecting the position of your hand. @John's answer is correct.
Comment: The nut is removable. In the photo, the ends are very square. It would make no difference to the playability of the instrument to round off the nut as long as you don't go near the slot. I personally would take the strings off and remove the nut before reshaping.  Having said all of that, I agree that a good left hand position will make a big difference.
Answer: Your thumb isn't along the middle of the neck. You're gripping/choking the neck.
Attempt playing any stringed instrument without the use of your thumb at all, at least in short bursts of scale practice. This can help ease you out of bad form.
Try to keep your thumb vertical and along the 'skunk line' that is on most stringed instruments.
That part of your hand should float away from the fretboard if the thumb is placed appropriately. Also, it's hard, but keep the tips of your fingers on the strings, so that force is being applied downward and not diagonally.
Comment: While a skunk line may be added for aesthetic purposes only, it originates from guitars and basses which use a truss rod inside the neck. To place the rod, the instrument manufacturer cuts a nut into the wood, places the rod, and then seals up the slit with a different wood to create the skunk stripe. This is purely a requirement for instruments with a very long neck in relation to string tension. An ukulele has a very short neck by definition, and it uses only 4 strings instead of 6 as guitars do. As such, I guess you won't find an ukulele with a truss rod, and very few with skunk stripes.


How to enable the dropdown list on a specific radio button

Question: I am trying to enable the dropdown list when the user select the radio button with a id =9, for some reason the jquery function is not working
For debugging purpose, i've tried to alert the selected id but it's null
Any thoughs?
C# code
  protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            string constr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
            using (MySqlConnection con = new MySqlConnection(constr))
            {
                string query = "SELECT * FROM case_cat_lv1";
                using (MySqlCommand cmd = new MySqlCommand(query))
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = con;
                    con.Open();
                    rblFruits.DataSource = cmd.ExecuteReader();
                    rblFruits.DataTextField = "category_name";
                    rblFruits.DataValueField = "id";
                    rblFruits.DataBind();
                    con.Close();
                }
            }
        }
    }

ASP.NET .aspx
<form id="form1" runat="server">

<asp:RadioButtonList ID="rblFruits" runat="server"    OnCheckedChanged="air_CheckedChanged" class="radio">
 </asp:RadioButtonList>

<asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="Submit" />

  <asp:DropDownList  ID="airlist" runat="server"  Font-Size="20px" class="dropdown">
    <asp:ListItem>Air India</asp:ListItem>
    <asp:ListItem>Kingfisher</asp:ListItem>
    <asp:ListItem>Jet Airways</asp:ListItem>
    <asp:ListItem>Spice Jet</asp:ListItem>
 </asp:DropDownList>

</form>

Comment: Try `$(this).find(":checked").val();` instead of `$(this).val()`. And if you wabt `id` of selected radio button then `$(this).find(":checked").attr("id")`.
Answer: Try $(this).find(":checked").val(); instead of $(this).val(). And if you want id of selected radio button then $(this).find(":checked").attr("id").
To enable dropdown list you can remove attribute disabled. It should work.
$('.dropdown').removeAttr("disabled");

For disabling your code will work fine.
$('.dropdown').attr("disabled", true);

Comment: @ Karan i notice the dropdown list still cant enabled
Comment: @ Karan but when i pick other radio btn, the dropdown list remain enabled instead of disabled
Answer: A few of things to consider. ASP.net webforms can mangle ids, RadioButtonList is not an HTML entity and is rendered as radio buttons with their own ids and values, finally you also have OnCheckedChanged="air_CheckedChanged" as a server side event handler which could be causing you problems.
With these kinds of issues with .net WebForms, always check the rendered HTML to see if it is what you were expecting.
Here's how I'd do it:
<form id="form1" runat="server">

<asp:RadioButtonList ID="rblFruits" runat="server"     class="radio">
 </asp:RadioButtonList>

<asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="Submit" />

  <asp:DropDownList  ID="airlist" runat="server"  Font-Size="20px" class="dropdown">
    <asp:ListItem>Air India</asp:ListItem>
    <asp:ListItem>Kingfisher</asp:ListItem>
    <asp:ListItem>Jet Airways</asp:ListItem>
    <asp:ListItem>Spice Jet</asp:ListItem>
 </asp:DropDownList>

</form>

See also: http://api.jquery.com/prop/


Error ao tentar instalar yowsup: Unable to find vcvarsall.bat

Question: Estou tentando instalar um aplicativo que realiza o registro de celulares no Whatsapp.
Eu tentei usar o  comando abaixo:
python setup.py install

E ocorre o seguinte erro:

error: Setup script exited with error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat).

Alguem sabe por que acontece este erro?
Agradeço desde já pelas respostas.
Comment: Microsoft Visual C++ 10.0 is required, já tentou instalá-lo?
Comment: já esta instalado tenho sql server e o visual studio , e já verifiquei que já se encontra instalado o visual c++ 10.0 não  sei o motivo do erro ainda
Comment: Se o Visual Studio já está instalado, verifique se está acessível por linha de comando. Abra um terminal e digite "vcvarsall.bat". Se a mensagem for de comando não encontrado, procure no seu computador por este arquivo e adicione o diretório na variável de sistema PATH. Abs!
Comment: Ok @FernandoMacedo irei tentar fazer isso. Obrigado
Comment: @JacobdeOliveira Tenho um post sobre como instalar o Python no Windows e configurar um compilador, pode ser que ajude: http://fernandomacedo.com/programacao/instalando-python-no-windows/
Comment: okay vou verificar o site obrigado @FernandoMacedo!
Comment: funcionou @FernandoMacedo coloquei vcvarsall.bat no path e funcionou muito obrigado :)
Comment: @JacobdeOliveira Posso colocar como resposta vc marca como a resposta certa?
Answer: Se o Visual Studio já está instalado, verifique se está acessível por linha de comando.
Abra um terminal e digite:
vcvarsall.bat

Se a mensagem for de comando não encontrado, procure no seu computador por este arquivo e adicione o diretório na variável de sistema PATH.
Tenho um post sobre como instalar o Python no Windows e configurar um compilador, pode ser que ajude: http://fernandomacedo.com/programacao/instalando-python-no-windows


A question while pvoing existence bi-invariant Volume element on a compact and connected Lie group

Question: I have a question while reading the following proof on William M.Boothby's textbook :

Thm3.6. An oriented, compact, conncted Lie group G has a unique bi-invariant volume element $\Omega$ such that $Vol G =1$.

The question I want to ask is the existence part. Since the author has already showed that every Lie group has a left-invariant volume element (as the $Corollary ~3.5)  $, he verifies that $\Omega$ is right invariant (volume element). Thus, he shows that $Ad(g)^{*} \Omega_{e}= \Omega_{e}$. When considering $Ad:G \to gl(\mathfrak{g}), g \mapsto \sum_{i=1}^{n} \alpha_{ij}(g)X_i$, and $g \mapsto (\alpha_{ij}(g))$ defines a $C^{\infty}$-homomorphism of $G \to Gl(n,\mathbb{R})$ Thus, $Ad(g)^{*} \Omega_{e}= (det(\alpha_{ij}))^{1/2}\Omega_{e}$. But I do not understand this part on the textbook:

However, Since G is compact and connceted, the same applies to its
image under the $C^{\infty}$-homomorphism of $G \to \mathbb{R}^{*}$,the
multiplicative group of nonzero real numbers. However, the only
compact connceted subgroup of $\mathbb{R}^{*}$ is $+1$...... (*)

Obviously, since (*) holds, in other words, $(det(\alpha_{ij}))^{1/2}=+1$ the existence of bi-invariant volume element is verified, but I don't know why the value of the determinant is only $+1$ just because of a compact and connected Lie group G.
Comment: Are you saying you do not know how to show that the only compact, connected subgroup of $\Bbb R$ is $\{1\}$?
Comment: @TedShifrin  Yes, Again, I want to know why determinient of adjoint matrix is  $+1$ on the given condition (compact and connected Lie group with left-invariant volume element)
Comment: edit : Adoint matrix --> Ad(g) (Adjoint representaion of the Lie group)
Answer: Suppose $H\subset\Bbb R^*$ is a compact, connected subgroup. Then $H$ is a closed interval $[a,b]\subset\Bbb R_+$. Since $H^2\subset H$, we have $a^2\ge a$ and $b^2\le b$, so $b\le 1\le a$, which says that $a=b=1$ and $H=\{1\}$.
Comment: Thank you for answering :) But, is it right $h^2 \in H$ instead of $H^2 \subset H$ ?
Comment: It is correct as I said it. Put a "for all $h\in H$" with your version and it's the identical statement.


Add node method for a double linked list?

Question: I currently have this but I want to make my list into a double linked list and can't work out how to do.
public void addDNode(DNode v)
{
    if(header == tail)
    {

        header = v;
    }
    else
    {
        DNode current = header;
        while (current.nextNode() != null)
        {
            current = current.nextNode();
        }
        current.setNext(v);
    }
}

Comment: @user979236: Then how did you write this code?
Comment: java.util.LinkedList is double-linked list. Don't you want ot use it or just look inside add() method?
Comment: The way to solve all linked-list problems is to draw a diagram.  This will help you establish precisely how many pointers/references need to be updated.
Answer: public void addDNode(DNode v) {
    if (header == null) {  // means list is empty, so add first element
        if (tail != null)
            throw new AssertionError(); // if head points to null then tail should too

        header = v;
        tail = header;  // first element so (head == tail)
    } else {
        tail.setNext(v);
        v.setPrev(tail);
        v.setNext(null);
        tail = v;
    }
}

Comment: It's generally frowned-upon to just give people complete code snippets for their homework problems...
Comment: Thankyou but what is the variable last?
Comment: Only thing that's missing is an overloaded `addDNode()` method that does the same thing.
Comment: @Oli Sharp of you to notice; I only figured it out by going through his question history.
Answer: Here is what a doubly linked list is: doubly linked list article
This is a one way to implement it in Java: doubly linked list example
Search on the internet, try implementing it and then if you have some issues ask here ;)


Kolmogorov Distribution D statistics

Question: As far as I have searched the cumulative distribution function of , asymptotically (kolmogorov distribution) is given by Pr(≤)=1−2∑∞=1(−1)−1−222=2√∑∞=1−(2−1)22/(82).
But I can not obtain the proof of it. Could you provide me with the proof or share some documents, links about it?
Comment: Welcome to the site. It would help if you could format your question in LaTeX.
Answer: Let $Y_1, \ldots, Y_n \sim_{\text{iid}} dF$ and $\hat{F}_n$ the corresponding empirical cumulative distribution.
The Kolmogorov statistic for the assumption $F = G$ is $K_n = \sup |\hat{F}_n(x) - G(x)|$.
Under the null hypothesis $F=G$, one has
$$
\Pr\left(K_n > \frac{c}{\sqrt{n}}\right) \to
2 \sum_{k=1}^\infty (-1)^{k-1} \exp(-2k^2c^2).
$$
This result is proved in Billingsley' book Convergence of probability measures. The proof involves the Brownian motion.

Kolmogorov Distribution D statistics


Problem on Lagrange multipliers

Question: This problem has two parts:
$a)$ Let $k>0$, find the minimum of the function $f(x,y)=x+y$ over the set S=$\{(x,y) \in \mathbb R^2_{> 0}:xy=k\}$. $b)$ Prove that for every $(x,y) \in \mathbb R^2_{> 0}$ the inequality $\frac{x+y} {2}\geq \sqrt{xy}$ holds.$$$$
 I want to find the minimum of $f$ restricted to the level set $g(x,y)=k$. The function $f$ and $g$ are differentiable and $\nabla g(x,y)=(y,x)\neq0$ for every $(x,y) \in \mathbb R^2_{> 0}$, then I can apply lagrange multipliers to find the critical points of f restricted to that region. By the equation $\nabla f(x,y)=\lambda\nabla g(xy)$ I get that $(1,1)=\lambda (y,x)$, which means $x=y$. By the conditions of the problem, it is required that the points of the form $(x,x)$ live in the level set. So, the only critical point is $(\sqrt{k},\sqrt{k})$. $$$$My question is, how can I prove that at $(\sqrt{k},\sqrt{k})$, $f|_S$ attains a minimum?$$$$For part $b)$, let's assume I could prove that $f(\sqrt{k},\sqrt{k})$ is a minimum of $f|_S$.Then, for all $(x,y) \in S$ it immediately follows that $x+y\ge \sqrt{k}+\sqrt{k}=2\sqrt{k}$, so dividing both sides by $2$, I get $\frac{x+y} {2}\ge\sqrt{k}=\sqrt{xy}$. I don't see why this inequality would also hold for $(x,y) \in \mathbb R^2_{>0}\setminus S$
Answer: For (b), suppose that $x,y\in\Bbb R_{>0}$, and let $k=xy$; from (a) you know that $x+y\ge 2\sqrt{k}$ and hence that $\frac{x+y}2\ge\sqrt{xy}$.
For (a) you don't really need anything as fancy as Lagrange multipliers. You have $y=\frac{k}x$, so $x+y=x+\frac{k}x$; its derivative with respect to $x$ is $1-\frac{k}{x^2}$, which is increasing on $x>0$ and equal to $0$ at $x=\sqrt{k}$, so you have a minimum.
Comment: You're right, I was complicating it all. Thanks!
Comment: @user100106: You're welcome!
Answer: For (a), it is easier to use $y=\frac{k}{x}$ and minimize $\phi(x)= x+\frac{k}{x}$ on $(0,\infty)$. Since $\lim_{x \downarrow 0} \phi(x) = \lim_{x \to \infty} \phi(x) = \infty$, we see that $\phi$ has a minimum in $(0,\infty)$, hence $\phi'(x) = 0$ at this point. This gives $x = \sqrt{k}$, from which we get $\phi(x) \ge 2 \sqrt{k}$ for all $ x > 0$.
In particular, $x+y \ge 2 \sqrt{k}$ for all $x,y >0$ satisfying $xy = k$. Hence $x+y \ge 2 \sqrt{xy}$.
Answer: You already had proven that the point $ \ (\sqrt{k} \ ,  \sqrt{k}) \ $ is at the minimum when you made your gradient calculation.  You found that this point lies on the "level surface" $ \ x \ + \ y \ = \ 2\sqrt{k} \ $ , which represents a plane through the point with gradient $ \ \nabla f \ = \ \langle 1 \ , \ 1 \rangle \ $ there (really, everywhere on the plane).
For a line with slope $ \ m \ $ in the $ \ xy-$ plane, its direction vector is   $ \ \langle 1 \ , \ m \rangle $ ; the associated unit vector is u  =  $ \ \frac{1}{\sqrt{1 + m^2}} \ \langle 1 \ , \ m \rangle \ $ .  Consequently, the directional derivative at  $ \ (\sqrt{k} \ ,  \sqrt{k}) \ $ is
$$ D_{\mathbf{u}} \  f \ \ = \ \ \nabla f \ \centerdot \ \mathbf{u} \ \ = \ \ \langle 1 \ , \ 1 \rangle \ \centerdot \ \frac{1}{\sqrt{1 + m^2}} \ \langle 1 \ , \ m \rangle \ \ = \ \ \frac{1 \ + \ m}{\sqrt{1 + m^2}} \ \ , $$
which is positive for $ \  1 \ + \ m \ > \ 0 \ \ \Rightarrow \ \ m \ > \ -1 \ \ . $ Since $ \ S \ $ is restricted to the first quadrant, this condition is certainly met by any ray within this quadrant extending from $ \ (\sqrt{k} \ ,  \sqrt{k}) \  . $  So the directional derivative of $ \ f(x,y) \ $ in the level surface at this point is always positive, which tells us that the point marks the minimum for $ \ x \ + \ y \ $ on  $ \ xy \ = \ k \ $  .
[Note that we are abandoned by a "Hessian matrix" calculation, since the plane $ \ x \ + \ y \ = \ 2\sqrt{k} \ $ has no critical points; the second partial derivatives tell us nothing of use.]

Problem on Lagrange multipliers


Python Testing - Is this a safe way of writing my tests to avoid repeating long dictionaries in each test function

Question: I'm new to Python and experimenting with writing some tests for an API endpoint. Is the way that I'm mocking the puppy object safe below? In my tests, it is working the way I'd expect. Do I run the risk in the future of the tests stepping on each other and the object's value that I think I'm testing, actually be referencing an older value in memory?
Should I be using a different strategy?
<code>class PuppyTest(APITestCase):
    """ Test module for Puppy model """

    def mock_puppy(self):
        return {
            "name": "Max",
            "age": 3,
            "breed": "Bulldog"
        }

    def test_create_puppy_with_null_breed(self):
        """
        Ensure we can create a new puppy object with a null "breed" value
        """
        url = reverse('puppy')
        data = self.mock_puppy()
        data['breed'] = None # Updating breed value

        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    def test_create_puppy(self):
        """
        Ensure we can create a new puppy object.
        """
        url = reverse('puppy')
        data = self.mock_puppy() # returns original "breed" value "Bulldog"

        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
</code>
Answer:
Is the way that I'm mocking the puppy object safe below?

Yes

Do I run the risk in the future of the tests stepping on each other and the object's value that I think I'm testing, actually be referencing an older value in memory?

No

Should I be using a different strategy?

Your method is OK, with a new dict being created for each test.  However, since you're using pytest, it might be more typical to put that data into a fixture rather than a method.
Comment: Move it out of the class. Preferably, don't even use classes at all, just module level functions for tests.
Comment: Hey @wim, thank you for your response. Do I lose the ability to include the self, parameter with the fixture? I updated based on the documentation and am getting this error: "TypeError: test_create_puppy_with_null_breed() missing 1 required positional argument: 'mock_puppy'"


Setting element ID in GWT

Question: I am trying to add ID to GWT element. I have tried following code.
In SubscribeView.java file, existingFundRadioButton field is defined, I am setting an ID for it as follows:
DOM.setElementAttribute( existingFundRadioButton.getElement(),
                         "ID",
                         "existingFundRadioButton" )

I tried using existingFundRadioButton.getElement().setId("existingFundRadioButton") but it's not working.
This is my code.
<g:FlowPanel width="100%">
    <g:FlowPanel>

        <g:HTMLPanel ui:field='searchPanel' styleName="{res.fdcWidgets.box}">

                <colgroup>
                    <col width="25%" />
                    <col width="75%" />
                </colgroup>

                            <fdc:I18NRadioButton name="fund"
                                ui:field="existingFundRadioButton" checked="true"
                                messageKey="buy.existingFundLabel" />

                            <hli:HoldingsListBoxWidget ui:field="holdingsListBox" />

        </g:HTMLPanel>
    </g:FlowPanel>
    <g:FlowPanel styleName="{res.fdcWidgets.contentRightColumn}">
        <fund:FundInformationWidget ui:field="fundInformationWidget" />
    </g:FlowPanel>
</g:FlowPanel>

Comment: It is a nice practice to close the question if it gets solved either by choosing an answer or by posting your own answer. Stackoverflow would not be this much helpful if the questions did not get closed!!!
Answer: Old Solution
If you are stuck on a old version of GWT - For RadioButton we use a browser specific approach. We this by extending RadioButton.
MyRadioButton extends RadioButton{
        public void setId( String id )
        {
            getElement().setId( id );
            Element child = DOM.getChild( getElement(), 0 );
            DOM.setElementAttribute( child, "id", id + CONST_INPUT_ELEMENT );
            final Element e_label = DOM.getChild( getElement(), 1 );
            // Handling IE
            DOM.setElementAttribute( e_label, "htmlFor", id + CONST_LABEL_ELEMENT );
            // Handling Other Browsers
            DOM.setElementAttribute( e_label, "for", id + CONST_LABEL_ELEMENT );
        }
}

New Solution
For those lucky enough to have latest GWT that supports ensureDebugId across all widgets you can use ensureDebugId("someid") available in all ui elements inherited from UIObject!!!!
Comment: Thank you for reply. I tried using elementname.ensureDebugId("abc") and it worked.
Comment: Thanks to YOU!!! We never updated to this approach as the earlier one was working! Its time to update our wrappers :) . Of course the above answer might be needed in some older versions of GWT.
Comment: You can add ensureDebugId("abc") method in java code or You can set debugId attribute in ui.xml file...It worked for me

Setting element ID in GWT


every map $S^4\to S^2\times S^2$ has degree $0$

Question: I am working on Algebraic Topology in the past Quals.
"Prove that every map $S^4\to S^2\times S^2$ has degree $0$,
      i.e. the induced homomorphism in $H_4$ is $0$."
Here is how I approach: the first observation is that we can use Kunneth formula to compute $H_4(S^2\times S^2)=H_4(S^4)=\mathbb{Z}$. Since $S^4$ is simply connected, a map $f:S^4\to S^2\times S^2$ is lifted to a map to the universal cover $g:S^4\to S^2\times S^2$, which basically means nothing here. (this approach can be used to solve a similar problem: "any map $S^2\to S^1\times S^1$
is nullhomotopic" because the lift gives us more information.)
I'm stuck here. How do I solve this?
Answer: Here's a solution.
Translating degree into cohomology
We can translate degree into cohomological terms using the universal coefficient theorem.
We have natural short exact sequences
$$\newcommand\Ext{\operatorname{Ext}}\newcommand\Hom{\operatorname{Hom}}
0\to \Ext^1_{\Bbb{Z}}(H_{i-1}(X),\Bbb{Z})
\to H^i(X) \to \Hom(H_i(X),\Bbb{Z})\to 0
$$
which are split, though not naturally.
If $H_i$ is always free, or at least $H_{n-1}$ is free, then the $\Ext$ terms vanish, and we have a natural
isomorphism
$$H^n(X)\xrightarrow{\sim} \Hom(H_n(X),\Bbb{Z}).$$
Naturality means that for $f:X\to Y$,
$f^*:H^n(Y)\to H^n(X)$ corresponds under the isomorphism to
$\Hom(f_*,\Bbb{Z}) : \Hom(H_n(Y),\Bbb{Z})\to \Hom(H_n(X),\Bbb{Z})$.
Note that $\Hom$ is contravariant in its first argument, so the direction makes sense.
Thus if $X$ and $Y$ have chosen fundamental classes $[X]$ and $[Y]$, so that
$H_n(X)\cong \Bbb{Z}\{[X]\}$ and $H_n(Y)\cong \Bbb{Z}\{[Y]\}$, we know that
$f_*[X]=k[Y]$ for some integer $k$, which is the degree of $f$. ($\Bbb{Z}\{a,b,c,\ldots\}$ is notation for the free $\Bbb{Z}$-module on the set of generators.)
Then $H^n(X)\cong \Hom(H_n(X),\Bbb{Z})$ is also isomorphic to $\Bbb{Z}$, and is  generated by the map $\alpha_X:[X]\mapsto 1$. Similarly for $Y$.
We know that $f^*\alpha_Y = k'\alpha_X$ for some integer $k'$, which we might call the cohomological degree of $f$.
In fact,
since $f^*\alpha_Y = \alpha_Y\circ f_*$, we know
$$f^*\alpha_Y([X]) = \alpha_Y(f_*[X])=\alpha_Y(k[Y])=k\alpha_Y([Y])=k.$$
Therefore $k'=k$, so cohomological degree is the same as the usual degree, and we can just call both the degree and measure it using either homology or cohomology.
The cohomological one is more useful in our case, since we have additional structure on cohomology, namely the cup product.
Applying the cohomological version of degree to solve the problem
For cohomology, when all the Tor factors vanish, the Kunneth theorem gives an isomorphism of graded rings, not just groups. See the answers here and probably check Hatcher for a reference, though I haven't looked recently, but I think it's in there somewhere.
Now we know $H^*(S^2) \cong \Bbb{Z}[x_2]/(x_2^2)$, where $|x_2|=2$, so
$H^*(S^2\times S^2)=\Bbb{Z}[x_2,y_2]/(x_2^2,y_2^2)$, and
$H^*(S^4)=\Bbb{Z}[x_4]/(x_4^2)$, where $|x_4|=4$.
Then the induced map $f^*:H^*(S^2\times S^2)\to H^*(S^4)$ is determined by where it sends $x_2$ and $y_2$, and it has no choice but to send these to $0$, since $H^2(S^4)=0$. Thus
$f^*(x_2y_2) = f^*(x_2)f^*(y_2)=0$.
Thus the degree of $f$ is $0$.
Comment: Marcos G Neil, Yeah basically, actually let me expand on that. The details aren't really obvious.
Comment: @MarcosGNeil Edited.
Comment: degree is defined on homology. Are you saying we should use the universal coefficient theorem  to prove that it is the same when we can define the degree on cohomology?


Pass parameters in Spring data

Question: I wonder how to pass parameter to bean.xml.
If I write like this in bean.xml, it works as expected
<bean id="notificationReader" class="org.springframework.batch.item.database.JdbcCursorItemReader" scope="step">
        <property name="dataSource" ref="dataSource" />
     <property name="sql" value="SELECT r.EDCBATCH_OPEN_DATETIME As openDate FROM rev_acq_edcbatch r WHERE r.EDCBATCH_STATUS ='A'" />
    <property name="rowMapper">
    <bean name = "campaignMapper" class="rh.com.app.domain.AgingMapper">
            </bean>
        </property>
    </bean>

But if I write like this, I get error
  <property name="sql" value="SELECT r.EDCBATCH_OPEN_DATETIME As openDate FROM rev_acq_edcbatch r WHERE r.EDCBATCH_STATUS = #{jobParameters['edcbatchStatus']}" />

My bean.xml
 <task:scheduled-tasks>
            <task:scheduled ref="agingScheduler" method="run" cron="*/5 * * * * *" />
        </task:scheduled-tasks>

    <bean id="agingScheduler" class="rh.com.ap.AgingScheduler">
        <property name="jobLauncher" ref="jobLauncher" />
        <property name="agingJob" ref="agingJob" />
        <property name="mailClient" ref="mailClient" />
    </bean>

    <batch:job id="agingJob">
      <batch:step id="step1" next = "emailFile" >
                <batch:tasklet transaction-manager="transactionManager">
                    <batch:chunk reader="notificationReader" writer="notificationWriter" processor="notificationProcessor" commit-interval="10" />
                </batch:tasklet>
            </batch:step>
            <batch:step id="emailFile">
                <batch:tasklet ref="emailTasklet" />
            </batch:step>

            <batch:listeners>
                <batch:listener ref="jobListener" />
            </batch:listeners>
        </batch:job>

AgingScheduler
  JobParametersBuilder builder = new JobParametersBuilder();
            builder.addDate("date", new Date());
            builder.addString("fileName", "AgingReporting_" + PropertiseUtil.settlementDateyyyyMMdd());
            builder.addString("edcbatchStatus","A").toJobParameters();

Error
Job failed with following exceptions
exception :Failed to initialize the reader

Answer: Hello John,
You could create a subclass of JdbcCursorItemReader where you set #{jobParameters['edcbatchStatus']}
as a seperate parameter. And then use Springs InitializingBean to set
the Sql property. How about something like this?
class EdcBatchStatusItemReader extends     org.springframework.batch.item.database.JdbcCursorItemReader implements
org.springframework.beans.factory.InitializingBean {

    protected String batchStatus;

    public void getBatchStatus(String batchStatus) {
            this.batchStatus = batchStatus;
    }

    public void afterPropertiesSet() {
        setSql("SELECT r.EDCBATCH_OPEN_DATETIME As openDate FROM rev_acq_edcbatch r WHERE r.EDCBATCH_STATUS ='" + batchStatus + "'");
    }

}

and then leave sql out of the bean definition and use setBatchStatus instead:
<bean id="notificationReader" class="EdcBatchItemReader" scope="step">
    <property name="dataSource" ref="dataSource" />
    <property name="batchStatus" value="#{jobParameters['edcbatchStatus']}" />
    <property name="rowMapper">
        <bean name = "campaignMapper" class="rh.com.app.domain.AgingMapper">
        </bean>
    </property>
</bean>

Best wishes
Marc
Answer: PS the reason your code doesn't work is that Spring thinks #{jobParameters['edcbatchStatus']} is part of the SQL and doesn't interpret it. If you pass it as the complete value of a field it should work, assuming the syntax is correct.

Pass parameters in Spring data


How to add react-navigation in react-native?

Question: I followed every steps specified in the docs.Installed the specified packages and  While trying to run the app in android-emulator, I'm getting the error:
TypeError: (0, _stack.StackNavigator) is not a function. (In '(0, _stack.StackNavigator)()', '(0, _stack.StackNavigator)' is undefined

The following is content in my App.js file
import * as React from 'react';
import {NavigationContainer} from '@react-navigation/native';
import {StackNavigator} from '@react-navigation/stack';
import {View, Text} from 'react-native';
const Stack = StackNavigator();
function HomeScreen() {
  return (
    <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
      <Text>Home Screen</Text>
    </View>
  );
}
function DetailsScreen() {
  return (
    <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
      <Text>Detail Screen</Text>
    </View>
  );
}
const App = () => {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Details" component={DetailsScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
};
export default App;

The following is dependencies in my package.json file
 "dependencies": {
        "@react-native-community/masked-view": "^0.1.7",
        "@react-navigation/core": "^5.3.2",
        "@react-navigation/native": "^5.1.4",
        "@react-navigation/stack": "^5.2.9",
        "react": "16.11.0",
        "react-native": "0.62.1",
        "react-native-gesture-handler": "^1.6.1",
        "react-native-reanimated": "^1.7.1",
        "react-native-safe-area-context": "^0.7.3",
        "react-native-screens": "^2.4.0"
      }

As mentioned in the Docs, I tried placing the following code at the top of both index.js and App.js
import 'react-native-gesture-handler';

Answer: You're importing the wrong function import {StackNavigator} from '@react-navigation/stack';
instead it should be
import { createStackNavigator } from '@react-navigation/stack';
and
const Stack = createStackNavigator();
check the get started guide


In undestanding and investigating regression coefficients, what's the difference between the F test vs the T-test?

Question: suppose I do a basic linear regression and output my summary statistics.  One of the metrics that I would get is the p-value, which is derived from the t-statistics and tests the null hypothesis that the slope is equal to 0.
If I do an anova on the model, I would get the sum of squares metrics, along with an F value.  I understand that the F statistic tests the overall model by testing the null B1 = B2 = B3  = 0. However, there is also an individual P_value for the F statistic for each coefficient.
What is the different between the p_value for the F statistic vs the p_value for the T statistic?
Answer: The t-test and F-test are looking for evidence of different things. The F-test is measuring the variance between groups, while the t-test is measuring the difference in means between two groups.
In other words, the F-test will give evidence (low p-value) that the groups don't come from the same distribution if their sample variances are significantly different. The t-test gives evidence (low p-value) that the groups don't come from the same distribution if the differences in group means are significantly different.
Hope this helps!
Comment: thanks.  appreciate.  so I have definitly read those definitions before of the T-test and F test. So how does that relate to linear regression?

The null hypothesis for both t test and F test is beta = 0, so I'm not sure how that is related to variance between groups and variance in means.
Comment: For the t-test, the difference your are measuring is the difference between your calculated slope value (beta) and 0 (or whatever your null hypothesized value of beta is), and the SE is the standard error of the slope estimate. The F-test is testing that at least one of the betas is not equal to zero; essentially meaning the model does better than making predictions off a constant (aka just the intercept of the model).


Find all intersections of subsets.

Question: I am having trouble with what seems like it should be a simple problem. I am trying to find intersections of connections between multiple people but I want to include any intersection of connections found between any two of the sets.
For example, Let
$A$ = {January, February, March, April, May, August}
$R$ = {January, February, March, April, September, October, November, December}
$Y$ = {January, February, May, July}
Now, $A \cap R \cap Y$ = {January, February},
but $A \cap R$ = {January, February, March, April},
$A \cap Y$ = {January, February, May},
and $R \cap Y$ = {January, February}
So what I really want is {January, February, March, April, May}
Now, I may not just have $A, R, $ and $Y$, I may have a lot more to sift through. Is there a more simple principle that I am missing to group all of these intersections together as a subset?
One thing I thought of was creating a graph, but I am rusty on my graph algorithms. Any suggestions though would be great.
Thanks!
Answer: It looks like you want any month that is in more than one subset.  You can go through all the months and count how many subsets each one is in.  If it is greater than one, put it in your final list.
Comment: Ok, cool. Thanks. Is there not a more underlying principle that doesn't require me to go through each set and count how many times an element appears? I'm speaking from a programming standpoint I guess. It seems like that is really my only option though, huh?
Comment: Depending on how things are stored, it might be faster to make an array for the months, initialize to zero, then read each subset once and increment the elements of the array for each month that is in the subset.  This will be much better if most months are not in most subsets.  Say you had 5000 months and 3000 subsets.  The first answer would need $5000*3000$ inquiries.  The second would only need the total of the sizes of the $3000$ subsets.
Answer: The set you are after can be formalised thus:$ \bigcup\limits_{\substack{A,B \in I \\ A \ne B}} A\cap B$, where $I$ is your set of subsets (i.e. in the example you gave $I=\{A,R,Y\}$).
This will give you the set of elements that are in at least two of your subsets.
In terms of a programming standpoint, I think you would have to go through each month in turn and count how many subsets it is in. Once you count it twice you can add it to your result set and move on to the next month.

Find all intersections of subsets.


mySQL private/conn issues

Question: I'm having some issues with a 1&1 account a client of mine is hosted with.
I'm getting errors on lines 2 & 20 (denoted as bold below), which doesn't make sense as they're basic php functions.
I've used this same script dozens of times with no issues, until putting it on this 1&1 account. Is anyone seeing something I may be missing?
class Mysql
{
  private $conn;

  function __construct()
  {
    $this->conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or
       die('There was a problem connecting to the database.');
  }

  function verify_Username_and_Pass($un, $pwd)
  {
    $query = "SELECT * FROM users WHERE username = ? AND password = ? LIMIT 1";

    if ($stmt = $this->conn->prepare($query)) {
      $stmt->bind_param('ss', $un, $pwd);
      $stmt->execute();
    }
}

Thanks in advance!
EDIT:
thanks pinkgothic for reminding me to put the errors on here >.<
Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in /homepages/24/d100728/htdocs/members/classes/Mysql.php on line 6

^thats for the private class
Fatal error: Call to a member function on a non-object in /homepages/24/d100728/htdocs/members/classes/Mysql.php on line 20

^when the private line is commented out, im able to reach the login screen but get this error on submission.
Also, the database is running MySQL5.0.
Answer: If its failing on the private variable declaration, it could be running PHP 4, as there was no way to make private class properties til PHP 5.
Comment: your right, thats what it was. they still have the server at PHP Version 4.4.9. is there a workaround for this?
Comment: @Nick: You mean "aside from rewriting the code to downgrade it to PHP 4?" Not really.
Comment: Well, it may or may not work. But you can change the private to say var. And PHP4 also doesn't support the __construct method.  The old way was to make a function with the same name of the class for the constructor.  So change __contstruct to Mysql.
Comment: thanks for your help guys. after searching through obscure help pages in their 'knowledgebase', i found out they do offer PHP 5 access, you just have to rename all your files to .php5.

mySQL private/conn issues


SciPy Pearsonr p-value is returning value greater than 1

Question: I am using pearsonr to get statistical significance on some data. Below is the code I am using and also the output. The second value is the pvalue and should be between 0 and 1, so I'm confused as to how I am getting otherwise. tis is also the case on other values with very high correlations.
stats.pearsonr(dataset['Vertical Velocity'],dataset['Drop Height'])
(-0.9944267653880902, 4.500312000521201e-16)

Comment: Could you add an extract of the dataset ?
Answer: This: e-16 is the representation of exponential. In this case your number is to the MINUS 16, therefore your number is between 0-1.
4.500312000521201e-16 = 0.0000000000000004500312000521201


operator & overload and indexing in C++

Question: Is it possible to create an "address of" (&) operator overload that would allow passing an arg? So kind of a mixture between overloading the operator [] and operator &.
So regular [] overload can be used like this
val = myobj[arg];

where:
SomeReturnType MyClass::operator[](SomeArgType i)
{
   // Code to handle indexing
}

But if we want a pointer to that item, what I'm looking for would provide this use:
ptr = &myobj[arg];

Maybe this isn't possible directly, and I know there's other ways to achieve this, but if it is possible I do not know the syntax.
Comment: This sounds like an XY problem.  Can you detail a little more why you want to do this?
Comment: If you make it `SomeReturnType& MyClass::operator[](SomeArgType i)` you will get a pointer to the indexed element with `ptr = &myobj[arg];` without overloading the address-of operator.
Comment: Do you have a reason to overload `&`?
Comment: `ptr = &myobj[arg];` will work fine if `operator[]` returns by reference.
Comment: It depends on what `SomeReturnType ` is. You can code it to be a copy of the item, or a reference to it (which has some interesting features).
Answer: You do not need to overload adress of operator when operator[] returns a reference:
#include <iostream>

struct foo {
    int x;
    int& operator[](int){
        return x;
    }
};

int main() {
    foo f;
    std::cout << &f.x << "\n";
    std::cout << &f[42] << "\n";
}

Possible output:
0x7ffc8cd2d46c
0x7ffc8cd2d46c

The example uses only a single int, but it will be the same when operator[] is returning reference to an element of some container.
Returning a copy from operator[] and then get the adress of the original element is not possible via operator& overload (unless you return some proxy that holds both, the copy of the element and the adress of the original, from operator[]).

operator & overload and indexing in C++


Prove that $f(z) = |z|$ is not analytic.

Question: I do not fully grasp what it means to be analytic and therefore do not know the conditions on which I have to show in order to complete the proof.
Comment: Have you learned about the Cauchy-Riemann equations yet?
Comment: "I do not fully grasp what it means to be analytic" What *definition* have you read in the book?
Answer: If a function is analytic in a neighborhood of a point, then it satisfies the Cauchy-Riemann equations.
But we have
$$|z|=\sqrt{x^2+y^2}$$
Clearly, with $u=\sqrt{x^2+y^2}$ and $v=0$ we see that for $(x,y)\ne (0,0)$
$$\frac{\partial u}{\partial x}=\frac{x}{\sqrt{x^2+y^2}}\ne 0 =\frac{\partial v}{\partial y}$$
And for $z=0$, we see that $\lim_{\Delta \to 0}\frac{|0+\Delta z|-|0|}{\Delta z}$ fails to exist.
Therefore, $|z|$ is nowhere analytic.
Answer: Every analytic function is differentiable. But $f$ isn't, that is, the limit$$\lim_{z\to0}\frac{|z|}z$$does not exist (as in the reals). So, $f$ is not analytic.
Comment: You've shown only that $|z|$ is not analytic at $z=0$.  You'll need to augment this to show that it is nowhere analytic.
Answer: Given $z, a, t\ne0$, with $t>0$ real, we have
\begin{eqnarray}
\lim_{t\to0}\frac{|z+at|-|z|}{at}&=&\lim_{t\to0}\frac{|z+at|^2-|z|^2}{at(|z+at|+|z|)}=\lim_{t\to0}\frac{t(\bar{a}z+a\bar{z})+a^2t^2}{t(|z+at|+|z|)}\\&=&
\lim_{t\to0}\frac{\bar{a}z+a\bar{z}+at}{|z+at|+|z|}=\frac{\bar{a}z+a\bar{z}}{2|z|}
\end{eqnarray}
this shows two things: first, $f$ is not holomorphic for all $z\ne0$, and second if it were holomorphic it would have been at $z=0$. Since we also have
$$
\lim_{t\to0}\frac{|0+at|-|0|}{at}=\lim_{t\to0}\frac{|a|t
}{at}=\frac{|a|}{a}
$$
Hence $f$ is not holomorphic.


How to find the rows that meet some conditions in a sequence data set

Question: Here is the summary of my sequence data generated in the SPELL format. All sequences are supposed to have the same length of 1440, but the summary tells me that they are not the same (see "min/max sequence length:91/1440").
I want to find the rows:

that do not have the 1440 sequence length
that have missing states (*)
that have void elements (%)

Do you have any suggestions?
> summary(diary.seq)
 [>] sequence object created with TraMineR version 1.8-3
 [>] 4971 sequences in the data set, 4160 unique
 [>] min/max sequence length: 91/1440
 [>] alphabet (state labels):
     1=Cr (Cr)
     2=Ec (Ec)
     3=Eo (Eo)
     4=Hb (Hb)
     5=Hc (Hc)
     6=He (He)
     7=Hr (Hr)
     8=Hs (Hs)
     9=Ir (Ir)
     10=Lt (Lt)
     11=Or (Or)
     12=Pb (Pb)
      ...
 [>] dimensionality of the sequence space: 27360
 [>] colors: 1= 2= 3= 4= 5= 6= 7= 8= 9= 10= 11= 12= 13= 14= 15= 16= 17= 18= 19= 20=
 [>] symbol for missing state: *
 [>] symbol for void element: %

Answer: To select some sequences, you need to create a condition vector. For instance, you can select the sequences with a length lower than 1440 using the seqlength function. Here is an example with the "mvad" data set.
## Loading the library
library(TraMineR)
data(mvad)
## Defining sequence properties
mvad.alphabet <- c("employment", "FE", "HE", "joblessness", "school", "training")
mvad.lab <- c("employment", "further education", "higher education", "joblessness", "school", "training")
mvad.shortlab <- c("EM", "FE", "HE", "JL", "SC", "TR")
## The state sequence object.
mvad.seq <- seqdef(mvad, 17:86, alphabet = mvad.alphabet, states = mvad.shortlab, labels = mvad.lab, xtstep = 6)

Now we can compute sequence length and build the vector (here all sequences have the same length of 70, so it does not make a lot of sense...). We used "<=" otherwise no sequences are selected, but in your case, you should use "<".
condition <- seqlength(mvad.seq) <= 70
seqdplot(mvad.seq[condition, ])

To count the number of time a state appears in each sequence you can use the "seqistatd" function. For instance, if we want to select all sequences with the "JL" (joblessness) state, we can use:
state.count <- seqistatd(mvad.seq)
condition <- state.count[, "JL"] > 0
seqdplot(mvad.seq[condition, ])

You can use the same strategy for the "*" missing state. There is no need to count "%" (void), since this will lead exactly for the same result as using "seqlength".


Periodic "Batman" function?

Question: I'm just wondering, is there a function that when graphed displays periodic "Batman" logos. This question is inspired by "Batman" equation.
Thank you for your answers!
Answer: You can represent the function that takes a real $x=n\pi+t$, where $n$ is an integer and $\pi/2<t\leq \pi/2$ to $t$ as
$$\sin^{-1}(\sin(x)).$$
So, if you scale the range of input of your "Batman" function that give a real output to the range $(-\pi/2,\pi/2]$, and it can be represented as the zero set of some function $f(x,y)$, you can represent a "periodic Batman function" as the zero set of
$$f\left(\sin^{-1}\left(\sin(x)\right),y\right).$$

Periodic "Batman" function?


What's the difference between CAAnimation, CABasicAnimation, CAKeyFrameAnimation and the standard [UIView beginAnimations] Core Animation stuff?

Question: Are all these things basically the same? I did the exact same thing now with CAAnimation rather than using an simple UIView animation block. What are the big differences?
Answer: They are all interfaces to Core Animation. The various interfaces generally trade off simplicity versus control. Everything that you can do with a UIView animation block can be done with a CAKeyFrameAnimation, but you'll probably write more code to do to.
Comment: A UIView animation block pulls together the ideas of animation groups, transitions and transactions into a single interface, and it defines that interface in terms of the view. CAKeyFrameAnimation is likely the most complex to use of the concrete classes, but of course you could reach even further down and implement your own CAPropertyAnimation to get even more control (such as more complex timing), or you could implement your own CoreImage filters to create new CATransitions. So there are definitely more complex things than CAKeyFrameAnimation. But they're all part of the same framework.
Comment: I see... so UIView animation blocks are the most simple, while CKeyFrameAnimation is the most complex of them all?


Fullcalendar scheduler limit month view on screen and enable scroller (15 days on screen + 15 days to scroll)

Question: I have a fullcalendar scheduler on my web app.
The problem is that some event have long text, so I enabled this css:
.fc-timeline-event .fc-title {
        white-space: normal;
    }

Result is better but not acceptable yet cause events of 1 day one with long text, are not good to read. See events i've selected in red in the screenshot.

My question is: is it possible to force fullcalendar-scheduler to view on screen only 15 days (based on month) and others 15 outside screen enabling automatic horizontal scroller?
I tried: slotWidth: 300 option. It seem ok. Working good on desktop...but on mobile phone i'd like to set another value...
Answer: You asked

is it possible to force fullcalendar-scheduler to view on screen only 15 days

That part is quite easy to achieve using custom views:
views: {
  resourceTimelineFifteen: {
    type: "resourceTimeline",
    duration: { days: 15 },
    buttonText: "15 day",
    slotDuration: { days: 1}
  }
},

Demo: https://codepen.io/ADyson82/pen/YzzKdXv?&editable=true&editors=001
The other part of your requirement

others 15 outside screen enabling automatic horizontal scroller

is not really possible because the width of the slots and the width of the calendar is not known in advance until the calendar is rendered (and can even change if the screen resizes). So simply splitting the view into 15-day sections is probably the best compromise. The user can just click the "next" button to see the next set of dates.
N.B. This approach will not always result in the view starting exactly on month boundaries (either start of the month or half-way through it), because months are not all the same length. You could try and do something a bit cleverer with the visibleRange setting if you wanted to attempt to correct that, but I'll leave that as an exercise for you if you feel you need it.


stack install codecov-haskell failed with error

Question: I am trying to install codecov-haskell via stack using stack install codecov-haskell -v, I've got the following error:
2019-10-07 19:31:22.039891: [info] codecov-haskell> build
2019-10-07 19:31:22.040092: [debug] Run process within /tmp/stack30689/codecov-haskell-0.5.0/: /home/mkultra/.stack/setup-exe-cache/x86_64-linux-tinfo6/Cabal-simple_mPHDZzAJ_126.96.36.199_ghc-8.6.5 --builddir=.stack-work/dist/x86_64-linux-tinfo6/Cabal-22.214.171.124 build --ghc-options " -fdiagnostics-color=always"
2019-10-07 19:31:22.129625: [info] codecov-haskell> Preprocessing library for codecov-haskell-0.5.0..
2019-10-07 19:31:22.129758: [info] codecov-haskell> Building library for codecov-haskell-0.5.0..
2019-10-07 19:31:22.264569: [warn] codecov-haskell>
2019-10-07 19:31:22.264773: [warn] codecov-haskell> <no location info>: warning: [-Wmissing-home-modules]
2019-10-07 19:31:22.264869: [warn] codecov-haskell>     These modules are needed for compilation but not listed in your .cabal file's other-modules:
2019-10-07 19:31:22.264938: [warn] codecov-haskell>         Paths_codecov_haskell
2019-10-07 19:31:22.265078: [info] codecov-haskell> [1 of 9] Compiling Paths_codecov_haskell
2019-10-07 19:31:22.494452: [info] codecov-haskell> [2 of 9] Compiling Trace.Hpc.Codecov.Config
2019-10-07 19:31:22.534420: [info] codecov-haskell> [3 of 9] Compiling Trace.Hpc.Codecov.Paths
2019-10-07 19:31:22.714734: [info] codecov-haskell> [4 of 9] Compiling CodecovHaskellCmdLine
2019-10-07 19:31:24.097299: [info] codecov-haskell> [5 of 9] Compiling Trace.Hpc.Codecov.Types
2019-10-07 19:31:24.245865: [info] codecov-haskell> [6 of 9] Compiling Trace.Hpc.Codecov.Curl
2019-10-07 19:31:25.632324: [warn] codecov-haskell>
2019-10-07 19:31:25.632698: [warn] codecov-haskell> /tmp/stack30689/codecov-haskell-0.5.0/src/Trace/Hpc/Codecov/Curl.hs:55:20: error:
2019-10-07 19:31:25.632804: [warn] codecov-haskell>     • Couldn't match type 'IO (Maybe a)'
2019-10-07 19:31:25.632879: [warn] codecov-haskell>                      with 'RetryStatus -> IO (Maybe a)'
2019-10-07 19:31:25.632955: [warn] codecov-haskell>       Expected type: IO (Maybe a) -> IO (Maybe a)
2019-10-07 19:31:25.633025: [warn] codecov-haskell>         Actual type: (RetryStatus -> IO (Maybe a)) -> IO (Maybe a)
2019-10-07 19:31:25.633090: [warn] codecov-haskell>     • In the expression: retrying expRetryPolicy isNothingM
2019-10-07 19:31:25.633165: [warn] codecov-haskell>       In an equation for 'performWithRetry':
2019-10-07 19:31:25.633236: [warn] codecov-haskell>           performWithRetry
2019-10-07 19:31:25.633310: [warn] codecov-haskell>             = retrying expRetryPolicy isNothingM
2019-10-07 19:31:25.633382: [warn] codecov-haskell>             where
2019-10-07 19:31:25.633464: [warn] codecov-haskell>                 isNothingM _ = return . isNothing
2019-10-07 19:31:25.633537: [warn] codecov-haskell>     • Relevant bindings include
2019-10-07 19:31:25.633610: [warn] codecov-haskell>         performWithRetry :: IO (Maybe a) -> IO (Maybe a)
2019-10-07 19:31:25.633685: [warn] codecov-haskell>           (bound at src/Trace/Hpc/Codecov/Curl.hs:55:1)
2019-10-07 19:31:25.633758: [warn] codecov-haskell>    |
2019-10-07 19:31:25.633831: [warn] codecov-haskell> 55 | performWithRetry = retrying expRetryPolicy isNothingM
2019-10-07 19:31:25.633905: [warn] codecov-haskell>    |                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2019-10-07 19:31:25.703733: [warn] codecov-haskell>
2019-10-07 19:31:25.703992: [info] Completed 2 action(s).
2019-10-07 19:31:25.794909: [error]
--  While building package codecov-haskell-0.5.0 using:
      /home/mkultra/.stack/setup-exe-cache/x86_64-linux-tinfo6/Cabal-simple_mPHDZzAJ_22.214.171.124_ghc-8.6.5 --builddir=.stack-work/dist/x86_64-linux-tinfo6/Cabal-184.108.40.206 build --ghc-options " -fdiagnostics-color=always"
    Process exited with code: ExitFailure 1

I had a similar error using cabal install codecov-haskell and the same error on CI using stack install codecov-haskell.
Previously I had a problem with curl during codecov-haskell installation on my local machine. On CI didn't have any problem with it.
Any suggestion?
Stack version: 2.1.3
Description:    Ubuntu 19.04

Answer: There is a bug and merge request ready to be merged from Jul 26, 2017, for it.
Looks like the author doesn't support this project anymore.
Comment: I have dropped him an email, asking about the current project status.
Answer: You can fix this by doing something like this in cabal and stack:
resolver: lts-13.25
extra-deps:
  - github: guillaume-nargeot/codecov-haskell
    commit: 8448801f8d01624e4cd60420beb3fdc85c099576
packages:
  - .

You basically anchor a specific commit from github as your dependency that actually compiles!


A generic question on stochastic integrals

Question: What is the right approach to take and find the moments of the following:
$$\mathcal{Z}_t=\int\mathcal{W}_t^k\,d\mathcal{W}_t=?$$
$$\mathcal{W}_t \sim \mathcal{N}(0, t),\ k=2,3...$$
$$\operatorname{E}(\mathcal{Z}_t)=?$$
$$\operatorname{Var}(\mathcal{Z}_t)=?$$
I know that $\mathcal{Y}_t=\int\mathcal{W}_t\,d\mathcal{W}_t=\frac{\mathcal{W}_t^2-t}{2}$ and $\operatorname{E}(\mathcal{Y}_t)=0$. One can derive it from Ito's lemma and the fact that $\operatorname{Var}(\mathcal{W}_t)=t=\operatorname{E}(\mathcal{W}_t^2)$. Is there another way to prove it?
Is there also some generic rules to deal with $\int t\,d\mathcal{W}_t$ and $\int \mathcal{W}_t\,dt$?
Thanks!
Comment: Hint: A stochastic integral is a martingale that starts at zero. What does that say about its mean?
Comment: @byron-schmuland Thanks! Yes, it is always zero.
Answer: You might try working formally with
$$\mathbb{E}[\int e^{u \mathcal{W}_t}\,d\mathcal{W}_t]
  = \sum_{n=0}^\infty \frac{u^n}{n!} \int \mathcal{W}^n_t\,d\mathcal{W}_t$$
which should give you the right result.
To compute variances, recall the Ito isometry:
$$\mathbb{E}[(\int X_t\,d\mathcal{W}_t)^2] = \mathbb{E}[\int X_t^2\,dt]$$
which gives you a simpler integral to deal with.


Solving 1D Poisson equation using finite element method and understanding the Galerkin orthogonality

Question: Let's consider the following test problem
$$
u'' = 12x^2 - 36x + 18 \qquad u(0) = u(3) = 0
$$
Analytical solution is
$$
u(x) = (x-3)^2 x^2
$$
I'm solving this using the finite element method, discretizing the interval $I = [0, 3]$ to $I_1 = [0, 2]$ and $I_2 = [2, 3]$. So we have a linear basis function defined piecewise,
$$
v\left(x\right)=\begin{cases}
\frac{1}{2}x & x\in I_{1}\\
3-x & x\in I_{2}.
\end{cases}
$$
Weak form is
$$
\int u' v'\,\mathrm{d}x=\int fv\,\mathrm{d}x
$$
If I denote the only unknown in the problem as $u_2$, this leads to the equation ($k = \frac{1}{2}+1, f = 6 + 0$)
$$
\frac{3}{2}u_{2}=6
$$
and thus $u_2 = 4$. The exact function and it's FE approximation is visualized
here.
The result makes sense.
According to Wikipedia, in the Galerkin method, the error between the function and solution is orthogonal to $v_n$:
$$
a\left(u,v_{n}\right) - a\left(u_{n},v_{n}\right) = 0.
$$
However, if I integrate the above, as a result, I get $\frac{27}{20}$. To satisfy this condition above, $u_2$ needs to be $\frac{107}{20} = 5.35$. This result is visualized here. It also makes somehow sense, because it looks like the approximation is minimizing the error with respect to the accurate solution.
The basic question is what is the right solution and why? What I'm missing here? For me, the both options somehow make sense. In the first solution (which I'm believing to be the right one), the approximation is exact in point $x = 2$, while on the other hand, another solution looks like it is minimizing the error to the accurate solution, making sense in the energy norm.
Answer: "The basic question is what is the right solution and why?"
Both solutions are correct in the sense of different norms. If you want to talk about good or bad you always need to define a measure.
The first approximation is a simple interpolation method which tries to minimize the error in a collocative sense. There exists different point disbributions for which the error is quasi best considering (i) the $L_{\infty}$ norm or (ii) the Lebesgue constant or (iii) the condition number of the Vandermonde matrix.
The seconde approximation is a projection method which tries to minimize the error in an integral sense. Here the Galerkin approximation is quasi best considering an energy norm ($L_2$ based).
As an additional example the least squares approximation minimizes the $L_2$ norm.
Regards


The bound points of the homography that exchanges $A$, $B$, $C$ cyclically

Question:
An homographic transformation transforms three points $A$, $B$, $C$ of a line into the points $A'$, $B'$, $C'$. Prove that it transforms the bound points of the homography that exchanges $A$, $B$, $C$ cyclically into the the bound points of homography that exchanges $A'$, $B'$, $C'$ cyclically.

I'm studying homographies and I found this exercises, but I don't understand very well how to begin it. Any help would be appreciate.
Answer: Let $\pi$ be the projectivity that sends $(A,B,C)$ to $(A',B',C')$ and $\tau$ be the projectivity that sends $(A,B,C)$ to $(B,C,A)$. Let $X$ be a fixed point of $\tau$. Then $$\pi\circ\tau\circ\pi^{-1}$$ sends $(A',B',C',\pi(X))$ to $(B',C',A',\pi(X))$. It means that $\pi(X)$ is a fixed point of the projectivity that sends $(A',B',C')$ to $(B',C',A')$, as we had to prove.


Can you statistically compare two indirect effects in metaSEM?

Question: I'm conducting a meta-analytic structural equation model (MASEM) using the two-stage approach in metaSEM in R. I have fit a model with two indirect effects, and would like to compare them to see if they differ in magnitude. Is it possible to constrain the indirect effects to equality so I can compare this model fit to the full model? Or is there some other way of testing differences between indirect effects?
Stage 2 R code here:
stage2total <- wls(Cov = cordat, aCov = Acov,
              n = sum(unique(SGMAdata.db$N)), Amatrix = A, Smatrix = S,
              diag.constraints = TRUE,
              intervals.type = "LB",
              mx.algebras = list(
              depindirectEffect = mxAlgebra(b21*b42,
              name="depindirectEffect"), indepindirectEffect =
              mxAlgebra(b31*b43, name="indepindirectEffect"))
              )

summary(stage2total)

Answer: Adding such a constraint is a bit tricky, but you should get an LBCI for the difference between the two indirect effects by adding this in the mx.algebra list:
difference = mxAlgebra(depindirectEffect-indepindirectEffect,name="difference")
Comment: That worked! Thank you so much for your help.


Preg_match exact word (UA google tag)

Question: I'm trying to match the exact UA tag with a curl and preg_match
here is my code
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'http://symfony.com');
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_USERAGENT, 'UA checker');
    $result = curl_exec($ch);
    curl_close($ch);
    $chaine = "UA-89393-6;

Chaine being the UA tag entered by the user in DB.
    preg_match('~\b'.$chaine.'\b~', $result);

UA-89393-5 return false
UA-8939 return false
UA-89393- return true
UA-89393 return true
is there something wrong with my regex ?
how can i find the exact match of the UA string even after the dash ?
Comment: What is the exact content of `$chaine`?
Comment: where does `$tag` come from?
Comment: i've updated my asnwer with a concrete example
Comment: Still not reproducible, https://3v4l.org/4tgc6.
Answer:
Chaine being the UA tag entered by the user in DB.

If you're looking for an exact match of the tag the user entered, don't use regex. Just use strpos():
if (strpos($result, $chaine) !== false) {
    // found it
}

Answer: Preface
The best solution was given to you by Alex. This is not necessarily a good place to use regex, but it doesn't mean it's impossible. The reason regex is not really suitable for this is due to the multiple regex's that would be ideally needed for this (or the dynamic nature of your question, which requires parsing two string separately).
Answer
Since, however, you are looking for a regex-based solution, I've decided to come up with some regex hackery. This method would require you to concatenate the two UA codes on either side of a unique delimiter that would not show up in the UA codes. For simplicity, I've chosen ||.
Here is the regex that I've used to parse the UA codes and ensure they match according to your specifications.

Assuming the $chaine = UA-00000000-1
UA-00000000-0 return false
UA-0000000 return false
UA-00000000- return true
UA-00000000 return true

Note: Ensure that you are using the g and m modifiers if you want to test against multiple using newline characters to delimit the end of a line.
Concatenation
Assuming the simplest version of your code...
$chaine = 'UA-00000000-1';
$match = 'UA-00000000'; // or any other value
$delimiter = '||';

$string = "{$chaine}{$delimiter}{$match}";
// perform regex match against the above $string

Regex
^(UA-\d+)(-)(\d+)\|\|\1\2?((?=\3).*)?$

Functionality

Match UA- followed by between one and unlimited digits
Match -
Match between one and unlimited digits
Match the delimiter ||
Match the first capture group (1.)
Match the second capture group (2.) between zero and one times
Match any character between zero and unlimited times if it matches the third group (3.) - between zero and one times

Here is an example of the regex being used against the concatenated strings.

Preg_match exact word (UA google tag)


Programmatically changing the global site name?

Question: I'm making a multi-site setup using the same install and the same database, basing it off domains. I'm trying to programmatically alter the site_name variable so that it displays a different site name based on the domain being used.
I am using 3 different methods to achieve this at the same time, however even that is not bullet-proof. Certain instances (i.e. some administration pages, user login, or user profile edit) still display the default site name in the page title (or elsewhere).
I am doing the following:

$conf['site_name'] = $my_title; in settings.php
$vars['site_name'] = $my_title; in my theme's hook_preprocess_page
using hook_tokens_alter in a custom module to change the [site:name] token to $my_title

Despite all these measures, it seems I did not enforce the site name change in a bulletproof way. Is there a better method I have missed?
Worth mentioning: I am using the Metatag module, which seems to alter page titles on a fundamental level. I am not sure if this is related to my problem.
Answer: What is the value for the site_name variable in the variables table? (e.g. what's the output of variable_get('site_name')?)
If it's overridden from the value that you set in your settings file, reset it like so:
variable_set('site_name', $my_title)
Answer: From PHP code, it's just:
variable_set('site_name', 'My Site Name');

If it doesn't work, clear you caches, restart your memcached if you're using it or check if you didn't export it into Features or hardcoded into your settings file.
One-time go is via drush:
drush -y vset site_name "My Site Name"

To check if the value was changed:
drush vget site_name


Show that $g(x)=r f(x)$ for some rational number $r$.

Question:
Let $f(x)$ and $g(x)$ be two quadratic polynomials all of whose coefficients are rational numbers. Suppose $f(x)$ and $g(x)$ have a common irrational root. Show that $g(x)=r f(x)$ for some rational number $r$.

My solution (please check if it is correct or not)
Denote this irrational root to be $k=a+b\sqrt{c}$ where $a, b, c \in \mathbb{R}$ and $c$ is not divisible by the square of any prime. Then if $a+b\sqrt{c}$ is a root of the polynomial, so does $a-b\sqrt{c}$ by the Irrational Conjugate Theorem. Then we may write $f(x)=\alpha(x-(a+b\sqrt{c}))(x-(a-b\sqrt{c}))$ and $g(x)=\beta(x-(a+b\sqrt{c}))(x-(a-b\sqrt{c}))$ where $\alpha, \beta \in \mathbb{Q}$. Dividing both sides by $\beta$ gives $f(x)=\frac{\alpha}{\beta}(x-(a+b\sqrt{c}))(x-(a-b\sqrt{c}))$ and $g(x)=(x-(a+b\sqrt{c}))(x-(a-b\sqrt{c}))$; since $\alpha$ and $\beta$ are rational. Let $r=\frac{\alpha}{\beta}$ and hence we are done.
Answer: You solution is OK, but it can be even simpler, because you don't really need to write out the root at all.

Let $x_0$ be the irrational root of $f$ and $g$, and let $x_1$ be the irrational conjugate of $x_0$. Then, by the Irrational Conjugate theorem, $x_1$ is a root of $f$ and of $g$. This means that $f(x)=a(x-x_0)(x-x_1)$ and $g(x)=b(x-x_0)(x-x_1)$ for some $a,b\in\mathbb R$.
Because $f$ and $g$ have rational coefficients, $a,b\in\mathbb Q$ because $a$ is the leading coefficient of $f$ and $b$ is the leading coefficient of $g$.
Finally, because $$g(x) = \frac{b}{a}\cdot f(x),$$ we can set $r\frac ba$ and we have $g(x)=rf(x)$.

Or, you can also argue another way, a little more hand-wavy, but for most purposes, still rigorous enough.

If $x_0$ is the irrational root of $f$ and $g$, then so is the irrational conjugate of $x_0$. Because $f$ and $g$ are quadratic polynomials with identical roots, we know that $g(x)=r\cdot f(x)$ for some real number $r$ and all real numbers $x$. Plugging in $x=0$ we get $r=\frac{g(0)}{f(0)}$, meaning $r$ is a rational number (because $g(0)$ and $f(0)$ must be rational numbers).


ratio of lengths of median and altitude

Question: 'In a triangle ABC the side opposite $A$ has length $a$, and similarly for $b$ and $c$. Let $l$ be the length of the median and $d$ be the length of the altitude from $A$ to $BC$. Prove that $$\frac{l}{d} \geq \frac{b^2 + c^2}{2bc}.$$
I wrote d^2 in terms of a,b,c using heron's formula = ad/2, and l^2 using Apollonius theorem, but then I get a mess that doesn't seem to simplify. Please help!
Thanks.
Answer: $$\dfrac {m_a}{h_a}=\dfrac {2m_aa}{S}=\dfrac {8m_aR}{bc} $$
$$ m_a(2R-m_a) \ge \dfrac {a^2}{4} \Rightarrow 8m_aR \ge \dfrac {b^2+c^2}{2}$$
Comment: Shouldn't the inequality sign next to a^2/4 be flipped since (a-x)x in the triangle's side which has been divided is less than or equal to a^2/4?
Answer: Since $l=\frac{1}{2}\sqrt{2b^2+2c^2-a^2}$, $d=\frac{2S}{a}$
and $S=\sqrt{p(p-a)(p-b)(p-c)}=\frac{1}{4}\sqrt{\sum\limits_{cyc}(2a^2b^2-a^4)}$, we need to prove that
$$abc\sqrt{2b^2+2c^2-a^2}\geq2(b^2+c^2)S$$ or
$$4a^2b^2c^2(2b^2+2c^2-a^2)\geq(b^2+c^2)^2\sum\limits_{cyc}(2a^2b^2-a^4)$$ or
$$(b^2-c^2)^2(b^2+c^2-a^2)^2\geq0.$$
Done!

ratio of lengths of median and altitude


Inverse Hyperbolic Sine Transformation (IHS) for dependent variable - How to back transform predictions?

Question: I am doing IHS transformation for the dependent variable (count data, mostly 0 and small counts) while training a non-parametric tree-based machine learning model. I've seen posts saying it will induce bias if the predictions are back transformed using
For example, this post.
Instead of transforming using the above formula, the author proposed to multiply the formula by exp(s^2 /2) to adjust for biases.
I want to back transform my predictions to the original scale and calculate the RMSE and then compare the performance of models with and without transformation. Is it a feasible comparison? In addition, the back transformed predictions will then be used further as an input to another model. There are also several questions which I cannot answer.
Firstly, I do understand that back transforming without bias adjustment will bring some problems. The same thing applies to log transformation as well. The only thing I don't understand is why kagglers only use exp(pred) to transform the predictions to the normal scale? Will that not induce bias?
Secondly, I am not sure if I have understood the above post correctly. My understanding is that s is the standard deviation of a list of predictions on the IHS scale before back transformation. Please correct me if I am wrong.
Thirdly, does this formula also apply to prediction results from a non-linear regression model?
Comment: You should explicitly credit the author you're quoting (as well as linking as you do now).
Comment: It's interesting that the analysis ignores the effect of the bias in the estimate of the mean due to estimating $\sigma^2$ by $s^2$. If the corresponding situation in the lognormal is anything to go by (as we might expect because of their close connection), that's going to be a much more substantial effect.
Answer: Your proposed comparison seems like a solid one.
My guess on the first question is that they repress all memories of Jensen's inequality from traumatic statistics classes. More seriously, even advanced people do all kinds of silly things with statistics until they learn better.
$s^2$ is the sum of the squared residuals on the transformed scale, divided by (n - k): $$\frac{\sum_i^N \left( \hat \sinh^{-1}(y_i)- \sinh^{-1}(y_i) \right)^2}{n-k}.$$
This formula only applies to linear models.
Also note that this retransformation should improve the mean prediction, but does not ensure that predictions for individual cases are particularly good. You might also try some sort of GLM (like a het-robust poison) that avoids all these transformations.


Count number of higher lines for each line pandas

Question: I have a 2 columns DataFrame:
positions = pd.DataFrame({"pos" : [1, 2, 3, 4, 5], "mcap" : [1, 4, 3, 2, 5]}, index = ["a", "b", "c", "d", "e"])

For each index value I need to find amount of points that lay to the upper right corner in 2D world, i.e. for each line I need to count number of lines  which are strictly higher than current line.
So the answer for the example above would be:
pd.Series([4, 1, 1, 1, 0], index = ["a", "b", "c", "d", "e"])

I know how to do that in loop, but that takes much computational time once DataFrame becomes large, thus I'm looking for a more pythonic way to do it.
EDIT. simple solution by loop.
answer = pd.Series(np.zeros(len(positions)), index = ["a", "b", "c", "d", "e"])
for asset in ["a", "b", "c", "d", "e"]:
    better_by_signal = positions[positions["pos"] > positions["pos"].loc[asset]].index
    better_by_cap = positions[positions["mcap"] > positions["mcap"].loc[asset]].index
    idx_intersection = better_by_signal.intersection(better_by_cap)
    answer[asset] = len(idx_intersection)

Comment: @AJS I have attached loop solution.
Comment: @ArtyomAkselrod Some numpy/pandas function return unexpected results, when NaN values are present.
Comment: What should happen in case of equality, e.g., mcap : [1, 4, 3, 2, 4]? Are there any NaN values in your dataframe?
Comment: @Mr.T no NaNs, actually each value in mcap and pos is unique, thus you can assume anything (while I believe that that should not change the answer much).
Comment: if possible please post your solution you have with loop included with your question, that should help
Answer: You could employ numpy broadcasting to find all positive difference pairs for the x-axis (pos) and y-axis (mcap):
import numpy as np
import pandas as pd

positions = pd.DataFrame({"pos" : [1, 2, 3, 4, 5], "mcap" : [1, 4, 3, 2, 5]}, index = ["a", "b", "c", "d", "e"])

arrx = np.asarray([positions.pos])
arry = np.asarray([positions.mcap])
positions["count"] = ((arrx - arrx.T > 0) & (arry - arry.T > 0)).sum(axis = 1)

print(positions)

Sample output
   pos  mcap  count
a    1     1      4
b    2     4      1
c    3     3      1
d    4     2      1
e    5     5      0

Comment: I've checked speed of all solutions suggested, this one is the best, works much faster comparing to the loop solution from the question.
Answer: Use map instead of looping over the index, this should work:-
  import pandas as pd
  import numpy as np

  positions = pd.DataFrame({"pos" : [1, 2, 3, 4, 5], "mcap" : [1, 4, 3, 2, 5]}, index = ["a", "b", "c", "d", "e"])
  answer = pd.Series(np.zeros(len(positions)), index = ["a", "b", "c", "d", "e"])

  def set_pos(asset):
     better_by_signal = positions[positions["pos"] > positions["pos"].loc[asset]].index
     better_by_cap = positions[positions["mcap"] > positions["mcap"].loc[asset]].index
     idx_intersection = better_by_signal.intersection(better_by_cap)
     return len(idx_intersection)

  len_intersection = map(set_pos, answer.index.tolist())
  final_answer = pd.Series(len_intersection, index = answer.index.tolist())

Comment: This solution gives just a small speed increase comparing to the loop solution suggested in question.
Answer: You could instead of a for-loop use a list comprehension like so:
import pandas as pd
import numpy as np

positions = pd.DataFrame({"pos": [1, 2, 3, 4, 5],
                          "mcap": [1, 4, 3, 2, 5]},
                         index=["a", "b", "c", "d", "e"])

# gives you a list:
answer = [sum(np.sum((positions - positions.iloc[i] > 0).values, axis=1) ==
              2) for i in range(len(positions))]

# convert list to a `pd.Series`:
answer = pd.Series(answer, index=positions.index)

Comment: This solution seems to be even worse comparing to loop one mentioned in the question. It worked almost 4 times slower.
Answer: You can use convolutions. Convolution does something like this (more info here):

It will go through the matrix multipling your filter or pad by the elemnts of the matrix and then adding them together in this case.
For this question, lets first add a new element f to the dataframe so at least one row have more than one element.
>> positions

   pos  mcap
a    1     1
b    2     4
c    3     3
d    4     2
e    5     5
f    3     2

The positions can be also seen as:
df = pd.crosstab(positions['pos'], positions['mcap'],
                 values=positions.index, aggfunc=sum)

df

mcap    1    2    3    4    5
pos
1       a  NaN  NaN  NaN  NaN
2     NaN  NaN  NaN    b  NaN
3     NaN    f    c  NaN  NaN
4     NaN    d  NaN  NaN  NaN
5     NaN  NaN  NaN  NaN    e

df_ones = df.notnull() * 1

mcap  1  2  3  4  5
pos
1     1  0  0  0  0
2     0  0  0  1  0
3     0  1  1  0  0
4     0  1  0  0  0
5     0  0  0  0  1

We can create a window that slides through df_ones and sum the number of elements that fall under the window. This is called 'convolution' (or correlation).
Now let us create a window that avoids the upper left corner element (so it is not counted) and convolute it with our df_ones to get the result:
pad = np.ones_like(df.values)
pad[0, 0] = 0

pad

array([[0, 1, 1, 1, 1],
       [1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1]], dtype=object)

counts = ((signal.correlate(df_ones.values, pad,
                            mode='full')[-df.shape[0]:,
                                         -df.shape[1]:]) * \
          df_ones).unstack().replace(0, np.nan).dropna(
          ).reset_index().rename(columns={0: 'count'})

   mcap  pos  count
0     1    1    5.0
1     2    3    3.0
2     2    4    1.0
3     3    3    1.0
4     4    2    1.0

positions.reset_index().merge(counts,
                              how='left').fillna(0
     ).sort_values('pos').set_index('index')

       pos  mcap  count
index
a        1     1    5.0
b        2     4    1.0
c        3     3    1.0
f        3     2    3.0
d        4     2    1.0
e        5     5    0.0

All in a function:
def count_upper(df):
    df = pd.crosstab(positions['pos'], positions['mcap'],
                     values=positions.index, aggfunc=sum)
    df_ones = df.notnull() * 1

    pad = np.ones_like(df.values)
    pad[0, 0] = 0

    counts = ((signal.correlate(df_ones.values, pad,
                                mode='full')[-df.shape[0]:,
                                             -df.shape[1]:]) * df_ones)
    counts = counts.unstack().replace(0, np.nan).dropna(
    ).reset_index().rename(columns={0: 'count'})

    result = positions.reset_index().merge(counts,
                                         how='left')
    result = result.fillna(0).sort_values('pos').set_index('index')
    return result

For your example the result would match your expected result:
positions = pd.DataFrame({"pos" : [1, 2, 3, 4, 5],
                          "mcap" : [1, 4, 3, 2, 5]},
                         index = ["a", "b", "c", "d", "e"])
>> count_upper(positions)
       pos  mcap  count
index
a        1     1    4.0
b        2     4    1.0
c        3     3    1.0
d        4     2    1.0
e        5     5    0.0

Comment: This code does not work as `NameError: name 'signal' is not defined`


Migrating Conditional Styling From jQuery to AngularJS

Question: I'm making my first Angular app and am struggling with the thought processes behind conditionally styling the DOM in AngularJS.
I was previously doing this in jQuery like so:
containerWidth = lineWidth / numberOfObjects;
$container.css('width',containerWidth);
So if there's 1 object the width is 100% and if there are 5 the width becomes 20%.
I'm unsure whether to do this in link, inside a directive or in the controller itself?
Comment: DOM manipulation is basically done in Directive, However, you can use jquery syntax inside controler. eg .$("your selector").css() in controler
Comment: Possible duplicate: http://stackoverflow.com/questions/20287241/how-to-set-div-width-using-ng-style
Answer: Please see ng-style
Example:

and JS:
$scope.divStyle = {'width' : (lineWidth / numberOfObjects) + 'px;' };

(I don't know where lineWidth comes from... but that's the idea)
Comment: Does the JS part go in the controller?
Comment: Yes, the controller that renders the part of the view you're interesting in dynamically styling


jQuery .ajax load function, how to pass in data and retrieve it?

Question: I have something like the following:
    $.ajax({
        url: "info.html?" + $(this).attr('id'),
        cache: false,
        success: function(html){
            $('#list-content').load("info.html?" + $(this).attr('id'));
        }
    })

In info.html, if I get the document.href and try to parse it, I don't get info.html?..., instead, I get the URL of the containing window which is index.html. Question, how do I get the data trailing the 'info.html?''? Is this good practice? How else can I pass in data and how can I retrieve it from info.html on document ready?
One more question, is there a way to access the elements inside info.html after loading it?
Thanks in advance.
Answer: i think this is more like something you want:
    $.ajax({
      url: "info.html",
      data: {
        id:$(this).attr('id')
      },
      cache: false,
      success: function(html){
          $('#list-content').html(data);
      }
    })

If I understand you correctly, you are currently on index.html and you want to grab info.html and put it in a div?  If so, this is how you do it.
I'm not entirely sure why you are putting GET params on the url though.  There is a data param in the ajax function that will automatically create your GET string, I put it in the example if that is what you want.

ANSWER TO BELOW QUESTION:
Well you'd want to use a server side language, php is a popular choice.  So you might want to consider renaming your file to info.php (don't worry, it will still work if it's filled with html).  Then you'll have access to the GET param in php, you can do something like:
<?php
$id=isset($_GET['id']) ? $_GET['id'] : null;
?>

From there you can do whatever you want with $id, echo it, use it in a db query, etc.
Comment: My main question is, how do I access 'id' from info.html? Or should I do a callback function within index.html and manipulate #list-content from there?
Answer: Thats because ajax request are handled by the server and you are still inside index.html, which is on the client side.  You can access them via $_GET in php which is the default method for load. As for accessing data in  info.html, you can easily do it in a callback function after load.
$('#list-content').load("info.html?" + $(this).attr('id'), function() {
     // js stuff here
});

Comment: The callback function is in index.html; are you suggesting manipulating info.html within index.html instead of having a document ready function in info.html?
Comment: Yes, everything you have in info html can be put inside this callback function, or you can just put it in document ready inside your index.html file and use live/bind functions
Comment: I want something to load dynamically based on the 'id' data when info.html loads, but I don't know what event I would use for .live(). Ideally, I would do something like `$("#infobox").html("something that goes here on load")` inside the call back function, but nothing happens! Help?
Comment: Oh, it works now! I must have had some dead code in there somewhere, but the callback function from .load works and I can access the elements that were dynamically loaded. Thanks!