"Permission denied" & 500 Internal Server error serving PHP in Mac OS X

Question: I just set up Web Sharing in Mac OS X 10.6.2 Snow Leopard. My httpd.conf allows for ExecCGI and all the folders and files are readable by everybody and even writable by me.
I put a simple Hello World in index.php in my base site and yet my apache error log shows this:
[Thu Mar 18 00:17:18 2010] [error] [client 192.168.11.135] (13)Permission denied: exec of '/Users/abhic/Sites/index.php' failed
[Thu Mar 18 00:17:18 2010] [error] [client 192.168.11.135] Premature end of script headers: index.php
<code><html>
<head>
    <title> Hello </title>
</head>

<body>
    <?php echo "Hello"; ?>
</body>

</html>
</code>
is what my index.php looks like placed in /Users/abhic/Sites
My browser shows a 500 Internal Server Error
Any help would do me good in the middle of the night. I have been trying to solve this for way too long.
Thank you.
Answer: It looks like you may have attempted to configure php to be executed as CGI.  This would not be the ideal implementation for PHP.
Do you have handlers specified?  Is the module loaded?
If you provide your full configuration file, we should be able to help you.
Comment: Do I copy paste the entire httpd.conf file here?
Comment: Thank you, it worked!

I just took out **.php** from this line in my httpd.conf

    AddHandler cgi-script .cgi .php .pl


Can $n!+1$ be a square number when n is a big number?

Question: To be specific, $n$ and $a$ are positive integers.
I guess the equation $n!=a^2-1$ just have three solutions.
There are $n=4,a=5;n=5,a=11;n=7,a=71$.
How to prove it? Or my guess is wrong.
Comment: This is [Brocard's Problem](https://en.wikipedia.org/wiki/Brocard%27s_problem).  The solution is unknown.
Answer: As requested in the comments:  This is a (fairly) well known open problem.  It is known as Brocard's Problem. The $abc$ conjecture would show that there are only finitely many solutions, though I do not believe it would establish that the known list is complete.


What ML architectures might be best to classify text as containing an event or not?

Question: I was looking for some ML/NLP advice. I have 50,000 newsletters (emails) that are labelled either "event" or "not event". Here is an example of each:
Not event:
COMPLIMENTARY STANDARD SHIPPING ON ALL DOMESTIC ORDERS.

ENDS SOON
TIMELESS SKIN SERUM DUO
http://enews.ernolaszlo.com/q/bmhc31K1AEaZwmn8quhjEVD2Gn6bhKECHXID2Z_-oGFLUexGdsY3pzTtf

Protect your youthful glow; stock up now.
http://enews.ernolaszlo.com/q/Y16cHUQU_1l761il6e1xyZBSB5Kl1GNI9uyRdaZhOJoy7obGhj-Hm_eoW

Transphuse Rapid Renewal Cell Protocol
This month only, get our full-size, revolutionary age-reversing serum free when you spend $400
http://enews.ernolaszlo.com/q/W5UbQ8S85EcX85jCVa01TKcQIR9f0F27SnHlrel6xmpasf7GYw-gCjpHQ

Event:
First Street Gallery Logo [http://r20.rs6.net/tn.jsp?f=001HzXGe-7Pq8-
zlt4lLYuOB6gUgJEJfvwghspnK22oQib-   APXPI0NJvw4FOyJ-

OPENING RECEPTION THIS THURSDAY

JULY 23, 6-8 PM
2015
MFA NATIONAL EXHIBITION

Thomas Wharton, Martini, digital print on canvas, 9 x 8 inches

JULY 23 - AUGUST 14, 2015

First Street Gallery proudly presents our fifth annual MFA NATIONAL
EXHIBITION.

This exhibition highlights the vast reach of fine arts teaching throughout the United
States. The competition is open to all current and former MFA graduates within the
past three years. Our Juror, David A. Ross, former Director of The Whitney Museum
of American Art and The San Francisco Museum of Modern Art, has a 40-year career
 as a museum professional and educator. He is currently the Chair of the MFA Art
 Practice Program at SVA.

ARTISTS: Danny Baskin (UARK), Kimberly Becker (Heartwood), William
Chambers (Mass
Art), Donna Cleary (SVA), Sarah Dahlinger (Ohio), Jason Egitto
(Syracuse), Lindsey
Elsey (Clemson), Dan Fenstermacher (SJSU), En Iwamura (Clemson),
Richard James (KU),
Annie Johnston (UT-Austin), June Korea (SVA), James Lambert (Mass
Art), Junko Ledneva
(UAF), J. Myszka Lewis (UW-Madison), Wilson Parry (Parsons), Veronica
Perez (MECA),
Danette Pratt (Ohio), Jason Schwab (CCAD), Thomas Wharton (UT-Knoxville).

For more info please visit the 2015 MFA NATIONAL EXHIBITION album on our
Facebook
page. [http://r20.rs6.net/tn.jsp?f=001HzXGe-7Pq8-
zlt4lLYuOB6gUgJEJfvwghspnK22oQib-
APXPI0NJv4vTi_KIZjl5AqU4Nfz6z3iB6MWBRsf5QHv-
4T8IUSmtSVEItfj8TEaoluebDWPmWv8D8ayfdc-wgMtgkfoRJvH4e6-
s0HG2jeuCsdSgT2q8uK4gve2K-u9S0X-AI-dtxpp72dGVY3orPDp-aCm-
Gm8b_bp2B_Kh4JXLtEQn1qL6y-

 T3w2wKAO_Ijb4WKJM54g==&c=ThoQa9dOxQlD2qj4Bk8tMgN
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Summer Gallery Hours: 11 am - 6 pm, Monday through Friday

526 West 26th Street, Suite 209, New York, New York 10001

646-336-8053 · 646-336-8054 (fax)

First Street Gallery is located in the heart of Chelsea, NYC between
10th & 11th
 Avenues.

 [Nearest Subways: C,E,R,1,F,V to 23rd St. - crosstown bus to 10th Ave.

Nearest Buses:  9th Avenue (#11), 8th Avenue (#10)

FSG Gallery Location (Larger) [http://r20.rs6.net/tn.jsp?f=001HzXGe-7Pq8-zlt4lLYuOB6gUgJEJfvwghspnK22oQib-

~~~~~~~~~~~~~~~~~~~~~~~~~~

 Join Our Mailing List [http://visitor.constantcontact.com/email.jsp?m=1103049216003]

 © 2001-2011 First Street Gallery

 Artist images copyrighted by the individual artists. All rights reserved.

~~~~~~~~~~~~~~~~~~~~~~~~~~
Forward email
http://ui.constantcontact.com/sa/fwtf.jsp?
email@example.com$&a=1121719149089

This email was sent to email@example.com by
email@example.com.

Update Profile/Email Address
http://visitor.constantcontact.com/do?
p=oo&m=001JtllHKXFqd_bBq0Avb7lPA%3D%3D&ch=0d2a4930-e9f2-11e4-af5b-d4ae52754aa9&ca=cd656f5e-7d82-4a66-9e64-9ee1bb170ae9

Instant removal with SafeUnsubscribe(TM)
http://visitor.constantcontact.com/do?
p=un&m=001JtllHKXFqd_bBq0Avb7lPA%3D%3D&ch=0d2a4930-e9f2-11e4-af5b-d4ae52754aa9&ca=cd656f5e-7d82-4a66-9e64-9ee1bb170ae9

Privacy Policy:
http://ui.constantcontact.com/roving/CCPrivacyPolicy.jsp

Online Marketing by
Constant Contact(R)
www.constantcontact.com

First Street Gallery | 526 W. 26th Street, Suite 209 | New York | NY | 10001

I want to create a model that can triage new newsletters as either event or not. My current plan was to:

Strip all HTML
TFIDF on events vs non-events
Create something that searches for a date/time (events have to have date/time), and then labels the post either 1 or 0
Use some type of spam email code to assess if an email looks like spam, and label it as such

Then throw that data, with the labels, and train using XGBoost or something. Does that sound reasonable? I don't have a strong background in NLP, but I know a lot of you are NLP experts, what kind of architecture would you recommend for this problem? Should I be using LDA or something to identify the parts of speech? Any recommended way to clean HTML?
Answer: If the only distinction between an event and a non event is the presence of day/time element you might not even require any classification algorithm. Wouldn't just mining for the day or time elements in the text be sufficient?


Datatables TableTools stopped working with missing file

Question: Setting up the jQuery-datatables-rails gem gave me a error message with a missing file with this gem and installing bootstrap3 data tables:
gem 'jquery-datatables-rails', git: 'git://github.com/rweng/jquery-datatables-rails.git'
Sprockets::FileNotFound in Posts#index
//= require dataTables/jquery.dataTables is missing
Am I doing something wrong on install or what has changed?
-R
Answer: try to use https://github.com/rweng/jquery-datatables-rails (follow "General Installation" guide and do not use master version from git)
Comment: Already did unfortunately.  Kept getting the error for: ```//= require dataTables/jquery.dataTables```


Find the limit points of the following set

Question: Find the limit points of the following set :
$$S=\left\lbrace\left(m+\dfrac{1}{4^{|p|}},n+\dfrac{1}{4^{|q|}}\right):m,n,p,q\in \Bbb Z\right\rbrace$$
My try:
For any $(m,n)\in \Bbb Z \times \Bbb Z$ we can find a sequence
$$\left(m+\dfrac{1}{4^{|p|}},n+\dfrac{1}{4^{|q|}}\right)\to (m,n)$$
Hence the set of limit points of $S$ is $\Bbb Z \times \Bbb Z$.
Is the answer correct?
Comment: You have $\Bbb{Z} \times \Bbb{Z} \subset L$, where $L$ is the set of limit points.  This is half of an equality.  How do you know there aren't more?
Answer: You need to show that if $x$ is a limit point of $S$, we must have $x \in \mathbb{Z}^2$. Your current result only shows that $\mathbb{Z}^2$ contains some limit points of $S$.
Answer: Your attempted proof would show that $\mathbb{Z}^2 \subseteq S'$, where $S'$ is the set of limit points of $S$. You do have to be more precise in how you mean that the sequence converges to $(m,n)$, however. Which variables are fixed? Which variable is the index for your sequence? I'm staring in particular at the $p$ and $q$ in your formula there, which are looking mighty ambiguous.
Also, we do not have containment in the other direction. Consider the sequence $$\left(m + \frac1{4^{|p|}}, n + \frac1{4^{|q|}}\right)$$ as $m,n,p$ remain fixed and $q \to \infty$. This converges to $\left(m + \frac1{4^{|p|}}, n\right) \not\in \mathbb{Z}^2$. Similarly, anything of the form $\left(m, n + \frac1{4^{|p|}}\right)$ is also a limit point. These however, together with $\mathbb{Z}^2$, do in fact comprise the entirety of $S'$. To show this, you need to show that any limit point of $S$ is actually of the form described above.


Why "Honestly" in Tukey's Honestly Significant Difference (HSD)?

Question: Why is the word "Honestly" in "Tukey's Honestly Significant Difference"?  It seems unusual.  Most statistical procedures are developed with the intent to give an "honest" answer.  Why is that word used for this particular one?  What's the historical background?
Comment: John W. Tukey was fond of down-to-earth and homespun terms.  Honest wasn't intended to imply that any other procedure, let alone analyst, is dishonest, just to convey realism.
Answer: When doing multiple comparisons, the alpha value (Type I error rate) is accumulated over all tests. One method to do multiple comparisons is Fisher's Least Significant Difference (LSD).
Fisher's LSD computes the "least" or minimum value of difference required between two group means. If the difference between two group means is larger than this computed value, then the two groups are declared "significantly different".
However, LSD fails to maintain the overall Type I error rate. The true overall $\alpha$ value of the multiple comparisons test is not $\alpha$, but is inflated to $1-(1-\alpha)^c$, where $c$ is the number of pairwise difference tested. This can lead to incorrect conclusion.
Tukey's Honestly Significant Difference (HSD) is developed to combat this error rate inflation, hence the word "honestly significant", as compared to the error rate inflation being "dishonest".
Relevant read on LSD's weakness can be found at this question's answers.
Answer: The general idea is that you have lots of comparisons that may be flagged as different in the multiple comparison context. However, this protocol is designed to determine which of those flagged differences can be considered "honestly" different from one another.


Determining to what extent an independent variable drives a dependent variable?

Question: For dependent variable (d), I have three independent variables (a),(b), and (c) which are good predictors of (d). All dependent and independent variables are time series which correspond to a given quarter of the year. I've found that (a) and (d) are related in that quarter over quarter increases in (a) correspond with quarter over quarter decreases in (d), and vice versa, but this isn't always true. I've found that on average a 10,000 unit change (increase or decrease) in (a) results in an average 0.05 unit change (increase or decrease) in (d). While assuming a positive change in (a) will lead to a negative change in (d), and vice versa, I want to explain how much (d) would change given a 560,000 unit decrease in (a), while assuming a 560,000 unit change in (d) corresponds to an average 0.05 unit change in (a). Working that out I get a 560,000 unit decrease in (a) will lead to an increase in (d) of about 2.54.
My question this this: d is driven by more than just a, so I cannot say that if (a) drops by 560,000 we will see (d) increase by 2.54. I'm thinking I could run a multiple regression and get the coefficients of each independent variable (a), (b), and (c). Then somehow use the coefficients or another metric to say that (a) drives x% of the change we observe in (d). Then I could say a 560,000 unit decrease in (a) would correspond with a 1.27 unit increase in (d)? Sorry if I'm not making sense! I'm trying to explain as much as possible so you can see where my thinking is at. Thank you.
Answer:
Then I could say a 560,000 unit decrease in (a) would correspond with a 1.27 unit increase in (d)?

Yes. This is exactly why multiple regression is superior to univariate regression when the dependent variable has $>1$ predictor.
If you compare the following 2 models:
\begin{align*}
y &= \beta_0 + x_1\beta_1\\
y &= \beta_0 + x_1\beta_1 + x_2\beta_2
\end{align*}
Then the 2nd model, which explicitly includes $\beta_2$, tells you what is 1 unit increase in $y$ given 1 unit increase in $x_1$, as if $x_2$ were fixed across every sample in your data. In the first model, which does not include $x_2$, the effect of $x_1$ on $y$ is assumed to be uncorrelated with $x_2$ (a tenuous assumption). And no, you do not have to use another metric to see the effect of $x_1$ on $y$ when you include $x_2$. $x_1$'s effect is exactly $\beta_1$, and so is $x_2$'s effect exactly $\beta_2$.


postgresql 12 jsonb_path_query how to select some keys to construct a small object from a big jsonb object?

Question: i have a data JSONB column in Postgres 12, which saved a big object with a .interactions field which is an array of big objects, each object is pretty big, having too many fields which are not needed by app layer, wonder is there a way to query out only the interested fields?
{
  "interactions": [
    { "k1": ..., "k2": ..., "k3": ..., "k4": ... },
    { "k1": ..., "k2": ..., "k3": ..., "k4": ... },
    { "k1": ..., "k2": ..., "k3": ..., "k4": ... },

  ]
  // many other key-value pairs
}

Want something like this:  suppose if the only interested fields are k1, k3, ...
SELECT jsonb_path_query_array(data, '$.interactions[*].{k1,k3}')

to get slim result objects like:
[ { "k1", ..., "k3": ... }, { "k1", ..., "k3": ... } ]

On command line with jq would be as simple as { k1,k3 }:
➸  echo '{"k1":3,"k2":4,"k3":5,"k4":"ok"}
{"k1":-1,"k2":2,"k3":6}' | jq -c '{ k1, k3 }'
{"k1":3,"k3":5}
{"k1":-1,"k3":6}

One further question:  can the interested field names like k1,k3 be not hard-coded but as parameters provided by different application logic?
Answer: so far I only know how to build a single object, from a big object to a slim one with only interested fields,
SELECT jsonb_build_object(
    'k1', data->'k1',
    'k3', data->'k3',
    // ...
) FROM ...

but not sure how can apply for each object from an array? something like this in javascript:
dataArray.map(obj =>
  ['f1', 'f3'].reduce((acc, k) => Object.assign(acc, {[k]: obj[k]}), {}))


Android USB Storage missing

Question: I have an odd problem with my rooted/CM10.1 Android phone.
I realized a problem with my storage a while ago. Until now I believed it would be a hardware defect. When booting my internal USB-Storage is missing (not the external SD card). All I have is my "Internal Storage" and the external SD. So all data (like camera pictures and some apps) on this "drive" are not available.
But after a while I realized, when connecting the phone to the PC - it is still not there then initially. But after disconnecting (and thus remounting the devices) it suddenly is there.
So I understood it as a problem with the mounting or something like that.
When looking at the log while booting I found messages like this:
I/DefContainer-JNI(2799): error opening: /storage/sdcard0: Permission denied
So I came to the idea that a program takes the permissions but does not release them until remounting.
When booting, there are not really any suspicios apps running. So I dont see the problem there.
Has anyone an idea how to "remount" the internal Storage without connecting it to the pc? I tried fixing the permissions of the file system already. This wasn't working! I just bought the ROM Toolbox. I thought this tool might do it, but I have no idea where to start.
Thanks for your help,
 Tobias
Answer: Okay, it took me a while but I think I have found the problem (or at least a solution).
Another user was describing a problem which reminded me on my own here:
http://forum.xda-developers.com/showthread.php?t=601340
It looks like the "checking for errors" is locking the card until it is finished with the scan. As described in this discussion, there might be a problem with the fsck_msdos file
When I eventually deleted this file from system /bin everything worked fine.
So I assume the checking process was in a kind of deadlock and couldn't finish the checking to mount the sdcard.
I hope this helps to whoever might have the same problem.
Regards,
 Tobias

Android USB Storage missing


error executeSql

Question: I have received message "could not prepare statement" when try execute a select below
What is wrong my tx.executeSql?
What is correct syntax for executeSql?
<code>var DB;
var tx;
var sql = "select nome from LivroDaBiblia;";
$(document).ready(function () {
    try {
        if (window.openDatabase) {
            DB = window.openDatabase('Biblia', '', 'App Database', 1000000, errorHandler);
            DB.transaction(function (tx) {
                tx.executeSql(sql, [], function (trx, result) {
                }, errorHandler);
            });
            function errorHandler(transaction, error) {
                alert('Oops. Error was ' + error.message + ' (Code ' + error.code + ')');
                return false;
            };

        }
    } catch (e) {
        // Error handling code goes here.
        if (e == 2) {
            // Version number mismatch.
            alert("Invalid database version.");

        } else {
            alert("Unknown error " + e + ", please contact your local   ntative.");
        }
    }

    DB.close();

}); // JavaScript Document
</code>
Answer: I could be wrong, but looks to me like this line:
tx.executeSql(sql, [], function (trx, result)
should actually read as:
tx.executeSql(sql, [], function (tx, result)
Otherwise you're trying to call something you've not defined -- trx vs tx.

error executeSql


Inserir o valor de uma String do Javascript em um arquivo

Question: Tenho o seguinte código Javascript:

// Converts XML to JSON
// from: http://coursesweb.net/javascript/convert-xml-json-javascript_s2
function XMLtoJSON() {
    var me = this; // stores the object instantce

    // gets the content of an xml file and returns it in
    me.fromFile = function(xml, rstr) {
        // Cretes a instantce of XMLHttpRequest object
        var xhttp = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
        // sets and sends the request for calling "xml"
        xhttp.open("GET", xml, false);
        xhttp.send(null);

        // gets the JSON string
        var json_str = jsontoStr(setJsonObj(xhttp.responseXML));

        // sets and returns the JSON object, if "rstr" undefined (not passed), else, returns JSON string
        return (typeof(rstr) == 'undefined') ? JSON.parse(json_str) : json_str;
    }

    // returns XML DOM from string with xml content
    me.fromStr = function(xml, rstr) {
        // for non IE browsers
        if (window.DOMParser) {
            var getxml = new DOMParser();
            var xmlDoc = getxml.parseFromString(xml, "text/xml");
        } else {
            // for Internet Explorer
            var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.async = "false";
        }

        // gets the JSON string
        var json_str = jsontoStr(setJsonObj(xmlDoc));

        // sets and returns the JSON object, if "rstr" undefined (not passed), else, returns JSON string
        return (typeof(rstr) == 'undefined') ? JSON.parse(json_str) : json_str;
    }

    // receives XML DOM object, returns converted JSON object
    var setJsonObj = function(xml) {
        var js_obj = {};
        if (xml.nodeType == 1) {
            if (xml.attributes.length > 0) {
                js_obj["@attributes"] = {};
                for (var j = 0; j < xml.attributes.length; j++) {
                    var attribute = xml.attributes.item(j);
                    js_obj["@attributes"][attribute.nodeName] = attribute.value;
                }
            }
        } else if (xml.nodeType == 3) {
            js_obj = xml.nodeValue;
        }
        if (xml.hasChildNodes()) {
            for (var i = 0; i < xml.childNodes.length; i++) {
                var item = xml.childNodes.item(i);
                var nodeName = item.nodeName;
                if (typeof(js_obj[nodeName]) == "undefined") {
                    js_obj[nodeName] = setJsonObj(item);
                } else {
                    if (typeof(js_obj[nodeName].push) == "undefined") {
                        var old = js_obj[nodeName];
                        js_obj[nodeName] = [];
                        js_obj[nodeName].push(old);
                    }
                    js_obj[nodeName].push(setJsonObj(item));
                }
            }
        }
        return js_obj;
    }

    // converts JSON object to string (human readablle).
    // Removes '\t\r\n', rows with multiples '""', multiple empty rows, '  "",', and "  ",; replace empty [] with ""
    var jsontoStr = function(js_obj) {
        var rejsn = JSON.stringify(js_obj, undefined, 2).replace(/(\\t|\\r|\\n)/g, '').replace(/"",[\n\t\r\s]+""[,]*/g, '').replace(/(\n[\t\s\r]*\n)/g, '').replace(/[\s\t]{2,}""[,]{0,1}/g, '').replace(/"[\s\t]{1,}"[,]{0,1}/g, '').replace(/\[[\t\s]*\]/g, '""');
        return (rejsn.indexOf('"parsererror": {') == -1) ? rejsn : 'Invalid XML format';
    }
};

// creates object instantce of XMLtoJSON
var xml2json = new XMLtoJSON();

Esse código é interpretado no meu index.html através do código:

Result JSON

Alguém pode me indicar uma forma de eu inserir o valor do "jsnstr" dentro de um arquivo.txt(Sendo que o código vai criar o arquivo)?
Devo usar php para isso ? Jquery ?
Qual a forma mais simples?
Answer: até onde sei não é possível fazer a gravação de arquivos no servidor usando somente javascript.
Você vai precisar criar um script PHP que ficara responsável por salvar o arquivo no servidor, algo como:
$file = fopen("upload/arquivo.txt", 'w');// Cria um novo arquivo
fwrite($file, $data); // Insere o conteúdo
fclose($file);

A partir dai você poderia mandar o conteúdo que quer salvar via Ajax pro script PHP.
Espero ter ajudado.
Comment: quanto a criar usando javascript eu já sabia, esse código que você me enviou eu estava testando mas sem sucesso, usei da seguinte forma:      "document.write(jsonstr)";
$myfile = fopen("m_visa.json", "w") or die("Unable to open file!");
$txt = convert;
fwrite($myfile, $txt);
fclose($myfile);
?>"  porém não funcionou ou eu não soube como fazer. Como devo fazer pra funcionar via ajax ?
Comment: Não dá pra passar a string pro PHP usando "document.write". Faça uma requisição post via AJAX, passando a string como parâmetro, para um script PHP que a recebe no array $_POST e aí sim escreve em arquivo como o @BrunoM recomendou. =)


The coefficient of one variable in Cox regression becames negative when doing multiple variable regression

Question: I am doing Cox proportional regression. I first did Cox regression with only one variable var; its coefficient 0.8752721 was about what I expected and is easy to interpret in my situation. But when I added some other variables, the coefficient of var in the model became negative (-0.894304). I have performed the stepwise process. The negative coefficient seems wrong and is hard to interpret in my problem.
Where am I wrong? Thanks.
Comment: Note to others: I was going to mark this as a duplicate, but it seems to me to ask more than one question, each of which is duplicate.
Answer: First, you shouldn't use stepwise; you can search on the term, it's been discussed a lot here.
Second, when you add another variable you ask a different question, so you get a different answer. Specially, you ask about the effect of the variables while controlling for (holding constant) other variables.
Third, unless you show your code, we can't tell if you made an error there, but, assuming you did not, then the new model isn't wrong and it does explain your data. But there could be some complications. One thing, the variables could be collinear (search on that term too, and on multicollinearity, both have been discussed a lot).
Fourth, if you haven't made any errors and there are no other data problems, then you have a surprising result. My favorite professor in grad school used to say "If you're not surprised, you haven't learned anything".
Finally, if you tell us what these variables are, we might be able to tell what is going on. You may find this post from my blog useful.
Comment: thanks for you reply. I have 55 variables in my data set (60x55), including both categorical and quantitative variables. First, I made univariate regression on each varible, and then select variables whose p-values are significant, denoted by V_1. Second, with the variables in V_1, I made  a cox regression on these variables, and then used stepwise method to select the final variables. I know stepwise is a way to select variables. Maybe should I select variables manually? Alternatively, I used penalized cox model to select variables automaticly, which gave a more interpretive model.
Comment: Penalized Cox looks better than bivariate screening and stepwise. The latter are not recommended.
Comment: "The latter", did you mean selecting variables manually is not recommended? Thanks.
Comment: No, I meant doing bivariate screening is not recommended, nor is stepwise.


Isomorphism of preduals implies isomorphism of the $W^*$-algebras or not??

Question: Let $M$ and $N$ are two von Neumann algebras such that their preduals $M_{*}$ and $N_{*}$ are isomorphic in the sense of Banach spaces, does it imply $M$ and $N$ are $*$-isomorphic or not??
Answer: No, but you can refine the data of a predual to get a positive answer:
https://mathoverflow.net/questions/50302/can-we-recover-a-von-neumann-algebra-from-its-predual


PHP hiding div on empty result from database

Question: I need to hide a full div if variable from database is empty.
I've looked at different similar cases but could not make any of them working. Perhaps someone could help me with it.
So I have my SELECT statement:
<?php
$user = 'myuser';
$pass = 'mypassword';
$db = new PDO( 'mysql:host=localhost;dbname=mydb', $user, $pass );
$sql = "
SELECT id,education_school,education_diploma, DATE_FORMAT(education_start, '%Y %M') as education_start, DATE_FORMAT(education_finish, '%Y %M') as education_finish, education_description
FROM candidates_education
WHERE login='[login]'
ORDER BY education_finish DESC
";
$query = $db->prepare( $sql );
$query->execute();
$results = $query->fetchAll( PDO::FETCH_ASSOC );
?>

And then I have my html (part of it below):
<?php foreach ($results as $row) : ?>

<div class="col-xs-12" style="margin-top:-25px;"   <?php
if(empty($education_description)||!isset($education_description)) echo 'style="display: none;"'; ?>   >

Addtional description:
 <?php echo $row['education_description']; ?>

<?php endforeach; ?>

The problem I am having is that the div class="col-xs-12" should not be displayed if 'education_description' is empty. What am I doing here wrong?
Thank you in advance for any help
Comment: You want `$row['education_description']` instead of `$education_description`.
Comment: And what is the problem? Except using undefined variable `$education_description`.
Comment: How is your variable `$education_description` being set?
Comment: taking from your both comments, not defined variable $education_description is the problem here
Comment: Is this the answer then?
Comment: it would be the answer, yes. Now all I need to do is set the variable I guess. My php is very very poor :).
Comment: so you want to hide whole div section or just remove `col-xs-12` and you need class replacement if empty? `style="margin-top:-25px` poor choice for boostrap
Comment: @skunkhaze I want to hide the whole div when education_description is empty on DB
Comment: @Don'tPanic that does not really work for me
Comment: use `if ($results) { //place foreach and html inside }`
Answer: Change your HTML code like this:
<?php foreach ($results as $row) :
        $isEmpty = empty($education_description); ?>

                    <div <?php if(!$isEmpty): ?> class="col-xs-12" <?php endif; ?> style="margin-top:-25px;"   <?php
                        if($isEmpty || !isset($education_description)) echo 'style="display: none;"'; ?>   >

Addtional description:
 <?php echo $row['education_description']; ?>

<?php endforeach; ?>

Comment: aidin - this does not really work as I need. It replaces the class but it still displays the div..
Comment: to see if it would work for me I slighlty modified it:

 class="bold"   >Addtional description:

 But it hides the title of the element even if education_description is not empty as per the image ( http://imgur.com/a/50gRe ) - in the second row "Additional Description" should be displayed above "description here"
Answer: Don't Panic's solution with
$row['education_description']

worked after I removed unnecessary part
style="margin-top:-25px;"

Thank you ALL for help! Your time is much much appreciated


solving a system of equation by rotation

Question: Somebody hinted that one can solve a system of equations with some method of rotation. This is only needed for numeric solutions, otherwise Gauss-Jordan (RREF) is just fine.
What is this rotation about?
Comment: That would be either QR decomposition (which is doable with rotation matrices), or the eigendecomposition of a matrix with [Jacobi's algorithm](http://en.wikipedia.org/wiki/Jacobi_eigenvalue_algorithm). Both are more expensive than Gaussian elimination, which remains applicable for numerical solutions as long as you pivot.
Answer: It's called a Givens rotation. Similarly to Gaussian elimination, you can use a Givens rotation to eliminate a variable from a system of linear equations.
The basic idea is to find a 2D rotation matrix that will rotate a coefficient in the linear system to lie on the x-axis, thus eliminating it.
Note that this method is not trivially immune to numerical problems. If you directly compute the rotation angle, then you may have continuity issues. If you instead compute cos(alpha) and sin(alpha), you may risk division by zero if the radius is too small. Here is a numerically stable way to compute the rotation.
Givens rotations are also used for computing a QR decomposition: the triangular R is created by a series of eliminations by Givens rotations. Q is simply the product of all the rotation matrices, which are orthogonal.
Comment: Explicitly determining the rotation angle is **never** the right way. See [this](http://books.google.com/books?hl=en&id=mlOa7wPX6OYC&pg=PA216), for instance.
Comment: Also, you have the convention backwards. $\mathbf Q$ is the orthogonal factor (it's supposed to be $\mathbf O$, but seeing that "O" often gets confused with "0"...) and $\mathbf R$ is the upper triangular (or "*right* triangular") factor.


Abstract nonsense proof of snake lemma

Question: During my studies, I always wanted to see a "purely category-theoretical" proof of the Snake Lemma, i.e. a proof that constructs all morphisms (including the snake) and proves exactness via universal properties. It was an interest little shared by my teachers and fellow students, but I have recently found the time to pursue it again.
There is a wonderful book on category theory containing such a proof: The Handbook of Categorical Algebra, Volume 2, by Francis Borceux. I have a question about the proof, however, which I can't seem to resolve.
The Snake Lemma is Lemma 1.10.9, and I have a problem with one of the preliminaries: Namely, the "restricted" Snake Lemma 1.10.8.
Edit: I scanned the diagrams in question from the book. The following is what we want, i.e. we want to construct $\omega$ from the rest of the diagram where all squares commute and all rows and columns are exact.

The construction is then as follows: $\Delta$ and $\Gamma$ are obtained by pull-back and we define $\Sigma:=\mathrm{Ker}(\Delta)$. Dually with $\Lambda$, $\Xi$ and $\Upsilon$.

On page 46, he says that

By lemma 1.10.1 and its dual, there are morphisms $\Psi$ and $\Omega$ making the diagram commutative and the outer columns exact.

I can not verify this statement. For instance concerning $\Psi$, it seems to me that in order to apply lemma 1.10.1, one would require that the sequence $(\Gamma,\lambda)$ is exact, but I do not see how that would follow from the construction. What am I doing wrong?!
Edit: Lemma 1.10.1 is the statement that in the following diagram, with commutative squares (1) and (2) and exact rows $(\zeta,\eta)$ and $(0,\nu,\xi)$ with $\gamma=\mathrm{Ker}(\theta)$, $\delta=\mathrm{Ker}(\lambda)$ and $\varepsilon=\mathrm{Ker}(\mu)$, there exist unique morphisms $\alpha$ and $\beta$ making the diagram commutative. Additionally, $(\alpha,\beta)$ is exact.
Comment: Simply for your information: Lemma $ 5 $ of Section $ 4 $ of Chapter $ 8 $ of *Categories for the Working Mathematician, Second Edition* by Saunders Mac Lane also gives a purely categorical proof of the Snake Lemma. :)
Comment: @Jesko: Jonathan Wise has written up a direct proof of the Snake Lemma. http://math.stanford.edu/~jonathan/papers/snake.pdf. You can also find a proof in the first paper on abelian categories. Not Grothendieck's Tohoku, but "Exact Categories and Duality" D. A. Buchsbaum, published in 1955.
Comment: It would be helpful if you could post some pictures of the relevant diagrams, to make the question more self-contained.
Comment: @Zhen Lin: There you go!
Comment: @Haskell Curry: Thanks for the tip, but Saunders Mac Lane has never really worked that well for me. If I get no answer to this question I might check it out, but usually I prefer Borceux' writing style.
Comment: I think you can apply Lemma 1.10.1 by replacing some morphisms with the cokernel of their kernel, e.g. $(\Gamma, \operatorname{coker} \Gamma)$ and $(\epsilon, \operatorname{coker} \epsilon)$.
Comment: @Zhen Lin: I don't see how that would work. We could apply the lemma, but we would apply it to a totally different diagram. We could not conclude that $(\Psi,\theta)$ is exact. What we really need is the fact that $\Gamma=\mathrm{Ker}(\lambda)$, and I do not see why this holds.
Comment: That's because it's not true. Take $E = \mathbb{Z}$, $F = I =  \mathbb{Z} / 2 \mathbb{Z}$, $H = \mathbb{Z} / 4 \mathbb{Z}$. Rather, what is true is that $\Gamma = \ker (\mu \circ \eta)$.
Comment: @Martin Brandenburg: +1 and thanks a lot, that looks great. I am still curious if anyone can explain the reasoning in Borceux' book, though.
Comment: You just have to rotate the diagram in Lemma 1.10? Keep in mind that the double headed arrows are epimorphisms (so those show up in the dual of Lemma 1.10) while the special single headed arrows which have arrowheads as their tails are monomorphisms (e.g. $\nu$ in Lemma 1.10). In particular to make things clearer add zeros to the left of X, D, G, J, and add zeros to the right of C, F, I, W.
Comment: @MartinBrandenburg LINK BROKEN!!!
Answer: In any abelian category you can introduce the notion of element. An element $y$ of an object $Y$ of an abelian category $\mathcal{A}$ is an equivalence class of pairs $(X,h)$, $X \in Ob(\mathcal A)$, $h: X \to Y$ by the equivalence relation
$$
(X,h) =(X',h')  \iff \exists Z \in Ob(\mathcal A), u:Z \to X, u':Z \to X'\, s.t. \, hu=hu',
$$
where $u$ and $u'$ must be epimorphisms. Using the notion of element you can prove the statement in the category of abelian groups. See Gelfand, Manin "Metheods of homological algebra for details.
Comment: @MarkS. is correct. I primarily want to understand the reasoning in Borceux' book. I hope you don't take my downvote as a personal offense, but this is precisely what I did *not* want.
Comment: I think the primary interest in the posting of the question was to patch/explain the proof in Borceux (see Jesko's comment on the question from March 23rd).
Comment: @user46336 I like your answer because this answers the question I am curious about for so long - why every result proved by diagram chasing in R-Mod is always true in abelian category. For times this seemed to me really mysterious but amazing, just like some principles that always work but cannot be precisely formulated. But now I find this principle could be "exact"(LOL).
Comment: @JeskoHüttenhain It does seem to be a good answer to your *title*, but not your question "What am I doing wrong?!" However, the convention on math.stackexchange is that a question in the body takes priority, over the title.
Comment: I tried but still have no idea how this works. Could you illustrate it using categories that really have elements, such as abelian groups?

Abstract nonsense proof of snake lemma


Diferença entre activity e Content

Question: Não sei se é aqui o lugar certo para isso, se não for peço orientação onde tiro esta dúvida. Estou aprendendo a desenvolver apps no Android Studio, e estou seguindo alguns tutoriais. Alguns casos tenho percebido que alguns tem apenas activity e outros além da activitytambém tem contentque é o caso deste:

e neste apenas a activity

sempre que eu crio um projeto ele nunca gera o context. Gostaria de saber qual a diferença de ambos e a sua finalidade. e se tem necessidade de ter a context.
Answer: Quando você cria um Basic Activity ele cria o xml da activity e do content junto, este modelo já vem com um FABButton junto com o layout por isso ele cria 2 arquivos o ideal é utilizar o content para colocar outros componentes assim o funcionamento do FABButton não é afetado.
Caso você não queira que ele crie esse modelo sempre basta selecionar o Empty Activity quando for criar uma nova.
Espero que te ajude.
Comment: Certo Guilherme acho que entendi agora, este `FABButton`seria o botão voltar?
Comment: Não, ele é um botão circular que quando você cria o Basic Activity já vem adicionado no seu xml com o evento de click na Activity
Comment: No caso deste que aparece nesta primeira `activity` da imagem que vc postou, a `Basic Activity`?
Comment: Exatamente...!!
Answer: Aquilo que refere são apenas nomes de arquivos de layout.
Um layout pode ser usado por uma Activity ou não.
Entre outros, eles são usados em Activities, Fragments, itens de ListView's ou RecyclerView's.
Um arquivo de layout pode também usar outros arquivos como parte integrante dele, ou seja, partes de um layout podem estar em outros arquivos de layout.
Esse é o caso(julgo eu) do primeiro exemplo que refere: o arquivo(layout) content_primeira.xml é usado no arquivo(layout) activity_primeira.xml.
A inclusão de arquivos de layout em um outro é feita com o uso da tag <include>.
Se for ver o xml do activity_primeira.xml encontrará uma linha com o conteúdo seguinte
<include layout="@layout/content_primeira"/>

Uma vantagem desta abordagem é possibilidade de um arquivo/xml/layout ser utilizado em mais de um layout.
Comment: Obrigado pela explicação ramaral, abriu um pouco mais a mente.

Diferença entre activity e Content


How to set orientation for AMCharts Stockchart to vertical

Question: I am playing around with AMCharts StockChart for a projcet I am working on.
I will like to change the orientation for the StockCharts to vertical:
i.e. the categoryAxis on the Left, and the Value Axis bottom - so the lines would show vertically instead of horizontal (as it is by default)
Does anybody know how to do this?
Basically, I want to take This Horizontal Chart and turn it into this vertical chart
Answer: Stock charts can only be rotated at the panel level. You can set rotate: true directly in each panel or in panelsSettings:
panelsSettings: {
  rotate: true
}

You'll need to disable the global scrollbar and use a panel-level chartScrollbar as the global one doesn't get rotated.
panels: [{
  chartScrollbar: {},
  // ...
}],
chartScrollbarSettings: {
  enabled: false
}

Here's a demo


Quotient of Dihedral groups

Question: Let $D_{2n}$ be the dihedral group of order $2n$, where $n$ is an even integer.
We know that $H=\langle \sigma^{\frac{n}{2}} \rangle$ is a normal subgroup in $D_{2n}$. What about $D_{2n}/H$? And is it true that $D_{2n}$ is isomorphic to $D_n \times H$?
I think that $D_{2n}/H=D_n$. In fact, I consider the map the generators of $D_{2n}$ to those of $D_n$. It is surjective by definition (I sent generators in generators, it suffices, right?). Moreover, the kernel is $D_{n}$, since $\sigma^{\frac{n}{2}}$ goes to $\sigma'^{\frac{n}{2}}=Id$ and then I use the first isomorphism theorem.
Is my attempt to the first question correct? I have no clue for the second part.
Comment: What is $|H|$ (the order)? So what is $|D_{2n} / H|$?
Comment: $|H|=2$ and $|D_{2n}/H|=n$.
Comment: In your proof you need to check out that multiplication is preserved; easy by looking at the relations satisfied by the generators - but needs done
Answer: The answer to your two questions are:

yes (your proof of $D_{2n}/H\cong D_n$ is correct)
no if $n>2$ ($D_{2n}$ is not isomorphic  to $D_n\times C_2$: $D_{2n}$ has an element of order $n$ and $D_n$ doesn't) but yes if $n=2.$
Answer: The dihedral group $D_{2k}$ has $k+2$ elements satisfying $x^2=1$.
So the dihedral group $D_{4k}$ has $2k+2$ elements satisfying $x^2=1$.
And the group $D_{2k}\times C_2$ has $2k+4$ elements satisfying $x^2=1$.
So $D_{4k}\not\simeq D_{2k}\times C_2$.

Quotient of Dihedral groups


$\lim_{n \rightarrow \infty} \sum_{n=1}^{n}\frac{a_n}{n}$ is equal to?

Question:
Let $$a_n=\int_{0}^{\pi/2}(1-\sin(t))^{n}\sin(2t)\, dt$$ then $$\lim_{N
 \rightarrow \infty} \sum_{n=1}^{N}\frac{a_n}{n}$$ is equal to?

I tried to apply L'Hospital's rule initially but it will not work directly as there is a summation involved.
Next I tried to convert the $a_n$ to summation form using first principle and then substitute in second.But that makes things even more complicated with two summations.
Also I tried using King's rule to express $a_n$ differently.But that introduces a cosine term.Doesn't help much.
What else to try?
Answer: Hint: One has $$a_n=2\int_{0}^{\pi/2}(1-\sin t)^n \sin (t)\cos (t) dt$$
$$=2\int_{0}^1(1-x)^n x dx.$$
Denote $$b_n=2\int_{0}^1(1-x)^n dx=\frac{2}{n+1}.$$
Then consider $b_n-a_n$.
Answer: For any $t\in\left(0,\frac{\pi}{2}\right)$ we have
$$\sum_{n=1}^{+\infty}\frac{(1-\sin t)^n}{n}=-\log\sin t \tag{1} $$
hence our limit equals
$$ -\int_{0}^{\pi/2}\sin(2t)\log\sin t\,dt\stackrel{IBP}{=}\frac{1}{2}\int_{0}^{\pi/2}(1-\cos(2t))\cot(t)\,dt=\color{red}{\frac{1}{2}}.\tag{2} $$


DNSimple SSL for Ruby on Rails Heroku App - Which Email to Use?

Question: I've got a Ruby on Rails app setup with Heroku and DNSimple, however when I went to purchase an SSL certificate for the site it shows the following:
<code>Send Email to Approve SSL Certificate

Select an active email address from the list below. You will receive an email to approve the SSL    certificate.

Approver *
firstname.lastname@example.com
admin@______.org
administrator@_______.org
hostmaster@______.org
postmaster@_______.org
webmaster@______.org
admin@www.______.org
administrator@www.______.org
hostmaster@www.______.org
postmaster@www.______.org
webmaster@www.______.org
</code>
(I removed the actual site's name for privacy reasons)
How am I supposed to claim one of these email addresses and use it to finish the approval process of my domain's certificate?
Answer: From http://support.dnsimple.com/articles/ssl-certificates-email-approval/

The email approval is required for domain-validated certificates.

You need to use an email you have access to. It is required to approve the certificate, you will receive an email from the CA.
Comment: If my domain's email is protected by WHOIS, and DNSimple uses the publicly available information for the registrant when deciding which emails may be used to verify an SSL, how do I get the confirmation email sent to myself? (Since all of my contacts are hidden with the WHOIS service)
Comment: We do not use your contact information for certificate approval. The CA uses administrative contacts and the contact visible in the whois. As explained in the link I posted, you need to temporary disable the WHOIS privacy if you want to use the email in the whois.
Comment: I guess I need to do some more learning, because I still don't understand how to setup email to be received at one of the "@_____.org" addresses for purposes of receiving the SSL Certificate confirmation email (I know it must be done somehow through my Ruby on Rails App and/or Heroku?)
Comment: It has nothing to do with Heroku or Rails. You need to configure an email in your email provider for the domain. If you don't have one, you can use a temporary email forwarder http://support.dnsimple.com/articles/email-forwarding/


Finding the remainder when $p(x^7)$ is divided by $p(x)$, where $p(x)=x^6+x^5+ \cdots + x + 1$?

Question: I know there are one or two similar questions to this one but I did not want to look at them since I would like just a hint.

Find the remainder when $p(x^7)$ is divided by $p(x)$, where $p(x)=x^6+x^5+ \cdots + x + 1$?

I wrote $p(x)= \dfrac {x^7-1}{x-1}$, so $p(x^7)=\dfrac {x^{49}-1}{x^7-1}$. We are looking for the unique polynomial $R(x)$ with $deg (R)<6$ such that
$$\dfrac {x^{49}-1}{x^7-1} =Q(x)\left(\dfrac {x^7-1}{x-1}\right)+R(x)$$
Multiplying both sides by $x^7-1$,
$$x^{49}-1=Q(x)p(x)(x^7-1)+R(x)(x^7-1)$$
I know one way to do it would be to find $R(x)$ at $6$ different points and then set up a system of $6$ equations. I want to plug in values which will make the $Q(x)$ term zero because I can't evaluate $Q(x)$. But the values which will make the $Q(x)$ term zero are the $7^{th}$ roots of unity, which will also make the $R(x)$ term zero.
Comment: polynomial remainder theorem ...
Answer: Hint $\bmod p\!:\,\  \color{#c00}{x^7 \equiv  1} \Rightarrow\, p(\color{#c00}{x^7}) \equiv p(\color{#c00}1)\ $ by the Polynomial Congruence Rule
Or, without congruences put $\,y=x^7\,$ in $\,y\!-\!1\mid p(y)-p(1)\,$ by the Factor Theorem.
Comment: Your answers are really pleasing to eyes, really nice use of colour.
Comment: Note: the linked proofs of the Congruence Rules are given for integers but it is clear that they work in any commutative ring, since the use only commutative ring axioms.
Answer: One trick is to think of modular artithmetic (in the ring of rational polynomials):
$$x^7\equiv 1\pmod{1+x+\cdots+x^6}$$
So $$p(x^7)\equiv p(1)\pmod{1+x+\cdots+x^6}$$
Basically, this is true for any polynomial $p$.
In this case, $p(1)=7$, which is your remainder.
Comment: $\sin$ is not a polynomial. @123 So you'd need to know what ring you were in to define $\equiv$.
Comment: In particular, the value $\sin(x^7)-\sin(1)$ is not a finite sum of values divisible by $x^7-1$, but rather, an infinite sum, so divisibility is problematic.
Comment: But the basic answer is "no, we wouldn't write $\sin(x^7)\equiv \sin(1)$ in general." @123
Comment: Is $$\sin (x^7) \equiv \sin(1) \pmod{1+x+\cdots+x^6}$$ true ?
Comment: @123 Your query above is clarified by the proof of the Polynomial Congruence Rule linked in my answer (which, as  I mention, is valid in any commutative ring)
Answer: Let's tackle this with the notion of congruences. In the polynomial ring, $f(x)\equiv g(x)\pmod{m(x)}$ means that $f(x)-g(x)=m(x)q(x)$ for some
polynomial $q(x)$.
Here
$$x^7=1+(x-1)p(x)\equiv1\pmod{p(x)}.$$
So $x^{14}\equiv(x^7)^2\equiv1^2\pmod{p(x)}$ etc. Similarly, $x^{7k}\equiv1\pmod {p(x)}$.
But you are after $p(x^7)$ modulo $p(x)$. But $p(x^7)=x^{42}+x^{35}+x^{28}+x^{21}+x^{14}+x^7+1$. This should be
easy to tackle now...
Answer: Write $p(x^7) = q(x)p(x) +r(x)$ where $deg(r) <7$.
If we say $1,a_1,...a_6$ are all zeros (which are obviously different) of $x^7=1$ then for each $i$ we get:
$$  p(1) = p(a_i^7) = q(a_i)p(a_i) +r(a_i) = r(a_i)$$
Thus $r$ takes the same value for 6 different values and thus $r(x) \equiv  p(1) =7$.


How to programmatically print a webform block with caching enabled?

Question: When displaying a Webform inside a normal block (using admin/structure/block) Drupal manage to correctly cache the page, the HTTP header displays X-Drupal-Dynamic-Cache: HIT.
However we need to display this webform inside a paragraph so we tried the following :

use twig_tweak module and {{ drupal_block('webform_...') }}
programmatically put the block in a template preprocess like this :

$my_form = \Drupal\webform\Entity\Webform::load('contact_new');
$output = \Drupal::entityManager()
          ->getViewBuilder('webform')
          ->view($my_form);
$variables['contact_form'] = $output;

Both solutions seem to make the page uncacheable: X-Drupal-Dynamic-Cache: UNCACHEABLE.
What would be the correct way to put a block in a paragraph while make the page cacheable ?
How to mimic the standard block system to display a in our template ?
Answer: The Dynamic Page Cache needs to placeholder the dynamic part and it can only do so when it is built in a lazy builder:
/mymodule/src/WebformLazyBuilder.php
<?php

namespace Drupal\mymodule;

use Drupal\Core\Render\Element\RenderCallbackInterface;

class WebformLazyBuilder implements RenderCallbackInterface {

  public static function buildWebform($webform) {
    return  [
      'webform' => [
        '#type' => 'webform',
        '#webform' => $webform,
      ],
    ];
  }

}

Then you can put the lazy builder in a template preprocess hook:
$variables['contact_form'] =  [
  '#lazy_builder' => ['\Drupal\mymodule\WebformLazyBuilder::buildWebform', ['contact']],
  '#create_placeholder' => TRUE,
];

Blocks are placed in a lazy builder by default, see BlockViewBuilder::viewMultiple.
Comment: Your example code is making think we could provide optional lazy builder support for all webform instances.  For example, we would add a '#lazy_builder': true property to the Webform element, which returns a lazy builder instead of the webform.
Comment: @jrockowitz, that sounds like a great idea, the element base class is already implementing RenderCallbackInterface, so we could place the lazy builder callback directly in the webform element class.
Comment: Thank you, that is a great answer :)
Comment: @4k4 see https://www.drupal.org/project/webform/issues/3164675


how to connect to database for form submission

Question: I have website and on its home page there is form in which user enter his own label .As user enters label if the user with same label exists in database it through message that "This Label already exists.Use other Label OR Login". If the user is new it will be directed to other site i.e site "example.com".
The problem is I am getting the same message that "This Label is already exist.Use other Label OR Login" even I enter a new label.
Here is the code for this scenario.
function homepage_userlogin_form($form_state){
// drupal_set_title('Add New Person');
$form = array();

$form['name'] = array(
'#title' => '',
'#type' => 'textfield',
'#size' => '30',
'#placeholder' => "enter desired label",
);

$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Start',
"#submit"=>array('form_submit')
);

//$form['#attributes'] = array('id' => 'user-registration001');
return $form;
}

function homepage_userlogin_form_validate($form, &$form_state) {

$name = $form_state['values']['name'];
global $users;
$error=FALSE;

if (empty($name)) {
form_set_error("erorr",t("Please enter your Label."));
$error=TRUE;
}
//if(strlen($name)<6){
// form_set_error("Please Enter atleast 6 character Label.");
// }

if(!$error){

$result = db_select('users', 'u')
->fields('u',array('uid'))
->condition('name', $name,'=')
->execute()->fetchAssoc();

if($result['uid']>0){
form_set_error("erorr1",t("This Label is already exist.Use other Label OR Login"));
}

else{
global $users;
$user->name=$name;

}
}
}

function homepage_userlogin_form_submit($form, &$form_state) {
drupal_goto("http://example.com");

}

Answer: I think there is problem with the condition in the query. Try changing it
$result = db_select('users', 'u')

->fields('u',array('uid'))

->condition('u.name', $name,'=')

->execute()

->fetchField();

You better use Webform Module to create a form without any issues!!

Webform is the module for making surveys in Drupal. After a
  submission, users may be sent an e-mail "receipt" as well as sending a
  notification to administrators. Results can be exported into Excel or
  other spreadsheet applications. Webform also provides some basic
  statistical review and has and extensive API for expanding its
  features.
Answer: The title of OP seems misleading. The code is already connecting to the db on form submission. Perhaps revise the title? Unique usernames are default behaviour, so I'm assuming you're trying to do something different here. It's difficult to debug without running the code. This part looks problematic:
if($result['uid']>0){

You don't need to check uid, you just need to see whether the db query returns a result, in which case you could use $result->rowCount()
What do you get if you echo $result['uid']?

General comments:

You could consolidate your conditional logic. You possibly don't need to test for $error: if(){}else{} statements could be combined, or you could just return FALSE.
You're calling global $user twice.
Further down the script, you attempt to set the username in the global array, but that's not going to affect anything permanent, and you're basically saying that if the user exists, set their username to the current username, so I don't see how this changes anything.


Unable to Find My Error for First Order Differential Problem

Question: The Question: Given $f'(x) = 5f(x)$ and $f(3) = 2$ find the equation for $f(x)$
My Problem: My attempt to solve it produced the wrong answer. I got $f(x) = \frac{28}{5x - 1}$ but the correct answer is $f(x) = 2e^{5(x-3)}$ (you can follow this link to see how it is solved).
Note: I am not asking how to get the correct answer, as I have already found and understood such an explanation. I am instead asking why my process is incorrect.
My Method:

$\frac{df(x)}{dx} = 5f(x)$
$df(x) = 5f(x)dx$
$\int{df(x)} = \int{5f(x)dx}$
$f(x) = 5f(x)\cdot x + C$
$f(3) = 5f(3)\cdot 3 + C$
$2 = 30 + C$
$C = -28$
$f(x) = 5f(x)\cdot x - 28$
$28 = f(x)(5x - 1)$
$f(x) = \frac{28}{5x - 1}$

Explanation: I know my answer is wrong, as it does not satisfy the condition $f'(x) = 5f(x)$, yet I am intrigued by this problem as I cannot seem to figure out what I did wrong. My answer does satisfy the condition $f(3) = 2$ and its derivative - $f'(x) = -\frac{140}{(5x - 1)^2}$ - is suggestive of some similarity to the original differential (eg numerator is multiplied by 5). Perhaps someone can enlighten me regarding where I went astray. Thank you.
Comment: For what it's worth, this looks like a high-quality question to me. You made an earnest attempt and showed what you did in detail. I would just delete the disclaimer.
Answer: Your mistake is in going from (3) to (4).
Since $f(x)$ is a function of $x$, you cannot treat it as a constant in the integral. Basically, you should not say
$$\int 5 f(x) dx = 5 f(x) \cdot x + C$$
Answer: as  @Michael has pointed out, Line 3 is a bit complicated. Because you don't know how to integrate $\int f(x)dx$
$$f'=5f$$
$$\implies \frac {f'}{f}=5$$
$$(\ln f)'=5$$
Integrate
$$\ln f=5\int dx=5x+K$$
Therefore
$$f(x)=Ke^{5x}$$
$$f(3)=2 \implies K=\frac 2 {e^{15}}$$
$$f(x)=\frac {2e^{5x}} {e^{15}}=2e^{5(x-3)}$$
Comment: Did you use the condition $f(3) = 2$ in the question?
Comment: No sorry I will add some lines thanks @johnfowles


a lot of template (.tpl.php) files, is it good or not?

Question: I have used about 110 template files (tpl.php) in my theme, will that slow my drupal site?
I mean:

more template files == consume Server performance.
Comment: Having a lot of files by itself is not necessarily a problem.  If you're concerned, try benchmarking your site with a theme that uses the template files and then another theme that does not.
Comment: `Apache Bench`, `http-perf` are few famous ones. Just Google **Server Performance Benchmark Tool** you'll see lots of them both free and commercials. Chose what suits your best. I personally like `http-perf` and `Jmeter`
Comment: From your comment I understand that a lot of template files will not consume Server performance, is that right ?.
 If I try benchmarking I will not see the difference because Im working in Localhost. so you have any idea
Comment: localhost or remote host you need server to run PHP, and most of the bench-marking in world are done in local environment. Benchmark gives results, and those numbers can show you difference.
Comment: Im sorry Jhilke Dai, I dont get it !! is Benchmark software or what, Im sorry Im jsut a Beginner.
Comment: Patrick means to say try to test your current site with current theme and benchmark it with Other themes, for example `Bartik`. If your benchmark shows difference in performance then your theme is slowing the site.
Comment: What do you mean with "your benchmark", what is benchmark, and how to work with it !!
Comment: `Benchmark` means compare more than one things and see the similarities/Differences. I mean you to Check the Server performance of your site with your current theme . Next, enable `Bartik` theme and check the Server Performance of your site with `Bartik` theme. If Bartik's Performance is better than your current theme, your current theme is making your site slow with too many `.tpl.php`
Comment: I know all that, its logic !! . Im asking for how to Check the server performance ? as I said before Im working in LOCALHOST, so I dont have cPanel or something like that to check performance. PS: Thanx for your time ;)
Comment: OK Jhulke Dai, Thanx for All those information. you really help me, Thanx again
Comment: On properly configured server it'll be served from opcode cache anyway, so the number of files have literally no impact on performance, only the raw amount of code that needs to be executed (and it's cost) matters. One file, 110 files, one opcode entry either way.
Answer: Say you override the default page.tpl.php with your own in your theme folder, and compare this to the case of using the default. In both cases, one page.tpl.php is being evaluated during the page render process - either the default template or yours. Even if you do not override the template, Drupal must search the theme folder to check if an override exists. Of course, if you have a lot of complex logic in your override the page will render more slowly, but that is not due to the overriding itself.
Creating custom templates with hook_theme might slow things down, though.
In general, caching will do more to speed up your site since it bypasses page rendering altogether.
Comment: Thanx user24505 for the Answer
Comment: If you are replacing a theme function with call to template file, it will certainly slow down (at least relatively) because function calls are faster than file operations.


Is AR(1) a Markov process?

Question: Is AR(1) process such as
$y_t=\rho y_{t-1}+\varepsilon_t$ a Markov process?
If it is, then VAR(1) is the vector version of Markov process?
Answer: The following result holds: If $\epsilon_1, \epsilon_2, \ldots$ are independent taking values in $E$ and $f_1, f_2, \ldots $ are functions $f_n: F \times E \to F$ then with $X_n$ defined recursively as
$$X_n = f_n(X_{n-1}, \epsilon_n), \quad X_0 = x_0 \in F$$
the process $(X_n)_{n \geq 0}$ in $F$ is a Markov process starting at $x_0$. The process is time-homogeneous if the $\epsilon$'s are identically distributed and all the $f$-functions are identical.
The AR(1) and VAR(1) are both processes given in this form with
$$f_n(x, \epsilon) = \rho x + \epsilon.$$
Thus they are homogeneous Markov processes if the $\epsilon$'s are i.i.d.
Technically, the spaces $E$ and $F$ need a measurable structure and the $f$-functions must be measurable. It is quite interesting that a converse result holds if the space $F$ is a Borel space. For any Markov process $(X_n)_{n \geq 0}$ on a Borel space $F$ there are i.i.d. uniform random variables $\epsilon_1, \epsilon_2, \ldots$ in $[0,1]$ and functions $f_n : F \times [0, 1] \to F$ such that with probability one
$$X_n = f_n(X_{n-1}, \epsilon_n).$$
See Proposition 8.6 in Kallenberg, Foundations of Modern Probability.
Comment: The proposition mentioned in the answer is Proposition 11.6 in the third edition of _Foundations of Modern Probability_ by Kallenberg.
Answer: A process $X_{t}$ is an AR(1) process if
$$X_{t} = c + \varphi X_{t-1} + \varepsilon_{t} $$
where the errors, $\varepsilon_{t}$ are iid. A process has the Markov property if
$$P(X_{t} = x_t | {\rm entire \ history \ of \ the \ process }) = P(X_{t}=x_t| X_{t-1}=x_{t-1})$$
From the first equation, the probability distribution of $X_{t}$ clearly only depends on $X_{t-1}$, so, yes, an AR(1) process is a Markov process.
Comment: -1, the same reason as for another poster. The answer implies that it is easy to check the cited Markov property. It is not, unless demonstrated otherwise. Note also that AR(1) processes can be defined with $\varepsilon_t$ being non-iid, so this should be adressed also.
Comment: The main problem is that we can easily write $X_t=c+\phi c+\phi^2X_{t-2}+\phi\varepsilon_{t-1}+\varepsilon_{t}$ and then the last sentence would imply that $P(X_t=x_t|\text{entire  history})=P(X_{t}=x_t|X_{t-2}=x_{t-2})$.
Comment: Note I do not say that the answer is incorrect. I am just nitpicking at the details, i.e. that the second equality is intuitively evident, but if you want to prove it formally it is not so easy, IMHO.
Comment: Well, markov processes do depend on $X_{t-2}$ when you haven't also conditioned on $X_{t-1}$. I suppose a more formal argument would assume you're conditioning sequentially (i.e. you don't include $X_{t-2}$  unless you've already conditioned on $X_{t-1}$).
Comment: and what you've written there actually depends on both $X_{t-2}$ and $X_{t-1}$ (through the error term $\varepsilon_{t-1}$). The bottom line is that joint likelihood can be written easily as a product of conditional likelihoods which only require conditioning on the previous time point. Through parameter redundancies you can make it look like the distribution of $X_t$ depends on $X_{t-2}$ but, once you've conditioned on $X_{t-1}$, it clearly doesn't. (p.s. I was using a standard definition of an AR(1) process per Shumway and Stoeffer's time series book)
Comment: The answer could clarify that an AR(1) process is a particular type of Markov chain + the i.i.d. errors assumption. The particular type of Markov Chain referred to here is a time-homogenous Markov Chain. A non-homogenous Markov Chain is a very different beast than any AR(1) model.
Answer: What is a Markov process? (loosely speeking) A stochastic process is a first order Markov process if the condition
$$P\left [ X\left ( t \right )= x\left ( t \right ) | X\left ( 0 \right )= x\left ( 0 \right ),...,X\left ( t-1 \right )= x\left ( t-1 \right )\right ]=P\left [ X\left ( t \right )= x\left ( t \right )  | X\left ( t-1 \right )= x\left ( t-1 \right )\right ]$$
holds.
Since next value (i.e. distribution of next value) of $AR(1)$ process only depends on current process value and does not depend on the rest history, it is a Markov process. When we observe the state of autoregressive process, the past history (or observations) do not supply any additional information. So, this implies that probability distribution of next value is not affected (is independent on) by our information about the past.
The same holds for VAR(1) being first order multivariate Markov process.
Comment: -1, since the proof of Markovian property is not given. Also the hand waving argument is not consistent with formula given. current state = $t$, past means $t-1, t-2,...$, next means $t+1$, but the formula does not involve $t+1$.
Comment: Hm, if $\varepsilon_t$ are not iid, I do not think it holds. Also you did not give a proof, only cited the Markov property.
Comment: I thought that Markov Process refers to the continuous case. Usual AR time series are discrete, so it should correspond to a Markov Chain instead of a Markov Process.
Comment: So we observe state of autoregressive process, $X_t$. The past history is $X_{t-1},X_{t-2},...$. This does not supply any additional information?
Comment: @joint_p, the terminology is not completely consistent in the literature. Historically, as I see it, the usage of "chain" instead of "process" was typically a reference to the *state space* of the process being discrete but occasionally also time being discrete. Today many use "chain" to refer to discrete time but allowing for a general state space, as in Markov Chain Monte Carlo. However, using "process" is also correct.
Comment: @mpiktas If we observe autoregressive process of **first order**, then, conditional on the observed current state, we need no additional information from the past to know distribution of next value. I want to stress, that I do not have in mind inference, where statistical information is important.

Is AR(1) a Markov process?


Use path argument of display in fitler criteria

Question: I have a view which displays all terminology terms from a specific terminology.
The view also have a display with a path=/taxonomy/term/% so if I go to "details page" of a specific term, the display is used.
This works fine expect that it, of course, that the view filters for all terms in that terminology. I now want to only show the % one.
Can I somehow use the % in my filter criteria?
I think that what I want is to use the parametric value % inside "Configure filter criterion: Taxonomy term: Term ID"
Answer: The % sign corresponds with an argument. Within views, these are known as contextual filters (advanced section).
If you add a contextual filter for taxonomy id and provide a numeric value for the % it should work. You also get options for what to do when % is empty, etc.


Pandas DataFrame formatting to get expected output

Question: In the following Pandas DataFrame,
df = pd.DataFrame({'session' : ["1","1","2","2","3","3"],
                'path'  : ["p1","p2","p1","p2","p2","p3"], 'seconds' : ["20","21","132","10","24","45"]})

I need to get an output like the following. (Pages as columns, sessions as rows and seconds in each cell.)
session,p1,p2,p3
1,20,21,0
2,132,10,0
3,0,24,45

What I have done so far.
In [76]: wordlist = ['p1', 'p2', 'p3']
In [77]: df2 = pd.DataFrame(df.groupby('session').apply(lambda x: ','.join(x.path)))
In [78]: df2 #I have renamed the columns
Out[78]:

                  path
        session
        1        p1,p2
        2        p1,p2
        3        p2,p3

In [79]: df3 = pd.DataFrame(df.groupby('session').apply(lambda x: ','.join(x.seconds.astype(str))))
In [80]: df3 #I have renamed the columns
Out[80]:
                   path
        session
        1         20,21
        2        132,10
        3         24,45

The following just gives the boolean result. I need to get my expected output. Any help on this?
In [84]: pd.DataFrame({name : df2["path"].str.contains(name) for name in wordlist})
Out[84]:
            p1    p2     p3
session
1         True  True  False
2         True  True  False
3        False  True   True

Answer: Use a pivot table:
df.pivot(index='session', columns='path')

Then replace all the Nan's with zeros:
df2 = df1.fillna(0)

This gives you the following output:
        seconds
path         p1  p2  p3
session
1            20  21   0
2           132  10   0
3             0  24  45

Then you might want to drop the multiindex column:
df1.columns = df1.columns.droplevel(0)

Yielding your desired solution (sans commas):
path      p1  p2  p3
session
1         20  21   0
2        132  10   0
3          0  24  45

Finally you can convert it to comma-separated string using StringIO:
import StringIO
s = StringIO.StringIO()
df1.to_csv(s)
print s.getvalue()

With the following output:
session,p1,p2,p3
1,20,21,0
2,132,10,0
3,0,24,45


How to troubleshoot entity error

Question: How can I tell which entity is throwing this error (on all pages)?

TypeError: Argument 4 passed to Drupal\views\Plugin\views\display\Block::__construct() must implement interface Drupal\Core\Entity\EntityManagerInterface, instance of Drupal\Core\Entity\EntityTypeManager given, called in /usr/local/var/www/hifldlive/web/modules/contrib/ctools/modules/ctools_views/src/Plugin/Display/Block.php on line 54 in Drupal\views\Plugin\views\display\Block->__construct() (line 69 of core/modules/views/src/Plugin/views/display/Block.php).

I have run composer update on an un-familiar site.
Composer update, drush updb and drush cr all run without errors.
There are about 20 migration tables generated.
I'm guessing I need to roll back the composer update (since it trashes the site), fix the data, then re-run the composer update.
I stuck on how to identify what to fix.
It is no problem to roll back.
I can't where entities are stored in the database.
I also don't see entities in the admin pages.
I can use Drupal Entity API in a custom module, but the site won't load on any page.
Comment: This is not a problem with entities stored in the database. You have outdated core/module code, either core or ctools is much older than the other.
Answer: This is not a problem with entities stored in the database, it is is a version conflict between the module Ctools and Drupal core.
When you install the current version of Ctools with composer require 'drupal/ctools:^3.4' you see that __construct() is calling the parent constructor providing a parameter EntityTypeManagerInterface.
modules/contrib/ctools/modules/ctools_views/src/Plugin/Display/Block.php
  /**
   * Constructs a new Block instance.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity manager.
   * @param \Drupal\Core\Block\BlockManagerInterface $block_manager
   *   The block manager.
   * @param \Drupal\views\Plugin\ViewsHandlerManager $filter_manager
   *   The views filter plugin manager.
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, BlockManagerInterface $block_manager, ViewsHandlerManager $filter_manager, Request $request) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager, $block_manager);

    $this->filterManager = $filter_manager;
    $this->request = $request;
  }

This requires that your core version has this code change:
https://git.drupalcode.org/project/drupal/-/commit/12d7ed53087a469ef8f87476c2849f7b24bfbbb7#140e79af0797f7f25fd1f20e2ebc697be118fea6
So you have to make sure you are using a current core version 8.8.x or you have to downgrade Ctools to a version not having this change.
Comment: Thank you very much for the exact answer.  Changed composer.json to         "drupal/ctools": "3.2",  without the ^, ran composer update, and all is well.

How to troubleshoot entity error


Problema com box-sizing

Question: Tenho um input e gostaria de colocar um box-sizing pois vou usar padding-left e não gostaria de mexer na largura do elemento.
Meu HTML:

  <form>
    <input type="text" />
  </form>

Meu CSS:
.contato input {
    width: 480px;
    height: 50px;
    background-color: #e9e9e9;
    padding-left: 15px;
    box-sizing: padding-box;
}

O box-sizing não está funcionando, conforme imagem:
Comment: Nesse caso é o mesmo que o `border-box`. Dê [uma olhada aqui](https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing) acho que o comportamento/descrição com o padding é igual.
Comment: Ahh, você já esclareceu minha dúvida, eu não sabia que o `border-box` serviria para a minha necessidade. Muito obrigado.
Comment: Não é o `box-sizing: border-box;` que quer usar? o `padding-box` ainda não é suportado por quase nenhum browser...
Comment: Não sabia. É o `padding-box` mesmo, pois gostaria que os 15px do padding não fossem somados ao width do elemento.
Comment: Se juntar uma imagem com o problema seria bom, no caso de eu não estar a perceber bem o problema...
Answer: O padding-box ainda não é suportado por quase nenhum browser.
Acho que pode usar box-sizing: border-box;, para o que explica acho que é essa a solução. A descrição da MDN diz:

border-box
  A largura e altura includem o padding e o border mas não a margin
The width and height properties include the padding and border, but not the margin.

Problema com box-sizing


Frequency integration theorem (Laplace transform)

Question: In my textbook I have the following theorem about the integration of the frequency (F(s)):
Let the Laplace transform of a function $f(t)$ be $\mathscr{L}\{f(t)\}=F(s)$.
If $\dfrac{f(t)}{t}$ is the original, then
$\mathscr{L}\{\dfrac{f(t)}{t}\}=\int_s^\infty F(s)ds$.
Proof:
Let $\Phi(s)$ be the Laplace transform of function $\dfrac{f(t)}{t}$. For every Laplace transform holds $\lim_{s \to \infty} \Phi(s) = 0$. Using the theorem about the integration of the Laplace transform
$\mathscr{L}\{t\dfrac{f(t)}{t}\}=-\Phi'(s)$
so $\Phi'(s) = -F(s)$
Because of that, $\Phi(s)$ can be obtained by the definite integral:
$\Phi(s)=-\int_{s_{0}}^{s} F(s)ds+C=\int_{s}^{s_{0}} F(s)ds+C$
If we put $s=s_{0}$, we obtain that $C=\Phi(s_{0})$. We now let that $s_{0}$ goes to infinity:
$\Phi(s)=\lim_{s_{0} \to \infty}\int_{s}^{s_{0}} F(s)ds + \lim_{s_{0} \to \infty}\Phi(s_{0})=\int_{s}^{\infty} F(s)ds$
I don't understand how can that last equality be correct. Shouldn't the left hand side be equal to: $\lim_{s_{0} \to \infty}\Phi(s)$ instead only $\Phi(s)$, since we have taken the limit of the whole expression?
Comment: I don't know what level of rigor you are looking to achieve, but note that $\Phi(s)$ does not depend on $s_0$ (since $\Phi(s)$ is a constant), since $s_0$ is just a book-keeping parameter that we use to manipulate the expression $\int_{s}^{s_{0}} F(s)ds+\Phi(s_0)$. So while it's technically correct to write $\lim_{s_{0} \to \infty}\Phi(s)$ in the last step, it's sort of redundant, as it just simplifies to $\Phi(s)$. Does that answer your question?
Comment: Also, your integration property equation is incorrect, it should be properly written as $$\mathscr{L}\left\{\frac{f(t)}{t}\right\}(s)=\int_s^\infty F(\sigma)d\sigma,$$ not $\mathscr{L}\{\dfrac{f(t)}{t}\}=\int_s^\infty F(s)ds$ (you used the same variable $s$ for both the integration limit and the dummy variable in the integral).
Answer: You are correct.
However, $\Phi(s)$ is just a constant, and does not depend on $s_0$, so $$\lim_{s_{0} \to \infty}\Phi(s)=\Phi(s).$$


Insert table row after row called from JQuery

Question: I'm trying to insert another table row into a table after calling from a submit button,
PHP/CodeIgniter:
<tr id="wiring_details_<?php echo $part->id;?>-<?php echo $zone->id;?>">

    Wire Type:
    <select name='select_wire_<?php echo $part->id; ?>' onchange='Estimate.select_wire( <?php echo $part->id;?>, this.value );'>
        <option value='' selected>Select wire..</option>
        <option value='1'>14/2</option>
        <option value='2'>14/4</option>
        <option value='3'>16/4</option>
        <option value='4'>16/2</option>
        <option value='5'>RG6</option>
        <option value='6'>CAT5</option>
        <option value='7'>RG59</option>
        <option value='8'>LVT</option>
        <option value='9'>CAT6</option>
        <option value='10'>HDMI</option>
        <option value='11'>Shielded CAT6</option>
    </select>

Length: <input type='text' id='id_wire_length_<?php echo $part->id; ?>' name='wire_length_<?php echo $part->id; ?>' value='<?php echo $part->wire_length; ?>' />
Retail Price: <input type='text' id='id_wire_retail_<?php echo $part->id; ?>' name='wire_retail_<?php echo $part->id; ?>' value='<?php echo $part->wire_retail / 100; ?>' />
Add Another: <input type='submit' id='id_wire_retail_<?php echo $part->id; ?>' name='wire_retail_<?php echo $part->id; ?>' value='Add Wire' onClick="addWire();" />
<input type='hidden' id='wire_id_<?php echo $part->id; ?>' name='wire_id_<?php echo $part->id; ?>' value='<?php echo $part->wire_id; ?>'/>

The "Add another" column has a submit button in it which is going to insert another row into the DOM after the row it is called from, how can this be achieved in Javascript or JQuery as JQ is in this project too.
I know in JQ that I could use something like $(this).parent().after? But I am not 100% on its usage.
Thanks!
Answer: $(this).parent().parent().after('
...
');

Ammended. The first parent from the button should be the TD, the parent of that should be the TR element, so adding after that will give you a new row.
Comment: It isn't the last row in the table, I want it to insert after the row the submit button was activated from. Thanks though.
Answer: If you want to add row as last to table
$("#table_id").append($("
"))

If you want to add row after a certain row in which you have submit button do sth. like that
$("
").insertAfter($(this).parents("tr").eq(0))

The $("
") create jquery object so you can manipulate it so it can have content you would like to.
Comment: I want it to insert after the row the submit button was activated from. not just insert a `tr` into the table...
Comment: Will this insert into the DOM? As I need the data input then to be sent back to a DB, not just have it sitting on the page visually.
Answer: I would a class to the buttons (the add buttons) like class="add-button" and then
$('.add-button').click( function() {
   $(this).closest('tr').after('
...
');
   return false;
});

Demo at http://jsfiddle.net/gaby/WCprC/
Answer: Try this:
$("#my_row_id").after(my_new_rows_data);

Answer: Just noticed your have a hidden element just before the closing of your row you should really place that inside one of the td to validate your code.
I do this quiet a lot but I clone the last row of my table and then "reset" their values
Comment: @Myles Gray: say I had a table and each td had an input I would say $('#Mytable tr').filter(':last').clone().appendTo('#Mytable').find('input:text').each(function(){$(this).val('');});


Need another database value updated when dhtmlxgrid column select option changes

Question: I am using dhtmlxgrid to display MySQL database information to users with the ability to edit line cell data. One column productionstage displays as a combobox column with the ability to change the value to Staged Done. This updates the DB table perfectly. However, I need to check the value of the productionstage column to test for the Staged Done value. If productionstage is set to that value, I need another column stagestatus in the same table to also update it's value to Production. It's preferred that the stagestatus column in the DB table NOT be a end-user viewable column and instead triggered on the back end.
All help is appreciated. Thank you!
My CODE:
//update row
$sql =  "UPDATE invoices SET editby='".$editBy."', editpage='".$editPage."', serverip='".$serverIp."', ip='".$Ip."',floornotes='".$_GET["floornotes"]."',productionstage='".$_GET["productionstage"]."' where id=".$_GET["gr_id"]."'";
$res = mysqli_query($sql);

if (($_GET['productionstage']) == 'Staged Done' ) {
    //update stagestatus from 'Scheduled' to Production if moved to 'Staged Done' in Glass Prep.
$sql1 = "UPDATE invoices SET stagestatus = 'Production') WHERE id=".$_GET["gr_id"]."'";
$res1 = mysqli_query($sql1);

}

NOTE:: I understand that the existing method used by the previous programmer exposes the script to SQL Injection Attacks - I will also be updating this script to use prepared statements... Thank you!
Comment: Do you get any errors? You have an extra parentheses in `$sql1`, but it might be an typo.
Comment: I do not get any errors when inspecting the page but I do see that dhtmlxgrid fails any line update due to the second UPDATE statement. Is dhtmlxgrid only meant to handle one UPDATE statement per grid? If so, I will adjust the code to test for the value and run the correct UPDATE statement based on IF statement logic.
Answer: So I must have just had a bug in the code somewhere. Upon some testing and editing, the following code solved the issue (and yes dhtmlxgrid can handle more than one UPDATE statement per grid).
Solution:
    //update row
$sql =  "UPDATE invoices SET editby='".$editBy."', editpage='".$editPage."', serverip='".$serverIp."', ip='".$Ip."',floornotes='".$_GET["floornotes"]."',productionstage='".$_GET["productionstage"]."' where id=".$_GET["gr_id"]."";
$res = mysqli_query($sql);

if (($_GET['productionstage']) == 'Staged Done' ) {

    $sql1 = "UPDATE invoices SET stagestatus = 'Production' WHERE id=".$_GET["gr_id"]."";
    $res1 = mysqli_query($sql1);

} else {

    print("<action type='error'>SQL query error</action>");

}

Please Note: My Next step is updating the code further using prepared statements to make the script more secure.
Thank you!


ArtifactId is appended to SCM Url using Maven Release Plugin

Question: I have a master POM for all projects. The POM contains the following SCM part:
    <groupId>com.company</groupId>
    <artifactId>master</artifactId>
    <version>...</version>
    <packaging>pom</packaging>

    <scm>
        <connection>scm:git:https://firstname.lastname@example.com/scm/${scm.repository.name}/${scm.project.name}.git</connection>
        <developerConnection>scm:git:https://firstname.lastname@example.com/scm/${scm.repository.name}/${scm.project.name}.git</developerConnection>
        <url>https://bitbucket.server.de/scm/${scm.repository.name}/${scm.project.name}.git</url>
        <tag>HEAD</tag>
    </scm>

<properties>
     <project.scm.id>bitbucket-scm</project.scm.id>
     <scm.project.name>maven-master</scm.project.name>
     <scm.repository.name>tsu</scm.repository.name>
</properties>

Now, I have a maven multi module project, this is the parent POM:
    <parent>
        <groupId>com.company</groupId>
        <artifactId>master</artifactId>
        <version>...</version>
    </parent>

    <groupId>com.company.group</groupId>
    <artifactId>project-foo</artifactId>
    <version>...</version>
    <packaging>jar</packaging>

    <name>project FOO</name>

    <properties>
        <scm.project.name>project-foo</scm.project.name>
    </properties>

When executing the release plugin to release the master POM (first snippet), it works fine. However, when executing the release plugin to release the multi module project (second snippet), it fails, saying:

[ERROR] Failed to execute goal
  org.apache.maven.plugins:maven-release-plugin:2.5.3:prepare
  (default-cli) on project project-foo: Unable to commit files
  [ERROR] Provider message:
  [ERROR] The git-push command failed.
  [ERROR] Command output: [ERROR] fatal: remote error: Repository not found
  [ERROR] The requested repository does not exist, or you do not have permission to
  [ERROR] access it.

In the logs, I can also see the repository URL.
For the working release of the Master POM, it uses

https://user:********@bitbucket.server.de/scm/tsu/maven-master.git
  refs/heads/dev:refs/heads/dev

For the non-working release of the multi-module project, it uses

https://user:********@bitbucket.server.de/scm/tsu/project-foo.git/project-foo refs/heads/dev:refs/heads/dev

It seems to append the artifact-ID of the project to the URL when releasing the multi-module project.
When copying the entire SCM section to the multi-module project and modifying it, it works. However, I only want to interpolate a single property in the master POM to avoid having to copy the SCM tags to every project.
Any help to fix this issue is appreciated.
Comment: Possible duplicate of [Duplicate artifactId in child pom](http://stackoverflow.com/questions/26503589/duplicate-artifactid-in-child-pom)
Answer: Maven version older or equals to 3.6.1
Since Maven 3.6.1 you can set the following in the pom parent :
<scm child.scm.connection.inherit.append.path="false"
     child.scm.developerConnection.inherit.append.path="false"
     child.scm.url.inherit.append.path="false">
  <connection>scm:git:https://email@example.com/scm/${scm.repository.name}/${scm.project.name}.git</connection>
  <developerConnection>scm:git:https://email@example.com/scm/${scm.repository.name}/${scm.project.name}.git</developerConnection>
  <url>https://bitbucket.server.de/scm/${scm.repository.name}/${scm.project.name}.git</url>
  <tag>HEAD</tag>
</scm>

Maven version before 3.6.1
You have to redefine the scm in the children poms :
<scm child.scm.connection.inherit.append.path="false"
     child.scm.developerConnection.inherit.append.path="false"
     child.scm.url.inherit.append.path="false">
  <connection>scm:git:https://firstname.lastname@example.com/scm/${scm.repository.name}/${scm.project.name}.git</connection>
  <developerConnection>scm:git:https://firstname.lastname@example.com/scm/${scm.repository.name}/${scm.project.name}.git</developerConnection>
  <url>https://bitbucket.server.de/scm/${scm.repository.name}/${scm.project.name}.git</url>
  <tag>HEAD</tag>
</scm>


Biological interpretation of equilibrium points

Question: To answer the question what an equilibrium point biologically means, I found the following knowledge on internet and  I made a gist out of it.
When we say $N^*$ is an equilibrium point, we understand that there is no population growth in the population density. Or in other words, the population has attained its saturation level. If the initial population is much closer to the equilibrium point and it moves towards the equilibrium point as time increases, we say that the equilibrium is stable. If it is asymptotically stable, then all the initial populations will tend to move towards the equilibrium point as time increases. But if the population density is at unstable equilibrium, then eventually the population will move away from the equilibrium point.
Can I say that abovementioned lines biologically imply an equilibrium point? As far my concern, there is no biology involved in it.
Edit:
As Paichu mentioned in his answer, I am adding some more context to my question.
When we analysis a model, e.g. Malthus model or Logistic growth model or Allee effect, we find the equilibrium points first and then we find out whether the equilibrium point is ASE or an unstable equilibrium point. So what does an ASE point biologically mean? Or what does an unstable equilibrium point mean biologically?
Comment: In a stable population of common plants, say, there will be biological processes (predation, disease) that will reduce the population density if it gets too high or increase it (predators decrease, disease resistance develops) if it gets too low. This is a stable equilibrium. The biology is in the mechanisms that restore or remove equilibrium of the population density.
Answer: If you're looking for a realistic biological interpretation of equilibrium, you need to give a specific scenario. In population dynamics in general, equilibria are just points where the rate of changes of all variables are zeros, meaning for instance, the number of birth and death are the same at that point. But say in a human body, equilibrium can refer to the homeostasis of the system (everything is changing, but the aggregated change does not affect the core property of the system).
Once you have a good interpretation of the equilibrium, then you can start discussing the implications of stable and unstable equilibria. For example, why is an equilibrium unstable from a biological perspective? To answer this type of question, you would need to look at the parameters involved in the condition for the existence and stability of the equilibrium.
Comment: I have edited my question.


Inserting value in table with the click of a button

Question: I'm working on a file called test.php.
What I'm trying to do is, to insert a value into a table by clicking a submit button
I have two tables, tbl_1 and tbl_2
tbl_1
id | name | age

4  | john |  20

9  | tim  |  25

8  | lea  |  22

While tbl_2 have the same structure as tbl_1, it is empty or without any value in it... the idea is that I want to have a button, after clicking on that button, it will insert the value of tbl_1 into tbl_2 based on the id
The question is, how do I fill in tbl_2 with the value of tbl_1, through a click of a submit button?
I made a form, trying to bring the value from tbl_1 to tbl_2, but to no avail...
 <form action="test.php?id" method="post">
    <input type="submit" class="btn btn-info btn-xs" name="submit" value="Copy"/>
</form>

 <?php
if(isset($_POST['submit']))
{
     $io = $_POST['io'];
     $no_kes = $_POST['no_kes'];
     $SQL = "INSERT INTO tbl_2(name, age) VALUES ( '".$name."', '".$age."')";
     $result = mysql_query($SQL);
}
?>

Below is how my table looks like on the web.

Below is the code for the table I constructed.

      Id
      Name
      Age

  <?php
  // Read
  $per_page = 7;
  if (isset($_GET["page"]))
    $page = $_GET["page"];
  else
    $page = 1;
  $start_from = ($page-1) * $per_page;

  $sql = "select * from tbl_1";
  $result = $mydb->query($sql);
  while ($readrow = $result->fetch_array()) {
  ?>

    <?php echo $readrow['id']; ?>
    <?php echo $readrow['name']; ?>
    <?php echo $readrow['age']; ?>

Comment: How are you constructing this HTML table? Include all the relevant HTML and PHP code as well.
Comment: Where is the form from where you are getting the name and age?
Comment: @RajdeepPaul done
Comment: @Exprator done.
Comment: @abcd I've given an answer below, hopefully this will resolve your issue.
Answer: There are couple of things you need to change in your code, such as:

You need to change your form's action attribute in the following way,
<form action="test.php?id=<?php echo $readrow['id']; ?>" method="post">
    <input type="submit" class="btn btn-info btn-xs" name="submit" value="Copy"/>
</form>

Subsequently, you have to catch a particular row's id in test.php page the following way,
$id = (int)$_GET['id'];

Finally perform your INSERT operation in the following way,
if(isset($_POST['submit'])){
    $id = (int)$_GET['id'];
    $SQL = "INSERT INTO tbl_2(name, age) SELECT name, age FROM tbl_1 WHERE id = {$id}";
    $result = mysql_query($SQL);
}

Sidenote: Don't use mysql_* functions, they are deprecated as of PHP 5.5 and are removed altogether in PHP 7.0. Use mysqli or pdo instead. And this is why you shouldn't use mysql_* functions.
Comment: @abcd Glad I could help. Cheers! :-)
Answer: Since you already mentioned tbl_2 has the same structure as tbl_1, you may simply construct your DB query as:
insert into tbl_2(id, name, age) select tbl_1.id, tbl_1.name, tbl_1.age from tbl_1 left join tbl_2 on tbl_1.id = tbl_2.id;

What this does:

It scans tbl_1 and inserts any values that are missing in
  tbl_2 table. It has the potential to insert duplicate values. For
  that, you should have enough robust DB structure that avoids
  duplicate values in a table (using unique keys etc).


How to measure and visualise relationship between two sets of count data over time?

Question: I have two sets of count data - one for different viral species, and one for different mosquito species. The count data spans 7 weeks, in 3 different locations.
I want to be able to show that changes in the mosquito species counts correspond to changes in the viral species counts. This is how far I've gotten in visualising that relationship:

While this clearly shows what kind of data I have, it is pretty clunky and I haven't actually measured the correlation between the two datasets.
I'm struggling to figure out what kind of statistical test I should use for this. I've looked into a different options - I thought perhaps something like:
cor(as.vector(mosquito_matrix), as.vector(virus_matrix))

But my matrices are of different dimensions and that only gives me one value. I was hoping for something that could show the correlation over time. Is there a statistical test suitable for this?
I am working in R and have been using the Phyloseq package to analyse my data so far.
Thank you so much for your help. Apologies if there is already a question about this - the only one that seemed to have the same kind of data was this one: Count Data and Relationships but it has 0 answers.
Answer: Modelling the data: You have multivariate count data over time, so you are going to need to look up models that are appropriate for that kind of data.  There are a number of different classes of models that have been applied to this kind of data.  One commonly used class of models are multivariate extensions to standard count models, such as the negative-binomial GLM (e.g., Davis and Wu 2009; Motta et al 2012; Zhang et al 2017).  Another class of models that has recently become popular for this kind of data are copula models (see e.g., Song et al 2008;
Nicoloulopolous and Karlis 2009; Madsen and Fang 2010).
I recommend you read some of this literature to get an idea of the available models for this kind of data.  So far as I know, there are computational packages in R to implement most of these model forms, but I will leave it to you to check the details.  Personally, I have always found that the negative-binomial GLM models most count data well, so I would start by fitting a multivariate negative-binomial GLM.  If you are willing to ignore possible auto-correlation over time, one option would be to drop the time variable from the model, and treat the outcomes at different times as exchangeable data points.  This should allow you to estimate the statistical association between the counts of mosquito species and virus species.
Visualising the data (and model output): I think you have made quite a good attempt at visualising your data.  You are trying to visualise the relationship between three variables at a time (species, time, count), and this can be difficult, so kudos on your attempt.  I agree with you that the present plots are quite complicated, and not easy to interpret, so I will offer some suggestions that can simplify them.  Probably the most obvious way to simplify this visualisation would be to replace the bar-charts for each time point with a $5 \times 7$ heatmap showing the log-counts of each combination of virus and mosquito species.  (I am assuming that none of your counts are zero, so a log-scale would not drop any of the values.)  This would give you one heatmap showing each time period, and you could then see the change in the pattern in the heatmap over time.  Another way to further simplify the visualisation would be to change your time-series plot to an animation.  If you made both of these changes then you would end up with a single animation of a $5 \times 7$ heatmap that is changing over time.  (If you can post your data I might have time to knock up a plot to show you what I have in mind.)
That is how I would suggest you visualise the raw data.  However, the relationships between the species counts will probably not be all that clear in the plot of the raw data, and for this latter task you will need to make plots of the outputs of your model.  The usual thing to do in these cases is to make barplots of the regression coefficients, with error bars showing confidence intervals.  Since the coefficients in the model directly estimate the relationships in the species counts, this will give the viewer/reader a clear visualisation of the estimated relationships in the data.
Comment: Thank you, this is really helpful. For the visualisation, I think the heatmap is a good idea, but I do have some zero counts - what does this mean for the log-scale? Also, does having zero counts effect what models I should use?

If it helps, here is my data:
Mosquito matrix: https://figshare.com/articles/mosquito_matrix/10229129
Virus matrix: https://figshare.com/articles/virus_matrix/10229453
Comment: Zero counts shouldn't really be a problem.  For the visualisation it just means they'll be off the scale and show up as blank (which is fine anyway).  Standard models for count data can handle zero counts, so they are certainly not a problem for the model.