Converting a (signed) permutation to a reduced word

Question: I vaguely know that by looking at the inversions of a permutation, you can write down the reduced word expressing the permutation as a product of adjacent transpositions $s_i = (i,i+1)$.  However, I am a little unclear on what order you check the inversions, or if there is a simple way to do it without multiplying your original permutation by all the transpositions you've found so far.

Is there a simple algorithmic description of how to convert a permutation's inversion set to its reduced word?

Secondly, I'd actually like to do this in the signed permutation group (whose elements are monomial matrices with nonzero entries taken from $\{1,-1\}$; a monomial matrix is like a permutation matrix except the nonzero entries don't have to be $1$).
I'm a little unclear on when you look for the sign changes, but possibly this is due in large part to not having a specific algorithm for the plain permutations.

Is there a simple algorithmic description of how to convert a signed permutation's inversion set and positions of $-1$s to its reduced word?

Example:
The permutation $$\pi = (1,2,3) = \begin{bmatrix} 1 & 2 & 3 \\ 2 & 3 & 1 \end{bmatrix}$$ has inversion set $$\{ \{1,3\}, \{2,3\} \}$$ since $1 < 3$ but $\pi(3) < \pi(1)$ and $2 < 3$ but $\pi(3) < \pi(2)$. The $\{2,3\}$ is pretty clearly caused by $(2,3)$ and so we need to multiply by something to invert $\{(1,3)\}$. Since already know $(2,3)$ is used, that moves the $3$ to a $2$, and $\{1,2\}$ is caused by $(1,2)$. Now depending on which order you apply your functions, we get the product of $(1,2)$ and $(2,3)$ is $(1,2,3)$.
How did I know to use $\{2,3\}$ first? Should I really transform the inversion set by every adjacent transposition I discover?
What if it was $$\sigma = (1,\bar 2,3) = \begin{bmatrix} . & -1 & . \\ . & . & 1 \\ 1 & . & . \end{bmatrix}$$
with the same inversion set as before, but with the $2$nd column negated? When do we take of the negative?
Comment: @Henning, I have a feeling it might be an answer (at least for unsigned ones). I have this suspicion that I look for adjacent inversions (like {2,3} or {i,i+1}), and there will ALWAYS be one. Use it, then adjust the inversion set. There will still always be one.  I think this is bubble sorting, but I'm not sure.
Comment: My second suspicion is that if the first row has the -1 in it (the 1 has the bar), then you throw in the special -1 generator and un-bar the one. otherwise, ignore the -1s and bars.  I'm going to code this up and check it, but I really want a good intuitive understanding of this.
Comment: (Second suspicion is quite wrong. Take the identity matrix and flip some signs.)
Comment: This is a special case of a length reduction in crystallographic finite reflection groups. A useful way of expressing this in terms of the corresponding root system goes as follows. If $\sigma(\alpha)<0$ for some simple root $\alpha$, then $\ell(\sigma s_\alpha)=\ell(\sigma)-1$. Rinse. Repeat. As @Henning pointed out, in the case of a root system of type $A_n$ this leads to bubble sorting. The other root systems lead to slight generalization. If you also allow reflections with respect to hyperplanes determined by non-simple roots, then you get analogues of shell sorting.
Answer: While counting inversions is a great way to calculate the (Coxeter) length, it turns out a related notion called descents is better for factorizing the element. (Note that my answer is basically unrelated to "inversion length", which appears to be a hot topic in computational biology).
For a permutation $\sigma$, the Coxeter length $\ell(\sigma)$ is the length of the shortest sequence of adjacent transpositions $s_i=(i,i+1)$ whose product is $\sigma$. For instance $\ell(s_1 \cdot s_2 \cdot s_3) = 3$, but $\ell(s_1 \cdot s_1 \cdot s_2) = \ell(s_2) = 1$. For a signed permutation (a permutation of $\{\pm1,\ldots,\pm n\}$ such that $\sigma(-i)=-\sigma(i)$), we define the Coxeter length similarly, except there is now one more generator allowed: $s_0 = [\bar1]$ which takes $1$ to $-1$ and fixes $i$ if $|i| \geq 2$.
The Coxeter length can be calculating from so-called inversion sets:
$$\begin{array}{rcl}
\ell(\sigma) &=& \left| \{(i,j) : 1 \leq i < j \leq n \mid \sigma(i) > \sigma(j) \}\right| \\
&+& \left| \{(i,j) : 1 \leq i \leq j \leq n \mid \sigma(-i) > \sigma(j) \} \right|
\end{array}$$
where the bottom line is defined to be $0$ for a plain permutation (which agrees with the value calculated from the signed permutation that agrees with $\sigma$ on $\{1,\ldots,n\}$).
Any element in the first of those inversion sets is a place where the permutation is "out of order". One can either swap $i$ and $j$ on the input side, or swap $\sigma(i)$ and $\sigma(j)$ on the output side.
For unsigned permutations this leads to a fairly obvious factorization method.  The key observation is that we can always find an inversion where the two numbers are adjacent. On the output side this seems a bit fantastical, but on the input side it is obvious: in order to check if a sequence is sorted, you just move along checking if $\sigma(i) < \sigma(i+1)$. If all of those check out, then the transitive property of $<$ implies everything checks out (and so you have the identity permutation!). Otherwise we have our magical $\{i,i+1\}$ we needed to pull off one factor of $s_i$ on the input side.
Thus we define the (input-side) descent set to be: $$\newcommand{\des}{\operatorname{des}} \des(\sigma) = \{ i : 1 \leq i \leq n \mid \sigma(i) > \sigma(i+1) \}$$
And we have the relation that $\ell( s_i \sigma ) < \ell(\sigma)$, that is that an input-side $s_i$ is going to be cancelled by a hidden $s_i$ that is already there, if and only if $i \in \des(\sigma)$. Thus every reduced factorization of $\sigma$ is found by pulling out one generator $s_i$ from each descent set $\des(\sigma)$ and replacing $\sigma$ with $s_i \cdot \sigma$. [The actual replacement need not be done in code, compare to partial pivoting elimination versus explicitly moving the rows around in memory.]
For signed permutations, one gets the "obvious" thing (which is extremely close to my suspicion, but my suspicion radically mishandled negative numbers):
$$\des(\sigma) = \{ i : 0 \leq i \leq n ~|~ \sigma(i) > \sigma(i+1) \}$$
where we extend signed permutation to $\{-n,\ldots,n\}$ by defining $\sigma(0)=0$. Again, this easily becomes a full factorization algorithm by replacing $\sigma$ by $s_i \sigma$ for $i \in \des(\sigma)$ until $\des(\sigma)$ is empty.
This is discussed (probably with the inputs on the right) in Bjørner–Brenti (2005), page 248 and surrounds.

Bjørner, Anders; Brenti, Francesco.
Combinatorics of Coxeter groups.
Graduate Texts in Mathematics, 231. Springer, New York, 2005. xiv+363 pp. ISBN: 978-3540-442387; 3-540-44238-3
MR2133266
DOI:10.1007/3-540-27596-7
Comment: (Also thanks to Henning for making me consider bubble-sort. The input/output problem had previously kept me from understanding this approach. Once resolved Henning's answer made the unsigned case perfectly clear. Then I found Bjørner–Brenti's "this-just-works" definition, which was obvious once you realized taking absolute values was dumb.)
Comment: Another good source is chapter 9 of the book *The Geometry of the Classical Groups* by *D.E. Taylor* (combined with my answer to http://math.stackexchange.com/questions/106462/on-the-group-of-signed-permutations)
Comment: @jug: thanks. I liked the answer (and remember liking the book). I'll check the book during the week. Your answer only makes some sense without the book. The vector space over Z/2Z looks like it will make some calculations easier, but I think need the book to see which calculations those will be.
Comment: From (9.22) in the book rsp. Claim (a) and (b) in my answer you can easily deduce that $\mathop{des}(\sigma)$ is essentially the same as $\mathop{D}(\sigma)\cap R$ (with $R$ the set of Coxeter generators): just identify $0$ with $(1\; -1)$ and $i>0$ with $(i\; i+1)$.


Is there any hat-trick wickets taken by as a team?

Question: In Cricket, is there any hat-trick wickets taken by as a team except the individual person's hat-trick?
Example:

With in a over in continuous three balls as wickets - mixed of run out, caught, bowled, stumped, LBW, hit wicket and handling the ball.

or

On any over's last two balls as wickets and next over's first ball as wicket- mixed of run out, caught, bowled, stumped, LBW, hit wicket and handling the ball.

I didn't find any reference in the internet. If any one aware of that, please share the reference link.
Answer: I don't think you looked very hard ;-) A simple Google for "cricket hat trick run outs" led to this rec.sport.cricket thread and the Ireland vs Netherlands match in the 2011 World Cup which had four run outs in consecutive balls in the last four balls of the innings:

49.3 AF Buurman run out 26 (49m 30b 4x4 0x6)
49.4 PM Seelaar run out 0 (1m 1b 0x4 0x6)
49.5 Adeel Raja run out 0 (1m 0b 0x4 0x6)
49.6 Mudassar Bukhari run out 11 (22m 8b 0x4 1x6)

Given that, it doesn't seem too unlikely there are going to be quite a lot of these incidents out there.
Answer: Such an incident of a team hat-trick happened in the final of the 2016 Big Bash League. Melbourne Stars who were batting first, lost 3 wickets in the last 3 balls of the innings. Here is the match report of the final.

Adam Zampa was the first to be the run out from a direct hit on the stumps.
Evan Gulbis was caught out off the next ball.
Daniel Worrall was run-out off the last ball by the wicket-keeper.

The team picked up 3 wickets, although Clint McKay was only credited with the one in the middle. Here is a video of the three wickets taken in three successive balls.
Answer: In 2016 T20 world cup this happen to India, during the group match against Bangladesh.
here is the link of that match


Is it mandatory to use Group Policy to install or deploy applications?

Question: Using Windows Server 2012 R2 Essentials on 1 server and about 5 workstations, do I have to use GPO to "deploy" the applications?  i.e. CorelDraw, Adobe CS6, Office, Acrobat, etc.
Or can I just go to each workstation (sneakernet) and install them individually?  I'd prefer to do it this way to make sure everything is installed fine.  Or would I lose the Group Policy control here doing it this way?
Is there any pros or cons to doing it these ways?
thank you!
Comment: `Is it mandatory to use Group Policy to install or deploy applications?` - No. `would I lose the Group Policy control here doing it this way?` - Yes.
Comment: Thank you for being concise with that answer.  So if I want the control, then GPO it is.  thank you.
Comment: Your comment I also consider an answer to my questions.  Thank you Joe.
Answer: As a Windows domain administrator it is up to you on how you choose to manage your environment.  There are pros and cons to every choice.  In a large environment manual tasks are frowned upon, as they will take up a lot of time.  Group policy and automation will make your job much easier.
If you prefer to install everything manually, go ahead and do that.  You are the administrator and what you decide goes.
Here are a couple of basic links regarding GPOs and installing software packages:
http://community.spiceworks.com/how_to/8595-deploy-msi-s-through-your-network-with-gpo
https://www.youtube.com/watch?v=zadvca6LlzA
Comment: No problem.  If you are looking to control the employees' actions on the systems, you will want to learn and implement group policy. I suggest keep reading/researching and ask questions when you cannot find solutions online or through IT colleagues or friends.
Comment: Please read here: https://technet.microsoft.com/en-us/library/cc738858%28WS.10%29.aspx?f=255&MSPPError=-2147217396
Comment: Very small office here.  5± users.  therefore the reasoning not to complicate this any more than it should be as I am finding out moving to a server is just becoming much more headache than there was before.  I need the server for basic things such as backups, networking the workstations, and some sort of control of what the employees do and cannot do.  I just need it kept simple.  Thanks for the links, I'll check them out and keep learning!
Comment: yes, still in the new process of reading up and learning about the server realm.  I am very fluent in pc tech, but servers I never had a need for until now.  For the most part, Essentials is pretty straight forward, but then there are things that ar eleft to be desired...therefore I am here looking for help in those areas I am unfamiliar with completely.  thank you for your help!
Comment: The video was very helpful and straight forward.  I figured it would be like most pc/windows things, but I just never really looked at GPO yet to know.  What is the difference between Computer Configuration and User Configuration for software installation?  What are the major difference and pros/cons.  Software types that are better for one over the other configurations?  i.e. Adobe Photoshop, Acrobat, Chrome, Office, specialized software (that may have dongle keys, serial no., online or email activation) used in connection with manufacturing devices, etc.
Comment: VERY helpful again! Much appreciated bentek! ; )


Import csv into Neo4j where multiple columns have empty cells

Question: I am looking to import a csv where records in columns have null values (empty). There is a chance that any column could have an empty record, so ultimately the query should be able to handle any column. Here is an example of my table with and example of the expected graph output:
Group       Capability      Functionality   Status        Dev    Input         Output
Pipeline    DataIngest      Read CSV        Complete      Ben    source.csv    masterTable
Pipeline    DataQuality     Quality score   Complete             masterTable
Analytics   Summary         Minimum score   In progress   Jill   masterTable   dataSummary
Analytics   Summary         Maximum score   In progress          masterTable   dataSummary
Analytics   Prediction      Future score
Output      Report          Bar chart       Not started   Ben    dataSummary
Output      Report          Line chart      Not started   Fred

The following is what I have tried, which does not produce that I was expecting. The query produces the following issues:

Functionality is not its own labelled node (it is part of capability)
Properties are not stored within Functionality (this may be because of issue 1)

CREATE CONSTRAINT ON (g:Group) ASSERT g.name is UNIQUE;
CREATE CONSTRAINT ON (c:Capability) ASSERT c.name is UNIQUE;
CREATE CONSTRAINT ON (f:Functionality) ASSERT f.name is UNIQUE;
LOAD CSV WITH HEADERS FROM 'file:///MasterSheet.csv' AS line

WITH line
MERGE (g:Group {name: line.Group})
MERGE (c:Capability {name: line.Capability})
FOREACH(x IN CASE WHEN line.DevStage IS NULL THEN [] ELSE [1] END |
  MERGE (f:Functionality {name: line.Functionality, status: line.Status, developer: line.Dev}))
MERGE (i:Data {name: line.Input})
MERGE (o:Data {name: line.Output})

CREATE UNIQUE (g)-[:PART_OF]->(c)
CREATE UNIQUE (c)-[:HAS]->(f)
CREATE UNIQUE (f)-[:INPUT]->(i)
CREATE UNIQUE (f)-[:OUTPUT]->(o)

Comment: Can you show the actual contents of your CSV file?
Comment: The example table in the question is the contents of the table
Answer: You have multiple issues.

A big issue is that your Comma Separated Values (CSV) file is badly formatted. By default, as the name implies, a CSV file should use the comma character as the value delimiter. Your data file has no commas at all. Here is a properly formatted version of your file:
Group,Capability,Functionality,Status,Dev,Input,Output
Pipeline,DataIngest,Read CSV,Complete,Ben,source.csv,masterTable
Pipeline,DataQuality,Quality score,Complete,,masterTable
Analytics,Summary,Minimum score,In progress,Jill,masterTable,dataSummary
Analytics,Summary,Maximum score,In progress,,masterTable,dataSummary
Analytics,Prediction,Future score
Output,Report,Bar chart,Not started,Ben,dataSummary
Output,Report,Line chart,Not started,Fred

Notice how "empty" values are represented by consecutive commas, or if they are at the end of a line they are just omitted. Values can have embedded spaces.
You have a typo. DevStage should be Dev.
The clauses that depend on f must not be executed unless the f node was created, and they must be executed when f is in scope. f is out of scope outside of the FOREACH clause.
Recent versions of neo4j no longer support CREATE UNIQUE, and MERGE should be used instead.

Here is a query that solves issues 2 through 4, and relies on the above proper data format:
LOAD CSV WITH HEADERS FROM 'file:///MasterSheet.csv' AS line
MERGE (g:Group {name: line.Group})
MERGE (c:Capability {name: line.Capability})
MERGE (g)-[:PART_OF]->(c)
FOREACH(x IN CASE WHEN line.Dev IS NOT NULL THEN [1] END |
  MERGE (f:Functionality {name: line.Functionality, status: line.Status, developer: line.Dev})
  MERGE (c)-[:HAS]->(f)
  FOREACH(x IN CASE WHEN line.Input IS NOT NULL THEN [1] END |
    MERGE (i:Data {name: line.Input})
    MERGE (f)-[:INPUT]->(i)
  )
  FOREACH(x IN CASE WHEN line.Output IS NOT NULL THEN [1] END |
    MERGE (o:Data {name: line.Output})
    MERGE (f)-[:OUTPUT]->(o)
  )
)

NOTE: Your expected output data visualization is not possible with your sample data.


How do I Print/Display Site information Form

Question: I'm trying to print the Site Information Form, and a series of other forms in the near future, inside a lightbox using a snippet of code I found similar to the following.
global $user;
module_load_include('inc', 'user', 'user.pages');
print user_edit($user);
This, along with some other code not mentioned, will display the user account form. But I'd like to know how do I print the Site Info Form, and any other form I may wish to display in the future? What process or methods can I use to find out what I need to do?
I hope I'm not being too vague. Any pseduo-code, suggestions or even a hint would be greatly appreciated.
Thanks.
Answer: <code><?php print drupal_get_form('system_site_information_settings'); ?>
</code>
You can output any form in Drupal using drupal_get_form once you know it's form_id (which is the function name that returns the form array)
Answer: You might wanna look at the answer provided at - Theming the node edit forms  to open them within Lightbox - You can use popups module to display and work with any form in a lightbox like popup which u can theme.
Comment: Did I totally get the question wrong, wondering why the answer was downvoted?


Unsure how this MLE was derived from given normal distribution

Question: I came across this mle formula in some (undocumented) code performing linear regression with input matrices $A$ and $B,$ and was wondering how it was derived. It might also be some level of approximation, I'm not entirely sure.
$y$ is a $N$-dimensional vector, $A$ is $N \times M$ matrix, $B$ is $N \times P$ matrix
$$y \sim \operatorname{Normal}(A\alpha + B\beta, \sigma^2I)$$
the MLE $\hat{\alpha}$ is supposedly $\hat{\alpha} = \frac{y \cdot A \: - \: (Q^TA \:\cdot\: Q^Ty)}{A  A \: - \: (Q^TA \:\cdot \:Q^TA)}$
where $Q$ in the above formula is $Q$ from QR-decomposition on $B$ (the $Q$ in this case is from thin/skinny QR-decomp, but I doubt it affects the derivation). I don't understand where $\hat{\alpha}$ formula comes from, any help would be appreciated!
Comment: A, B and y are defined, but X is not. ... What's X? What matrix is Q from the QR decomposition of? Normally, the parameters of a normal are mean and variance. $y$ is presumably an N-vector but you appear to have a scalar variable to represent the variance-covariance matrix (additionally lower-case $\sigma$ is normally used to stand for standard deviation). Do you intend to have $\sigma^2 I$ there or something else? Is there any information about what this code is for?
Comment: X was me getting my variables confused, and I further clarified the question. If I am still missing information let me know, and I will try my best to add it. Thanks!
Comment: What does $\text{" }A\cdot y\text{ ''}$ mean when $A$ is an $N\times M$ matrix and $y$ is an $N\times 1$ matrix?
Comment: I imagine y is 1 x N, and I just changed it to y⋅A
Answer: Intuitively, our answer must consider some projection of the data onto the residual from the prediction of B: Q provides an orthonormal basis for B, so we must remove the components on Q.
More rigorously,
We can directly compute the MLE using the formula for linear estimator. We have that
$$ \begin{bmatrix} A & B \end{bmatrix} \begin{bmatrix} \alpha \\ \beta \end{bmatrix} + \epsilon = y $$
Using the formula to solve for $\hat{\alpha}, \hat{\beta}$, we must have
$$ \begin{bmatrix} A^T A & A^T B \\ B^T A && B^T B \end{bmatrix}^{-1} \begin{bmatrix} A \\ B \end{bmatrix} y = \begin{bmatrix} \hat{\alpha} \\ \hat{\beta} \end{bmatrix} $$
Using the formula for 2x2 block matrix inversion, we have
$$ \hat{\alpha} = ((A^T A - A^T B (B^T B)^{-1} B^T A)^{-1} A^T - (A^T A - A^T B (B^T B)^{-1} B^T A)^{-1} A^T B (B^T B)^{-1} B^T) y $$
Now note that
$$ A^T B(B^T B)^{-1} B^T = A^T Q Q^T $$
Substituting, we have
$$ \hat{\alpha} = (A^T y - A^T Q Q^T y) (A^T - A^T Q Q^T A)^{-1} $$
as desired.


What is the optimal strategy to invest a limited resource in N uncertain options?

Question: Suppose I have a £100 to invest in 2 options.  Each option has a expected value, but the value is unknown.
Option A has the highest average expected value, but a bigger uncertainty range.

If we just looked at means we would invest everything in A.
What circumstances would cause a mixed investment strategy?
Comment: what do you mean by "optimal"?
Comment: @shimao - I guess I mean 'what definitions of optimal make this an interesting question'?
What would cause you to legitimately invest in B over A (or a Mix)
Comment: This seems to be an related question: https://stats.stackexchange.com/q/347650/26948
Comment: Suppose that losing all your money would be catastrophic to you, that A has an appreciable chance of losing it all, and B has almost no chance: which option would you chose?  Simple *gedankenexperimenten* like this show why *how you value the potential gains and losses* is an essential part of the analysis.  This idea is the basis of online retirement calculators that suggest what mixture of investments to make depending on how much money you need to have and by when. The thread indicated by @shimao is indeed relevant. In practice (unfortunately) stocks never behave independently!
Answer: One important consideration is your risk tolerance.
For concreteness, let's say that the above curves represent the distributions of the potential eventual value of a £1 investment. For option A, it looks like the expected value is £1.5, versus £1.3 for option B. Yes, if all you cared about was the expected value, you would choose option A.
But if the dashed vertical lines represent 95% confidence limits, it also appears that you have about a 2.5% chance of the eventual value under option A being £0.5 or lower, in which case you've lost half of your investment. Under option B, although your expected value is lower than for option A, a similarly improbable (2.5%) scenario would be an eventual value of about £0.95, or only a 5% loss of your investment.
So what's your tradeoff between risk and reward? In many cases, your particular tradeoff might mean a mixed investment strategy is best. That way you can protect some of your investment under option B while hoping for the possibility of higher yields under option A from the rest of your £100 investment.


Unable to run CPLEX on Pulp in Python

Question: I am trying to use Pulp to setup my LP model and solve it using CPLEX solver.
I have CPLEX installed with license on my laptop but getting the below error :
PulpSolverError: PuLP: cannot execute cplex.exe

Comment: You may want to consider using [docplex](https://developer.ibm.com/docloud/documentation/optimization-modeling/modeling-for-python/) (a modeling language) or the [CPLEX Python API](https://www.ibm.com/support/knowledgecenter/SSSA5P_12.8.0/ilog.odms.cplex.help/refpythoncplex/html/cplex-module.html) instead as they are supported by IBM.
Answer: Make sure that cplex.exe is in your PATH (see Adding directory to PATH Environment Variable in Windows).
Alternately, you can set the path argument to the location of cplex.exe in the CPLEX_CMD constructor (see the source code).

Unable to run CPLEX on Pulp in Python


Hello, In pyhton, the xpath of the button is not correct, it gives an error

Question: What could I be missing?
mınPrice = driver.find_element("xpath","/html/body/div[3]/div[1]/div[3]/div[4]/div[1]/div[1]/div/form/fieldset[1]/div[1]/div[2]/div/div[1]/div/div[1]/input").send_keys("500")
maxPrice = driver.find_element("xpath","/html/body/div[3]/div[1]/div[3]/div[4]/div[1]/div[1]/div/form/fieldset[1]/div[1]/div[2]/div/div[2]/div/div[1]/input").send_keys("90000")
time.sleep(1)
entered_button=driver.find_element(By.ID,"//*[@id="minisearch-search-btn"]")
entered_button.click()
time.sleep(1)

Answer: You should be able to find that button with:
entered_button=driver.find_element(By.XPATH,"//*[@id='minisearch-search-btn']")

Answer: No, unfortunately. But I changed it like this.
entered_button=driver.find_element(By.CSS_SELECTOR,"#minisearch-search-btn")
I replaced xpath with selector.
Comment: XPATH works as well, like in my response... nevermind.


How do I change the admin toolbar search input box to type=search?

Question: I'd like to change the attribute "type" to "search". The search icon goes over the top of the text making it hard to see what you are typing. The themes are a combination of Adminimal for admin and Bulma for the front end. The Bulma front end is the problem.
The source html is as follows.
<input id="admin-toolbar-search-input" aria-labelledby="toolbar-item-administration-search" type="text" size="60" maxlength="128" class="form-text input ui-autocomplete-input" autocomplete="off" tabindex="-1">

I want the type attribute to be search so that the icon is hidden when you enter text.
I've tried overriding the bulma template input--bulma.html.twig. Not ideal from a scope perspective and setting these attributes here doesn't work.
{{ attributes.setAttribute('type', 'search') }}
Ideally I would find a theme pre-process function. I can't see to find one that works. How do I go about it?
Answer: The following hook works. I found it by text searching the project
function mytheme_preprocess_input(&$variables, $hook) {
 if ($hook == "input" && $variables['attributes']['id'] == "admin-toolbar-search-input") {
   $variables['attributes']['type']  = "search";
 }
}

It does not solve the icon problem in this case. The icon is in a different DOM element.
The fix to the search icon being over the text was
#admin-toolbar-search-tab input:focus + .icon.is-left {
 display: none;
}


Uniformly Integrable of sets in $L_{1}(\mu)$ is equivalent to almost order boundedness

Question: A bounded set $F\subseteq L_{1}(\mu)$ is said to be uniformly integrable if : $\forall \epsilon$ there is a  $\delta>0 $, such that $\forall$ measurable set $A$, and $\forall f\in F$ , if $\mu(A)< \delta$ , then $\int_A |f|d\mu< \epsilon$.
$F$ is called almost order bounded if for $\forall \epsilon$, there exists $u\in L_{1},u>0$ such that $F\subset [-u,u]+ \epsilon B_{1}(L_{1})$.
I want to prove that $F$ is uniformly integrable iff it is almost order bounded.
I have no idea how to start!
Comment: What about the measure space you are considering? And in the definition of almost order bounded, isn't it "for all $\varepsilon>0$, there exists $u>0$, $u\in L^1$ such that for each $f\in F$, $f=g+h$, where $|g|\leqslant u$ and $\lVert h\rVert_{L^1}<\varepsilon"?
Comment: @DavideGiraudo, yes you are right, I edit the definition, and about the measure space, consider $L_{p}[0,1]$. Actually I have a solution, and I may post it after finishing my final exams. Thank you!
Answer: If the measure space is $[0,1]$, one can check that a family $\mathcal F$ which satisfies the condition $\forall\varepsilon>0,\exists \delta>0$ such that if $A$ is measurable of measure $<\delta$, then for each $f\in\mathcal F$, $\int_A|f|d\mu<\varepsilon$ satisfies the equivalent condition
$$\lim_{R\to +\infty}\sup_{f\in \mathcal F}\int_{\{|f|>R\}}|f|d\mu=0.$$
More generally, such an equivalence holds if the measure space $(X,\mathcal B,\mu)$ is finite and $\mu$ doesn't contain any atom (that is, if $\mu(A)>0$, we can find $B\subset A$ such that $0<\mu(B)<\mu(A)$). This relies on the fact that for each $\delta>0$, we can write $X$ has a finite partition of sets of measure $<\delta$.
Once we have this equivalence, assume that $\mathcal F$ is uniformly integrable. Then for a fixed $\varepsilon$, take $R$ such that $\sup_{f\in\mathcal F}\int_{\{|f|>R\}}|f|d\mu<\varepsilon$. With $u:=R$, we are done.
Conversely, assume that $\mathcal F$ is almost order bounded. We need to show that if $u$ is integrable, then for all $\varepsilon>0$, there is $\delta>0$ such that if $\mu(A)<\delta$ then $\int_A |f|<\varepsilon$.


How can I get the Django SplitDateTimeWidget to recognize AM/PM inputs?

Question: I can't for the life of me figure out how to get the SplitDateTimeWidget (link to ref doc) to recognize AM/PM inputs.
I've tried both the template-style input:
widgets={'start_datetime':forms.SplitDateTimeWidget(time_format='h:i A')}

and the standard Python time inputs (suggested here):
widgets={'start_datetime':forms.SplitDateTimeWidget(time_format='%I:%M %p')}

As you could guess, start_datetime is a DateTimeField in my model:
start_datetime=models.DateTimeField('Start', default=datetime.now())

Nothing I do seems to get this to pass validation -- I keep getting errors in that field. Any suggestions? I've been searching now for 2 hours to no avail. I can get it to validate if I stick with 24-hour time or if I leave out the AM/PM part, but I'd rather be able to correctly interpret AM/PM.
Thanks
Comment: After a lot of researching, I realized time_format isn't what I want at all. time_format only specifies how the default form value will look -- NOT how the input data is parsed.
Answer: You could just override django.contrib.admin.widgets.AdminSplitDateTime
This is the code:
class CustomAdminSplitDateTime(AdminSplitDateTime):
def __init__(self, attrs=None):
    widgets = [AdminDateWidget, AdminTimeWidget(attrs=None, format='%I:%M %p')]
    forms.MultiWidget.__init__(self, widgets, attrs)

Now you can use it as follows:
class MyForm(forms.ModelForm):

  class Meta:
    model=MyModel
    exclude=()
    start_datetime= forms.DateField(
        widget=CustomAdminSplitDateTime()
    )
    end_datetime= forms.DateField(
        widget=CustomAdminSplitDateTime()
    )

Don't forget to add the time format to the supported formats in your settings file, e.g.:
TIME_INPUT_FORMATS = [
    '%I:%M %p',
    '%H:%M:%S',
    '%H:%M:%S.%f',
    '%H:%M'
]

Answer: Ultimately, after poking around a lot in the source for the SplitDateTimeWidget, I didn't see a way to pass input_time_formats into the widget. Perhaps there is a way (I don't understand the common lineage between fields and widgets well enough to say for sure one way or another), but I couldn't find it.
However, I was able to get it working by overriding the fields and using SplitDateTimeField in the ModelForm (original fields in model are DateTime type). I then needed to pass the DateTime from the SplitDateTimeField back to the original model, since the form field and the model field were unlinked since I overrode it.
class MyForm(forms.ModelForm):
  start_datetime=forms.SplitDateTimeField(input_time_formats=['%I:%M %p'])
  end_datetime=forms.SplitDateTimeField(input_time_formats=['%I:%M %p'])

  class Meta:
    model=MyModel
    exclude=('start_datetime','end_datetime')

  def clean(self):
    self.instance.start_datetime=self.cleaned_data.get('start_datetime')
    self.instance.end_datetime=self.cleaned_data.get('end_datetime')

Comment: does it mean that without the changes you've made the code here does not work ?


Decision Tree Overfitting - Reference Request

Question: Multiple papers and online texts start from the position that decision tree overfitting can be taken for granted.
I am not here to dispute this. However, the claim of decision tree overfitting is often uncited.
Therefore, I wondered if there was a central reference for this to justify this universal claim, or if it is broadly just taken for granted?
Any help with a citation would be appreciated.
Answer: I'm sure someone may have proven this somewhere, but it is obvious for either making a single tree bigger, bigger and bigger, or also for boosted decision trees (which you could re-represent as a single tree, of course) - that's both from a theoretical perspective and to any one that has ever used them.
Theoretically, decision trees obviously can approximate any function arbitrarily well through step functions. So, they can arbitrarily closely fit the data (up to the point where identical data points have different observed outcomes). If no two data points are exactly the same, they can basically (given sufficiently deep trees - or sufficiently many somewhat less deep trees in boosted decision trees) memorize the exact value for any data point (and this really happens in practice).
In practice, you routinely watch as overfitting happens, if you look at training loss and validation loss (e.g. in a cross-validation set-up) as you keep expanding the size of a single tree (or adding more trees in a gradient boosted decision tree setup). So, I'd guess any one who uses them in practice probably would just know that this is a fact of life (unless you set various regularization parameters - although one of the most important one tends to be the complexity of trees/number of trees).
Comment: Hi @Bjorn. Thanks for your time and response. I totally get what you're saying that it is somewhat self-evident. But, it was really the central reference I was looking for


ssh port forwarding with permament connection between remote and destination

Question: I know you can use ssh to forward a local or remote port to another destination and port. So for example let's say I have this command:
ssh -L *:8443:10.0.0.1:443 email@example.com

So this allow to open a listening socket on the machine where the command is issued (let's say that its ip is 10.0.0.3) on port 8443. When some client connect to 10.0.0.3:8443 the packets flow through the ssh channel established between 10.0.0.3 and 10.0.0.2 then the ssh server on 10.0.0.2 forward the packets to the destination which is in this case 10.0.0.1:443.
I'm wondering if the server 10.0.0.2 can makes a permanent connection to 10.0.0.1:443 so that the connection 10.0.0.2:xxxxx -> 10.0.0.1:443 is opened once and never dropped. All the traffic coming from the clients connecting to 10.0.0.3:8443 should use this permanent channel.
So basically I don't want that when a new client connect to 10.0.0.3:8443 a new channel 10.0.0.2:xxxxx -> 10.0.0.1:443 is established. This prevent me from reusing the same session and invalidate a the request sent by another client after the first one.
Answer: One cannot do this with SSH. And such a generic approach would not be a good idea in the first place anyway.
TCP is a byte stream and not a message protocol. This means if multiple clients send messages in parallel, then the messages might be mixed up. The resulting data might start with the beginning of msgA from client A, continue with parts from msgB from client B, the continue with another part from msgA etc.
Thus, instead of a generic approach one would actually need a mixer which understands the specific application protocol spoken and would make sure that the message syntax in the merged data stream is preserved, no matter how the clients send the messages.
Note that this would be different with UDP since UDP is message based. But your use case seems to be TCP.
Comment: @Bemipefe: In this case you would need some mixer which can merge HTTP traffic and keep it as proper HTTP. Maybe haproxy can do what you need - see the chapter *Keep-alive and server side connection pooling* in [this blog entry](https://www.haproxy.com/blog/http-keep-alive-pipelining-multiplexing-and-connection-pooling/).
Comment: Yes in my case the protocol is HTTP so TCP at the network level.


LTE broadcasr or eMBMS is a RESTFull service ?

Question: LTE Broadcast (eMBMS) enables a Single Frequency
Network (SFN) broadcast capability within LTE, so that the same content
can be sent to a large number of users at the same time, resulting in a
more efficient use of network resources than each user requesting the
same content and then having the content unicast to each user. eMBMS uses HTTP protocol , so wanted to know if it is a REStfull api?
Comment: [An architecture style](http://en.wikipedia.org/wiki/Representational_state_transfer) is not the same as a low-level protocol.  I'm not sure what it is you're asking here.
Comment: @okoto- eMBMS implements broadcasting feature using HTTP protocol(implementation), so wanted to know if it falls in the the category of Restfull api?
Answer: Simple answer is no - eMBMS is more than just an interface, as Makoto says, it is a set of specifications that make up a Mobile Multicast solution.
There is a good overview which should illustrate this here:

http://www.slideshare.net/zahidtg/lte-embms-technology-overview


Use node.js and ANSIcolor plugin in Jenkins

Question: I want to display colored output in jenkins which is produced by node.js
Both work separately, but not combined:
Node Script
My test script test.js:
console.log(require("chalk").red("Node Red"))

Calling the test script in the shell works:
node test.js => OK

Calling a colored shell script in jenkins works:
echo -e "\033[31mShell Red\033[0m" => OK

But calling the node script in jenkins does not display any colors:
node test.js => No Color, when executed in jenkins

Answer: For me it worked when putting
export FORCE_COLOR=1

at the top of my script.
See https://github.com/chalk/supports-color#info
Answer: The answer of Raphael pointed me in the right direction. Here my complete solution for a Jenkins Pipeline Script (Scripted Pipeline):
:
node {
    ansiColor('xterm') {
        withEnv(['FORCE_COLOR=3']) {
            ...
            sh "some-node-script-using-chalk.js"
            ...
        }
    }
}

If you are using the Declarative Pipeline see https://jenkins.io/doc/pipeline/tour/environment/ how to set environment variables in a Declarative Pipeline Script.
Answer: I just found the problem in my case :

In The Job Configuration
Look at the Bindings
Check the checkbox named "Color ANSI Console Output"

And it works (for  me...)


Factorial design name

Question: I was just wondering, as I have been using ordinary least squares regression a lot lately, could anyone explain why a factorial design called a "factorial" design?
What part of the calculation is factorial? The number of regressors doesn't seem to increase in a factorial manor... is this just a name?
Answer: Factorial in factorial design doesn't refer to the mathematical operation $n!$ during the analysis but instead is named for using factors (or categories) in the experiment. In R factors are represented as a vector of integers that are displayed with character values (e.g. some descriptive text). A factor usually comes with multiple levels. For example the factor Fertilizer can have 3 levels, such as QuickGrow, SuperGrow and InsaneYield.
From Wikipedia:

In statistics, a full factorial experiment is an experiment whose design consists of two or more factors, each with discrete possible values or "levels", and whose experimental units take on all possible combinations of these levels across all such factors.

The terms factor (in context of experimental design) as well as factorial design were first mentioned in print by Ronald Fisher (see Wikipedia entry here).

The term "factorial" may not have been used in print before 1935, when Fisher used it in his book The Design of Experiments.

So in order to figure out why Fisher chose the term factorial for factorial designs, we should grab a copy of the book. But I am guessing it has something do with multiplying factor levels in order to get to the total number of treatment combinations in an experiment. But I am not sure.
Comment: Incidentally as you add more factors, the number of combinations grow exponentially, like a factorial
Comment: Good point @qwr! The total number of treatment combinations in a factorial experiment can simply be calculated by multiplying the levels of each factor in the experiment, whereas the total number of pairwise comparisons is calculated as $\binom{n}{k}$, which is equivalent to $\frac{n!}{(n-k)!k!}$, i.e. combinations without repetition.
Comment: Hmm... thank you... I am still a little confused though - would these not also be called factors when used in any regression design? What makes the use of factors specific to a factorial design?
Comment: @JDoe2 by "any regression design" to you mean **continuous** predictor/independent variables? Those I would call covariates and not factors. Factors to me are discrete experimental manipulations (categories) for which I want to estimate and compare mean values (and not slopes).
Comment: @JDoe2 reading your comment again I should add, yes factors are also called factors in other designs (e.g. split-plot designs, repeated measures design, nested designs, etc.). Again, I think "factorial" refers to the fact that all treatment combinations are **equally** represented and factors are said to be crossed. The downside of factorial designs is, as mentioned before, that the treatment combinations grow exponentially, i.e. $n^k$, where $n$ is the number of levels and $k$ the number of factors (assuming the same number of levels across factors).

Factorial design name


Proof of vectorization of product of three matrices

Question: On Wikipedia, it is written that $$\mathrm{vec}(ABC) = (C^\top\otimes A)\mathrm{vec}(B)$$
I am trying to show that it is true, but couldn't succeed. $A$ is $m\times n$, $B$ is $n\times p$ and $C$ is $p\times q$ matrix.
My attempts
The $ij$th element of the matrix $ABC$ is
$$\sum_{k=1}^n\sum_{l=1}^pa_{ik}b_{kl}c_{lj}$$
Now, since $ABC$ is an $m\times q$ matrix, so if
$$i = am+b;\hspace{1cm}a\in\Bbb N,0<b<m$$
then the $i$th element of $\mathrm{vec}(ABC)$ is actually the element in the $b$th row and $a+1$th column in the matrix $ABC$ which can be found by the above double sum. But I don't know what to do for the RHS.
Please help
Answer: Here's an approach I like, which avoids getting bogged down in summation and the vectorization reindexing wherein the $i,j$ entry of an $m \times n$ matrix becomes the $[1 + i + m(j-1)]$th entry of a length $mn$ column-vector.
We first observe that the maps $B \mapsto \operatorname{vec}(ABC)$ and $B \mapsto (C^T \otimes A)\operatorname{vec}(B)$ are linear maps from $\Bbb R^{n \times p}$ to $\Bbb R^{mq}$.  In order to show that these maps are identical, it suffices to show that they agree on a basis.
One particularly nice basis of $\Bbb R^{n \times p} = \{E_{ij}: 1 \leq i \leq n, 1 \leq j \leq p\}$, where $E_{ij}$ denotes the matrix that has a $1$ as its $(i,j)$ entry and zeros everywhere else. We make two observations:

$E_{ij} = e_i^{(n)}{e_j^{(p)}}^T$ where $e_1^{(n)},\dots,e_n^{(n)}$ denotes the standard basis of $\Bbb R^n$,
$\operatorname{vec}(uv^T) = v \otimes u$ for any vectors $u,v$ (this in turn can be proven by first considering the case where $u,v$ are standard basis vectors), then making an argument by linearity.

We then have
$$
\begin{align*}
(C^T \otimes A)\operatorname{vec}(E_{ij}) &=
(C^T \otimes A)\operatorname{vec}(e_i^{(n)}[e_j^{(p)}]^T)
\\ &=
(C^T \otimes A)(e_j^{(p)} \otimes e_i^{(n)})
\\ & =
(C^Te_j^{(p)}) \otimes (Ae_i^{(n)}).
\end{align*}
$$
On the other hand,
$$
\operatorname{vec}(AE_{ij}C) = \operatorname{vec}(Ae_i^{(n)}[e_j^{(p)}]^TC)=
\operatorname{vec}([Ae_i^{(n)}][C^Te_j^{(p)}]^T) = (C^Te_j^{(p)}) \otimes (Ae_i^{(n)}).
$$
The conclusion follows.
Comment: That is quite some attitude you have for somebody asking for help.  You're welcome, by the way.
Comment: $E_{ij} = e_if_j$ where $e_i$ is standard basis vector for $\Bbb R^n$ and $f_j$ is that for $\Bbb R^p$. Similarly further arguments should change.
Comment: And it is $C^\top\otimes A$ and not $C^\top\otimes D$.
Comment: I am upvoting and accepting your answer, assuming that you will correct it.


Azure Bot gets stuck on login card after successful login using OAuth2 Generic Provider

Question: Starting from the following sample:
https://github.com/Microsoft/BotBuilder-Samples/tree/master/samples/csharp_dotnetcore/24.bot-authentication-msgraph
Replaced the authentication provider with an OAuth2 generic provider.
When clicking on the login button, the login windows pops up and user is able to authenticate successfully. However, when it gets back to main window, the "You are now logged in" response is not obtained.
When testing on the Azure portal, token is successfully obtained.
Kindly advise.
Thanks
Comment: When you say that the user is able to authenticate successfully in the login window, does it show the validation code? Also, there might be issues with the Emulator. What version of emulator are you using?
Comment: 4.2.1 --> Checked the "Use the sign in verification code for OAuthCards" as per your unedited comment, and now everything is working. May need to update documentation on https://learn.microsoft.com/en-us/azure/bot-service/bot-builder-authentication
Comment: Glad that it helped. If you look at the README.md for the [sample](https://github.com/microsoft/BotBuilder-Samples/tree/master/samples/csharp_dotnetcore/24.bot-authentication-msgraph#testing-the-bot-using-bot-framework-emulator), it specifies that you need to enable the option.
Comment: Found it. Thanks!
Answer: The bot-authentication-msgraph sample uses the bot authentication capabilities of Azure Bot Service, providing features to make it easier to develop a bot that authenticates users to various identity providers such as Azure AD (Azure Active Directory), GitHub, Uber, and so on. While testing the sample on the emulator, enable 'Use a sign-in verification code for OAuthCards' in the Bot Framework Emulator Settings and save, to receive the magic code.


What is the value of $\beth_{\omega_1}^{\aleph_0}$?

Question: It is well known that $\beth_\omega^{\aleph_0} = \beth_{\omega+1}$. This follows since for strong limit $\kappa$, we have $\kappa^\kappa = \kappa^{\mathrm{cf}(\kappa)}.$
Question. To the extent that ZFC can pin it down, what is the value of $\beth_{\omega_1}^{\aleph_0}$?
Clearly its between $\beth_{\omega_1}$ and $\beth_{\omega_1+1}$ (again using $\kappa^\kappa = \kappa^{\mathrm{cf}(\kappa)}$ for the upper bound), but that is all I have been able to puzzle out.
I've actually been thinking about this for a while. At first I was thinking that perhaps since $\aleph_0 < \mathrm{cf}(\beth_{\omega_1}),$ we can safely deduce $\beth_{\omega_1}^{\aleph_0} = \beth_{\omega_1}.$ That is, I thought it might be a general principle that if $\nu < \mathrm{cf}(\kappa)$, then $\kappa^\nu = \kappa.$ Hence this question. Unfortunately, however, the conjecture is false (see Asaf's answer in the link), and I cannot think of anything else to try.
Comment: The English phrase "It's all Greek to me" has as French counterpart "C'est de l'hébreu pour moi" which translated means "It's Hebrew to me". Exactly my feeling.
Comment: Any function from $\aleph_0$ to $\beth_{\omega_1}$ is bounded. That should get you started.
Comment: @Georges: And I can find someone from Israel for whom it's Chinese! :-)
Comment: By the way, user18921, indices are ordinals and not cardinals. So it's better to write $\beth_{\omega_1}^{\aleph_0}$.
Comment: About my answer that you refer to, note that it is *far far* below $\beth_{\omega_1}$.
Answer: Here's another way to see that $\beth^\omega_{\omega_1}\leq \beth_{\omega_1}$.
First, note that by a simple induction we can show that for uncountable ordinals $\alpha$, $\beth_\alpha = |V_\alpha|$. In particular $\beth_{\omega_1} = |V_{\omega_1}| $. So every function from $\omega$ to $\beth_{\omega_1}$ can be coded as a function from $\omega$ to $V_{\omega_1}$. Since any such function will be a subset of $V_{\omega_1}$ of size $\omega$, it will have to exist at some $V_\alpha$ for $\alpha<\omega_1$. Thus, $\beth^\omega_{\omega_1}\leq \beth_{\omega_1}$.
Answer: I think I got it.
Definition. Whenever $\kappa$ is a cardinal number, write $\mathcal{B}(\kappa)$ for the boundful powerset of $\kappa$ i.e. the set of all bounded subsets of $\kappa$.
Proposition. If $\kappa$ is a strong limit cardinal, then $|\mathcal{B}(\kappa)| = \kappa$.
We need to show that $|\mathcal{B}(\kappa)| \leq \kappa.$ Now I think it is a general principle that $|\mathcal{B}(\kappa)| = 2^{<\kappa}.$ But for strong limit $\kappa$, we have $2^{<\kappa} = \kappa.$ Hence the result follows.
Corollary. If $ν<\mathrm{cf}(\kappa)$ and $\kappa$ is a strong limit cardinal, then $κ^ν=κ$.
This follows since $κ^ν$ is the cardinality of $[\kappa]^\nu$ (the set of all subsets of $\kappa$ with cardinality precisely $\nu$). By hypothesis, every element of $[\kappa]^\nu$ is bounded, hence $[\kappa]^\nu \subseteq \mathcal{B}(\kappa).$
Corollary to that. $$\beth_{\omega_1}^{\aleph_0} = \beth_{\omega_1}$$


How do I log when CPU usage is over 40% per process

Question: I have a problem with my server. Once in a while the CPU spikes to 100% and the server crashes and then needs to be rebooted.
I've tried to go through my current logs but no luck.
I would like to log every time a process uses more then say 40% of my CPU.
I've read about a sar solution here:
sar -u 1 0

but that doesn't have a treshold for what to log.
Idealy this would be something that runs continously so that I can see after the next time the server crashes what actually caused the crash!
Specs:
Ubuntu 12.04 LTS
CPU: 1 Core(s) 2048MB
CPU Flags: advcpu,acpi,pae,virtblk,virtio

Answer: based on results from:

https://stackoverflow.com/questions/9229333/how-to-get-overall-cpu-usage-e-g-57-on-linux

The I would install mpstat program, from that Based on a few user suggestions:
mpstat | grep -A 5 "%idle" | tail -n 1 | awk -F " " '{print 100 -  $ 12}'a

This will give you total CPU usage, you could then use that as a safe threshold in a script to take action.
EDIT:
Example:
#!/bin/bash

while :

do PROC= ` mpstat | grep -A 5 "%idle" | tail -n 1 | awk -F " " '{print 100 -  $ 12}'a` if [$PROC > 55]; then    PS ua >> log.txt echo "---------" >> log.txt fi

Sleep 1 done

to gain a log.
Comment: @EEAA Thanks for the assist. Apparently I was a little loopy last night, on my drive to work i was just thinking I had some errors. Though you've made it better still than I would have.
Answer: I've had a lot of luck using monit for logging and alerting when server issues arise.
For example, you could specify the following in your config file to alert and log if a process exceeds 40% CPU usage:
if cpu is greater than 40% for 5 cycles then alert


Broken/missing handler error for my custom views filter?

Question: I am trying to write a custom filter for views. The goal is to filter by alias, but that's not important now. It seems like I am missing a step to get view to recognize my filter hander after adding my filter in hook_views_data_alter as in the following:
/**
 * Implements hook_views_data_alter().
 */
function alias_views_filter_views_data_alter(array &$data) {
  $data['node']['alias'] = [
    'title' => t('alias filter'),
    'filter' => [
      'title' => t('alias filter'),
      'help' => t('Provides a custom filter nodes by their alias.'),
      'field' => 'nid',
      'id' => 'entity_alias',
    ],
  ];
}

I am able to get the filter to show in a view filter list.
Now, my filter handler defined in /docroot/modules/custom/alias_views_filter/Plugin/views/filter/Alias.php but it does not seem to be picked up by views and I always get Broken/missing handler whenever I try to add the filter. Here is my handler definition:
<?php

namespace Drupal\alias_views_filter\Plugin\views\filter;

use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\Plugin\views\filter\StringFilter;
use Drupal\views\ViewExecutable;
use Drupal\Core\Form\FormStateInterface;

/**
 * Filters by alias.
 *
 * @ingroup views_filter_handlers
 *
 * @ViewsFilter("entity_alias")
 */
class Alias extends StringFilter {

  /**
   * The current display.
   *
   * @var string
   *   The current display of the view.
   */
  protected $currentDisplay;

  /**
   * @var views_plugin_query_default
   */
  public $query;

  /**
   * Constructs a new StringFilter object.
   *
   * @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\Database\Connection $connection
   *   The database connection.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, Connection $connection) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    // this does seem to get evaluated at all ?
    die('Death in handler');
  }

  protected function defineOptions() {
    $options = parent::defineOptions();
    $options['fields'] = ['default' => []];

    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);
    $this->valueTitle = t('Filter by alias');
  }

  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);
    $this->view->initStyle();
  }

  function query() {
    $this->ensureMyTable();
    $field = $this->tableAlias."nid"; //table_alias.".nid";
    $nids = $this->getNidsByAliasString($this->value);
    if (!empty($nids)) {
      $this->query->addWhere('AND', $this->options['group'], $field, $nids, 'IN');
    }
  }

  function getNidsByAliasString($aliasString) {
    $query = db_select('url_alias');
    $query->condition('alias', '%'.$aliasString.'%', 'LIKE');
    $result = $query
      ->fields('url_alias')
      ->execute();

    $nids = array();
    foreach ($result as $data) {
      array_push($nids, end(explode("/",$data->source)));
    }
    return $nids;
  }

}

Am missing a step or naming the filter incorrectly?
Checking the logs,  I am getting these errors:
Notice: Undefined index: field in Drupal\views\Plugin\ViewsHandlerManager->getHandler()
Notice: Undefined index: table in Drupal\views\Plugin\ViewsHandlerManager->getHandler()
Notice: Undefined index: id in Drupal\views\Plugin\ViewsHandlerManager->getHandler()

Comment: I believe this line is wrong: '$this->query->addWhere('AND', $this->options['group'], $field, $nids, 'IN');' as the addWhere only accepts 4 parameters, I see 5 parameters in there.
Answer: Specify the data table instead of the base table, just replace node with node_field_data in your hook and run drush cr.
/**
 * Implements hook_views_data_alter().
 */
function alias_views_filter_views_data_alter(array &$data) {
  $data['node_field_data']['alias'] = [
    'title' => t('alias filter'),
    'filter' => [
      'title' => t('alias filter'),
      'help' => t('Provides a custom filter nodes by their alias.'),
      'field' => 'nid',
      'id' => 'entity_alias',
    ],
  ];
}

Comment: I tried with both but it does not seem that's the issue. In fact initially wrote my question with `node_field_data` then edited it.


Como criar Header fixo sem javascript?

Question: Quero criar um header em uma pagina html, estilo responsivo que se adapte a plataforma mobile e a redução da pagina no browser, como faço?
Obs: Nada que li na internet no momento foi de utilizade, quero sem javascript.
Comment: Menu responsivo, que se adapte ao dispositivo em questão
Answer: Da pra fazer com css sim!
O básico:
HTML:
Menu

CSS:
header {
     position: fixed;
     top: 0;
     left: 0;
     width: 100%;
}

Exemplo do Básico apenas com umas customizações:

/* Header e Nav */

header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  background-color: #342e37;
  color: #fafffd;
  height: 50px;
}
header nav ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}
header nav ul li {
  float: left;
}
header nav ul li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}
header nav ul li a:hover {
  background-color: #111;
}
hr {
  margin-top: 80px;
}
p {
  text-align: justify;
}

Página inicial

Sobre

Contato

Lorem ipsum

  Lorem Ipsum é simplesmente uma simulação de texto da indústria tipográfica e de impressos, e vem sendo utilizado desde o século XVI, quando um impressor desconhecido pegou uma bandeja de tipos e os embaralhou para fazer um livro de modelos de tipos. Lorem
  Ipsum sobreviveu não só a cinco séculos, como também ao salto para a editoração eletrônica, permanecendo essencialmente inalterado. Se popularizou na década de 60, quando a Letraset lançou decalques contendo passagens de Lorem Ipsum, e mais recentemente
  quando passou a ser integrado a softwares de editoração eletrônica como Aldus PageMaker.

Lorem ipsum

  Lorem Ipsum é simplesmente uma simulação de texto da indústria tipográfica e de impressos, e vem sendo utilizado desde o século XVI, quando um impressor desconhecido pegou uma bandeja de tipos e os embaralhou para fazer um livro de modelos de tipos. Lorem
  Ipsum sobreviveu não só a cinco séculos, como também ao salto para a editoração eletrônica, permanecendo essencialmente inalterado. Se popularizou na década de 60, quando a Letraset lançou decalques contendo passagens de Lorem Ipsum, e mais recentemente
  quando passou a ser integrado a softwares de editoração eletrônica como Aldus PageMaker.

Lorem ipsum

  Lorem Ipsum é simplesmente uma simulação de texto da indústria tipográfica e de impressos, e vem sendo utilizado desde o século XVI, quando um impressor desconhecido pegou uma bandeja de tipos e os embaralhou para fazer um livro de modelos de tipos. Lorem
  Ipsum sobreviveu não só a cinco séculos, como também ao salto para a editoração eletrônica, permanecendo essencialmente inalterado. Se popularizou na década de 60, quando a Letraset lançou decalques contendo passagens de Lorem Ipsum, e mais recentemente
  quando passou a ser integrado a softwares de editoração eletrônica como Aldus PageMaker.

Lorem ipsum

  Lorem Ipsum é simplesmente uma simulação de texto da indústria tipográfica e de impressos, e vem sendo utilizado desde o século XVI, quando um impressor desconhecido pegou uma bandeja de tipos e os embaralhou para fazer um livro de modelos de tipos. Lorem
  Ipsum sobreviveu não só a cinco séculos, como também ao salto para a editoração eletrônica, permanecendo essencialmente inalterado. Se popularizou na década de 60, quando a Letraset lançou decalques contendo passagens de Lorem Ipsum, e mais recentemente
  quando passou a ser integrado a softwares de editoração eletrônica como Aldus PageMaker.

Lorem ipsum

  Lorem Ipsum é simplesmente uma simulação de texto da indústria tipográfica e de impressos, e vem sendo utilizado desde o século XVI, quando um impressor desconhecido pegou uma bandeja de tipos e os embaralhou para fazer um livro de modelos de tipos. Lorem
  Ipsum sobreviveu não só a cinco séculos, como também ao salto para a editoração eletrônica, permanecendo essencialmente inalterado. Se popularizou na década de 60, quando a Letraset lançou decalques contendo passagens de Lorem Ipsum, e mais recentemente
  quando passou a ser integrado a softwares de editoração eletrônica como Aldus PageMaker.

Lorem ipsum

  Lorem Ipsum é simplesmente uma simulação de texto da indústria tipográfica e de impressos, e vem sendo utilizado desde o século XVI, quando um impressor desconhecido pegou uma bandeja de tipos e os embaralhou para fazer um livro de modelos de tipos. Lorem
  Ipsum sobreviveu não só a cinco séculos, como também ao salto para a editoração eletrônica, permanecendo essencialmente inalterado. Se popularizou na década de 60, quando a Letraset lançou decalques contendo passagens de Lorem Ipsum, e mais recentemente
  quando passou a ser integrado a softwares de editoração eletrônica como Aldus PageMaker.

Você pode criar o seu menu no header e utilizar media query para adapta-lo de acordo com a resolução.
Referencia: http://bradfrost.com/blog/mobile/fixed-position/
Comment: Mas esse não usa Java Script ? preciso de algo que não use, mas muito bom essa fonte
Comment: @Azevedo  Analise o código da resposta e as referencias, como exposto pela resposta é apenas css!
Answer: Podes usar a propriedade width e height em css:
header{
  width: 100vw;
  height: 100vh;
}

Mas se realmente quiseres ter um website que seja responsive à diferentes telas, usa media query (muito fácil):
/*-----------RESPONSIVE FOR THE IPHONE SCREEN-------------*/

@media only screen and (max-width:760px){

/*****************************************
         MUDAR PROPRIEDADES DE H1 NA TELA DE IPHONE
*****************************************/
    h1{
        font-size: 250%;
        word-spacing: 0px;
        letter-spacing: -2px;
        margin-bottom: 20px;
        width: 98%;
        margin-left: 1%;

    }
}

Comment: Bem visto, corrigo!
Comment: Não entendi o que sua resposta tem a ver com a pergunta. [**seu código**](https://jsfiddle.net/skcf7usw/) não deveria propor uma solução para fixar o `` de forma responsiva? E essa regra de *media query* é para todos os dispositivos, não faz sentido os comentários de "iphone".
Comment: O iPhone foi só um exemplo. Sabendo o número de pixels (width) de cada dispositivo, pode ser usada a mesma regra (com os pixels certos, claro) para o determinado dispositivo.

Como criar Header fixo sem javascript?


Essential reads for people interested in Actuary and Actuarial science

Question: My girlfriend (B.B.A) is really interested in Actuarial science. She's looking at self teaching her self. She's good with basic math (Calculus 1 and 2) and stats
What are some of the essential sources she needs to read in order to learn and excel in the field?
Comment: Converted to community wiki.
Answer: And for bedtime reading, "Against the Gods: The Remarkable Story of Risk" by Peter L. Bernstein. She'll find out how Lloyds of London started, among many other interesting bits. Highly recommended and only $13 from amazon.
Answer: sources:
1) statistics upto ANOVA
2) probability upto Central limit theorem
3) Basic programming and data analysis skills
4) Familiarity with business economics
5) Financial mathematics
This is a verrry basic smattering of things that she needs to read.


Having a static variable called as argument

Question: I would like to implement a structure which contains a defined color issued from System.Drawing.Color. Here is my final code.
namespace ColorSystem
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

    }

    internal void testfunc(Label lbl, System.Drawing.Color newcolor)
    {
        lbl.BackColor = newcolor;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        var getvalue = ColorValues.NormalFont;
        testfunc(label1, ColorValues.NormalFont);
        testfunc(label2, ColorValues.NormalFont2);
    }

}
public static class ColorValues
{
    // Private variable to hold font once instantiated
    public static System.Drawing.Color NormalFont{ get{ return Color.AliceBlue;}}//Dynamic
    public static System.Drawing.Color NormalFont2 =         Color.AliceBlue;//static ??
}

What I still don't get is what the difference between those two lines:
 public static System.Drawing.Color NormalFont{ get{ return        Color.AliceBlue;}}//Dynamic
 public static System.Drawing.Color NormalFont2 =         Color.AliceBlue;//static ??

When I look with the mouse I see that.

What is the difference between the cube and the hand? Hand is the (get) so is it dynamic? and the cube is a data in memory... ??
Thanks a lot folks!
Comment: It should work, what exception do you get?
Comment: A word on struct vs class: https://msdn.microsoft.com/en-us/library/ms229017(v=vs.110).aspx
Comment: So reading this article it means that it's better for the memory to have a reference type (class) than a variable type (struct).... thanks.
Answer: Your first example works, but then you say you want make your method take your struct ColorValue as parameter, sure you can do it, but you can't fill BackColor of Label with your struct, because it is of different type and as you guess you would have to pass instance of your struct as you did in your last example.
So either go with your first example, or with your last, but you have to create instances of your struct.
Regarding memory, if you created 1000 instances of Form1 you would make 1000 instances of ColorValue, but if your struct ColorValue will stay as it is, it is only 1 byte. Generally memory is not an issue.
Edit:
What is the difference between the following?
public static System.Drawing.Color NormalFont{ get{ return        Color.AliceBlue;}}//Dynamic
public static System.Drawing.Color NormalFont2 =         Color.AliceBlue;//static ??

First one is a property, while the second is a field. Properties have set and get methods, so difference is that trying to get value of property will call get method which will return what you want, while field is direct reference to what you want. It is generally advised to expose only properties and hide fields, reason being, that you cannot (or cannot easily) debug/monitor access to fields, while it is easy to debug access to properties.
Answer: Your testfunc should look like this:
internal void testfunc(Label lbl, ColorValue newcolor)
{
    lbl.BackColor = newcolor.NormalFont;
}

How are you passing in your struct? It should be like so:
ColorValue colorstruct;
testfunc(somelabel, colorstruct);

Also, consider changing the name of NormalFont since its not really a font but a color.
Answer: I would use a static class, and have some read-only properties. Only instantiate the colors when they are used, so your class will start out with all nulls (no memory allocated), then as you read/get each property, it will instantiate based on the System.Drawing.Color
public static class ColorValues
{
    // Private variable to hold font once instantiated
    private static System.Drawing.Color _normalFont;
    public static System.Drawing.Color NormalFont
    {
        get
        {
            // Only instantiate when needed
            if (_normalFont == null)
            {
                _normalFont = Color.AliceBlue;
            }
            return _normalFont;
        }
    }
}

Then you can use in your form like:
   private void button1_Click(object sender, EventArgs e)
   {
       testfunc(label1, ColorValues.NormalFont);
   }

I tried this
  public partial class Form1 : Form
  {
    public Form1()
    {
        InitializeComponent();
    }

    internal void testfunc(Label lbl, ColorValues newcolor)
    {
        lbl.BackColor = newcolor;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        testfunc(label1, ColorValues.NormalFont);
    }

}
public static class ColorValues
{
    // Private variable to hold font once instantiated
    public static System.Drawing.Color NormalFont{ get{ return Color.AliceBlue;}}
}
/*  public struct ColorValue
{
    public static System.Drawing.Color NormalFont = Color.AliceBlue;
}*/

Comment: but if my class Color contains 1000 definitions would it good to put a get for each?? Thanks
Comment: Yes. Remember your ColorValues class will not use any memory until each color is instantiated. Even better might be to just put the get { return Color.AliceBlue } and not even keep a reference to it in a local variable. That way you are basically just "wrapping" a bunch of colors using your own labels. This is basically a theme class.


how to prove that the volume of unit hypersphere is max when dimension is 5?

Question: Given the volume formula of unit hypersphere
$V\left(n\right) = \left(2/d\right)\left[\pi^{d/2}\,/\,\Gamma\left(d/2\right)\right]$:

How do one prove that the max volume occurs when $d = 5\, ?$.
I try the ratio $V\left(n\right)/V\left(n - 1\right)$ and see when this is smaller than $1$ but ends up with something like
$\Gamma\left(d - 1/2\right)/\Gamma\left(d/2\right)$ which I am not sure how to deal with.
Answer: It may be easier to work with the ratio
$$ \frac{V(n)}{V(n-2)} = \frac{2\pi}{n}. $$
Using this ratio you cannot compare an odd dimension hypersphere with an even-dimension hypersphere, but you can find the largest odd-dimension hypersphere and the largest even-dimension hypersphere.
Then you just need to find the sizes of those two hyperspheres (working your way upward from low dimensions whose "volumes" you know)
to determine that the odd-dimensioned one (dimension $n=5$)
is larger than the even-dimensioned one
and therefore is the largest over all dimensions.


How to programmatically print all comments from a given node?

Question: I need to print comments belonging to a given node. So basically, get a node id then choose all the comments from a given node and print them. I know that I can print one comment (for example with id=12) using the following code:
<?php
$comment = _comment_load(12);
return theme('comment',$comment);
?>

Can anyone tell me how to do this?
Answer: If you are looking for a ready to use function, take a look at comment_render().
Example use (say the node you want comments for has nid = 5):
<?php
  $node = node_load(5);
 print comment_render($node);
?>

Or else you can manually query the database (comments table) to get all comments that have a matching nid.
<?php
  $nid = 5;
  db_query('SELECT * FROM {comments} WHERE nid = %d', $nid);
?>

Comment: not a drupal 7 valid, for information
Answer: If you like to load the complete comment objects you can use this:
$result = db_select('comment')
  ->fields('comment', array('cid'))
  ->condition('nid', $node->nid, '=')
  ->execute();

$cids = $result->fetchCol();
$comments=comment_load_multiple($cids);

foreach($comments as $comment) {
  //do some stuff with the comment
  print $comment->comment_body ["und"][0] ["value"];
}

Comment: Please use the formatting options as explained above the answer form. It makes your answer better readable and thus provides for a better exchange of information.
Answer: In Drupal 7 and onwards comment_render has been removed. Instead, you can load comments like this.
$result = db_select('comment')
                  ->fields('comment', array('name','subject'))
                  ->condition('nid', $node->nid, '=')
                  ->execute()
                  ->fetchAssoc();
foreach($result as $comment) {
   print $comment;
 }


Java Swing JLabel setText doesn't work

Question: I want to update JLabel with setText() method, but when I update it, text shows like this:
Comment: Er, what layout manager are you using? Could you show us the code for your GUI?
Answer: This is caused by not having a layout manager and not setting the location of the labels. By not setting any location for the labels they have defaulted 0 (x) and 0 (y), there for they are on top of one another. To set the location of a label do label.setlocation(x, y); and to set a layout manager do frame.setLayout(Type layout manager here);

Java Swing JLabel setText doesn't work


SQL query for count employee gender

Question: The question is: For each publisher list the publisher name and the number of male and the number of female employees employed by the publisher. The SQL statement should display the result in the following format:
Publishername    Male    Female
Academic            4   0
Ace Books           4   3
Oxford Press        0   4

The employee table to take info from is:
EMPNO LNAME                GENDER PUBLISHERNAME        SUPEREMPNO
----- -------------------- ------ -------------------- ----------
E1    Black                M      Pearson
E2    Clark                M      Pearson              E1
E3    Bean                 M      Pearson              E1
E4    Cassidy              M      Pearson              E1
E5    Smith                F      Elsevier
E6    Jones                F      Elsevier             E3
E7    Smith                F      Elsevier             E3
E8    West                 F      Elsevier             E3
E9    Smith                M      Planeta
E10   Love                 M      Planeta              E5
E11   Fish                 M      Planeta              E5
E12   Wood                 M      Planeta              E5
E13   Thorpe               F      Planeta              E5
E14   Gibson               M      Wiley
E15   Bergin               M      Wiley                E8
E16   Love                 F      Wiley                E8
E17   Owen                 F      Wiley                E8
E18   Haddock              F      Wiley                E8

18 rows selected.

Thanks
Comment: What's your code at this point?
Comment: What if the publisher employs non-gender-binary workers? You're going to need a better table schema to represent this. #no-SexQL
Answer: This is a simple conditional aggregate:
select publishername,
       count(case when gender = 'M' then 1 end) as Male,
       count(case when gender = 'F' then 1 end) as Female
from employee
group by publishername
order by publishername;

Comment: Does the `count (case ...)` work on anything different of Microsoft SQL Server?
Comment: @sergiol: that is most basic standard SQL. And (SQL based) database where that does *not* work is seriously broken.

SQL query for count employee gender


Docker doesn't connect under proxy

Question: My configuration is: Win 10 Pro; Virtual Box 6.0; in Virtual Box, Linux Mint Cinnamon 19.2; and in Linux I have Docker 19.03.5.
From my home connection all works fine and also Docker; I can, i.e., make a "search" without problems. At my work I have a proxy and proxy is well configured  (Internet is available and also the browser works fine); for Docker proxy configuration, I have done exactly what is described in this official page https://docs.docker.com/network/proxy/ but Docker doesn't work. If I try a sudo docker search, I see a message:
Error response from daemon: Get https://index.docker.io/v1/search?q=mysql&n=25: dial tcp 188.8.131.52:443: i/o timeout

How can I fix the problem?
Edit
This is another response, if I try to run something:
user@User-VirtualBox-Mint:/$ sudo docker run hello-world
[sudo] password for user:
Unable to find image 'hello-world:latest' locally
docker: Error response from daemon: Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers).
See 'docker run --help'.

Comment: I hope yes, I read very carefully the rules and also "software tools common used by programmers" are under permitted discussion. And docker is for sure one of this. Have you a solution for my post? Thank you very much for your reply.
Comment: Did you set the environment variables for proxy inside the containers?
Comment: Thank you very much 7_R, no, because the problem is not related to a particular image or container or --env variable but simply to a connection. In other cases, almost a search command would be correctly works. So, at this point, my problem is simply see correctly a search list. Thanks.
Comment: Do you have proxy credentials? If yes, did you put them in the docker config file?
Comment: Absolutely yes, already inserted and checked several time. Identical to other proxy config which I wrote in Linux network setting, which perfectly work and allow me to normally navigate.
Comment: Can you *show us* your Docker configuration (e.g. `/etc/docker/daemon.json`) in your question? Otherwise it's hard for us to tell what your environment looks like.
Comment: Sure. In my folder /etc/docker I haven't any daemon.config file; I have only the key.json (but is not related to the problem, I suppose, there are only key). Where can I found the info you need? Tell me and I will send you in a second (Tip: a colleague with a older Docker version has this file, so I think that the presence of this file is related to the version; mine is 19.03.05).
Comment: Problem solved, I reply the solution.
Answer: Solution: the solution is in this forum
https://docs.docker.com/config/daemon/systemd/
I created a new folder /etc/systemd/system/docker.service.d and in this folder I created the file http-proxy.config. In this file I wrote the following line. Reload demon, restart docker and all works fine.
[Service]
Environment="HTTP_PROXY=http://127.0.0.1:my_port/"
Environment="HTTPS_PROXY=http://127.0.0.1:my_port/"

Docker doesn't connect under proxy


Get the mocha "end" event from gulp

Question: I'm using gulp-mocha with gulp and I'm trying to get a notification when the mocha tests get completed.
This is my gulpfile.js
var gulp = require('gulp');
var mocha = require('gulp-mocha');
var notify = require("gulp-notify");

gulp.task('test', function () {
  return gulp.src(['test/**/*.js'], { read: false })
    .pipe( mocha({ reporter: 'nyan' }))
    .on("error", notify.onError({
      message: 'Error: <%= error.message %>'
    }))
    .on('end', function () {
      notify( "Tests passed" )
    });
});

gulp.task('watch-test', function () {
  gulp.watch(['./**'], ['test']);
});

gulp.task( 'default', [ 'test', 'watch-test'] );

I managed to see the notification on the "error" event, but I couldn't find a way to get the "end" event.
Any idea about how to get it?
Comment: I'm having a similar issue... Did you ever find a solution?
Comment: nope @AdrianE, unfortunately i didn't
Answer: gulp-notify works with streams (i.e. pipe(notify...), use node-notifier.
I'm doing it like this:
let gulp     = require('gulp');
let gulpeach = require('gulp-foreach');
let mocha    = require('gulp-mocha');
let notifier = require('node-notifier');

// Run tests.
gulp.task('test', function () {
  gulp.src(['test/test-*.js'])
    .pipe(gulpeach(function (stream, file) {
      return stream
        .pipe(mocha())
        .on('error', (error) => {
          notifier.notify({
            message: ('Command: ' + error.cmd),
          })
        })
      ;
    }))
    .on('finish', () => notifier.notify('Tests completed'))
  ;
});

Get the mocha "end" event from gulp


Como fazer para trazer tabela com dados ao retornar de um insert

Question: Editei a pergunta do post pois considero ser a solução mais lógica para a questão.
Tenho uma páginas com 3 tabs e em uma dessas faço um upload de arquivos para a minha hospedagem e envio as informações necessárias ao banco de dados, monto uma tabela html com os registros que acabei de cadastrar para exibir ao usuário mas a página não é atualizada, gostaria de poder ao cadastrar voltar a página mostrar uma tabela com os dados cadastrados, sempre sendo atualizada a cada nova inserção e se possível na aba de origem do cadastro, não consegui encontrar nem exemplo que pudesse me ajudar.
Algo parecido com esse post:
https://stackoverflow.com/questions/16707648/using-jquery-ajax-to-retrieve-data-from-mysql
O que tenho é isso no retorno do upload:

header('Content-Type: application/json');
echo json_encode($aretorno);

E nome da TAB é:

Script que envio o Upload e seu retorno:
    // INICIA O UPLOADO DO ARQUIVO
$(document).ready(function() {

    function getDoc(frame) {
        var doc = null;

        // IE8 cascading access check
        try {
            if (frame.contentWindow) {
                doc = frame.contentWindow.document;
            }
        } catch (err) {}

        if (doc) { // successful getting content
            return doc;
        }

        try { // simply checking may throw in ie8 under ssl or mismatched protocol
            doc = frame.contentDocument ? frame.contentDocument : frame.document;
        } catch (err) {
            // last attempt
            doc = frame.document;
        }
        return doc;
    }

    $("#multiform").submit(function(e) {
        $("#multi-msg").html('');

        var formObj = $(this);
        var formURL = formObj.attr("action");

        if (window.FormData !== undefined) // for HTML5 browsers
        //  if(false)
        {

            var formData = new FormData(this);
            $.ajax({
                url: formURL,
                type: 'POST',
                data: formData,
                mimeType: "multipart/form-data",
                contentType: false,
                cache: false,
                processData: false,
                success: function(data, textStatus, jqXHR) {
                    $("#multi-msg").html('
' + data + '
');
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    $("#multi-msg").html('
AJAX Request Failed
 textStatus=' + textStatus + ', errorThrown=' + errorThrown + '
');
                }
            });
            e.preventDefault();
            e.unbind();
        } else //for olden browsers
        {
            //generate a random id
            var iframeId = 'unique' + (new Date().getTime());

            //create an empty iframe
            var iframe = $('');

            //hide it
            iframe.hide();

            //set form target to iframe
            formObj.attr('target', iframeId);

            //Add iframe to body
            iframe.appendTo('body');
            iframe.load(function(e) {
                var doc = getDoc(iframe[0]);
                var docRoot = doc.body ? doc.body : doc.documentElement;
                var data = docRoot.innerHTML;
                $("#multi-msg").html('
' + data + '
');
            });
        }
    });
    $("#multi-post").click(function() {

        $("#multiform").submit();
    });
});

PHP que insere dados no BD:

require_once("../_connections/pcon.php");
require_once("../_comp/internos/funcoes.php");

//Array que irá retornar o status da execução do script (JSON)
$aretorno = array();
$aretorno["msg"] = "";
$aretorno["status"] = "";

@$conn = new mysqli($hostname_pcon, $username_pcon, $password_pcon, $database_pcon);

// Checar conexão
if ($conn->connect_errno) {
    $aretorno["msg"] = "Conexão ao banco de dados falhou.";
    $aretorno["status"] = "ERRO";
    header('Content-Type: application/json');
    echo json_encode($aretorno);
    exit;
}

if (!$conn->set_charset("utf8")) {
    $aretorno = array();
    $aretorno = "Erro ao carregar conjunto de caracteres utf8.";
    header('Content-Type: application/json');
    echo json_encode($aretorno);
    exit;
}

// RESGATE DAS VARIÁVEIS
$IdContrato = $_POST["IdContrato"];
$Observacao = $_POST["Observacao"];
$DataHora = date('Y-m-d H:i:s');

// REGISTRO DO LOG
$dataAgora = date('d/m/Y');
$hora = date("H:i:s");
$partes = explode("/", $dataAgora);
$dia = $partes[0];
$mes = $partes[1];
$ano = $partes[2];

// DIRETÓRIO
$diretorio = 'upload/';

if (!empty($_FILES)) {
    $ArquivoTemporario = $_FILES['arquivo']['tmp_name'];
    $NomeArquivo = $_FILES['arquivo']['name'];
    $CaminhoAnexo = dirname(__FILE__) . '/' . $diretorio;
    $targetFile = rtrim($CaminhoAnexo,'/') . '/' . $_FILES['arquivo']['name'];
    $TipoArquivo = strtolower(pathinfo($NomeArquivo, PATHINFO_EXTENSION));

    $Caminho = $diretorio;

    // Validate the file type
    $fileTypes = array('jpg','jpeg','gif','png','pdf','doc','docx','xls','xlsx'); // File extensions
    $fileParts = pathinfo($_FILES['arquivo']['name']);

    if (in_array($fileParts['extension'],$fileTypes)) {
        move_uploaded_file($ArquivoTemporario,$targetFile);
    } else {
        echo 'Tipo de Arquivo invalido';
        exit;
    }
}

// COMPONDO O LOG
$Log = $_SESSION['u_login']."_".$dia.$mes.$ano."_".$hora;
$Usuario = 'Valter';

$sql = "INSERT INTO gerDoctoContrato ( IdContrato, NomeArquivo, TipoArquivo, CaminhoAnexo, Usuario, DataHora, Observacao, Log ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?)";

// Preparar os dados:
// i corresponde a uma variável de tipo inteiro
// d corresponde a uma variável de tipo double
// s corresponde a uma variável de tipo string
// b scorresponde a uma variável que contém dados para um blob e enviará em pacotes

if($stmt = $conn->prepare($sql) ){

    $stmt->bind_param(
        "ssssssss",

    // RESGATE DAS VARIÁVEIS
    $IdContrato,
    $NomeArquivo,
    $TipoArquivo,
    $Caminho,
    $Usuario,
    $DataHora,
    $Observacao,
    $Log
    );

    // DESLIGA O AUTO COMMIT
    // $conn->autocommit(false);

    // INSERINDO REGISTRO NO BD
    if ($stmt->execute()) {
        $aretorno["msg"] = "Registro inserido com sucesso.";
    } else {
        $aretorno["msg"] = "Ocorreu um erro na inclusão dos dados:". $stmt->error ." Verifique";
        $aretorno["status"] = "ERRO";
    }

} else {
    $aretorno["msg"] = "Ocorreu um erro na preparação dos dados: "  . $stmt->error . ". Verifique.";
    $aretorno["status"] = "ERRO";
}

// FECHA CONEXÃO COM BD
$conn->close();

//retornando o status / mensagem da execução
header('Content-Type: application/json');
echo json_encode($aretorno);

Não sei exatamente o que postar para exemplificar o que já tenho.
Answer: Tente alguma coisa assim, no data, tente dar um parse:
var saida = jQuery.parseJSON(data);
Pega a saída do status, e faz uma consulta no banco trazendo os dados num array, neste array traz a coleção via JSON e retorna ela montando a tabela:
function getLines(saida) {
    var html ='';
    for (var i in saida.collection) {
                html += "
" +
                          "" + saida.collection[i].idContrato + "	" +
                          "" + saida.collection[i].NomeArquivo + "	" +
                          "" + saida.collection[i].tipoArquivo + "	" +
                          "" + saida.collection[i].DataHora + "	" +
                        "
";
    }
 return html;
}

function getHeader() {
    var html = "
" +
                 "ID	" +
                 "Arquivo	" +
                 "Tipo	" +
                 "Período	" +
                "
";
 return html;
}

function getTable(saida) {
    if (saida.status == 1) {
        var tabela = ["
",
                      getHeader(),
                      getLines(saida),
                     "
"].join("");
       $('#panel-2').html(tabela);
    }
}

$.ajax({
         url: formURL,
         type: 'POST',
         data: formData,
         mimeType: "multipart/form-data",
         contentType: false,
         cache: false,
         processData: false,
         success: function(data, textStatus, jqXHR) {
                  $("#multi-msg").html('
' + data + '
');
                  //console.log(data);
                  getTable(jQuery.parseJSON(data));
                  },
         error: function(jqXHR, textStatus, errorThrown) {
                    $("#multi-msg").html('
' +
                                         'AJAX Request Failed' +
                                         '
 textStatus=' +
                                         textStatus +
                                         ', errorThrown=' +
                                            errorThrown +
                                         '
');
                }
});

No PHP, você trás os dados da consulta como no exemplo abaixo:
$sql = "SELECT * FROM gerDoctoContrato where 1 order by Tipo Arquivo ASC, DataHora DESC, NomeArquivo ASC";
$result = mysqli_query($conn, $sql);
$data = $stmt->fetch_all($result, MYSQLI_ASSOC);
    if ($stmt->execute()) {
        $aretorno["msg"] = "Registro inserido com sucesso.";
        $aretorno["status"] = "1";
        $aretorno["collection"] = $data;
    } else {
        $aretorno["msg"] = "Ocorreu um erro na inclusão dos dados:". $stmt->error ." Verifique";
        $aretorno["status"] = "ERRO";
        $aretorno["collection"] = null;
    }


Increasing Convex Function Increasing Second Derivative?

Question: Let $f(x)$ be increasing and convex on a certain interval. Then, $f''(x)\geq 0$ on this interval. I was wondering if it could be further said that $f''(x)$ is increasing (or at least non-decreasing) on this interval.
Comment: Constant functions are convex.
Comment: What if $f$ is convex and strictly increasing?
Comment: @CyclotomicField the question asks about an increasing function.
Comment: @RadialArmSaw linear functions are also convex and can be strictly increasing.
Comment: In either case, wouldn't the second derivative still be non-decreasing?
Comment: Yes, they would be non-decreasing in the constant and linear cases as the second derivative is always zero. I mention them only to encourage you to check trivial cases since they often provide counter examples.
Comment: Thank you for your help. I just pointed it out as the linear examples don't provide a counter-example for saying the second derivative is non-decreasing.
Comment: @CyclotomicField Yes.  But I was addressing someone who mentioned constant functions, because the question doesn't ask about constant functions. The question asks about strictly increasing functions.
Answer: No it can not be said. The second derivative gives you strength of the curvature but since a convex function can have decrasing curvature too the answer is no.
Imagine x^2 beeing cutoff at 1 and then continuoued with constant increase. Then f''(x) = 0 for x >1
Comment: Thank you for your comment. Could it be said differently if $f$ had no sharp turns on the interval?
Comment: @bryanjaeho yes
Comment: whats wront with my answer? Did i miss something?


Some module is adding info below 'Nice Menus'

Question: I believe some module is somehow hooking into nice menus and adding a div of content below the menu. However I can't for the life of me find out which one.
Here's what I know:
There is a content type called 'nice_menu_addition'. When creating an item of that content type you chose which menu item you would like it placed beneath, and it shows up there. However, I can't find ANY modules anywhere, or any theme info that shows where this is being done. Any suggestions as to where to look?
Answer: suggestion from average drupal guy.... try using the module_implements() with watchdog method to check the available hooks from nice menu or menu docs that can cause the change and track the module...hope it helps you in some way
Comment: Agreed, that's a great option. Also, would it be worth doing a global search of codebase for 'nice_menu_addition'?
Comment: Thanks you guys, that was a good suggestion, but it actually ended up being a view that was attaching itself to the menu. That's why I couldn't find anything in any of the modules. I'm checking this though since it was the best suggestion.
Answer: Would Theme Developer give you the module function that was generating the spurious info?


Multivariable Limit Question-Arctan and ln

Question: Can someone help me calculate :
$$\lim _{(x,y)\to (1,2)} \frac {\arctan(x+y-3)}{\ln(x+y-2)}?$$
I think substituting $x+y = t $ might help, but I am not sure that doing such a substitution in a multivariable case is legitimate, and I prefer not doing this.
Can you help me?
Thanks !
Comment: l'Hôpital's rule?
Answer: $$\lim\limits_{(x,y)\to (1,2)} \frac {\arctan(x+y-3)}{\ln(x+y-2)}=\lim\limits_{(x,y)\to (1,2)} \frac {\arctan((x-1)+(y-2))}{\ln((x-1)+(y-2))}=\\
=\left|\matrix{u=x-1\\
v=y-2} \right|=\lim\limits_{(u,\,v)\to (0,0)} \frac {\arctan(u+v)}{\ln(1+u+v)}=1$$
since both numerator and denominator depends only on sum $u+v.$
Answer: It is better to take $t=(x-1)+(y-2)$. Then we obtain
$$
\lim_{t\to 0}\frac{\arctan{t}}{\ln(1+t)}=1.
$$


Get time signatures to show up in a ChordNames context

Question: I'm working off the "adding bar lines to chord names context" example, but have variable time signatures in my piece.  I'd like those to show up as numeric time signatures in the same line as the chord names.  How can I get the time signature to show up?
This minimal example:

\version "2.18.2"

\new ChordNames \with {
   \override BarLine.bar-extent = #'(-2 . 2)
   \consists "Bar_engraver"
}

\chordmode {
   \time 4/4 f1:maj7
   \time 2/4 f2:7
   \time 4/4 bes1:7
}

gets the bar lines in the right places but does not display the time signature in any form.
Answer: Add the time signature engraver using \consists, and (optionally) set the context to use numeric time signatures:

    \version "2.18.2"

    \new ChordNames \with {
        \override BarLine.bar-extent = #'(-2 . 2)
        \consists "Bar_engraver"
        \consists "Time_signature_engraver"
        \numericTimeSignature
    }


SSH Tunnel Inside SSL

Question: Someone can explain me which tools and how i have to use to setup SSH tunnel encapsulated in SSL on both server and client sides?
Thanks in advance.
Comment: Better still, why would you want to?
Answer: Stunnel seems to do what you are waiting for : http://www.stunnel.org/?page=docs
It creates some SSL tunnel, and you can put any protocol you want : HTTP, POP, IMAP, SSH etc..
Hope it helps

SSH Tunnel Inside SSL


Simplification of the derivative

Question:  I have this equation $y=x^{5x^3}$ by doing a log transformation we get, $log (y) = 5x^3 log (x)$ upon doing a differentiation w.r.t $(x)$, we get
$$\frac{1}{y}\frac{dy}{dx} = 5x^3.\frac{1}{x} + log(x) . 15x^2 =>\frac{dy}{dx} = x^{5x^3}(5x^3.\frac{1}{x} + log(x) . 15x^2)$$
upon simplification we get $$\frac{dy}{dx}=5x^{5x^3+2}(1+3 log (x))$$
but the result says $$\frac{dy}{dx}=5x^{5x^3+2}.log (e^ {x^3})$$
Can you please tell me how do I simplify the whole equation to get the result
Thanks,
Kamal.
Answer: Your result is perfectly correct and the last is totally wrong. It could be $\log(e x^3)$ obtained from your since $$1+3\log(x)=\log(e)+\log(x^3)=\log(e x^3)$$ but $\log(e^{x^3})$ is perfectly wrong.
May be another typo in the book.
Comment: Yes. For most people (I think) $\log$ stands for $\ln$. For any other base $a$, inclusing $10$, most people use to write $\log_a$
Comment: Is log same as ln? ln(e) =1 but log(e), so just want to know  how is this done?
Comment: You are very welcome !

Simplification of the derivative