Webpage to take input from shell script and display result

Question: I am newbie to web programming and I have small shell script which basically gives output with two results. It's basically to find users on our directory.
#!/bin/bash
echo -n "Please enter username to lookup: "
read USERNAME
DISPLAYNAME=`ldapsearch -p xxx -LLL -x -w test -h abc.com -D abc -b dc=abc,dc=com sAMAccountName=$USERNAME | grep displayName`

if [ -z "$DISPLAYNAME" ]; then
  echo "No entry found for $USERNAME"
else
  echo "Entry found for $USERNAME"
fi

Looking out for perl web code which can display the results on browser.
I know, I would be asking too much here, but I would really appreciate if anyone can give me right direction to achieve this.
Thanks!
Comment: where is the code running (on the machine running the webserver)?
Comment: yes, the code is running on the webserver.
Answer: First of all, do not use $USERNAME in your BASH script. $USERNAME is a BASH variable that contains the current user's name. In fact, it is generally a bad idea to use UPPERCASE variables in BASH. Most BASH environment variables are upper case and that can lead to confusion. It is good practice to have your variables lower case.
Also, since I imagine you want to do this using an HTML form, you cannot have BASH read from STDIN. Modify tour script to take the user name as an argument:
BASH:
#!/bin/bash
user=$1;
DISPLAYNAME=`ldapsearch -p xxx -LLL -x -w test -h abc.com -D abc -b dc=abc,dc=com sAMAccountName=$user | grep displayName`
if [ -z "$DISPLAYNAME" ]; then
  echo "No entry found for $user"
else
  echo "Entry found for $user"
fi

Perl:
#!/usr/bin/perl
use CGI qw(:standard);
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);
use strict;
use warnings;
## Create a new CGI object
my $cgi = new CGI;
## Collect the value of 'user_name' submitted by the webpage
my $name=$cgi->param('user_name');

## Run a system command, your display_name.sh,
## and save the result in $result
my $result=`./display_name.sh $name`;

## Print the HTML header
print header;
## Print the result
print "$result
";

HTML:

<form ACTION="./cgi-bin/display_name.pl" METHOD="post">
<INPUT TYPE="submit" VALUE="Submit">
<INPUT TYPE="text" NAME="user_name">
</form>

This should do what you need. It assumes that both scripts are in the ./cgi-bin/ directory of your webpage and are called display_name.sh and display_name.pl. It also assumes that you have set their permissions correctly (they need to be executable by apache2's user, www-data). Finally, it assumes that you have set up apache2 to allow execution of scripts in ./cgi-bin.
Is there a specific reason you want to use BASH? You could just do everything directly from the Perl script:
#!/usr/bin/perl
use CGI qw(:standard);
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);
use strict;
use warnings;
## Create a new CGI object
my $cgi = new CGI;
## Collect the value of 'name' submitted by the webpage
my $name=$cgi->param('user_name');

## Run the ldapsearch system command
## and save the result in $result
my $result=`ldapsearch -p xxx -LLL -x -w test -h abc.com -D abc -b dc=abc,dc=com sAMAccountName=$name | grep displayName`;

## Print the HTML header
print header;
## Print the result
$result ?
      print "Entry found for $name
" :
      print "No entry found for $name
";

Comment: Terdon, Many Thanks.
I was trying your perl script. I am encountering below error.

Global symbol "$USERNAME" requires explicit package name at /var/www/cgi-bin/ldapquery line 13.

Any idea?
Comment: Please read my answer again @maneeshshetty, I explain this on the very first line. try using the BASH script I gave in my answer.
Comment: Sorry for that Terdon. I changed it to $user still it's getting
Global symbol "$user" requires explicit package name at /var/www/cgi-bin/ldapquery line 13.

Also I tried your Bash code. I am getting

syntax error at /var/www/cgi-bin/display_name.pl line 20, near "body>"
Comment: Getting error
Global symbol "$user" requires explicit package name at /var/www/cgi-bin/ldapquery line 13.
Comment: @maneeshshetty, please copy my script as I have posted it. The error you give is quite informative. It tells you that there is a problem with a variable called `$user` on line 13 of the script. My script has no `$user` variable on any line. Line 13 has a `$name` variable. My guess is that you have changed `$name` to `$user` on line 13 without the corresponding change for the variable declaration at line 9.
Comment: I did exactly now as you suggested me. Please see below errors.

==============================================================
[Thu Oct 4 14:37:11 2012] ldapquery: Use of uninitialized value in concatenation (.) or string at ./ldapquery line 13.
No such object (32)
Additional information: 0000208D: NameErr: DSID-031522C9, problem 2001 (NO_OBJECT), data 0, best match of:
''

Content-Type: text/html; charset=ISO-8859-1

[Thu Oct 4 14:37:12 2012] ldapquery: Use of uninitialized value in concatenation (.) or string at ./ldapquery line 19.
=========================================================
Comment: Web broswer displays only "No entry found"


Taking partial derivatives on the TI-89

Question: Does anyone know why when you take the partial derivative of say xy using the differentiate function on the TI-89 does it not give you the correct answer?
example
d/dx(xy) = 0 on the calculator
Am I doing something wrong here?
Comment: Does it know it is $\dfrac{d}{dx}(x * y)$ as opposed to thinking it is a single variable?
Answer: This was already mentioned as a comment, but just to be clear, in this instance the TI-89 will treat xy as a single variable, not as x*y.
For example:
d/dy(x*e^(xy)) = 0 ← variable is interpreted to be $xy$
whereas
d/dy(x*e^(x*y)) = e^(x*y)*x^2. ← variables are interpreted to be $x$ and $y$

Taking partial derivatives on the TI-89


Quoting square brackets in an Asciidoctor link description

Question: I am writing a release guide in Asciidoctor for a project I am contributing.
The document contains a link and the intended link description should contain placeholes like [variable]. As Asciidoctor alsi uses square brackets to enclose the link description I quoted my square brackets. But the result is not the indended one.
Here is an simplified example of my attempt:
Here comes the problem!

https://dist.apache.org/[https://dist.apache.org/repos/\[version\]\[project\]^].

Asciidoctor (version 126.96.36.199) renders the link as https://dist.apache.org/repos/dist/dev/incubator/tamaya/\[version]/\[project]. But I expected https://dist.apache.org/repos/dist/dev/incubator/tamaya/[version]/\[project]as result.
What did I miss?
Answer: In my experience, using the decimal HTML Entity code is the solution. This should work for both HTML and PDF. For your case:

left square bracket: [
right square bracket ]

I would write:
Here comes the problem!

https://dist.apache.org/[https://dist.apache.org/repos/[version][project]^].

If you use the entities a lot, you can use variables:
:left_sb: [
:rigth_sb: ]

Here comes the problem!

https://dist.apache.org/[https://dist.apache.org/repos/{left_sb}version{rigth_sb}{left_sb}project{rigth_sb}^].


Drag and Drop ( Drag um item já dropado )

Question: Bom dia!!
Estou precisando de uma ajuda em JScript.
Fiz um código de Drag and Drop onde coloco um gif dentro da div conteudo e posso move-lo livremente. Só não estou conseguindo fazer o seguinte:
Ao tentar dropar um gif próximo a um item já dropado na div conteudo, o gif empurrar o item dropado.(Atualmente, o item some quando tento colocar na imagem já dropada).
Podem me ajudar?? :(
Segue o código como exemplo:

  var elementCounter = 0; // to assign ids to dropped element.
  //Drag'n Drop functions
  function allowDrop(ev)
  {
      ev.preventDefault();
  }

  function drag(ev)
  {
        ev.dataTransfer.setData("text", ev.target.id);
        ev.dataTransfer.effectAllowed = "copy";
  }

  function drop(ev)
  {
      ev.preventDefault();
      var x = ev.clientX;
      var y = ev.clientY;
      var data = ev.dataTransfer.getData("text");
      var copyimg = document.createElement("img");
      var original = document.getElementById(data);
      copyimg.src = original.src;
      ev.target.appendChild(copyimg);
      if(original.parentNode.id == "conteudo")
     {
        original.parentNode.removeChild(original);
        alert("Movendo imagem");
        copyimg.id = "dropped_elem"+(++elementCounter);
        copyimg.setAttribute("style", "position: fixed; top: "+(y-50)+"px; left:"+(x-50)+"px;");
        copyimg.setAttribute('draggable', true);
        copyimg.setAttribute('ondragstart', "drag(event)");
      } else {
        alert("Nova imagem");
        copyimg.id = "dropped_elem"+(++elementCounter);
        copyimg.setAttribute("style", "position: fixed; top: "+(y-50)+"px; left:"+(x-50)+"px;");
        copyimg.setAttribute('draggable', true);
        copyimg.setAttribute('ondragstart', "drag(event)");
      }
  }
    #conteudo{
      width:500px;
      height:500px;
      float:left;
      background-color:#ff1;
      display: initial;
      margin: auto;
      z-index: 6;
      overflow: hidden;
    }

Comment: Isso que você quer é mais matemático do que pelo código, com o seu código mesmo da pra fazer isso, você precisa captar a posição e o tamanho dos dois elementos, e comparar dentro do pai se eles se encontram em algum momento, acho que a equação das retas básica você consegue cruzar um ou e o outro, caso cruze, só disparar mudando a posição com a proporção da sobreposição, se não conseguir ou ninguém mais responder a noite faço uma resposta, pois vai ser meio longa.
Comment: Entendi !
O disparar será feito pelo .setAttribute("style", "position: fixed; ... certo??
Porém ainda não tenho ideia de como compara-los, vou tentar algo aqui !! Obg :DD
Comment: Isso mesmo, você capta com o mesmo seletor também, só imaginar a div que os elementos estão dentro como um plano cartesiano(X,Y) pra conseguir aplicar a equação, desenha numa folha que vais entender facinho.
Comment: Beleza !! obg !!
Comment: Não consegui, após inserir a imagem dentro de outra imagem, ele não respeita o comando para mover para o lado, a imagem simplesmente some
Comment: coloca o codigo que você fez na pergunta, não tenho tempo pra fazer uma resposta completa, mas vo ajudando
Comment: Eu coloquei um else para diferenciar se é uma nova imagem ou se está movendo uma imagem da div conteúdo.
A única coisa que não consigo é diferenciar se esta nova imagem está caindo na div conteúdo ou em cima de outra imagem...
Pois se eu soltar uma imagem (²) em cima de uma outra imagem (¹), a imagem (²) some
Comment: É meio complicado, vou mover para o chat e tentar explicar um pouco melhor
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/65827/discussion-between-anthraxisbr-and-sora).
Answer: Consegui resolver esta questão substituindo o ev.target.appendChild(copyimg); por div.appendChild(copyimg); antes do if.


Is System.Data.DataTable in C# eligible for transactions?

Question: I am just a beginner in C# and now I work with table data only in the form of System.Data.DataTable, that is in-memory data. From my work elsewhere I know that there is such thing as transactions. Right now I need something like that in my work with DataTable. I found a System.Transactions namespace in the Visual Studio help. But I cannot dig whether it is applicable to DataTable. Neither could I find the answer in Google. Everywhere they are talking about transactions in C# concerning database engines like MS SQL, Oracle, ADO etc. So here I am with my probably very easy question: is System.Data.DataTable in C# eligible for transactions? For example, can I begin a transaction, add some rows to my DataTable, and then rollback? If this is possible, could you please give a sample code
Comment: Nope. But it's also not clear what you are trying to do. A DataTable is  just an in memory collectiom like and Array. If you would ask for DataSet it could make lil more sense. It is a collection of related tables. You could have a look at AcceptChanges available in DataTsble/DataSet. Maybe it comes close to what you need.
Comment: See: [AcceptChanges()](https://learn.microsoft.com/en-us/dotnet/api/system.data.datatable.acceptchanges?view=net-7.0) and [RejectChanges()](https://learn.microsoft.com/en-us/dotnet/api/system.data.datatable.rejectchanges?view=net-7.0)
Comment: I don't think either `AcceptChanges` or `RejectChanges` promise transactionality.  They promise "I'm going to try to accept all the changes you have made" - I think.  I'd be really surprised if you get an "either everything completed successfully or nothing completed" promise out of them.  What are you trying to do.  Generally, DataTable and DataSet are a little antique, and if you want database behavior, you should really use a database
Answer: Many thanks everyone for your prompt answer. Your suggestion about AcceptChanges and RejectChanges turned out to be exactly what I needed. I am inserting rows in a set of tables with parent-child relations. If no data is found for a certain subject for inserting in the last child table, then nothing should be inserted in any table at all. And now I can achieve this, by issuing DataSet.AcceptChanges() before starting a new subject, and issuing AcceptChanges() or RejectChanges() respectively after processing the subject completely


How can I prove that $(\mathbb Z,\leq_*)$ is isomorphic to $(\mathbb N,\leq )$

Question: We define the binary relation $\leq_*$ between integers by the following rule: For $n,m\in\mathbb Z$, $n\leq_∗m$ holds if and only if one of the following conditions is satisfied:
$|n|<|m|$, or
$|n|=|m|$ and $n<0\,$, or
$n=m$.
How can I prove that $(\mathbb Z,\leq_*)$is isomorphic to $(\mathbb N,\leq )$?
My thoughts:
I have to find a bijection $f : A_1 → A_2$. Then, I need to prove that $f$ is an isomorphism by showing that it is injective, surjective and that it preserves the order. However, I can't seem to find to find $f$. How can I do this?
Answer: Hint: $0 \leq_* -1 \leq_*1 \leq_* -2 \leq_* 2 \leq_*\dots$
Comment: So I need a function $f$ such that $f(0)=0$, $f(1)=1$, $f(2)=-1$, $f(3)=2$, $f(4)=-2$... Right?
Comment: That would do the job, yes.
Comment: $f(n)=|n|+||n|-1|$. Is this valid?
Comment: This would not give you negative integers, or even $0$. Try to define $f(n)$ for even $n$, and then for odd $n$.
Comment: Sorry, I was defining f:ℤ→ℕ (it's also wrong). What about this: $f(2n) = -n$ and $f(2n+1)=n+1$  ?
Comment: Yes, that works. It should be straightforward to check that $f$ gives you the required isomorphism.
Comment: Aren't the elements ordered this way: $ 0≤∗-1≤∗1≤∗-2≤∗2≤∗…$?
Comment: Hmm I don't think $1≤∗−1$.
Comment: Ah, you are right. My mistake! I will update my answer accordingly.
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/13357/discussion-between-nick-and-user132349)


Software to draw links or knots

Question: I am looking for software that can aid me in drawing knots and links. There are of course (examples) knotplotters all over the web, but they can only draw specific knots.
What I am looking for is the software that for example Selman Akbulut used to draw the pictures in his topology presentations (see for example http://www.math.msu.edu/~akbulut/vita/lec.html). It looks like he is using something (else than obviously a huge amount of caffeine) to draw freehand...
Alas, there is no email address on his homepage so I can ask him personally.
I looked into packages which can draw knots and links directly into LaTeX, but they all seem to be too cumbersome when you draw really complicated links.
Edit: Seems that Akbulut is just using a drawing aid. Probably one of those described in the answers below. Further, he seemed to be somewhat cross with the nomenclature (Kirby diagrams), since he developed something similar one year before Kirby's paper in 1977. So maybe we have to use a more careful phrase. Obviously, I didn't know of some friction going on there, I just think it is a nice way to represent 4-dimensional handlebodies, no matter what you call it...
Comment: [I managed to find his e-mail address by clicking around](http://mathdata.msu.edu/FD/RW/F2.html). ;)
Comment: Okay thanks. I'll write him an email and post the result back to Stackexchange. In the meantime, the question still stands.
Comment: Of course. :) I just helped you with the portion of your question that I am capable of helping you with.
Comment: The bottom of this course site http://www.math.uiuc.edu/~clein/m428_s11.html have some useful links.
Comment: This could be helpful: http://doc.sagemath.org/html/en/reference/knots/sage/knots/link.html
Answer: See Drawing knots using computers for a tutorial and Knot Software for a list of programs (some links are broken but Google can help). KnotPlot seems very nice if you want to get fancy.
Answer: If you are into LaTeX, you can use this package  to actually get fast results using the powerful TikZ/PGF packages. Or pst-knot package with PSTricks.
Answer: The standard first answer to questions like this is Inkscape.  (There are many other similar vector drawing programs, but for the given feature set, the price of $0 is hard to beat.)  I took a quick look at the presentations you linked to, and I didn't see anything there that one couldn't draw fairly easily in Inkscape after a bit of practice.
Answer: After a tremendous amount of experimentation with various software I wasn't really happy with, I settled on Xara. It's not free, but it saves me so much time and effort that it's worth every penny I paid. And of course you can draw many other things besides knots. I'm happy with the results.
Comment: You might want to carefully read the license for Xara.  I rejected the software when I found terms that amounted to "you cannot use this software on a computer than can be used remotely".  Since that's all of them now, it was impossible to comply with the license.
Answer: If I recall Selman uses Adobe Illustrator.
Also, you know his email address since you know that is website is math.msu.edu/~akbulut

Software to draw links or knots


Bass picking technique

Question: I play the bass in a metal band, so I usually need a pick to get both a more fitting sound and reach the right speed. But I cannot find the right technique to use it and I don't have much precision and control of the instrument. Also, palm-muting looks like unfeasible for me at the moment, and I should use it sometimes.
My question is: which is the best way to use a pick on a bass (position of the hand, angle of the arm, distance from pick-ups)? Can someone point me in the right direction or suggest some useful source?
Comment: I know there is a valid answer to your question beyond this, but it would be good to get a bass professional (perhaps a teacher) or more than one to observe your current technique and get them to recommend how you can personally improve it. We can probably tell you what to do, but there is no substitute for such observation.
Answer: You'll need lots of practice, as usual with any technique. Here's what you want to work towards with your practice:

Learn to be able to use as little of the pick as possible. By that I mean ideally you would be able to consistenly brush just the very tip of the pick across the top of the strings when picking. You may want to dig in to the string more for certain sounds, but that's easy to do once you can play with the minimum amount of pick.
Use a fairly heavy pick. Experiment with the heaviest pick you can possibly find and then try one or two lighter. A heavier pick gives you more control but is a bit more demanding on bullet number one above. That's because if you are using too much pick, a heavier pick won't give way and you will feel and hear that you are using too much. The upside to a heavier pick is twofold: first, as you learn and practice, you'll feel when you are doing better and when you're not. Second, having a heavier pick means you can player harder if you choose to, and also play lightly when you want to. With practice, you can play as lightly as you want with a heavy pick, but you can never play heavier than your pick.
You want to learn to pick both with your wrist wiggling slightly and with just your fingers moving the pick, so you can choose the most appropriate motion for the situation. Picking with finger motion only would be for precise, articulated passages. Picking with wrist movement only would be for playing even eighth, sixteenth, or faster notes continuously while fretting.
You want to learn to be able to pick closer to the bridge (easier) and closer to the neck (harder) so you can choose the ideal location to get the tone you want. Most of the time you'll be picking over the pickups, more or less. The faster and more complicated the passage is, the easier it will be to play closer to the bridge. If you recall the first bullet, above, optimizing pick use requires muscle memory of exactly where the string is. The string's position is a lot less predictable the farther you get from the bridge. Another reason why using as little pick as possible helps is that it minimizes string displacement so picking the next note is a little easier. The other side to that is the string is less mobile near the bridge, so it will fight you a lot more as you try to pick it. Once again, bullet number one is the answer to playing close to the bridge and dealing with the immobility of the strings in that area.
In all situations, whether playing with or without a pick, you will stand out among other bass players if you learn to play with even intensity at all times. Like using the minimum amount of pick, if you can play with even intensity you still can play harder or softer if the situation calls for it. Practice playing without any compression or distortion and work to make every note the same loudness and tone quality, across all the strings and frets. This is a lifetime mastery skill on bass so be patient. The more consistenly you can play, the more you will have that "professional" sound quality that is hard to define but you know it when you hear it. Precise timing is the other aspect of this, but that's not as relevant to picking.
Many people recommend angling the pick so that it is not hitting the strings flat. A small angle is good and a steeper angle is necessary for the fastest speed, but do not use a larger angle instead of using the minimum amount of pick. Using a steep angle and a lot of pick with slow you down and give you a not-good scraping noise. Sometimes a scraping noise is good for a song, but you want to be able to choose, and fast, articulated playing will require the minimum of scraping or else the notes will get lost. When you practice your picking, try to keep it flat so you are making things a little harder on yourself and forcing your muscles to rise to the challenge.

Regarding palm muting specifically:

Palm muting requires both effective muting and effective picking. "Effective" in this case mostly means "appropriate for the sound you are looking for". Sometimes you want more muting, and sometimes you want less. The more distortion you are using and the shorter you want the notes to ring out, the more muting you'll want to use (usually), and vice-versa. The proper way to get more muting is to move your palm (which is resting on the string(s) at the bridge) farther from the bridge and closer to the neck while keeping even pressure on the string(s). For less muting, you move your palm closer to the bridge. The minimum muting is with the corner of the palm just wresting on the bridge itself with the flesh lightly touching the string just where the string meets the bridge.
When you are wresting your palm on the strings/bridge for palm muting, it creates a challenge for picking and an opportunity. The challenge is that your motion is restricted, so changing strings is a bit harder. The opportunity is your motion is restricted, so it can be easier to pick precisely as required by the first bullet above (use as little pick as possible). You have to practice proper picking both with and without palm muting, since the muting action changes your hand position and range of motion.
The action of muting the string means the string "pushes back" against the pick more and resists moving. If you want to pick fast while palm muting, it's even more critical to use the barest minimum of pick (our old friend bullet number one), since the more pick you use the more the muted string will fight you and slow you down.
Comment: "pick both with your wrist wiggling slightly and with just your fingers moving the pick" : a very good point. I'd also add, learn to switch from fingers to wrist movement smoothly. Also, it's important to hold the pick closer to the index finger tip, this helps with the angle, especially with the low strap.
Answer: Not metal, but Carol Kaye has said a lot about bass pick technique, some of the key points being:

pick closer to the neck,
Grasp the pick with the side of the index finger,
keep your wrist flat, and
tap with your left foot (assuming you're right handed),
using a foam mute instead of palm muting (might not work in metal),

although some of here ideas might need to be modified to suit your genre, her approach might provide some useful approaches.
Comment: I think the picking position between closer to the neck versus closer to the bridge is very situational. In particular, in Metal there are famous performances of using an active bass and picking quite close to the bridge. Picking closer to the bridge can help with speed and accuracy since the average maximum displacement of the string is less than closer to the neck.
Comment: I'm relaying Carol Kaye's approach -- some aspects of it would probably need to be changed for specific applications.
Comment: Yes, definitely picking close to the neck doesn't fit with the speeds I need to reach.
Answer: A thing I would suggest to a beginner, is to have the bass quite high on its strap, so you can easily use the pick. If you have the bass low (like Flea or many other bassists), you won't be able to pick that fast at the beginning.
When the bass is high, your hand would feel more comfortable and you'll be able to use the pick (or fingerstyle for that matter) quite easily.
As far as the where you place the pick on the string, you'll see for yourself that the closer you play to the bridge, the fastest you'll be able to play.
Comment: Good point - not just for beginners. I tend to wear it high, in fact the same place sitting or standing. Saves having to adapt on stage after practising seated! It also puts (my) wrist/hand at a good angle for better playing. +1
Answer: If I ever need speed on a bass, I tend to rest the side of my hand on the bridge and pick near the bridge, using quite a shallow angle so the pick doesn't dig in too much and slow me down. Remember to use your tone controls on the bass and the amp as well to achieve the sound you're after (I know sound comes from the fingers, but gear helps too amirite?).
I would definitely recommend getting a teacher who will sit down with you and help you in the right direction after you've explained what your requirements are.

Bass picking technique


Separate table columns into different tables

Question: I have a task to separate n-columns table each column to different tables.
My idea in that:

I have th in each column.
So th may be a detector of new column.
I need to find tr td in each column.
I need to create new table-N with th-N value in th
I need to paste each tr td-N after th

So according to my idea, I have written following code:

jQuery(document).ready(function($) {
    function tableshoot() {

        $("table th").each(function() {
            var $this = $(this);
            var thistext = $this.html();
            var index = $this.index();

            var tdList = $this.closest("table").find("tr").find("td:eq(" + index + ")").html();

            $this.closest("table").append('

' + thistext + '

');

            $this.closest("table").find("tr").find("td:eq(" + index + ")").each(function() {
                var tdcontent = $(this).html();
                $('table.mob-table-' + index + ' tbody').append('
' + tdcontent + '
');
            });
        });

    };
    tableshoot();
});

        COL 1

        COL 2

        COL 3

      VAL 1
      VAL 2
      VAL 3

      VAL 11
      VAL 22
      VAL 33

      VAL 111
      VAL 222
      VAL 333

My question is:
Is it right way? Or are there more clean ways to do it?
No matter my code is workable. Hope this helps somebody.
Answer: Few small things:

"find("tr").find("td:eq(..." change to "find(tr td:eq..."
"$("table th").each(function()" change to "$("table th").each(function(index, value)", for clean access to index and value.

jQuery doc each


Group isomorphic to all its proper quotients, and not simple

Question: Let $G$ be a group such that for any proper normal subgroup $H \subset G$, we have $G/H \cong G$ (of course this isomorphism may not be given by the projection $G \to G/H$). Does it follow that $G$ is a simple group? What can we say about such a group $G$ in general?
Notice that $G/H \cong G$ doesn't imply $H = \{e\}$, for instance $z \mapsto z^2$ is a surjective morphism $\Bbb C^{\times} \to \Bbb  C^{\times}$ of kernel $\{\pm 1\}$.
Comment: How does $G/H$ trivial not imply $G=H$? If $g\in G\setminus H$, then $gH\ne 1H$ in $G/H$.
Comment: You write *non-trivial*, but I think it's *proper* you really mean.
Comment: @HagenvonEitzen  :  thanks, I edited my post.
Answer: $\newcommand{\C}{\mathbb{C}}$$\newcommand{\Set}[1]{\left\{ #1 \right\}}$The Prüfer $p$-group is non-simple, and satisfies your hypothesis.
Given a prime $p$, you realize it as the subgroup of the multiplicative group $\C^{*}$ given by
\begin{equation*}
  G = \Set { z \in \C^{*} : z^{p^{k}} = 1 \ \text{for some $k \ge 0$}}.
\end{equation*}
Comment: @YCor You have previously solved your possibly hard question: https://math.stackexchange.com/a/1985569/10513
Comment: @user1729 oops, thanks very much, I forgot this!
Comment: @Alphonse the wikipedia reference basically has it all, in particular it lists all the subgroups, which are normal, $G$ being abelian.
Comment: A possibly hard question is whether these are the only examples.
Comment: @YCor, brilliant, thanks!


Johansen cointegration test: interpret the result

Question: I am trying to develop a stationary time series with 6 variables in Matlab. Can anyone tell me whether the 6 variables are cointegrated? The results I got are:
Comment: *you are telling me that the six variables are not cointegrated and only the first two ones are cointegrated?* No. The cointegration takes place in the given system of variables (in this case, six variables). The question is, what is the cointegration rank, or alternatively, how many underlying random walks there are in the system. The table tells you that. I recommend Davidson & McKinnon ["Econometric Theory and Methods"](http://qed.econ.queensu.ca/ETM/) for an easy introduction into the subject.
Comment: What do you think about my answer? If it is helpful and clear, you may accept it by clicking on the tick mark to the left. Otherwise, you may ask for further clarification. This is [how Cross Validated works](https://stats.stackexchange.com/tour).
Answer: When examining the table you should go down row by row comparing the test statistic to the critical value, and see when you cannot reject the null hypothesis for the first time, for a chosen significance level. That will show whether the series are cointegrated and what the cointegration rank is.

If you cannot reject rank<=0, the series are integrated but not cointegrated.
If you reject all the cases including the maximum rank (here rank<=6), the series are not integrated to begin with (and hence there is no cointegration).
If you reject rank<=0 but stop before or at the maximum rank, the series are integrated and cointegrated, and the cointegration rank is the one at which you stopped (could not reject).

For example, choose 5% significance level. Then the first non-rejection when using the trace statistic is at r<=3, and the same is true for the eigenvalue statistic. Hence, you do not reject the null hypothesis that the data is cointegrated and the cointegration rank is 3.
Comment: This shows you how to interpret the table. However, it is not clear what you are up to in general and whether this table is relevant to what you are trying to achieve. It would help if you edited the post to include more specific information.
Comment: +1 For example, there are different tables for different specifications of the deterministic part of the model, and it is possible that the one you chose is not appropriate to your problem.
Comment: And what happens when you have mixed results? i.e. you cannot reject `rank<=0` but you can reject `rank<=1`? Do you take only the first result?
Comment: @tsando, you start from `rank<=0`. If you cannot reject, you conclude the series are integrated but not cointegrated. You do not proceed down the table if you cannot reject a row. Thus you do not consider the row `rank<=1` at all. It is just how the procedure is supposed to work.
Comment: ok. If I have only a two time series and I can reject all the cases including the maximum rank with 5% (there is no cointegration) rank <= 2, but I stop in the middle with 1% confidence (rank <= 1)? What should I do?
Comment: @ooolllooo, consider posting this as a separate question.


XWIKI Tags integration

Question: we are using our own application for tags management. We would like to integrate it with XWIKI Tag application so it would show our tags.
Is it possible to change a source of tags? To use REST endpoint, our DB, etc.
I checked XWIKI REST API, but it allows page tagging only, there is no way to create a tag (without tagging a page). Our use case is:
1. users create tags in our application
2. user opens XWIKI
3. our tags should be available in auto suggestion when tagging a page.
Any ideas?
Thank You
Answer: I have not found a way to do this via existing plugin/extension.
As all requests to our app. go via proxy, I routed all requests that XWIKI uses to load tags
<code>/xwiki/bin/view/Main/?xpage=suggest&classname=XWiki.TagClass&fieldname=tags&input=tag-name
</code>
to our endpoint and it works.

XWIKI Tags integration


First C# program with two Classes. Confused

Question: pretty new to programming and I'm a bit stuck. This is the first program I've written with two classes (in two seperate class files). I'll include all the code below. It's a program to play a dice game called Craps. My task is too create a method in the CrapsGame class that allows me to play the game over and over again until I decide to stop. But I'm having a little trouble working out how to correctly call the manyPlay() method. I'm not really sure what I'm doing. The program will play the game once by calling myCraps.play() but then won't go any further. If anyone else notices anything wrong with the code or anything that's bad practice then please point it out as I am very keen to learn. Thanks to anyone that takes the time to answer.
using System;

namespace Task4_7
{
    public class CrapsGame
    {
        string replay;
        private Craps myCraps;
        private CrapsGame newGame;

        public static void Main()
        {
            CrapsGame newGame = new CrapsGame();
            Craps myCraps = new Craps ();
            myCraps.play ();
            newGame.manyPlay ();
        }
        public void manyPlay() {
            string input; // declare local variable
            do {
                myCraps.play();
                replay:
                Console.Write("Would you like to play again? y/n");
                input = Console.ReadLine();
                if (input == "y") {
                    replay = input;
                }
                else if (input == "n") {
                    replay = "n";
                }
                else {
                    Console.WriteLine("\n Erroneous input. Please enter y (yes) or n (no)");
                    goto replay;
                }
            }
            while(replay != "n");
        }
    }
}

using System;

namespace Task4_7
{
    public class Craps
    {
        private Random randy;               // define randy as a Random class

        public Craps() {

            this.randy = new Random ();
        }

        public int oneThrow() {
            return randy.Next(6) + 1;        // pick a number from 1 to 6 and return this
        }
        public int throw2Dice() {
            int a, b, c;
            a = oneThrow ();
            b = oneThrow ();
            c = a + b;
            Console.WriteLine ("You threw a " + a + " and a " + b + " making " + c);
            return c;
        }
        public void play() {
            int result = throw2Dice ();
            switch (result) {
                case 2:
                    Console.WriteLine ("You lose! End of game!");
                    break;
                case 3:
                    Console.WriteLine ("You lose! End of game!");
                    break;
                case 12:
                    Console.WriteLine ("You lose! End of game!");
                    break;
                case 7:
                    Console.WriteLine ("You win! End of game!");
                    break;
                case 11:
                    Console.WriteLine ("You win! End of game!");
                    break;
                case 4:
                    Console.WriteLine ("Your point! Rolling again!");
                    throwPoint (result);
                    break;
                case 5:
                    Console.WriteLine ("Your point! Rolling again!");
                    throwPoint (result);
                    break;
                case 6:
                    Console.WriteLine ("Your point! Rolling again!");
                    throwPoint (result);
                    break;
                case 8:
                    Console.WriteLine ("Your point! Rolling again!");
                    throwPoint (result);
                    break;
                case 9:
                    Console.WriteLine ("Your point! Rolling again!");
                    throwPoint (result);
                    break;
                default:
                    Console.WriteLine ("Your point! Rolling again!");
                    throwPoint (result);
                    break;
            }
        }
        public void throwPoint(int result) {
            Throw:
            int a = throw2Dice();
            if (a == result) {
                Console.WriteLine ("You rolled the same score! You win!");
            } else if (a == 7) {
                Console.WriteLine ("You rolled a 7! You loose!");
            } else {
                Console.WriteLine ("You rolled a " + a + ". Rolling again!");
                goto Throw;
            }
        }
    }
}

Comment: I think this is the first time i see someone using "goto" in C#
Comment: Don't use `goto`, it's evil. As for actual problems: you never initialize the `myCraps` field and you don't want a `newGame` field. I think you're confusing the local variables inside the `Main` method with your class's instance fields.
Comment: As an aside, if you want a help code reviewing your code, check out http://codereview.stackexchange.com/
Comment: Don't use Main any more the necessary it is evel. It is not object orientated. Main should have one line `new Application.run();`
Answer: This is your problem:
Craps myCraps = new Craps();

You are hiding variable of class CrapsGame with a local variable of Main method. Simply change it to
myCraps = new Craps();

and it should work.
EDIT
and change myCraps declaration to static, of course.
EDIT2
Scope of variables: C# variable scoping not consistent?
Comment: Don't make the variables static, fix the real problem. Main is not object orientated. Use it only to bootstrap your start-up object.
Comment: You should explain more *why* this was the problem. What was really happening. Or maybe link to a tutorial which explains "hiding".
Comment: Well... it actually is hard to explain all the mistakes in different way than writing the program again from scratch. I'll do it later when I have more time. In the meantime link to SO similar question.
Answer: My first suggestion is put your Main method in a seperate file.For example you can use three files: Program.cs, CrapsGame.cs, Craps.cs. To do this just add a new class file,and move your main method to new Class file. Second, never use goto.Instead use while loop like this,
public void throwPoint(int result) {
   while(true)
   {
      int a = throw2Dice();
       if (a == result) {
           Console.WriteLine ("You rolled the same score! You win!");
           break;
       } else if (a == 7) {
          Console.WriteLine ("You rolled a 7! You loose!");
          break;
      } else {
        Console.WriteLine ("You rolled a " + a + ". Rolling again!");
    }
  }
}

Many play method:
public void manyPlay() {
    string input; // declare local variable
    myCraps.play();
    while(true) {
        Console.Write("Would you like to play again? y/n");
        input = Console.ReadLine();
        if (input == "y") {
            myCraps.play();
        }
        else if (input == "n") {
            break;
        }
        else {
            Console.WriteLine("\n Erroneous input. Please enter y (yes) or n (no)");
        }
    }

}

Answer: The problem looks like you where creating a game for use by the game iterator, but it needs to create a game for each iteration. So I delete some code: all the class variables have to go, variables should be as local as possible.
using System;

namespace Task4_7
{
    public class CrapsGame
    {
        public static void Main()
        {
            new Craps ().play ();
            new CrapsGame().manyPlay ();
        }

        public void manyPlay() {
            string replay;
            string input; // declare local variable
            do {
                new Craps().play();
                replay:
                Console.Write("Would you like to play again? y/n");
                input = Console.ReadLine();
                if (input == "y") {
                    replay = input;
                }
                else if (input == "n") {
                    replay = "n";
                }
                else {
                    Console.WriteLine("\n Erroneous input. Please enter y (yes) or n (no)");
                    goto replay;
                }
            }
            while(replay != "n");
        }
    }
}

Now fix that loop: no gotos. You need a loop in a loop, as you have but don't build your own loops.
Then if Craps.play() returned a score. You could add a class variable to accumulate the score.
Answer: Change replay to boolean and make set it to true if input is y and false if input is n.
Then change your main method.
  public static void Main()
{
    CrapsGame newGame = new CrapsGame();
    Craps myCraps = new Craps ();

    while (replay == true) {
       myCraps.play ();
       newGame.manyPlay ();
    }
}


OpenERP - Rename Page String

Question: I'd like to rename the string of a page on OpenERP. To be specific, the 'Description' page on the Expenses module.
I'm not able to inherit this through the xpath code as the page itself has no name and you cannot change the label/string through the attrs fields. Below is the code I attempted to do this however it failed:
<xpath expr="/form/sheet/notebook/page[@string='Description']" position = "attributes">
        <attriute name = "string" = "Expenses"/>
</xpath>

There has to be a way to do this but I can't seem to figure out how.
Answer: try this,
<xpath expr="//form/sheet/notebook/page[@string='Description']" position = "attributes">
    <attriute name = "string">Expenses</attriute>
</xpath>

For default attribute like
<xpath expr="path_of_field/page/group/whatever" position = "attributes">
    <attriute name = "attribute_name"> here is value </attriute>
</xpath>

Hope this will help you.

OpenERP - Rename Page String


Winning strategy, on a row with $n$ ones, two players take turn placing $+$ or $\times$ between the ones.

Question: On a paper, you create a row of $n$ ones. In one move, Art or Bart, choses two ones next to each other, placing either a $+$ or $\times$, in between the ones. After $n-1$ moves there will be either a $+$ or $\times$ between every pair of ones and the game is over. Then you calculate the total number $T$ containing all these ones: If $T$ is even, Art wins. If $T$ is odd, Bart wins.
Does either Art or Bart have a winning strategy? (Art starts of the game).
Comment: What are your thoughts on this problem?
Comment: Game is totally finite, so there must exist winning strategy for one of two players for any $n$.
Answer: I assume that multiplication will be evaluated before addition (using your preferred acronym for order of operations), and hence the result of any product will be $1$, as the product of $k$ $1$s for any $k$ is still inevitably $1$.
We can then see that $T$ simplifies to be a string of $1$s added together, with $n-k-1$ addition signs, hence the result will be $n-k$, where $k$ is the total number of multiplication signs used. Once we take care of the trivial case for $n=1$ where Bart wins immediately, we can see that whoever plays the last move can alter the parity to win.
We can see that if $n$ is odd then Bart plays last and wins, and if $n$ is even then Art plays last and wins. So yes a winning strategy does exist for Art or Bart depending on $n$, but there is no universal winning strategy for either for all $n$.


Calculate the standard error of the difference between two independent proportions

Question: Here's the question: A survey of 500 males and 700 females showed that 132 males and 226 females agreed with a particular statement. Use this information to calculate the proportions of males and females that agreed with the statement. This will give you the values for p1 and p2. Use this to calculate q1 and q2. Now calculate the standard error of the difference between two independent proportions. Then determine the confidence interval for the difference between two independent proportions for the 95 confidence level.
I think my formulas are wrong because they're not the standard error of the difference between two independent proportions or the confidence interval for the difference between two independent proportions like what these charts show, I have the specific bottom equation zoomed in. I'm still unsure what the q1 and q2 refers to.

Here's what I have for formulas so far:
p1 = 0.264 (132/500)
p2 = 0.322857 (226/700)
q1 =
q2 =

Stdev1 = sqrt (p(1-p)) = (1-0.264)*0.264 = sqrt(0.194304) = 0.44079927404
Stdev2 = sqrt(p(1-p)) = (1-0.322857)*0.322857 = sqrt(0.218620357) = 0.4675685586

Std error = standard deviation / square root(number of samples)
Std error1 = 0.44079927404/sqrt(500) = 0.44079927404/22.360679775 = 0.019713142
Std error2 = 0.4675685586/sqrt(700) = 0.4675685586/26.4575131106 = 0.017672430

Standard deviation = in R it's sd() and in sd you need series of values,
    m = mean of values
    x – m = difference of values minus mean
    sum of squared diff from the mean = sum(x-m)^2
    square root [(sum of squared diff from the mean) / (sample size -1)]

Confidence interval (95%)  =

    Margin of error = Square root [p(1-p)/n]  * 1.96  //n = sample size, 1.96 is 95% confidence interval
    Margin error1 = sqrt(0.194304/500)   * 1.96  = 0.01971314282  * 1.96 = 0.038637759
    Margin error2 = sqrt(0.218620357/700) ] * 1.96 = 0.01767240787  * 1.96 = 0.034637919

    P + margin of error = Upper confidence interval
        p1 = 0.264+0.038637759 = 0.302637759
        p2 = 0.322857 + 0.034637919 = 0.35749419
    P – margin of error = Lower confidence interval
        p1 = 0.264-0.038637759 = 0.225362241
        p2 = 0.322857 - 0.034637919 = 0.288219081

    P1 CI =  0.225362241 <  0.264 < 0.302637759
    P2 CI =  0.288219081 < 0.322857 < 0.35749419

Comment: $q_1$ is just $1-p_1$. I am not sure what you think is wrong with the formula for estimated standard error that you highlighted ($\sqrt{\frac{p_1q_1}{n_1}+\frac{p_2q_2}{n_2}}$).
Comment: that's the formula for the standard error of a difference between two independent proportions and the one next to it is the confidence interval difference between two independent proportions, it's highlighted because that's how you solve this question and that's what this question is about @Glen_b
Comment: You say in your question "they're ***not*** the standard error of the difference between two independent proportions..." (which as far as I can see is the exact opposite of what you just said in your comment).  Why do you say that in the question?
Comment: It says I think they're wrong because they're not the difference, and if you look at my formulas they're wrong because they're not the difference. @Glen_b
Comment: The formula for the variance *of* a difference does not itself involve a difference of variances ("variance of" and "difference of" are not *transitive* operations). Indeed that it should not is obvious, since you'd regularly get negative variances, which is impossible. (You take square roots of variances to get standard errors)
Comment: Buddy those are my professor's exact words for this problem, difference can also just mean different, that's literally the entire question being asked and answered here.
Answer: In order to understand this material, you should read about the properties of the variance operator.  This is a quadratic operator, which operates in a specific way on linear functions of random variables.  Once you understand the algebraic rules for the way this operator works, you will be able to see how to get the variance of differences between random quantities.
For completeness, I will go through the working here.  Suppose we let $\hat{p}_1 = x_1/n_1$ and $\hat{p}_2 = x_2/n_2$ be the observed sample proportions, where $x_1 \sim \text{Bin}(n_1,p_1)$ and $x_2 \sim \text{Bin}(n_2,p_2)$ are binomial random variables.  Assuming that these are from independent samples, using the rules for the variance operator, the true variance of the difference in proportions is:
$$\begin{align}
\mathbb{V}(\hat{p}_1-\hat{p}_2)
&= \mathbb{V} \Big( \frac{x_1}{n_1} - \frac{x_2}{n_2} \Big) \\[6pt]
&= \mathbb{V} \Big( \frac{x_1}{n_1} \Big) + \mathbb{V} \Big( -\frac{x_2}{n_2} \Big) \\[6pt]
&= \mathbb{V} \Big( \frac{x_1}{n_1} \Big) + (-1)^2 \mathbb{V} \Big( \frac{x_2}{n_2} \Big) \\[6pt]
&= \mathbb{V} \Big( \frac{x_1}{n_1} \Big) + \mathbb{V} \Big( \frac{x_2}{n_2} \Big) \\[6pt]
&= \frac{\mathbb{V}(x_1)}{n_1^2} + \frac{\mathbb{V}(x_2)}{n_2^2} \\[6pt]
&= \frac{n_1 p_1 (1-p_1)}{n_1^2} + \frac{n_2 p_2 (1-p_2)}{n_2^2} \\[6pt]
&= \frac{p_1 (1-p_1)}{n_1} + \frac{p_2 (1-p_2)}{n_2} \\[6pt]
&= \frac{p_1 q_1}{n_1} + \frac{p_2 q_2}{n_2}. \\[6pt]
\end{align}$$
Consequently, the true "standard error" of the estimator (the standard deviation of the difference between sample proportions) is:
$$\begin{align}
\text{se}
= \sqrt{\mathbb{V}(\hat{p}_1-\hat{p}_2)}
&= \sqrt{\frac{p_1 q_1}{n_1} + \frac{p_2 q_2}{n_2}}, \\[6pt]
\end{align}$$
and the "estimated standard error" (using the standard estimate) is:
$$\begin{align}
\hat{\text{se}}
&= \sqrt{\frac{\hat{p}_1 \hat{q}_1}{n_1} + \frac{\hat{p}_2 \hat{q}_2}{n_2}}. \\[6pt]
\end{align}$$
If you have a look at the working above, you will see that the negative since that occurs in the difference in proportions does not affect the variance.  This is because taking the negative of a random variable just changes its direction and not its variance.  Mathematically, this property is a consequence of the fact that constants inside the variance operator come out of the operator squared.
Comment: For binomial distributions, many authors use $q = (1-p).$ In the last panel of the table in your Question, it seems that equal sample sizes are used. @Ben's equations (using $n_1$ and $n_2)$ and my computations took the different sample sizes into account
Comment: Thanks! That explains the diagram in the chart. In the last steps where it goes from ```p1(1−p1)``` to ```p1q1``` what is the ```q``` representing? Is ```n``` either the 500 or 700 sample size, and would the variables with hats ```p^``` be the observed yes answers, so 132, with ```p``` being 500?
Answer: Confidence intervals for men and women separately. Let capital letters denote estimates: The point estimates for the proportions
of men and of woman who agree are $0.264$ and $0.323,$ respectively. The
corresponding Wald confidence intervals, based on normal approximation, are
$(0.225, 0.303)$ for men and $(0.288, 0.357)$ for women.
P.m = 132/500;  P.m
[1] 0.264
SE.m = sqrt(P.m*(1-P.m)/500);  SE.m
[1] 0.01971314
CI.m = P.m + qnorm(c(.025,.975))*SE.m
CI.m
[1] 0.225363 0.302637

P.w = 226/700; P.w
[1] 0.3228571
SE.w = sqrt(P.w*(1-P.w)/700);  SE.w
[1] 0.01767243
CI.w = P.w + qnorm(c(.025,.975))*SE.w
CI.w
[1] 0.2882198 0.3574945

The procedure binom.test in R gives (slightly different) exact binomial
confidence intervals, $(0.226, 0.305)$ for men and $(0.288, 0.359)$ for women, as shown below.
binom.test(132,500)$conf.int
[1] 0.2258560 0.3049604
attr(,"conf.level")
[1] 0.95
binom.test(226,700)$conf.int
[1] 0.2883144 0.3589013
attr(,"conf.level")
[1] 0.95

CI for the difference between men and women.
As in the last section of the table in your question and in @Ben's Answer (+1), the (estimated) standard error for the difference P_w - P_m is as follows:
SE.d = sqrt(SE.w^2 + SE.m^2);  SE.d
[1] 0.02647495

Then a 95% confidence interval for the difference, based on normal approximations,
is (0.0070, 0.1107),$ which is essentially the same
P.w-P.m + qnorm(c(.025,.975))*SE.d
[1] 0.006967198 0.110747087

In R the procedure prop.test gives the same 95% confidence interval
$(0.0070, 0.1107).$ [This interval is also based on a normal approximation; the continuity correction was declined on account
of the large sample sizes.]
prop.test(c(226,132), c(700,500), cor=F)$conf.int
[1] 0.006967198 0.110747087
attr(,"conf.level")
[1] 0.95

Notice that this 95% confidence interval does not include $0.$
Accordingly, a test the women and men have equally favorable opinions
is rejected at the 5% level (against the two-sided alternative).
The P-value of the (approximate normal) test is $0.028 < 0.05 = 5\%.$
prop.test(c(226,132), c(700,500), cor=F)$p.val
[1] 0.02802182

Comment: Thanks! Looks like my manual calculations were correct when I was doing the individual standard errors and confidence intervals but I didn't understand how to do the difference, now I have some extra R code too for future reference, this really helped a lot!
Comment: Edited to show numerical values of (estimated) standard errors.


What is the correct way of calculating Rectifier Linear and MaxOut functions?

Question: If I have a artificial neuron with 2 inputs:
input 1 = 0.7 & weight = 0.7
input 2 = 0.3 & weight = 0.3

If I use a Rectifier Linear (ReLU) as activation function ($f(x)=max(0,x)$) is the output of this neuron:
Outcome 1: {I assume this is correct}: ReLU = $max(0,0.7*0.7+0.3*0.3) = 0.58$
or
Outcome 2: ReLU = $max(0,0.7*0.7,0.3*0.3) = 0.49 $
Or in other words: is this max taken over the summation or individual inputs? As I see ReLU as a drop in replacement for sigmoid/tanh I expect the first one is correct.
Question 1: is outcome 1 or 2 the correct way of calculating ReLU
I started to hesistate because of maxout which is defined in the paper as:

$ h_i = \max_{j \in [1, k]} z_{ij} $ with $z_{ij} = x^T W_{ij} + b_{ij}$,  $ W \in \mathbb{R}^{d \times m \times k} $ and $b \in \mathbb{R}^{m \times k}$

Based on this definition I expect that the output of this neuron if maxout is used as activation is: $max(0.7*0.7,0.3*0.3) = 0.49$
Question 2: is this the correct way of calculating maxout for 1 layer with 1 neuron with these 2 input/weights??
The reason why I hesistate about the maxout/ReLU algo impls is because of the following phrase in this paper:

The only difference between maxout
  and max pooling over a set of rectified linear units
  is that maxout does not include a 0 in the max.

This suggests (to me) that $ReLU == MaxOut$ if the maximum $value > 0$ so that outcome 2 is correct where I first (still) assume outcome 1 is correct.
Answer:
If I have a artificial neuron with 2 inputs:
input 1 = 0.7 & weight = 0.7
input 2 = 0.3 & weight = 0.3

Let's make things clear. Consider the non-spatial case where activation function's input is just a 1D vector:
$\vec{x} = (x_1, ..., x_d)$ (where do your weights come from?), which is usually an output of a Linear or Batch Normalization layer but can be what you want.
Typical activation functions are $\mathbb{R}  \rightarrow  \mathbb{R} $. That means they handle each input component individually. For example, ReLU:
$ ReLU_i(x_i) = max(0, x_i) $; Note that no weight involved.
Applied to an input vector: $ ReLU((1, -2, 3, -4, 5)) = (1, 0, 3, 0, 5) $
But MaxOut is a $\mathbb{R}^d  \rightarrow  \mathbb{R} $ function:
$ MaxOut_s(\vec{x}) = max( \vec{w}_{s1} \vec{x} + b_{s1}, ... , \vec{w}_{sk} \vec{x} + b_{sk}) $
$ MaxOut(\vec{x}) = (MaxOut_1(\vec{x}), ..., MaxOut_m(\vec{x})) $
where the number of components $k$ in each MaxOut function and the amount $ m $ of such functions are up to you, $w_{sl} \in \mathbb{R}^d, b_{sl} \in \mathbb{R}$ are learned.
Comment: The weights are not necessary needed for this example, but typically the output of a neuron is calculated by f(sum of all (weights * input)), where then f is the activiation function.
Comment: @jos Yes, classical neuron is a composition (Activation ∘ Linear)(input). In practice, however, we separate these two parts as they are completely independent and have nothing to do with the internal structure of each other (activation function doesn't see linear layer's weights).


Question regarding the syntax of someting related to macro in C++

Question: #define minimum(mn, b) mn = min(b)
#define maximum(mx, c) mx = max(c)
#define INF 10000000
#define toStr(a) #a
#define io(v) v.push_back()
#define FUNCTION(a,b) #

#include <iostream>
#include <vector>
using namespace std;

#if !defined toStr || !defined io || !defined FUNCTION || !defined INF
#error Missing preprocessor definitions
#endif

FUNCTION(minimum, <)
FUNCTION(maximum, >)

int main(){
    int n; cin >> n;
    vector<int> v(n);
    foreach(v, i) {
        io(v)[i];
    }
    int mn = INF;
    int mx = -INF;
    foreach(v, i) {
        minimum(mn, v[i]);
        maximum(mx, v[i]);
    }
    int ans = mx - mn;
    cout << toStr(Result =) <<' '<< ans;
    return 0;

}

This is a sample question from a hackerrank question, so there would be some mistakes in it. I want to know what does the part
FUNCTION(minimum, <)
FUNCTION(maximum, >)

mean ? It doesn't look like a macro as it doesn't start with #define. The discussion forums too didn't have a good explanation about this part, just that it relates to the macro defined as #define minimum(mn, b) mn = min(b) and #define maximum(mx, c) mx = max(c).
'
I want to know what's it called and some advice on good resource to read about it.
The title is poorly written as I have no clue what to refer to that doubtful part of code as.
Comment: You should "refer to that doubtful part of code as" something that no self-respecting C++ developer should be writing. Sites like "hackerrank", and similar ones, are not teaching you well-written C++, and providing useful knowledge. They're a waste of web space.
Comment: I don't believe `#define FUNCTION(a,b) #` is valid syntax. `#` operator should precede a token.
Comment: @IgorTandetnik you can check the question in the link I provided.
Comment: The question at the link doesn't appear to contain `FUNCTION` at all, in any shape or form. At least not the way that page appears to a non-signed-in user, and I'm not going to create an account at that site.
Comment: It doesn't even compile (as expected): `main.cpp:6:21: error: '#' is not followed by a macro parameter`
Comment: @IgorTandetnik it does, you need to expand the code at line 3.
Comment: When I go to that page, I don't see any code.
Comment: You need to create an account and log in first.
Comment: I gathered as much, but I'm not going to.
Comment: Actually, no, it is there even without. just scroll to the bottom
Comment: It's not there for me, at the top or the bottom or elsewhere.
Comment: Just to clarify, the code that I posted is the one that I am working on right now. So there are mistakes, and the program won't compile. I just wanted to know what some lines there meant, so that I could go look and read about them.
Answer: Let's break this answer into parts:

First, the thing you show here isn't valid code. #define FUNCTION(a, b) # doesn't compile on GCC, it correctly says:
error: '#' is not followed by a macro parameter

# is supposed to work like shown in your toStr example, where #a causes it to emit a string with a's value as contents.

Second, I assume that the poster of this "solution" wanted FUNCTION to just do nothing.
It seems that some compilers do treat a sole # that way, but it's not correct. It would have worked to write #define FUNCTION(a, b) without anything afterwards (or
#define FUNCTION(a, b) // like I saw in some other solutions for this question).
So, the answer to "what does this part do" is literally "nothing". (At least, it was intended this way.)

Third, even with that fixed, the code doesn't look right, because unless I'm misreading this, it doesn't really calculate any minimum or maximum, because min doesn't get the previous minimum as argument (same for max)! I'd expect this...
#define minimum(mn, b) mn = min(mn, b)
#define maximum(mx, c) mx = max(mx, c)

...instead of the current min(b) and max(c) there.

Forth, it seems that most solutions on this hackerrank question turn FUNCTION into a no-op and instead create minimum and maximum as macros.
But, I feel like the intention behind FUNCTION was something else, something a bit more clever. You could define it as macro that creates functions (hence the name) named after the first argument, that compare the minimum/maximum based on the second argument used as comparison operator:
#define FUNCTION(_FN_NAME_, _COMPARISON_OP_) \
  void _FN_NAME_(int& limit, int newValue) { \
    if (newValue _COMPARISON_OP_ limit) { \
      limit = newValue; \
    } \
  }

This way, FUNCTION(minimum, <) and FUNCTION(maximum, >) would expand to:
void minimum(int& limit, int newValue) {
  if (newValue < limit) {
    limit = newValue;
  }
}

void maximum(int& limit, int newValue) {
  if (newValue > limit) {
    limit = newValue;
  }
}


Use SQL to assign id based on fields with duplicate values

Question: Do to a mistake in data entry I need to change the value in a table based upon the value in another table. The best way to explain is by showing a "contrived example".
Site Table

SiteId       SiteName
----------------------
1            Chicago
2            New York
3            Boston
4            Chicago
5            New York
6            Boston

Project Table

ProjectName      SiteId
---------------------------
Project #1         1
Project #2         2
Project #3         2
Project #4         3

I need to update the Project Table to use the "second" set of SiteIds from the Site Table instead of the ones being used. For example, I need The Project Table to look like ...
ProjectName      SiteId
---------------------------
Project #1         4
Project #2         5
Project #3         5
Project #4         6

I originally thought of a self join but I am not sure how to differentiate between SiteName values. I can join using the SiteName but how can I make sure I assign the second set of SiteIds
The actual list is very long so I cannot do it by hand.
UPDATE: The Project Name's are unique and there is also a unique row identifier for the Project Table.
Comment: I don't see any relation between Projects Table and Site table apart from Site ID. What exactly is your logic to assign the "second" set of Site ID?
Comment: Are the ProjectName unique?
Answer: Try this :
UPDATE p
SET p.SiteId=s2.SiteId
FROM Project p
INNER JOIN Site s on s.SiteId=p.SiteId
INNER JOIN (
SELECT SiteName,MAX(SiteId) as SiteId
FROM Site
GROUP BY SiteName) s2 on s2.SiteName=s.SiteName

Answer: UPDATE P
SET SiteId = S.maxSiteId
FROM Project P
INNER JOIN (SELECT MAX(SiteId) AS maxSiteId,
                   MIN(SiteId) AS minSiteId
            FROM   Site
            GROUP BY SiteName) S
   ON P.SiteId = S.MinSiteId

Comment: Did you perhaps mean `GROUP BY SiteName`?


Can't install own custom modules in Odoo 13

Question: During the last two days I have been trying to install a custom module in Odoo 13. I got the same error over and over again, telling that a column didn't exist in the model that I was creating (the variable in the class did, indeed, exist), I show the error down below.
The python code of the module is the following:
from odoo import models, fields, api

class OfferStage(models.Model):
    _name = 'offer.stage'
    _description = 'Offer stage'

    name = fields.Char()
    revisable = fields.Boolean()
    sequence = fields.Integer()
    modificable = fields.Boolean()
    notify_jefe = fields.Boolean()
    fold = fields.Boolean()
    convertible = fields.Boolean()
    notify_personal = fields.Boolean()
    notify_jefe_area = fields.Boolean()

And the error I get:
Error:
Odoo Server Error
Traceback (most recent call last):
  File "/opt/odoo/odoo/odoo/http.py", line 624, in _handle_exception
    return super(JsonRequest, self)._handle_exception(exception)
  File "/opt/odoo/odoo/odoo/http.py", line 310, in _handle_exception
    raise pycompat.reraise(type(exception), exception, sys.exc_info()[2])
  File "/opt/odoo/odoo/odoo/tools/pycompat.py", line 14, in reraise
    raise value
  File "/opt/odoo/odoo/odoo/http.py", line 669, in dispatch
    result = self._call_function(**self.params)
  File "/opt/odoo/odoo/odoo/http.py", line 350, in _call_function
    return checked_call(self.db, *args, **kwargs)
  File "/opt/odoo/odoo/odoo/service/model.py", line 94, in wrapper
    return f(dbname, *args, **kwargs)
  File "/opt/odoo/odoo/odoo/http.py", line 339, in checked_call
    result = self.endpoint(*a, **kw)
  File "/opt/odoo/odoo/odoo/http.py", line 915, in __call__
    return self.method(*args, **kw)
  File "/opt/odoo/odoo/odoo/http.py", line 515, in response_wrap
    response = f(*args, **kw)
  File "/opt/odoo/odoo/addons/web/controllers/main.py", line 1331, in call_button
    action = self._call_kw(model, method, args, kwargs)
  File "/opt/odoo/odoo/addons/web/controllers/main.py", line 1319, in _call_kw
    return call_kw(request.env[model], method, args, kwargs)
  File "/opt/odoo/odoo/odoo/api.py", line 387, in call_kw
    result = _call_kw_multi(method, model, args, kwargs)
  File "/opt/odoo/odoo/odoo/api.py", line 374, in _call_kw_multi
    result = method(recs, *args, **kwargs)
  File "<decorator-gen-60>", line 2, in button_immediate_install
  File "/opt/odoo/odoo/odoo/addons/base/models/ir_module.py", line 72, in check_and_log
    return method(self, *args, **kwargs)
  File "/opt/odoo/odoo/odoo/addons/base/models/ir_module.py", line 463, in button_immediate_install
    return self._button_immediate_function(type(self).button_install)
  File "/opt/odoo/odoo/odoo/addons/base/models/ir_module.py", line 573, in _button_immediate_function
    modules.registry.Registry.new(self._cr.dbname, update_module=True)
  File "/opt/odoo/odoo/odoo/modules/registry.py", line 86, in new
    odoo.modules.load_modules(registry._db, force_demo, status, update_module)
  File "/opt/odoo/odoo/odoo/modules/loading.py", line 421, in load_modules
    processed_modules += load_marked_modules(cr, graph,
  File "/opt/odoo/odoo/odoo/modules/loading.py", line 313, in load_marked_modules
    loaded, processed = load_module_graph(
  File "/opt/odoo/odoo/odoo/modules/loading.py", line 202, in load_module_graph
    registry.init_models(cr, model_names, {'module': package.name}, new_install)
  File "/opt/odoo/odoo/odoo/modules/registry.py", line 369, in init_models
    model._auto_init()
  File "/opt/odoo/odoo/odoo/models.py", line 2529, in _auto_init
    new = field.update_db(self, columns)
  File "/opt/odoo/odoo/odoo/fields.py", line 857, in update_db
    self.update_db_notnull(model, column)
  File "/opt/odoo/odoo/odoo/fields.py", line 921, in update_db_notnull
    sql.drop_not_null(model._cr, model._table, self.name)
  File "/opt/odoo/odoo/odoo/tools/sql.py", line 119, in drop_not_null
    cr.execute('ALTER TABLE "{}" ALTER COLUMN "{}" DROP NOT NULL'.format(tablename, columnname))
  File "/opt/odoo/odoo/odoo/sql_db.py", line 173, in wrapper
    return f(self, *args, **kwargs)
  File "/opt/odoo/odoo/odoo/sql_db.py", line 250, in execute
    res = self._obj.execute(query, params)
psycopg2.errors.UndefinedColumn: column "name" of relation "offer_stage" does not exist

After some trial and error, I tried to install a default module that is created with odoo-bin scaffold, and what was my surprise when I cound't install it neither.
The error I get when installing the default module is a collision with other tables of odoo packages, since I am in a test environment I tried removing those packages and, when trying to reinstall, the same error arose but with a different package. I can't figure out why this happens because, a priori, my package only depends on 'base'.
The code of the default module created with scaffold:
# -*- coding: utf-8 -*-
from odoo import models, fields, api

class borrar(models.Model):
    _name = 'borrar.borrar'
    _description = 'borrar.borrar'

    name = fields.Char()
    value = fields.Integer()
    value2 = fields.Float(compute="_value_pc", store=True)
    description = fields.Text()

    @api.depends('value')
    def _value_pc(self):
        for record in self:
            record.value2 = float(record.value) / 100

The error I get:
Error:
Odoo Server Error
Traceback (most recent call last):
  File "/opt/odoo/odoo/odoo/http.py", line 624, in _handle_exception
    return super(JsonRequest, self)._handle_exception(exception)
  File "/opt/odoo/odoo/odoo/http.py", line 310, in _handle_exception
    raise pycompat.reraise(type(exception), exception, sys.exc_info()[2])
  File "/opt/odoo/odoo/odoo/tools/pycompat.py", line 14, in reraise
    raise value
  File "/opt/odoo/odoo/odoo/http.py", line 669, in dispatch
    result = self._call_function(**self.params)
  File "/opt/odoo/odoo/odoo/http.py", line 350, in _call_function
    return checked_call(self.db, *args, **kwargs)
  File "/opt/odoo/odoo/odoo/service/model.py", line 94, in wrapper
    return f(dbname, *args, **kwargs)
  File "/opt/odoo/odoo/odoo/http.py", line 339, in checked_call
    result = self.endpoint(*a, **kw)
  File "/opt/odoo/odoo/odoo/http.py", line 915, in __call__
    return self.method(*args, **kw)
  File "/opt/odoo/odoo/odoo/http.py", line 515, in response_wrap
    response = f(*args, **kw)
  File "/opt/odoo/odoo/addons/web/controllers/main.py", line 1331, in call_button
    action = self._call_kw(model, method, args, kwargs)
  File "/opt/odoo/odoo/addons/web/controllers/main.py", line 1319, in _call_kw
    return call_kw(request.env[model], method, args, kwargs)
  File "/opt/odoo/odoo/odoo/api.py", line 387, in call_kw
    result = _call_kw_multi(method, model, args, kwargs)
  File "/opt/odoo/odoo/odoo/api.py", line 374, in _call_kw_multi
    result = method(recs, *args, **kwargs)
  File "<decorator-gen-60>", line 2, in button_immediate_install
  File "/opt/odoo/odoo/odoo/addons/base/models/ir_module.py", line 72, in check_and_log
    return method(self, *args, **kwargs)
  File "/opt/odoo/odoo/odoo/addons/base/models/ir_module.py", line 463, in button_immediate_install
    return self._button_immediate_function(type(self).button_install)
  File "/opt/odoo/odoo/odoo/addons/base/models/ir_module.py", line 573, in _button_immediate_function
    modules.registry.Registry.new(self._cr.dbname, update_module=True)
  File "/opt/odoo/odoo/odoo/modules/registry.py", line 86, in new
    odoo.modules.load_modules(registry._db, force_demo, status, update_module)
  File "/opt/odoo/odoo/odoo/modules/loading.py", line 467, in load_modules
    env[model]._check_removed_columns(log=True)
  File "/opt/odoo/odoo/odoo/models.py", line 2447, in _check_removed_columns
    tools.drop_not_null(cr, self._table, row['attname'])
  File "/opt/odoo/odoo/odoo/tools/sql.py", line 119, in drop_not_null
    cr.execute('ALTER TABLE "{}" ALTER COLUMN "{}" DROP NOT NULL'.format(tablename, columnname))
  File "/opt/odoo/odoo/odoo/sql_db.py", line 173, in wrapper
    return f(self, *args, **kwargs)
  File "/opt/odoo/odoo/odoo/sql_db.py", line 250, in execute
    res = self._obj.execute(query, params)
psycopg2.errors.UndefinedColumn: column "rows" of relation "product_packaging" does not exist

However, the table borrar_borrar does get created:
link to image showing table in pgadmin4
This only happens with modules created by me, I have downloaded several modules from github and the official Odoo store and all of them install flawlessly.
Note: for ease of maintenance I have the modules in a git repository and I have soft-linked them to the custom-addons folder in the odoo directory. I have also tried placing them directly in the directory and the errors are the same.
Answer: I found out the solution. I'm writing it here in case someone face the same problem in the future.
The issue was that I had a Foreign Data Wrapper (FDW) to read data from another database and, for some reason, it was causing some kind of interference with the database I was working on. When I removed the FDW, everything worked as expected.


Does being Nonempty Compact Set on $\mathbb{R^+_2}$ imply being Convex set?

Question: Look at the domain of a function $y=x-2$ where $x\in\mathbb{R_+}$.
 Then, the triangle produced by x and y-intercepts is bounded and closed. So it is compact. Suppose it is also nonempty.
 Does this imply the set is convex?
Graphically, the answer is YES. And using the definition of a set being convex, YES (e.g. for any $\alpha\in[0,1]$...).
 But my question is can we make a direct implication between compact set and convex set?
 Thanks!
Comment: If $x\in \mathbb R^2,$ what sense does $x-2$ make?
Comment: @zhw, a nonsense. well I call it Monday nonsense. you?
Answer: No, of course not. Any finite set with more than one point is compact and not convex.
Comment: Sure, that's an example.
Comment: Hi T, thanks for the answer. Can you give me a blatant example to shed some more light? I am keep thinking of the triangle that is created under the line say, $y=2-x$, and see that it is closed and bounded triangle... So from your answer, I thought of a set $S=\{1,5\}$. This is compact but not convex?
Comment: Is an example $S=\{1,5\}$?


Fastest way to search in millions of records which is the combination of two js objects

Question: I have millions of objects of messages
messages: [
    {
      id: Int,
      text: String,
      userId: Int,
      receiverId: Int,
    },

and thousands of users
  users: [
    {
      id: Int,
      name: String,
    },

I need to process two objects and return an object in format
[{ message, userFromName, userToName }]

I read about array methods like find, filter, some and all of these are slower than native for and foreach.
I also wrote a function which two foreach loops
msgData.forEach(function(msg,i) {
    ...iterating every msg
    userData.forEach(function(user) {
       ...iterating every user id over message sender and receiver id
    });
});

The complexity of the code O(n)square
How to get the required format in less amount of time?
Comment: Maybe it would be more efficient if you made the server process this data.
Comment: If your data can be converted to object with the id being the key, like `messages = {"id1": {...}, "id2": {...}}` and `users = {"id1": {...}, "id2": {...}}` then you can drastically improvement performance since look ups are now done by the Object key, not iterating through an array.
Comment: "*I need to process two objects*" - which ones? "*and return an object in format*" - do you mean returning an array with multiple objects?
Comment: What makes you think that  `find` or `some` are slower than `forEach`?
Comment: Put them in a few `Map`s: messages keyed by sender, messages keyed by receiver, users keyed by id. That should allow you to do most searches efficiently enough.
Comment: @Bergi - Please read https://codeburst.io/javascript-performance-test-for-vs-for-each-vs-map-reduce-filter-find-32c1113f19d7
Comment: @PuneetKushwah That article makes no sense. The `forEach` method has exactly the same disadvantages as a the other array iteration methods.
Comment: @Bergi -  I have also read the some thing on many other stackoverflow questions... if you are dealing in millions go for FOR loop or FOREACH loop... however I am not sure how correct it is.
Comment: @PuneetKushwah The only reasonable advise is to do your own benchmarks on your actual use case with your real data. That said, modern engines try to optimise all looping methods the same. And as always: if you are looping over millions of records, your data structure was chosen wrong.
Answer: Convert users to a dictionary for fast, non-iterative lookup:
Native Object:
let userDict = users.reduce((o,u)=> {
  o[u.id]=u.name;
  return o;
}, {});

Map:
let userDict = new Map();
userDict.forEach(u => userDict.set(u.id,u.name));

This is O(n). With this dictionary you can simplify the msgData forEach to this:
let result = msgData.map(msg => {
  return { message: msg.text, userFromName: userDict[msg.userId], userToName: userDict[msg.receiverId]};
 });

This is also O(n) as both object and Map lookups are O(1). See this question for performance details on those. Either way you go will be a significant performance improvement over your current O(n^2) solution.
Answer: Assuming that you will have a key in common between the two arrays, you could use a Hash Map Data Structure, in Javascript can be represented as a simple plain object, for example:

const users = [{id: 1, name: 'Marcela'}, {id:2, name: 'Ana'}];
const messages = [{id: 1, message: 'She is a great Graphic Designer'}, {id: 2, message: 'She likes watch movies'}];

// #1 convert one array to a hashmap
const userHashMap = {};

// O(N)
for (let user of users) {
  userHashMap[user.id] = user;
}

// above code will store a DS like
// {
//     1:
//         {
//             id: 1,
//             name: 'Marcela'
//         },
//     2:
//         {
//             id: 2,
//             name: 'Ana'
//         }
// }

// #2 Now you can iterate over messages in O(N)
// and we can get the values of users
// in constant time O(1) (That's the most important use of HashMaps):

messages.forEach(message => {
  console.log(`This id message ${message.id} belongs to ${userHashMap[message.id].name}`);
  console.log(`Message for ${userHashMap[message.id].name}: ${message.message}`);
});

Remember, we reduced time complexity using a technique that has an impact in memory (object HashMap is storing data for every user so space complexity is O(N)).


db_query - Get all nid in more than one nodetype

Question: This is a simple query , but i really dont know why its not working. I think the problem is with single quote used!
$type = array('node_type_1', 'node_type_2', 'node_type_3');
$placeholders = db_placeholders($type, 'text');
$query = "SELECT nid FROM {node} WHERE uid = %d AND type IN ($placeholders) AND status = 1 ORDER BY nid DESC";
$result = pager_query($query, 10, 0, NULL, $user->uid, $type);

It tried this also
$result = pager_query($query, 10, 0, NULL, $user->uid, implode(', ',$type);

I am getting error
warning: mysql_real_escape_string() expects parameter 1

Answer: The correct way to use db_placeholders() with page_query() is shown in taxonomy_select_nodes(). In your case, the code should be the following one.
$type = array('node_type_1', 'node_type_2', 'node_type_3');
$placeholders = db_placeholders($type, 'text');
$args = array_merge(array($user->uid), $type);

$query = "SELECT nid FROM {node} WHERE uid = %d AND type IN ($placeholders) AND status = 1 ORDER BY nid DESC";
$result = pager_query($query, 10, 0, NULL, $args);