How to detect what's blocking my incoming traffic on Ubuntu 14.04 LTS, if it's NOT iptables and NOT EC2 Security Group?

Question: I have SSH root access to an EC2 instance.
It's Ubuntu 14.04 LTS.
I have nginx web server listening on all interfaces on port 80 TCP. It's accessible from this server but not from the outside.
Apparently all of my incoming traffic except 22 TCP is blocked - other TCP ports, all UDP and ICMP.
Yet my iptables on this server are empty:
root@ip-x-x-x-x:~# iptables -v -L
Chain INPUT (policy ACCEPT 3162 packets, 1472K bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 4203 packets, 674K bytes)
 pkts bytes target     prot opt in     out     source               destination

Here's the nmap scan output from my local machine:
grzegorz@MacBook-Pro-Grzegorz:~$ sudo nmap -v -Pn -p 22,80 x.x.x.x

Starting Nmap 6.47 ( http://nmap.org ) at 2015-01-31 20:40 CET
Initiating Parallel DNS resolution of 1 host. at 20:40
Completed Parallel DNS resolution of 1 host. at 20:40, 0.16s elapsed
Initiating SYN Stealth Scan at 20:40
Scanning ec2-x-x-x-x.eu-central-1.compute.amazonaws.com (x.x.x.x) [2 ports]
Discovered open port 22/tcp on 126.96.36.199
Completed SYN Stealth Scan at 20:40, 1.38s elapsed (2 total ports)
Nmap scan report for ec2-x-x-x-x.eu-central-1.compute.amazonaws.com (x.x.x.x)
Host is up (0.035s latency).
PORT   STATE    SERVICE
22/tcp open     ssh
80/tcp filtered http

Read data files from: /usr/local/bin/../share/nmap
Nmap done: 1 IP address (1 host up) scanned in 1.58 seconds
           Raw packets sent: 3 (132B) | Rcvd: 1 (44B)

..so some kind of firewall is blocking my traffic.
Let's assume that it's NOT an EC2 Security Group.
What else can be blocking my traffic? Something that is running on the VPS itself? Something in the kernel or something in the user space?

UPDATE:
I tested apparmor:
root@ip-x-x-x-x:~# apparmor_status --verbose
apparmor module is loaded.
4 profiles are loaded.
4 profiles are in enforce mode.
   /sbin/dhclient
   /usr/lib/NetworkManager/nm-dhcp-client.action
   /usr/lib/connman/scripts/dhclient-script
   /usr/sbin/tcpdump
0 profiles are in complain mode.
1 processes have profiles defined.
1 processes are in enforce mode.
   /sbin/dhclient (607)
0 processes are in complain mode.
0 processes are unconfined but have a profile defined.

..and I interpret this output as it hadn't anything to do with the filtering but I have disabled it anyway:
root@ip-x-x-x-x:~# service apparmor stop
 * Clearing AppArmor profiles cache
   ...done.
All profile caches have been cleared, but no profiles have been unloaded.
Unloading profiles will leave already running processes permanently
unconfined, which can lead to unexpected situations.

To set a process to complain mode, use the command line tool
'aa-complain'. To really tear down all profiles, run the init script
with the 'teardown' option."
root@ip-x-x-x-x:~# service apparmor teardown
 * Unloading AppArmor profiles
   ...done.

..but it didn't help. nmap still shows filtered TCP 80, nginx still not accessible.
Comment: You need to find out who _does_ have access to the security group, then. Everything else is just wasting time.
Comment: Then the answer is no.
Comment: You should look at your EC2 security group.
Comment: @MichaelHampton It's AWS EC2 instance but this should not matter as I am asking about firewall **on the server itself**. But I have added this info to my question to prevent the further downvoting..
Comment: Are you actually trying to solve a problem? Why haven't you checked your security group?
Comment: @MichaelHampton Because I don't have access to it - see http://serverfault.com/questions/663843/how-to-list-ec2-security-group-rules-from-within-instance
Comment: It's kind of a test problem.
Comment: Did you have app-armor installed and running?
Try also wireshark for see blocked packets or something bad on network traffic
Comment: Yes, but it didn't filter any traffic. I will update my question with info about it.
Answer: It might be that the hosting provider have a firewall service defaulting to only permit ssh traffic to the server. The purpose of such a default could be to limit exposure of the server until you have had time to install all security updates, harden your configuration, and in general ensure your server is ready to go live.
If such a service happens to be in place, there is likely going to exist a web interface through which it can be configured. There should also exist a place to disable it completely.
The steps I would recommend are the following:

Read documentation from the hosting provider to find out if a firewall service like the one described above happens to be in place.
Use tools to narrow down the location of any filters you haven't found documentation for.
Ask the provider

What you can do to narrow down the location of filters is to use the traceroute command. Ubuntu 14.04 has a traceroute command with flags that can send packets with specific protocol and port number. That way you can for example compare the output obtained from a trace to port 22 and port 80.
traceroute -n -T -p 22 server

Notice that different traceroute implementations exist. If for some reason the flags seem not to work, then try traceroute.db, which should give you the version with support for the above combination of flags.
Comment: Thank you but the whole provider firewall part does not answer my question - see the "apart from external firewall" part.
Comment: I also already used `traceroute`, `tcptraceroute`, `nmap` and some other tools already and I am (pretty) sure that something is blocking my incoming traffic. The question that I am asking is: **what** is blocking it?
Comment: @GrzegorzDubicki Depends on what you mean by blocked. If TCP connections to port 22 work and TCP connections to port 80 get a RST, it simply means nothing is listening on port 80. If connections to port 22 work and SYN packets to port 80 are silently dropped, it has to be some kind of firewall, which is causing it. Notice that iptables is not the only firewall which could be used on a Linux machine. Also, have you actually verified that the host is receiving SYN packets in the first place?
Comment: @GrzegorzDubicki Have you compared traceroute output, like I suggested?
Comment: "Notice that iptables is not the only firewall which could be used on a Linux machine" - **that's what I am asking here. What are these other kinds of firewalls?** For what I know all others are some kind of `iptables` frontends (like `ufw`)..
Comment: I have done `nmap` TCP SYN scan which clearly says that traffic to port 80 TCP is filtered (I used word "blocked" in a comment before in a not very precise way - I meant "filtered"). I will add it's output to my question.
Answer: Apparently there is no other firewall solution on Linux that doesn't in fact use iptables/netfilter. Also a simple SYN test is the proper way to check if your traffic is filtered by a firewall. You are right that looking for an "upstream" firewall, a Security Group of this EC2 instance in this example, is the only reasonable way to resolve this. Thank you for all your input that led to this answer.


Compute probability from distance-score

Question: I compute Euclidian distances between a point I want to analyze and a set of points I have. I want to sort my points by decreasing "similarity".
I used to compute a "score" by inverting the distance ($s=1/d$), and use the $\cfrac{s_i}{\sum_k s_k}$ as a similarity that varies between $0$ and $1$.
I have seen that the $softmax$ function can also be used, the difference being that it uses $e^{1/d}$ as the score.
Which function would be closer to computing a kind of "probability"? I should apologize for probably mixing terms...
Comment: Probability of what? Both give nonnegative scores that sum to one. Neither is particularly anything like a probability. Softmax will decay quickly beyond the closest point, while the sum one will distribute scores more widely.
Comment: If you're not familiar, you might want to look at [kernels](https://en.m.wikipedia.org/wiki/Kernel_(statistics)#In_non-parametric_statistics).
Comment: @Dougal, thank you, your first comment answers my question ... and your second one gives me homework ;)
If you add that as an answer I'll accept it.
Answer: Credits to @Dougal for his comment-answer:

Both give nonnegative scores that sum to one. Neither is particularly anything like a probability. Softmax will decay quickly beyond the closest point, while the sum one will distribute scores more widely.

The decay part is interesting: $e^{1/x}$ is a lot bigger than $1/x$, so ${\sum_k e^x}$ will be a lot bigger than ${\sum_k 1/x}$, considering the value of $k$.
Answer: For those still looking for different answers, I was finding individual probabilities (something like Sigmoid) for similarity values provided by different algorithms. This is what I am doing..
 $(1-e^{-1/x})/(1+e^{-1/x})$
Considering that similarity provides value from 0 to 1, where o being most relevant one. This has provided me with pretty good results, not sure if something like this can used for distance as well, may be taking modulus of x in above equation solves the problem.
 $(1-e^{-1/|x|})/(1+e^{-1/|x|})$
Please let me know if someone tries this.
Thanks

Compute probability from distance-score


Equation paramétrique du second degré

Question: C'est un exercice du concours d'admission en économie de L'Université Protestante au Congo.
Voici la question: déterminer la valeur de m pour que la fonction f(x)=(x-7)/(mx²+ mx+m+1) admette deux asymptotes verticales.

[Edited English translation]:

This is an exercise from the economics entrance examination of L'Université Protestante au Congo. The question is: determine the value of $m$ such that the function:
  $$
f(x) = \frac{x - 7}{mx^2 + mx + m + 1}
$$
  has two vertical asymptotes.
Answer: Hint: If $m \neq 0$, then $mx^2 +mx+m+1 = m(x^2 + x + 1 + 1/m)$. Using the quadratic equation, the roots of $x^2+x+1+1/m$ are $$ -\frac{1}{2}\pm \frac{\sqrt{1-4(1+1/m)}}{2}.$$ You will get two real roots whenever the discriminant $1-4(1+1/m)$ is positive. That is, when $1-4(1+1/m) > 0$.
Can you take it from there?
Comment: I'm looking for the value of "m".
Comment:  Indice: Si $m \neq 0$, alors $mx^2 +mx+m+1 = m(x^2 + x + 1 + 1/m)$. En utilisant la formule quadratique, les racines de $x^2+x+1+1/m$ sont $$ -\frac{1}{2}\pm \frac{\sqrt{1-4(1+1/m)}}{2}.$$ Vous aurez deux racines réelles à chaque fois que le discriminant $1-4(1+1/m)$ est positif. C'est-à-dire lorsque $1-4(1+1/m) > 0$.

Pouvez-vous poursuivre à partir de là?
Comment: Oui biensûr! Mais celle-ci est une équation paramétrique du second degré, il faut d'abord trouver la valeur du paramètre (m) laquelle va nous aider à résoudre rationnellement l'équation. Merci!
Comment: ∆(m)=m²-4(m)(m+1)=m²-4m²-4m=-3m²-4m.
∆(m)=0 alors -3m²-4m=0
m= ?
Comment: Ce que Tom a fait, c'est diviser d'abord l'équation par $m$. Cela revient au même, en autant que $m \ne 0$. Mis à part certains cas exceptionnels que vous aurez peut-être à exclure, vous cherchez $m$ de façon que l'équation ait deux racines. Cela correspond au fait que le discriminant soit *positif*, et non pas nul comme vous l'affirmez.
Comment: Je peux en déduire que ce cas est une particularité? Déterminer la valeur de m pour que la fonction f(x)=(x-7)/(mx²+ mx+m+1) admette deux asymptotes verticales.
Comment: Écoutez, je vais donner des exemples qui ne correspondent pas au problème pour dire ce qui se passe. La fonction $g(x) = (x-7)/(x^2 - 9)$, elle a combien d'asymptotes verticales? La fonction $h(x) = (x-7)/(x^2 + 2x + 1)$? Et $k(x) = (x-7)/(x^2 + 9)$?
Comment: In order other participants can follow, may I suggest we all write in English ? (I am French)
Comment: Claude, I thought it would be more useful for the OP, has he posted his original question in French and appeared to have some difficulty following Tom's answer.
Answer: In order that function $$f(x) = \frac{x - 7}{mx^2 + mx + m + 1}$$ shows two vertical asymptotes, the denominator must cancel twice. This first implies that $m \neq 0$ (otherwise, the quadratic would not be anymore a quadratic).
Now, the roots of $${mx^2 + mx + m + 1}=0$$ are given by $$x_{\pm}=-\frac{m \pm \sqrt{-3 m^2-4 m}}{2 m}$$ and so the requirement is $$3m^2+4m=m(3m+4)\lt 0$$ which then implies $$-\frac{4}{3} <m<0$$
Comment: Thank you @claude-leibovici your resolution seems logical. But only by replacing m by  -4 / 3, f (x) has no solution in IR, was I wrong or not?
Comment: This answer is incorrect. There is only one vertical asymptote when $m=-1/57$ because the $x-7$ cancels.

Equation paramétrique du second degré


How exactly does curse of dimensionality curse?

Question: In what way does the curse of dimensionality affect the predictions?
I know that as the number of predictors increases the observations that are geometrically near decrease, so we have to spread out more to capture the nearest neighbours.
So my question is , in what other ways, than being computationally expensive , does the curse of dimensionality cause the non-parametric model to perform poorly?
Comment: Suppose you want to do regression in some 1d data in this way you should optimize the cost function which can be for example LSE. in other words you should search in 1d space to access the optimum point, but if you modify your input to 2d then you should find optimum point in 2d space. In other words if you needed one loop in 1d for find optimum point in here you roughly need two loop (for(for(...))) to find optimum.
Comment: Yes, that gets included under the computationally expensive,which I have already mentioned in the question , my question is how else?
Comment: There's a good discussion of this on Wiki https://en.wikipedia.org/wiki/Curse_of_dimensionality. To me, much of the concern seems driven by computational and combinatorial complexity in optimizing a fixed, closed form algorithm. Probit models are an example of this: when the dependent variable in a probit  model had more than 3 levels, observers opined that it could take 10,000 years of CPU for the solution to converge. With the approximating workarounds available today such as hierarchical Bayesian, bootstrap, jacknife, random forest, divide and conquer, etc., CoD has been greatly mitigated.
Comment: I'm sorry but both comments are not relevant. The curse of dimensionality (in statistics/machien learning) is not about computational complexity.
Answer: The idea of nearest neighbours is that, due to continuity, other points close to your point of interest have values close to the value of your point of interest. If you have to spread very far out to find the 100 (for example) closest points, well then these points are not very close or neighbours anymore, and thus there's no reason that their values are relevant at all to help you predict the value at your point of interest!
Comment: +1. I believe that in high-dimensional space, everything starts to be nearly equidistant from everything else, so as you say you have to look pretty far from yourself to find $k$ neighbors. In addition, the distance to your $k$ neighbors will tend to not be that much smaller than distances to everyone else, so you don't get a lot of traction.
Answer: The curse is that a lot of of things that work in lower dimension don't scale well (i.e. grow/shrink too fast compare to linear) with dimension. E.g. a measure of data quality is more than 2 times worse when you double the number of dimension. The curse comes in many form: the range of the data, the density of the data, the distribution, etc.
Take the example from ESL book. Says in every 1 dimension the possible values are in $[0,1]$, your data covers  $[0.1,0.9]$, i.e. the range of data $r=0.8$. That's pretty good of a range if your data is just 1D.
The generalization of range to dimension $p$ is $0.8^p$. As $p$ increase, the range of your data shrinks really fast. In 2D, $p=2$, even though in each dimension, your data spans 80% of possible range, the 'volume' range that it capture is only 64%. In 10D, $p=10$, your data only cover 10% of the space! If you want to cover 80% of the space, in each dimension, your data need to span $0.8^{\frac{1}{10}} \approx 0.98$% of possible range - that's very expensive.
Answer: It curses mainly in computational sense. However, if you expand the dimensionality from small to large to infinite, asymptotically any point that's not this point becomes infinitely far away.
If you're at point O, and are looking at points A and B, then both $OA=\infty$ and $OB=\infty$, and you can't distinguish which one is farther.


read density diagram generated in R

Question: Not sure if I read the density diagram correctly from R, I think it means overall, most a and b happens in the dark red area, and for specific a values, for example, if a is 0.1, most b values are in the small red circle area I drawn, and when a value is 0.2, most b values are in the bigger red ellipse area I drawn?
Post the density diagram and sample code,
b<-log10(rgamma(1000,6,3))
a<-log10((rweibull(1000,8,2)))
density<-kde2d(a,b,n=100)
filled.contour(density,color.palette=colorRampPalette(c('white','blue','yellow','red','darkred')))

Comment: Would you please set a seed so your code is actually reproducible? Also, please label your axes and title your plot.
Comment: You are reading the diagram correctly. If 'a' is on the x axis then when a=0.1 most b values are in the darker colored region vertically above a=0.1.
Comment: @LinMa that was a bad choice of words by me. In the two red circles you have white-dark blue colours and the b values in the most darkest shade of blue are most common. Of course if you look at a=0.35 then there are yellow and blue colours so the b values in the yellow region are most common.
Comment: @WaldirLeoncio, thanks for the comments and vote up. I updated my post to change `x` `y` to `a` `b` so that my statement aligns with code. What do you mean set a seed? Actually it does not matter which specific data set, my question is about in general how to read density diagram correctly. Given the density diagram I posted, wondering if it is correct for my description in above post? Thanks.
Comment: Thanks @Hugh, vote up. What do you mean darker colored region? Do you mean the blue region I am using red circle to highlight? :)
Comment: @Hugh, thanks and vote up, 1. so my reading of kernel density plot is correct? 2. I also have a further question, wondering if darker color area (dark-red in my example) means `a` and `b` has higher correlation, or not?
Comment: @Hugh, BTW, if you could add a reply, I can mark it as answer to benefit people who has similar issue in the future. :)
Answer: Yes, you are reading the diagram correctly. Regarding your question in the comments, "if darker color area (dark-red in my example) means a and b has higher correlation, or not?": Darker color area does not means a higher correlation. It just means that more data are observed in this area.
To make this last point more clear, I generate two independent and uncorrelated variables x and y. As the are uncorrelated, the dark area cannot show correlation. (PS: I think axis labels are a must have for statistical graphs, so a added them (and a title))
library(MASS)
set.seed(123)
x = rnorm(1000, mean = 10)
y = rnorm(1000, mean = 0)
density <- kde2d(x, y, n = 100)
filled.contour(density,
           color.palette = colorRampPalette(c('white', 'blue', 'yellow', 'red', 'darkred')),
           xlab = "x", ylab = "y", main = "contour plot of x and y")

Comment: @LinMa, The dark red area just says that there are many observations with a value of x in [9.5, 10.5] and y in [-1, 1]. Its sound a bit odd to me to say that x or y "enters into a region". How I would read it, would be: if x element [9.5, 10.5], the values of y are likely to be in [-1, 1]. The crucial point is, that the probability of y to be in [-1, 1] is independent of the value/range of x (as they are independent). For x = 8 you have the exact same probability of y to be in [-1, 1].
Comment: Thanks Qaswed, vote up. To read the density diagram you plot above, my reading is, when x enters into region (roughly) [9.5, 10.5], y enters into region dark-red [-1, 1]. There are correlation there. It seems. If I am wrong for any descriptions above, please feel free to correct me. :)
Comment: Nice answer Qaswed, mark your reply as answer.

read density diagram generated in R


Does Thompson's Calculus Made Easy have any discussion of implicit differentiation?

Question: I didn't see it in the index but would like to read his treatment if there is one. The version I'm thinking of is here: http://calculusmadeeasy.org/
(Sorry if this isn't an appropriate question for this forum, but I thought it might be alright.)
ADDITIONAL EDIT: Page 2 of this article has a differential-based treatment of implicit differentiation, although I don't quite understand it, nor am I sure that it's identical to how Thompson treated it: http://math.oregonstate.edu/bridge/papers/differentials.pdf.
Answer: Thompson's approach to calculus is through the use of differentials, and thus his treatment of the derivative is essentially the same as what one would call "implicit differentiation" in standard textbooks: given an equation that relates $y(x)$ and $x$, differentiate all terms with respect to $x$ to obtain an implicit definition of $dy/dx$. Consequently, there's no need to distinguish between finding the derivative of a function and takes derivatives on an implicit expression. See e.g. http://calculusmadeeasy.org/6.html
Comment: Page 2 of the document you have provided seems exactly like Thompson's approach.
Comment: Are any of the answers on that page actually examples of implicit differentiation, though? Or just Thompson's general approach? I still don't quite get how implicit differentiation ties in to his general approach (the latter of which I have *some* familiarity with).
Comment: See also my edit to the question.
Comment: Yeah I still kinda need a worked example of Thompson-esque implicit differentiation though in order to reach full understanding. Maybe someone else will answer with that.
Answer: I think B. Nunez gave a great answer, but I will follow on with a more specific example.  It's been a long time since I read Calculus Made Easy (CME), so apologies if this doesn't fit their methodology exactly.
In "traditional" calculus, you find the derivative with respect to a particular variable.  In CME, you find the derivative by incrementing each variable according to its own increment.  So, you replace $x$ with $x + dx$ and $y$ with $y + dy$.
So, let's say you have:
$$x^2 + y^2 = 1.$$
The CME approach would have you replace each $x$ with $x + dx$ and $y$ with $y + dy$.  This then becomes:
$$
(x + dx)^2 + (y + dy)^2 = 1 \\
x^2 + 2x\,dx + dx^2 + y^2 + 2y\,dy + dy^2 = 1 \\
2x\,dx + dx^2 + 2y\,dy + dy^2 = 0 \\
2x\,dx + 2y\,dy = 0 \\
2y\,dy = -2x\,dx \\
\frac{dy}{dx} = -\frac{x}{y}
$$
The simplification from step 2 to step 3 is because we subtracted the original equation from both sides.  The simplification from step 3 to step 4 is because the square of an infinitesimal is infinitely smaller than the original infinitesimal, and therefore infinitely more insignificant.  Then I just solved for $\frac{dy}{dx}$.
If you are interested, the way that I teach implicit differentiation is here.
Comment: Yes - you can write the derivative rules as differential rules.  Instead of the derivative of $y = x^n$ being $\frac{dy}{dx} = nx^{n - 1}$, you can write it purely in terms of the variables in the function, as $dy = nx^{n - 1}dx$.  Therefore, using these rules you would differentiate both sides by doing: $$d(x^2 + y^2) = d(1).$$  Addition rule gives you: $$d(x^2) + d(y^2) = d(1).$$  Applying basic rules gives you $$2x\,dx + 2y\,dy = 0.$$  That gets you to the 4th line above in basically 1 step.
Comment: Wait is there any faster way to do it than actually expanding out the (x+dx) and (y+dy) ... but still using differentials?


How to resolve lombok error "log cannot be resolved"?

Question: I have errors in the project (springboot) with all code "log." I have followed the advise from the link below (in my case using eclipse with spring tools):
enter link description here
I spent 2 hours delete the project and reopen, clean, build everything and nothing working. I also did mvn compile from command line and this seem to work fine, so it's clearly eclipse problem.
code from pom:
<code><dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
</code>
Eclipse ini file:

I run the jar (java application) and specify the ini file. The jar is added
to the eclispe directory but it has no  version on it.
Also lombok should appeared in the eclipse about screen and it's not.
Thanks.
Comment: Did you install Lombok into your IDE? Do you have a Lombok dependency in your pom.xml?  and can you share a code snippet?
Comment: hi @Habil have a look now I hope to get clearer idea.
Comment: I don't use Eclipse but in Intellij I had to enable annotation processing in the settings. Maybe this is also the case for eclipse
Comment: I've tried in eclispe as well, oit doen't work
Comment: Try to install lombok plugin.
Answer: In order to solve this problem I had to use STS4 and the same indtallation
for eclpise is work for STS.
lombok is added to the about screen, all good now.


Coefficient of $Y$ on $X$ and Coefficient of $X$ on $Y$

Question: Under what circumstances the coefficients from simple linear regression of $Y$ on $X$ is equal to that of $X$ on $Y$?
Will it hold when the standard deviations of $X$ and $Y$ are the same?
I would very appreciate it if anyone can give me any idea of it! Thanks.
Comment: See [my answer](https://stats.stackexchange.com/a/20556/6633) to _Effect of switching response and explanatory variable in simple linear regression_ where I show tat if $X$ is always plotted on the horizontal axis and $Y$ on the vertical axis, then the two regression lines are not the same except when all the data points lie on a straight line. If the response is on the vertical axis and the  explanatory variable on the horizontal axis, the two lines have the same slope when the variances are the same. But one line passes through $(\mu_X,\mu_Y)$ the other through $(\mu_Y,\mu_X)$.
Comment: This is becoming a FAQ: see https://stats.stackexchange.com/search?q=regression+x+y.
Answer: Yes. The least squares estimator when regressing $Y$ on $X$ is
$$ \hat\beta = \frac{\hat\sigma_{xy}}{\hat\sigma^2_x}$$
The only way to get the same value by regressing $X$ on $Y$ is if $\hat\sigma^2_x = \hat\sigma^2_y$. If so, $\hat\beta$ coincides with the correlation between $X$ and $Y$.
$$ \hat\rho = \frac{\hat\sigma_{xy}}{\hat\sigma_x \hat\sigma_y} $$


Dual of Sobolev space $H^{s}(\mathbb{R}^n)$ Taylor Michael.

Question:
Why the dual of $H^{s}(\mathbb{R}^n)$ is $H^{-s}(\mathbb{R})$?
I know that dual of $H^{s}(\mathbb{R}^n)$ is $\left\{T:H^{s}(\mathbb{R}^n)\to \mathbb{C}:T \text{ bounded and linear functional} \right\}$
Is it because $\Lambda^{-s}\Lambda^{s}u=u$ and $\Lambda^{s}\Lambda^{-s}u=u$? Is that argument enough?
Answer: You have already solved it with
 $(u,v)=\int \hat{u}(\xi)\tilde{v}(\xi)d\xi=\int\hat{u}(\xi)<\xi>^s\tilde{v}(\xi)<\xi>^{-s}d\xi$ is a isomorphism of $H^{-s}$ and the dual of $H^{s}$


xpath for background-image url

Question: I'm trying to get a background image url using xpath .
my xpath expression so far:
//div[@class='Header']/div[@class='Header-jpeg']

which points to the div that has the background-image but from there no idea how to get the img url, probably something in @style but no luck so far.
Css of that div:
div.Header-jpeg {
    position: absolute;
    z-index: -1;
    top: 0;
    left: 0;
    width: 874px;
    height: 94px;
    background-image: url('images/Header.jpg');
    background-repeat: no-repeat;
    background-position: center center;
}

and a real example ca be found here:
http://www.landenkompas.nl/
Answer: Something like this should work:
substring-before(substring-after(//div[@class='Header']/div[@class='Header-jpeg']/@style, 'background-image: url('), ')')

However, be warned that if you're using Java XPath it will only get the first element it finds. If you have multiple, you'll need to find another way to aggregate all the values.
Comment: That's the right answer as far as I remember, it might get tricky though sometimes as some sites use something slightly different like `"` vs `i` or an extra space etc
Answer: Assuming you are using selenium, you need to get a value of the CSS property.
In Java:
WebElement element = driver.findElement(By.xpath("//div[@class='Header']/div[@class='Header-jpeg']"));
element.getCssValue("background-image");

In Python:
element = driver.find_element_by_xpath("//div[@class='Header']/div[@class='Header-jpeg']")
element.value_of_css_property("background-image")

xpath for background-image url


Should I define a new function for making a matrix Hermitian?

Question: Let X be a square matrix. We want to force it to be Hermitian, that is: self-conjugate-transpose.  X = X^H = conj(X^T). To do this in Python with numpy is easy:
X = 0.5*(X + np.conj(X.T))

I haven't found in NumPy a single function that does it in a single experssion f(x).
The question is should I define a new function to do it? E.g.
def make_hermitian(X):
    return 0.5*(X + np.conj(X.T))

(one can come up with short name, e.g. "make_h" or "herm" or "selfconj").
Pros: more readable code, one operation in shorter form. If one uses shorter name it saves writing when repeated many times, and makes modification in this operation far more easy and comfortable (need to change only in place).
Cons: replaces a very short and straight-forward expression which is self-evident.
What is more appropriate way of programming: define a new function or just write the explicit expression repeatedly?
Answer: I would say it depends on how many times you need to reuse that function.
If it's more than twice, then definitely make a function. If it's only once or twice, I would say it's up to you. If you choose to go with no function, add a short comment specifying what such piece of code is supposed to do.
My preference in any case would be defining a function with a meaningful name, because if anyone else is going to / supposed to read the code, they may not know or remember how to achieve a Hermitian matrix, and hence the math alone ain't going to be sufficient.
On the other hand, a meaningful function name will tell them clearly what it's going on, and they can google after what a Hermitian matrix is.
Comment: I would accept your answer but I want to hear more opinions.
Comment: @Triceratops sure, makes sense to me


how do i pass arrays in java

Question: I am trying to compare to arrays defined in the main method and need to pass them to the compareAnswers method how do I do this?
here is my code:
/**********************************************
 *
 * Daniel Wilson
 *
 * CIS129
 *
 * November 15 2017
 *
 * Compaires test answers against correct answers
 *
 * ********************************************/

import java.io.*;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;

public class CIS129_DanielWilson_PC6 {

public static void main(String args[]) {

  final int SIZE = 20;
  String[] givenAnswers = new String[SIZE];
  String[] correctAnswers =      { "B", "D", "A", "A", "C", "A", "B", "A", "C", "D", "B",  "C", "D", "A", "D", "C    ", "C", "B", "D", "A"};
  String answers = compareAnswers();

  InputStreamReader input = new InputStreamReader(System.in);
  BufferedReader reader = new BufferedReader(input);

  try{
    System.out.println(Arrays.toString(correctAnswers));
    for (int i = 0; i<SIZE; i++) {
    System.out.println("please enter your answer for question " + (i+1));
      givenAnswers[i] = reader.readLine();
    }
  }catch (IOException e){
            System.out.println("Error reading from user");
      }
}
public static String compareAnswers(){

List<String> tempList = new ArrayList<String>();
for(int i = 0; i < correctAnswers.length; i++)
{
    boolean foundString = false;
    for(int j = 0; j < givenAnswers.length; j++)
    {
        if(givenAnswers[j].equals(correctAnswers[i]))
        {
            foundString = true;
            break;
        }
    }
    if(!foundString)
        tempList.add(givenAnswers[i]);
}
String ammountRight[] = tempList.toArray(new String[0]);
for(int i = 0; i < ammountRight.length; i++)
{
    System.out.println(ammountRight[i]);
  }
 }
}

I understand I need to pass by reference but my professor didn't cover that in much detail. any help is appreciated.
Comment: Java has no pass-by-reference, everything is passed by value
Comment: @AntonH and Antoniossss Java is always pass-by-value https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value Pass-by-reference would mean you could assign to passed variable, but you can't
Comment: Please learn to format your code better
Comment: Just pass it :)
Comment: I would say that everyghint is pass-by-reference but what can i know...
Comment: `compareAnswers` needs to accept two arrays - `public String compareAnswers(String[] givenAnswers, String[] correctAnswers)` and then you simply pass what ever information you need to the method; `compareAnswers(givenAnswers, correctAnswers)`;
Comment: MadProgrammer its now working your comment helped a lot.
Comment: Novaterata my class didn't teach how to format code I apologize if it was hard to read but I am trying my best
Comment: I hope that's not your real address on your profile.
Comment: it wasn't my current adress
Answer: how do i pass arrays in java?
java only has call by value;
but java can just pass a reference by copying the reference where needed.
e.g.
public class Main{
     public static void main(String[] args){
            String[] arr = new String[size];
            // fill your array!

            Main.foo(arr);

     public static void foo(String[] a){
          // do something with your array.
          // if you change a value of the array,
          // the array in main will be changed too.
     }
}

Answer: Like this
public static String compareAnswers(ArrayList<String> firstArray, ArrayList<String> secondArray)

how do i pass arrays in java


Is the date of the question relevant when reviewing suggested edits?

Question: Recently I see some users going through very old questions and answers with minor formatting edits. I say "minor" not because they change too little, but because the posts were readable before, just not perfectly formatted. The edits show some effort and make the posts look nicer but are not really necessary.
I flagged them as "No improvement whatsoever", but am not sure if this is the right thing to do.
My considerations:

the post was understandable as it is and the formatting was not broken
bumping many old posts just for perfect formatting might be annoying

On the other hand I tend to accept such edits if the post is just a few hours old and I don't think, editing old posts in general is bad if it's an improvement.
Should I pay attention to the post date at all when it comes to edits?
Comment: @QaisarSatti Thanks for your "formatting" edit ;-)
Answer: i think formating is necessary for question and answer. if the question or answer is formated then it is easy to read and understand so i always approve this kind  editing.
Answer: I'm like Qaisar on this one, I always approve edit that adds the code formatting to the post, it's a real improvement for me as you can clearly see what's related to code/commands/pathname/filename.
I reckon we should approve it.
When I reach a post where it's just a plain wall of text with no code formatting I don't feel like answering it.
Let's say I open a very old question for any reason, there's more chance I will answer it if there's code formatting than if there's none and it's hard to read.
To be honest if the question is related to something I'm working on or something I'm interested in, I will probably do the edit myself ^^
Answer: I believe edit suggestion should have the top priority irrespective of the relevance of that question. An edit suggestion in such cases will have two main motos.

One need more points. So he/she goes to old questions list and suggest some edits.
One comes to an old question by searching something on internet. He/she thinks questions presentation can be improved. So he/she is coming up with a new suggestion.

Whatever be the case, what we need to think is whether the suggested edit really makes question/answer more charm or not. If yes, we should approve it otherwise we should not.. We need to encourage such edits in any case.
Content is the king and it should be charm.


Interpolating curve equation from model data

Question: I need to define an equation to represent a series of points from a model. As they are predictions from an already fit non-linear regression, noise shouldn't really be an issue. I have seen many examples that allow predictions to be made on the curves, but I am still confused about how I can retrieve an equation from various functions such as spline, etc.
Based on the formula I supplied for the nonlinear regression in brms (b1^b2, where b1 ~ 1 + x and b2 ~ 1), I would expect the relationship to resemble some sort of power function [ax^b or possibly (int + ax)^b].
I understand it may be just an approximation - that is fine as long as it is relatively similar (will be plot alongside model for comparison). Would greatly appreciate any insight whatsoever, let me know if I can provide further information. Have provided example data below.
<code>
x <- c(7, 7.5, 8, 8.5, 9, 9.5, 10, 10.5, 11, 11.5,
       12, 12.5, 13, 13.5, 14, 14.5, 15, 15.5,
       16, 16.5, 17, 17.5, 18, 18.5, 19, 19.5,
       20, 20.5, 21, 21.5, 22, 22.5, 23, 23.5,
       24, 24.5, 25, 25.5, 26, 26.5, 27, 27.5,
       28, 28.5, 29, 29.5, 30, 30.5, 31, 31.5,
       32, 32.5, 33, 33.5, 34, 34.5, 35, 35.5,
       36, 36.5, 37, 37.5, 38, 38.5, 39, 39.5,
       40, 40.5, 41, 41.5, 42, 42.5, 43, 43.5,
       44, 44.5, 45, 45.5, 46, 46.5, 47, 47.5,
       48, 48.5, 49, 49.5, 50, 50.5, 51, 51.5,
       52, 52.5, 53, 53.5, 54, 54.5, 55, 55.5,
       56, 56.5, 57, 57.5, 58, 58.5, 59, 59.5,
       60, 60.5, 61)

y <- c(38.0136100143096, 41.7377019494229, 45.0570784133659, 49.7413206704322,
       54.1226793545035, 58.5143924911556, 64.0149939443995, 70.2996105120598,
       74.5157778956172, 82.0845639640055, 88.1447395709772, 96.0901896008888,
       104.331306746698, 112.587794035369, 116.793284692497, 129.660032344424,
       139.148796580701, 154.021720779283, 164.352212638548, 174.265834929441,
       186.345636353806, 199.537020067263, 217.599140020487, 233.877433057235,
       246.132735977878, 267.47374365421, 283.863259012889, 301.899794004843,
       322.769938301311, 351.430583957233, 383.849198025211, 390.736999633559,
       423.249193342341, 454.638021905869, 485.240521462023, 509.31872397953,
       560.804077944124, 580.52077607546, 623.750134417424, 663.267081364541,
       698.778452300861, 737.091827116676, 796.938400847035, 856.419990917143,
       906.017778910945, 965.168165262045, 1013.84413110147, 1065.85753522486,
       1154.33958805326, 1204.13058748532, 1322.42312105971, 1385.41472565674,
       1464.95636449756, 1526.04430007742, 1609.84006688626, 1738.45992222218,
       1816.05261609804, 1896.50702990984, 2024.59349402727, 2142.55345863206,
       2216.16848789472, 2384.32905391336, 2534.20713772314, 2599.97048189298,
       2800.82684813604, 2956.9306593113, 3133.9558188069, 3320.82577045419,
       3477.57994233654, 3602.69160098815, 3800.51701252841, 4062.6001499355,
       4238.73826354165, 4645.61124406474, 4731.78190196944, 4947.75977778357,
       5211.86923419648, 5619.65143369664, 5817.33879970144, 6079.00167282099,
       6205.39929607976, 6681.42573862285, 7198.53801041513, 7267.01092369979,
       7816.95660375773, 8133.793609116, 8261.13289172042, 9053.74531584895,
       9473.33768555856, 10137.0504777871, 10400.797014819, 10966.3727089692,
       11494.3384956937, 11920.4271066324, 12400.9643350626, 13096.7674700334,
       13798.7159321491, 14358.3675127649, 15266.2675882016, 16072.0949530508,
       17058.7362901159, 17663.6886724086, 18390.5282871649, 19307.9213621373,
       20392.6725381775, 21431.4257870743, 21624.312458088, 23099.2069971926,
       24090.3844352512)

data <- data.frame(x, y)

library(ggplot2)

ggplot(data, aes(x,y)) + geom_point()

</code>

Note: For anyone wondering why I don't just use the coefficients supplied by the model (and can maybe explain how to do so), I have made a post about this here: Interpreting non linear brms output - estimates of posterior cooefficient and user supplied formula
However, I think an answer to this question would also be valuable.
Answer: Plot in logarithmic scales :

Back to libear scales :

This is an example of function. Of course one could fit other kind of functions. For example :

This last function gives a better fitting considering the absolute errors while the preceeding function gives a better fitting considering the relative errors. This depends on the chosen criteria of fitting. Of course other functions could be considered and leave to even better fitting wrt the criteria.


Is A Relational Database Design Correct For Storing This Complex Structure

Question: TL;DR:
I want to use a non-relational design to store a tree of nodes in a self-referencing table because we will never need to relationally select subsets of data. This allows for extremely simple recursive storage and retrieval functions.
Coworker wants to use a relational design to store each specific field of the object -- I assume because he believes relational is simply always better. (he doesn't have any specific reasons) This would require more tables and more complex storage and retrieval functions, and I don't think it would serve to benefit us in any way.
Is there any specific benefits or pitfalls to either of the design methods?
How are trees normally stored in databases? Self referencing tables?
Are there any known samples of trees of data being stored in databases that might coincide with the task we are trying to solve?

At work we are using a complex structure to describe an object, unfortunately I cannot share the exact structure because of work restrictions but I will give an equivalent example of the structure and explain the features of it.
The structure can be represented in json but actually conforms to a much tighter syntax restriction.
There is four kinds of entities in the structure:

top level node

This node is a json object and it must be the top level json object
This node must contain exactly 4 attributes (meta info 1 through 4)
This node must contain exactly 1 'main' container node

container nodes

These are json objects that contain other containers and pattern nodes
Must contain exactly 1 attribute named 'container_attribute'
May contain any number of other containers and patterns

pattern nodes

These are json objects that contain exactly 3 attributes
A pattern is technically a container
May not contain anything else

attribute nodes

These are just json string objects

The top level container is always a json object that contains 4 attributes and exactly 1 container called 'main_container'
All containers must contain a single attribute called 'container_attribute'.
All patterns must contain exactly three attributes
An example of a structure in json looks like the following:
{
    "top_level_node": {
        "meta_info_1": "meta_info_keyword1",
        "meta_info_2": "meta_info_keyword2",
        "meta_info_3": "meta_info_keyword3",
        "meta_info_4": "unique string of data",

        "main_container": {
            "container_attribute": "container_attribute_keyword",

            "sub_container_1": {
                "container_attribute": "container_attribute_keyword",

                "pattern_1": {
                    "pattern_property_1": "pattern_property_1_keyword",
                    "pattern_property_2": "pattern_property_2_keyword",
                    "pattern_property_3": "unique string of data"
                },

                "pattern_2": {
                    "pattern_property_1": "pattern_property_1_keyword",
                    "pattern_property_2": "pattern_property_2_keyword",
                    "pattern_property_3": "unique string of data"
                }
            },

            "pattern_3": {
                "pattern_property_1": "pattern_property_1_keyword",
                "pattern_property_2": "pattern_property_2_keyword",
                "pattern_property_3": "unique string of data"
            }
        }
    }
}

We want to store this structure in our internal office database and I am suggesting that we use three tables, one to store all json objects in a self-referencing table and one to store all json strings in a table that references the json object table, and then a third table to tie the top level containers to an object name.
The schema would look something like this:
Where an attibutes table would be used to store everything that is a json string with references to parent container id:
CREATE TABLE attributes (
    id                  int DEFAULT nextval('attributes_id_seq'::text),
    name                varchar(255),
    container_id        int,
    type                int,
    value_type          int,
    value               varchar(255)
);

The containers table would be used to store all containers in a self-referencing table to create the 'tree' structure:
CREATE TABLE containers (
    id                  int DEFAULT nextval('containers_id_seq'::text),
    parent_container_id int
);

And then a single list of object names that point to the top level container id for the object:
CREATE TABLE object_names (
    id                  int DEFAULT nextval('object_names_id_seq'::text),
    name                varchar(255),
    container_id        int
);

The nice thing about the above structure is it makes for a really simple recursive function to iterate the tree and store attributes and containers.
The downside is it's not relational whatsoever and therefore doesn't help to perform complex relational queries to retrieve sets of information.
The reason I say we should use this is because we have absolutely no reason to select pieces of these objects in a relational manner, the data on each object is only useful in the context of that object and we do not have any situations where we will need to select this data for any reason except rebuilding the object.
However my coworker is saying that we should be using a relational database design to store this, and that each of the 'keyword' attributes should have it's own table (container keyword table, 3 pattern keyword tables, 4 top level keyword tables).
The result is storing these objects in the suggested relational design becomes significantly more complex and requires many more tables.
Note that query speed/efficiency is not an issue because this object/database is for internal use for purposes that are not time-sensitive at all. Ultimately all we are doing with this is creating new 'objects' and storing them and then later querying the database to rebuild all objects.
If there is no benefit to a relational database design then is there any reason to use it over something that allows for such a simple storage/retrieval API?
Is there any significant issues with my suggested schema?
Answer: "we will never need to X" is a rather bold assumption that turns out to be unwarranted more often than you might suspect.  And in fact with tree structures in particular, it is most natural for the requirement to arise to "zoom into a node" and treat that as a tree in its own right for a short time.
EDIT
And in case it wasn't clear why that matters : relational aproaches tend to offer more flexibility because such flexibility is built into the data structure.  Non-relational approaches (typically implying that everything is solved in code) tend to lead to additional rounds of codeshitting once requirements start to evolve.
Comment: Cool thanks for the insight, I can see what you mean by 'zoom into a node', I don't think that will be the case for our situation but it makes sense.


Variable Neighbourhood search (VNS): How to specify the neighborhood structures?

Question: I am new to optimisation and looking into VNS to attempt to apply a meta-heuristic to a MIQP in the form $$\max_x x^TQx$$
subject to: $x_i\in\{0,1\}$,  $\sum_i x_i=C$, where $C$ is an integer.
I don't fully understand how to initialise the VNS algorithm i.e. how to select the set of neighborhood structures $$N_k(x) \  \textrm{for} \ k=1,...,k_{\textrm{max}}.$$
How do I select $N_k(x)$? Could it for example be the number of bits I am prepared to flip in $x$ (e.g. $k=1$ represents 1 bit, $k=2$ represents 2 bits etc.)? Or am I misunderstanding?
Many thanks!
Answer: You cannot flip an odd number of bits and preserve the equality constraint. Instead, let $k$ be the number of bits that flip from $0$ to $1$, and flip the same number from $1$ to $0$.


Extending a projection $S\setminus L\to \Bbb{P}^1$ to the whole cubic surface $S$

Question: Let $S\subset\Bbb{P}^3_\Bbb{C}$ be a nonsingular cubic algebraic surface containing a line $L$. We define the projection $\varphi:S\setminus L\to \Bbb{P}^1$ away from $L$ in the following manner. Take $M=\Bbb{P}^1\subset\Bbb{P}^3$ a line disjoint from $L$. For $P\in S\setminus L$, define $\varphi(P)$ as the only point in the intersection of $M$ and the plane $\Pi$ containing $P$ and $L$.
In Miles Reid's chapters on algebraic surfaces (page $9$), there's the following reasoning for extending the projection $\varphi$ to the whole surface $S$ (I paraphrase):

Let $H=L+F$ be a hyperplane section containing $L$. Computing the intersection numbers we get $HL=1$, $FL=FH=2$, so $H^2=3$ and $F^2=0$. Since the $F$ are effective and disctinct, they must be disjoint, so $\varphi$ is well-defined along $L$ as well".

I do understand the computations of the intersection numbers and also the fact that $F\geq 0$ and $F^2=0$ implies that the linear system $|F|$ is base-point free, which means there is a morphism $S\to\Bbb{P}^n$, where $n=\dim|F|$ (dimension as a projective space).
I still wasn't able to explain 1) why $n=1$ and 2) why the new morphism $S\to\Bbb{P}^1$ given by $|F|$ actually extends $\varphi$.
Answer: Consider the short exact sequence
$$
0 \to \mathcal{O}_S(-L) \to \mathcal{O}_S \to \mathcal{O}_L \to 0.
$$
Twisting it by $H$ one gets
$$
0 \to \mathcal{O}_S(F) \to \mathcal{O}_S(H) \to \mathcal{O}_L(1) \to 0.
$$
The global sections are 4-dimensional for the middle term, 2-dimensional for the right term, and the restriction morphism is surjective, hence the global sections of  $\mathcal{O}_S(F)$ are 2-dimensional.
Moreover, this proves that the linear subsystem in $|H|$ consisting of divisors containing $L$ (which defines the morphism $\varphi$ away from $L$) coincides with the linear system $|F| + L$. If you recall the definition of a morphism given by a linear system you will see that the morphisms of $S \setminus L$ given by these two linear systems coincide.
Comment: To compute global sections of $\mathcal{O}_S(H)$ you can twist the resolution of $\mathcal{O}_S$ on $\mathbb{P}^3$. I wouldn't write $(\ell_1 : \ell_2) = (1 : \ell_2/\ell_1)$. Instead, it makes sense to note that since $L \subset S$ the cubic equation of $S$ can be written in the form $\ell_1 q_1 + \ell_2 q_2$, then on $S$ one has $(\ell_1 : \ell_2) = (q_2 : -q_1)$, so the morphism $\varphi$ can be given by $(q_2 : - q_1)$. Finally, note that $q_1$ and $q_2$ form the basis of $|F|$.
Comment: The linear system $|F|$ consists of effective divisors linearly equivalent to $H - L$. Both $q_1 = 0$ and $q_2 = 0$ are such divisors.
Comment: How did you know the dimension of $H^0(S,\mathcal{O}_S(H))$ is $4$?
Comment: If $L=V(\ell_1,\ell_2)$, where $\ell_1,\ell_2$ are linear forms, then $\varphi=(\ell_1:\ell_2)=\left(1:\frac{\ell_2}{\ell_1}\right)$. Since $F\geq 0$, then $1\in\mathcal{L}(F)$. So I should be able to prove that $\frac{\ell_2}{\ell_1}\in\mathcal{L}(F)$, i.e.  $\text{div}\left(\frac{\ell_2}{\ell_1}\right)+F\geq 0$, right?
Comment: Sasha, but $q_1,q_2$ are polynomials, not rational functions, so how do they belong to $|F|$? And I still can't see how do we associate $q_1,q_2$ to $F$.
Comment: Oh, I see! Thank you!


Block Module jQuery Slider for Homepage

Question: I have a simple jquery slider for the homepage of a website, which works in my static HTML/CSS layouts.
I want to incorporate this front-end mark-up into a block module that will allow an admin to add/edit/remove slides. Is there a good module that already does this that I could hack with to get this functionality. Or even better does anyone know a good tutorial (doesn't have to be for a slider), that shows developing a module where you can add/edit multiple items specific to that block module (separate to the main content); in my case it would be adding/editing slide items to the slider.
Comment: Sorry, I'm not sure I follow what you are asking, mostly because I don't understand what you already do have.
Comment: I have a jquery slider in HTML/CSS, looking to create a block module that will allow edit and update of this.
Answer: From reading your question, I take it you have zero integration with Drupal. You simply hardcode your entire slideshow in a block.
What I would suggest is that you start with creating a new content type, and then apply either Field slideshow or Views slideshow onto it.

Provides a Slideshow formatter for Image fields, using JQuery Cycle plugin.
Compared to Views slideshows, building the slideshow from multiple nodes, this module builds it from a single node, with a multi-valued Image/Media/Field Collection field.

Views Slideshow can be used to create a slideshow of any content (not just images) that can appear in a View. Powered by jQuery, it is heavily customizable: you may choose slideshow settings for each View you create.
Answer: To create a slider u need install this modules (1) Views (2) Views UI (3) Views Slideshow (4) Views Slideshow: Cycle (5) Chaos tools (6) Link (7) Libraries (8) Token (Optional)
First of all you need to create Image Cache with core module named Image Styles to resize your images for slider. Then u need to create new Content type with hidden comments and hidden author and date info. After this you will need to add some fields to this content type:
1) Image Field with this settings

<code>(1) Label: Slider Image
(2) Field: slider_image
(3) Field type: image
(4) Widget (form element): image
(5) Click Save button, and on the field settings page leave default settings and click on Save field settings button.
(6) On the image field configuration settings page you can configure as you wish.
</code>

2)Link Field:

<code>(1) Label: Slider Link
(2) Field: slider_link
(3) Field type: link
(4) Widget (form element): link
</code>

Next you need to create content and upload there your images
After this you will need to create new View, where you can display your slider what ever you want.
Full tutorial you can find HERE

Block Module jQuery Slider for Homepage


A fair die is rolled five times. What is the probability that the largest number rolled is 5?

Question: I was confused how to approach this problem. It is provided in the sample paper for mma of isi masters exam of 2021.
Comment: @DuncanRamage  That is a different question.  In that case, you can use symmetry to conclude that the answer is $1/2$.  Here, you have to subtract the probability that no roll results in a number higher than $4$ from the probability that no roll results in a number higher than $5$.
Comment: @N.F.Taussig Exactly true. I think I've seen this question before on MSE but I have not been able to find it.
Comment: @DavidK  I found this [related question](https://math.stackexchange.com/questions/1696623/what-is-the-expected-value-of-the-largest-of-the-three-dice-rolls).
Answer: The probability the highest number is less than $5$ is $(4 / 6)^5$, since every die roll must be $1, 2, 3,$ or $4$.  The probability the highest number is no greater than $5$ is $(5/6)^5$, since every die roll must be $1, 2, 3, 4,$ or $5$.  Thus, the probability the highest number is exactly $5$ is
$$\left(\frac56\right)^5 - \left(\frac46\right)^5 \;=\; \frac{2101}{7776} \;\approx \;0.27.$$


vector Declaration in c++

Question: I am trying to write a code using c++  for the first time and I found this line:
vector<vector<vector<double> > > h(hist1, vector<vector<double> >(hist2, vector<double>(nb_bins, 0.0)));

I don't understand what does it means, can you help me guys? Thanks.
Answer: Let's unpack it!
vector<vector<vector<double> > >
  h(hist1,
    vector<vector<double> > (hist2,
                             vector<double> (nb_bins, 0.0) ) );

This is a declaration of a variable of type vector<vector<vector<double> > > called h.  h is initialized by calling its constructor, passing in as a first parameter hist1, and as its second parameter a temporary object of type vector<vector<double> >.  This temporary object is in turn initialized by calling its constructor, passing in hist2 as its first parameter and a temporary vector<double> as its second parameter.  This second temporary is then initialized by calling its constructor, passing in nb_bins as its first parameter and 0.0 as its second.
The result is that this ends up acting as a three-dimensional array of dimension hist1 × hist2 × nb_bins, where each value is initialized to 0.0.
That said, if you want to use a 3D array, look into the Boost.MultiArray package, which gives a much cleaner way to do this.
Hope this helps!
Answer: It's a vector of vector of vector of double, something like a tridimensional array of double. See here : http://www.cplusplus.com/reference/vector/vector/

vector Declaration in c++


Plot with multiple categorical predictors and before/after comparison

Question: I have a dataset with 5 categorical variables that relate to before/after numerical data. I need to plot the relationship between the categorical data and the numerical results. Each category relates to a part of the research in which kind_of_measure is related to how the measure was taken, cause_variation_turb and associated_condit are descriptions of human impacts on water quality and kind_particle is the kind of particle that altered water quality. The numerical data (mean_turb_contr and mean_turb_antrop) are compared to show if there was an increase or decrease in turbidity and are used to assess if water quality increased or decreased.
Is there any way to plot all information in a single plot? I have plotted individual plots with before/ after bars but it gave me 5 plots that take too much space. I need to present as much data as possible in the least number of figures and I already have many figures, so it is essential to summarize my results. Any ideas on how can I do this? Is there any graphical way to join categorical variables showing their relation to before/ after information?
Here is an example of my data.

kind_of_measure
cause_variation_turb
associated_condit
kind_particle
unit
mean_turb_contr
mean_turb_antrop

repeat_time
dam_removal

suspended_solids
FNU
39.24
211.19

repeat_time
dam_removal

suspended_solids
NTU
3.93
334.35

repeat_time
dam_flush

suspended_solids
FNU
48.57
1405

repeat_time
dam_flush

suspended_solids
FNU
103.8
203

repeat_time
dam_flush

suspended_solids
FNU
162.7
1506.5

repeat_time
dam_flush

suspended_solids
FNU
78.14
950.7

repeat_time
dam_flush

suspended_solids
FNU
63.2
2285.7

repeat_time
dam_flush

suspended_solids
FNU
50.92
1372.9

repeat_time
sediment_washout
el_nino
suspended_solids
TSS
54
25.2

dif_places
deforestation

suspended_solids
NTU
2.6
3

dif_places
deforestation

suspended_solids
TSS
4.2
5.8

repeat_time
mining_dam_break
copper_gold
tailing
NTU
0.29
116.54

repeat_time
drought

algal_biomass
NTU
2.87
9.11

repeat_time
wetland_restoration
wastewater_effluent
suspended_solids
TSS
3.16
9.46

repeat_time
fire

ashes
TSS
12.92
8.41

dif_places
best_management_practices
cattle_grazing
suspended_solids
TDS
382.32
251.22
Comment: Could you clarify whether the categorical variables are the predictors or the response?
Comment: Either way, I don't think there's a reasonable way to join these variables (there rarely is, whether categorical or continuous). Multiple panels in a single figure would be the standard solution.
Comment: The categorical variables are predictors. They´re a part of a survey about aquatic systems and are site descriptions and/ or causes for turbidity change (before/after comparison)
Answer: I don't see any reasonable way to combine these into a single predictor (there rarely is). That said, with 5 categorical predictors and 2 continuous responses you have just 10 panels. 5 rows of 2 panels (or 2 rows of 5 panels) is quite reasonable if you do not have too many categories in each of the predictors.


Why /Drupal\Core\Form\FormBuilder->renderPlaceholderFormAction is taking so long?

Question: I'm profiling drupal 8 website in New Relic
Report shows me that method:

/Drupal\Core\Form\FormBuilder->renderPlaceholderFormAction

takes ~2sec.
This method is called in:

\Drupal\Core\Render\Renderer->doRender

Code related to execution:
<code>// Build the element if it is still empty.
if (isset($elements['#lazy_builder'])) {
  $callable = $elements['#lazy_builder'][0];
  $args = $elements['#lazy_builder'][1];
  if (is_string($callable) && strpos($callable, '::') === FALSE) {
    $callable = $this->controllerResolver->getControllerFromDefinition($callable);
  }
  $new_elements = call_user_func_array($callable, $args);
  // Retain the original cacheability metadata, plus cache keys.
  CacheableMetadata::createFromRenderArray($elements)
    ->merge(CacheableMetadata::createFromRenderArray($new_elements))
    ->applyTo($new_elements);
  if (isset($elements['#cache']['keys'])) {
    $new_elements['#cache']['keys'] = $elements['#cache']['keys'];
  }
  $elements = $new_elements;
  $elements['#lazy_builder_built'] = TRUE;
}
</code>
Method code:
<code> /**
   * #lazy_builder callback; renders a form action URL.
   *
   * @return array
   *   A renderable array representing the form action.
   */
  public function renderPlaceholderFormAction() {
    return [
      '#type' => 'markup',
      '#markup' => $this->buildFormAction(),
      '#cache' => ['contexts' => ['url.path', 'url.query_args']],
    ];
  }

 /**
   * Builds the $form['#action'].
   *
   * @return string
   *   The URL to be used as the $form['#action'].
   */
  protected function buildFormAction() {
    // @todo Use <current> instead of the master request in
    //   https://www.drupal.org/node/2505339.
    $request = $this->requestStack->getMasterRequest();
    $request_uri = $request->getRequestUri();

    // Prevent cross site requests via the Form API by using an absolute URL
    // when the request uri starts with multiple slashes..
    if (strpos($request_uri, '//') === 0) {
      $request_uri = $request->getUri();
    }

    // @todo Remove this parsing once these are removed from the request in
    //   https://www.drupal.org/node/2504709.
    $parsed = UrlHelper::parse($request_uri);
    unset($parsed['query'][static::AJAX_FORM_REQUEST], $parsed['query'][MainContentViewSubscriber::WRAPPER_FORMAT]);
    return $parsed['path'] . ($parsed['query'] ? ('?' . UrlHelper::buildQuery($parsed['query'])) : '');
  }
</code>
I don't get it at all. This is basic method, no rocket science and 2 sec of execution :(
New Relic output:
Comment: What is telling you that that takes two seconds?
Comment: @Berdir I've added screenshot from New Relic, thanks.
Answer: Pretty sure that report is bogus.
That's just an arbitrary method, not a controller. They somehow identify that as the controller for that request but of course that doesn't make sense. That page lists transactions, so complete requests, not single method calls. So some requests take 2s which it incorrectly identifies as this.
Looks like new relic still can't reliably detect the route/controller for a request. Try our new relic module: https://www.drupal.org/project/new_relic_rpm. It reports the route name for the controller, then you'll see what kind of request this actually is.


Losing the ability to access the editor after switching themes

Question: New installation, even newer user of Silverstripe (V 4.5);
Losing the ability to access the editor with [URL]/admin after switching theme from "SIMPLE" (default) to theme created from scratch after switching in 'theme.yml'. Switching back to 'SIMPLE' brings back the editor.
Did anyone else have this problem?
Answer: Add $Form below $Content, the default $Form is the editor login form.
-resolved-
Answer: Try running the url [site_url]/dev/build?flush=1
Comment: Thanks Hemant,
I found that suggestion too, didn't work though.
Turned out, I didn't put the $Form variable underneath the $Content. In the "simple" default theme, the variable is not in the page.ss script, so I didn't figure it out for quite a while.
Thanks for the suggestion, though. Closing question.


Manipular XML com Javascript

Question: Estou com uma dúvida e já busquei muito e mesmo assim não consegui resolver.
Tenho um XML com uma tag chamada <child id='minhatag'/>.
Preciso fazer com que o javascript faça a leitura dessa tag e consiga me retornar o valor do ID da tag child para que o valor eu consiga colocar em um botão, porque minha tela terá varios botões que serão apresentados de acordo com os valores das "Child's ID's".
OBS: Vale lembrar que serão varias childs por exemplo:
<child id='child1'/>
<child id='child2'/>
<child id='child3'/>

E o XML ficará na mesma estrutura de pastas do código ou seja não vai ser um acesso via URL, pelo menos não a princípio.
Comment: Isso esta junto com os elementos HTML? é uma result de uma chamada AJAX?
Comment: Mas qual o valor do `child`?
Comment: @Guilherme Lautert não os valores no CHILD estão em um arquivo separado.
Comment: @MagicHat a child não tem um valor em si eu preciso ter o retorno do valor do ID da child.
Answer: Você pode utilizar o código abaixo para fazer isso, porém precisa de um pai para cosneguir fazer o parse:

var xml, parser, xmlDoc;
text = "<children><child id='child1'/>" +
       "<child id='child2'/>" +
       "<child id='child3'/></children>";

parser = new DOMParser();
xmlDoc = parser.parseFromString(text, "text/xml");
xmlDoc.getElementsByTagName("children")[0].childNodes.forEach(function(value) {
    console.log(value.id);
});
Comment: mas como faria no caso pra acessar um xml que está em um arquivo dele, porque dessa forma que você apresentou ele está puxando itens fixos dentro do próprio script na index certo ? Seria como se ele estivesse em um XML chamado "child.xml" por exemplo e todo o código estará lá.
Comment: esqueci mesmo de comendar eles tem um pai, no caso o  basicamente
Comment: Sem problemas, só trocar o seletor do pai de childs para children. Foi até uma falha do meu inglês rs
Comment: e quanto a parte do acesso a um arquivo xml e não dentro da própria estrutura do script no js ?
Comment: Aqui está uma pergunta com uma ótima resposta para de ajudar. Já que o foco dessa pergunta não foi como ler a partir de um arquivo: [https://stackoverflow.com/questions/14446447/javascript-read-local-text-file](https://stackoverflow.com/questions/14446447/javascript-read-local-text-file)
Comment: valeu com sua resposta consegui um resultado satisfatorio para questão, vou abrir outra pergunta pra um outro problema que surgiu. Obrigado.
Answer: Tipo assim:

var childs = document.getElementsByTagName("child");
for (var i = 0; i < childs.length; i++) {
  console.log(childs[i].id);
}
    <child id='child1'/>
    <child id='child2'/>
    <child id='child3'/>

Manipular XML com Javascript


Erro: string indices must be integers em loop

Question: boa noite, estou precisando fazer um for para uma requisição baseado em um excel, com isso estou fazendo assim:
df1 = pd.read_excel('D:/repositorio/python/leitura.xls')
count = 0
for y in df1['EAN']:
        data ="{\"productCode\":\"EAN%d\"}" % (y)

Funciona corretamente, mas preciso usar outros campos do Excel Po, e estou tentando fazer assim:
df1 = pd.read_excel('D:/repositorio/python/leitura.xls')
count = 0
for y in df1:
        data ="{\"productCode\":\"EAN%d\"}" % (y['EAN'])

Só que assim esse erro está dando:
TypeError                                 Traceback (most recent call last)
C:\Users\OTACIO~1.BAR\AppData\Local\Temp/ipykernel_11848/1268633844.py in <module>
     19 for y in df1:
     20
---> 21         data ="{\"productCode\":\"EAN%d\"}" % (y['EAN'])
TypeError: string indices must be integers

Poderiam me ajudar com a forma correta de fazer?
Answer: Você deve usar a função iterrows do dataframe do panda.
Faça algo como:
for index, row in df1.iterrows():
data ="{"productCode":"EAN%d"}" % (row['EAN'])


Eclipse RCP CoolBar Action FORCE_TEXT

Question:    </extension>
       <extension
             point="org.eclipse.ui.menus">
          <menuContribution
                allPopups="false"
                locationURI="toolbar:com.*****.*****.ui.main.toolbar?after=workbenchActions">
             <command
                   commandId="org.eclipse.ui.file.save"
                   disabledIcon="icons/save24x24_disabled.png"
                   icon="icons/save24x24.png"
                   label="Save"
                   mode="FORCE_TEXT"
                   style="push">
             </command>
          </menuContribution>
   </extension>

I'm pointing to the workbench's Save command using a menu command, because I want to change the icon and force the text underneath it.
Icon works fine, but the text won't show (it should say Save below the icon, because I set the mode to FORCE_TEXT and have a label present).
Is it a bug, or a limitation of the framework?
Answer: If you are running Eclipse 4.2 or 4.3 this looks like Eclipse bug 399065

Eclipse RCP CoolBar Action FORCE_TEXT


What does "Kuratowski's theorem" refer to in the context of dense linear subspaces being Borel?

Question: Kuratowski was a busy man who showed many results in topology and functional analysis, so when a writer says that some result follows from ''Kuratowski's theorem", it could apply to many different ones.
I am currently studying "Stochastic Partial Differential Equations: An Introduction", by Wei Liu and Michael Röckner and in Chapter 4, they introduce the Gelfand triple $\left(V,H,V^*\right)$ and sketch the situation where they work in.
For this Gelfand triple (or evolution triple), we have a reflexive Banach space $\left(V,\|\cdot\|_{V}\right)$ and a Hilbert space $\left(H,\langle\cdot,\cdot\rangle_{H}\right)$, such that $V \subset H$ and $V$ can be continuously and densely embedded in $H$. It also follows that $H^*$ can be densely embedded into $V^*$, by restricting the functionals on $H$ to $V$ (call this (isomorphic!) map $\rho$). As the Hilbert space $H$ and its dual are isomorphic by the Riesz representation map $\Phi$, we can identify $H$ and its image under the map $\rho\circ\Phi$; we will write $\bar{H}$ for $\rho(\Phi(H))$.
Then, they claim that by Kuratowski's theorem, we know that
$$
V \in \mathcal{B}(H) \quad \text{ and } \quad \bar{H}\in\mathcal{B}\left(V^*\right)
$$
but I don't know which theorem they refer to and that is my question. I've scoured the internet to find what they mean, but my attempts have not yet been fruitful, so I was wondering if any of you could help me out.
Comment: I might be inclined not so much to look for a theorem by Kuratowski, but for a book on PDEs written by authors who had more respect for their readers' time.
Comment: None at all -- this is completely outside my area of expertise. But it's a general rule: avoid authors who don't take *your* time seriously.
Comment: @johnhughes is certainly right about generally avoiding texts which send you on snipe hunts. With that said, it's slim pickings for stochastic PDE texts, but I prefer Prevot and Roeckner as an elementary text.
Comment: @NormalHuman: Excuse me, I forgot to include that $\mathcal{B}(H)$ is the Borel-$\sigma$-field of $H$.
Comment: @NormalHuman And I completely forgot to answer your question: the way this is set up is to show the existence of solutions to stochastic differential equations. They first assume the solutions are $V^*$-valued, but that they really are $\bar{H}$-valued, so can be translated back to being $H$-valued. That is essentially what it comes down to.

If you think: what is this bloke rattling about, then I agree that my comment might not be particularly helpful.
Comment: @JohnHughes Any recommendations?
Comment: @JohnHughes  Ah, that's a bummer. Thanks for your quick response anyway!
Answer: I think the authors refer to the following theorem:

Theorem. Suppose $X, Y$ are Polish spaces and $f : X \to Y$ is continuous. If $A \subset X$ is Borel and $f_{|A}$ is injective, then $f(A)$ is Borel.

It is a theorem of Lusin and Souslin, as stated in Classical Descriptive Set Theory by Alexander Kechris, Theorem 15.1 on page 89. Sometimes it's attributed to Lusin alone. I haven't been able to connect Kuratowski to this result.
Every separable Banach space is a Polish space, and the embeddings $V\subset H$ and $H^*\subset V^*$ are continuous injective maps. So one needs to assume that $H$ (equivalently, $V$) is separable, which I believe is a standard assumption when considering Gelfand triples.
Comment: Great find! Did it take long?

(I indeed forgot to mention that these spaces were assumed to be separable.)
Answer: As a complementary of the previous answer, Kuratowski proved a similar result to Souslin's for Borel measurable mappings (not only continuous mappings) in page 489 of his book "Topology: Volume I".


Integral of $\frac{1}{y-x}$ in the direction of a line.

Question: $\displaystyle{\int_{C}\frac{dC}{y-x}}$ where $C$ is the line connecting $(0,-2)$ and $(4,0)$.
Here's the working I've done: the line is equivalent to $y=\frac{1}{2}x-2$ hence the integral $\displaystyle{\int_{C}\frac{dC}{y-x} = \int_{0}^4\frac{1}{-2-\frac{1}{2}x}\,dx}$. Is this method correct, I can complete the computation however I'm new to these sorts of integrals so I'm not 100% confident. Any help is greatly appreciated, thank you!
Answer: That is not correct. You need to integrate the function along the curve and not just along $x$.
$y = \frac{x}{2} - 2 \implies \frac{dy}{dx} = \frac{1}{2}$
So the integral,
$ \displaystyle \int_C \frac{ds}{y-x} = \int_0^4 \frac{1}{-2 - x/2} \sqrt{1 + \left(\frac{dy}{dx}\right)^2} ~ dx$
$ \displaystyle  = \frac{ \sqrt5}{2}\int_0^4 \frac{dx}{-2 - x/2} = - \sqrt 5 \ln 2$
Or you could parametrize the curve as,
$r(t) = (0, -2) + (1, \frac{1}{2}) t, 0 \leq t \leq 4$
$r'(t) = (1, \frac 12), |r'(t)| = \frac{\sqrt 5}{2}$
$y = - 2 + \frac{t}{2}, x = t$
Now the integral is $ ~ \displaystyle \int_0^4 f(r(t)) ~ |r'(t)| ~ dt ~ $ and you get the same answer as earlier.
Answer: You are almost there. Just keep in mind that $dc \ne dx$.
Comment: great! I simply got -2ln(2) which seems to be correct. Thank you for the reminder.


apache port number

Question: For each development sites I want to have a unique port number. For instance, domain.com:1234
This is what I have in my httpd.conf file. After restart the page domain.com:1234 is not showing in the browser. Is there anything else that I need to do besides what I have already done to make this work?
Listen *:1234

<VirtualHost *:1234>
DocumentRoot /var/www/dev_sites/test
ServerName domain.com
</VirtualHost>

It looks like if I go to my local hostname (kk.local:1234) it shows. Is there some sort of dns that I need to do? I really don't want to go into godaddy everytime I add a development site. Is there a way around that?
Comment: What does it says `netstat -tulnp` ? Do you see anything listening on port 1234 ?
Comment: Looks like it is...`tcp        0      0 :::1234                     :::*                        LISTEN      -`
Comment: Does `domain.com` resolve to the correct address on the client? Does the browser show an error message? Does the website access show in your Apache log files?
Comment: @AnsgarWiechers - domain.com resolves correctly along with just entering the ip of the machine. Also my local hostname:port works. domain.com:1234 and ip:port does not. It is like it doesn't allow external access or something. Which makes me think firewall but SELinux and Firewall are disabled.
Comment: Try `telnet domain.com 1234`. If you get `connection refused` or a timeout, something is blocking access to that port. Use `tcptraceroute` (on Windows [`tracetcp`](http://tracetcp.sourceforge.net/) to find out where. If `telnet` can establish a connection, you should see something in your Apache logs.
Answer: Adding the name/address mapping to your client's hosts file should get you around the name resolution problem in development scenarios. There's also the option to set a wildcard record in DNS if your DNS provider allows it. As soon as the thing goes beyond developer scope I'd strongly recommend setting up proper DNS resolution for it, though.
Comment: I want it to be accessible to the public so I'm trying to avoid the hosts file.
Answer: The ServerName should not include the port number.  In your example, just make it "domain.com" for every VirtualHost.  ServerName directives do not need to be unique in your situation where you have each VirtualHost on a different port.  You also don't need the NameVirtualHost because you're doing virtual hosting by port (although it's not harmful to include).
As a troubleshooting step, make sure IPTables is fully disabled (assuming this is Linux), and verify that by doing "iptables -L -n -v"; look for each table to be empty.  You might also make sure SELinux is disabled; see your distro's documentation for how to do that properly, as the procedure varies.  If either of those is shown to be the issue, you can either choose to keep them turned off, or configure them correctly to allow Apache to listen on these ports.
Here is an example from the Apache 2.2 documentation about port-based virtual hosting:
http://httpd.apache.org/docs/2.2/vhosts/examples.html#ipport
Comment: I fixed the ServerName. I added the NameVirtualHost (even though you said it wasn't required). Iptables each table is empty. Firewall and SELinux are disabled. I'm stumped.
Answer: Is there a firewall like iptables that is blocking it?  If so, turn it off or better yet add a rule to allow 1234 through.
Comment: @Michael_Beattie - firewall has been off. Is there a command line to test it? Would it still Listen in the netstat if it was being blocked by the firewall?
Answer: Do you have this directive in your configuration:
NameVirtualHost *:1234

If you don't your VirtualHost will never be used.
Comment: added this but no improvement.

apache port number


Consume DirectExchange messages using routing key and exchange in spring boot

Question: Am trying to consume the message from exiting queue which is of type Direct Exchange(created with the help of exchange and routing key). I have only the exchange name and routing key and not the queue name. There were support for plain Java, but there was no place where I can find it for Spring boot.
@RabbitListener
    @RabbitHandler
    public void consumeMessage(Object message) {
        LOGGER.debug("Message Consumed.... : {}", message.toString());
    }

How can I consume messages  with routing key and exchange name not the queue  name as @RabbitListener asks for queue.
Comment: With a direct exchange, the routing key is the queue name.
Comment: @theMayer ```@RabbitListener(queues = "${routing.key}")
 @RabbitHandler
 public void consumeMessage(Object message) {
  LOGGER.debug("Message Consumed.... : {}", message.toString());
 }``` This is giving a exception 404 - `reply-code=404, reply-text=NOT_FOUND - no queue`
Comment: Have you declared the queue?
Answer: Consumers consume from queues not exchanges. You must bind a queue to the exchange with the routing key.
EDIT
There are several ways to automatically declare a queue on the broker.
    @RabbitListener(bindings =
        @QueueBinding(exchange = @Exchange("myExchange"),
            key = "myRk", value = @Queue("")))
    public void listen(String in) {
        System.out.println(in);
    }

This will bind an anonymous queue (auto-delete) which will be deleted when the application is stopped.
    @RabbitListener(bindings =
        @QueueBinding(exchange = @Exchange("myExchange"),
            key = "myRk", value = @Queue("foo")))
    public void listen(String in) {
        System.out.println(in);
    }

Will bind a permanent queue foo to the exchange with the routing key.
You can also simply declare #Bean s for the queue, exchange and binding.
See Configuring the broker.
Comment: I was supplied only with the Exchange Name and Routing Key not the queue name.
Comment: So you need to bind a queue to that exchange with the routing key and then consume from that queue.
Comment: Thanks @Gary Russel.
One more question - Do we have any provision to keep on retrying for a RMQ connection if there were any interruption in the connnection or channel?
Comment: You should really ask a new question each time - new questions in comments don't help people to find answers. On the consumer sider, the listener container will attempt to reconnect every 5 seconds (by default). On the producer side you can add a suitably configured `RetryTemplate` to the `RabbitTemplate`.
Comment: Thanks and it works.... :) From next time I will post it as a question. @gary-russell


defining node multicolumn layout with twig template

Question: Sometimes I get lost in all the options I have on the drupal platform.
I am currently creating a site for a choir. I want them to be able to add new concerts. There has to be a page for every concert. I want to use a multicolumn layout for those concertpages. This layout I want to define using a twig template. Each concert would get a standard layout at creation.
I want to be able to override that template for each individual concert. Once the grafic design for promotion material is finished the page has to be inline with the grafic design. But it still has to be editable like a normal drupal-page.
I thought about doing that with a content type. But can I theme that in a multicolumn layout using twig? It seems like I only have a {{ content }} variable in twig.
Am I missing something? It seems like a custom entity would be a better solution since I can define a render array and add the fields in different variables wich I can then use in my twig file.
Maybe I got it all wrong, this is my second drupal project and I'm still learning to find the best way of getting things done.
Matt.
Comment: Custom theming stuff like this is usually a road to hell with regards to maintenance and changes over time, just use Display Suite.
Comment: Totally. Look at what you can do with display suite and layout plugin before you reach for custom templates. Particularly if you want to be able to override for each concert, as Display suite gives you some UI options for picking layouts and applying classes.
Answer: Make a copy of node.html.twig and rename the copy to node--[content-type-name].html.twig which goes inside your theme's template folder.
Then in node--[content-type-name].html.twig find and delete {{ content }} and instead in there you put
{{ content.title }}
{{ content.body }}
{{ content.field_name }}

This is how you can render your fields individually.
Then, you can wrap them inside an id or class divs. Ex:

{{ content.field_name }}

{{ content.field_name_other }}

Comment: @Pierre.Vriens [right](http://www.classicrockhistory.com/wp-content/uploads/2015/12/Kiss_202.jpg)
Comment: man... can't believe it is that simple. But that was my missing link. Can I ask just one more question? If I have a field that consists of multiple values. Can I also loop through those?

say I have a field with multiple dates. can I have those rendered individually too?
Comment: @DragonEye funny, I just answered that in the [newest questions](http://drupal.stackexchange.com/questions?sort=newest), the one below yours. Anyhow, here is the direct link [How To Wrap Multiple Content Field Items In Li Tag](http://drupal.stackexchange.com/questions/214372/how-to-wrap-multiple-content-field-items-in-li-tag)
Comment: **K**eep **I**t **S**uper **S**imple, right?


Como ler um número n positivo em ordem crescente e hexadecimal?

Question: Estou com problema em uma questão e não consigo resolve-la.
O meu problema é referente de como inserir esses valores e organiza-los da forma igual o exemplo abaixo.

Crie um programa em C/C++ lê um número positivo n e imprime, em
  ordem crescente, todos os números hexadecimais com n nibbles. (1
  nibble = 4 bits ou 1⁄2 byte)
Restrições adicionais:

Não pode trabalhar com números no formato decimal e convertê-los para hexadecimal.
A solução deve adotar, obrigatoriamente, um vetor para armazenar os nibbles.
A solução pode ser recursiva ou não.

Exemplo 1:

Exemplo 2:

MEU CÓDIGO ATÉ AGORA:
#include <stdio.h>
#include <stdlib.h>

/*
Crie um programa em C/C++ lê um número positivo n e imprime,
em ordem crescente, todos os números hexadecimais com n nibbles. (1 nibble = 4 bits ou 1⁄2 byte)

Restrições adicionais:
1. Não pode trabalhar com números no formato decimal e convertê-los para hexadecimal.
3. A solução deve adotar, obrigatoriamente, um vetor para armazenar os nibbles.
4. A solução pode ser recursiva ou não.
*/
int main (int argc, char* argv){
    unsigned short int n = 0;

    painel_quantidade_n(n);
    ordem_crescente();

    /*
    int hex = 0xFF;
    printf("Valor inteiro: %i \n", hex);
    printf("Valor hex: %x \n", hex);
    printf("Valor hex (maiusculo): %X \n", hex);
    printf("Valor hex (4 casas): %4x \n", hex);
    printf("Valor hex (Completar com zeros): %04x \n", hex);*/

    return 0;
}

int painel_quantidade_n(int n){
    printf("DIGITE A QUANTIDADE DE NIBBLES:\n");
    scanf("%d", &n);

    if(n < 0){
        printf("OPS ... VOCE DIGITOU: (%d) NIBBLES... TENTE COM UM NUMERO POSITIVO !\n\n", n);
        n = 0;
        painel_quantidade_n(n);
    } else {
        return n;
    }
}

void ordem_crescente(){
    int nibbles[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f};
    int tam = (sizeof(nibbles) / sizeof(nibbles[0])), tmp = 0;

    for (int i=0; i<tam; i++){
        if(nibbles[i]>nibbles[i+1]){
            tmp = nibbles[i+1];
            nibbles[i+1] = nibbles[i];
            nibbles[i] = tmp;
            i = -1;
        }
    }
    printf("\n*IMPRIME ORDEM CRESCENTE*\n");
    for(int i=0; i<tam; i++){
        printf("%04X\n", nibbles[i]);
    }
}

Answer: Em painel_quantidade_n(int), no lugar onde está painel_quantidade_n(n);, fazer return painel_quantidade_n(n);. De preferência, mudar a assinatura da função para int painel_quantidade_n(void)
Em ordem_crescente(), fazer:
void ordem_crescente(int n)
{
    int nibble[n];
    char printer[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                       'A', 'B', 'C', 'D', 'E', 'F' };
    int i, j;
    int vaiUm = 0;
    int fim = (n > 0) ? 0 : 1;

    // Zera nibbles.
    for (i = 0; i < n; ++i)
    {
        nibble[i] = 0;
    }

    do
    {
        // Mostra o numero atual;
        for (j = n - 1; j >= 0; --j)
        {
            printf("%c", printer[nibble[j]]);
        }
        printf("\n");

        // Incrementa o nibble menos significativo, de um.
        for (j = 0, vaiUm = 0; j < n; ++j)
        {
            nibble[j] += (j == 0) ? 1 : vaiUm;

            vaiUm = nibble[j] / 16;

            if (vaiUm)
            {
                nibble[j] %= 16;
            }

            if (vaiUm && j == n - 1)
            {
                // Todos os numeros foram mostrados. Fim do programa.
                fim = 1;
            }
        }
    } while (!fim);
}

Comment: Nossa cara, parabéns. Mandou muito bem! Irei analisar o seu código e aprender com o mesmo.


Hospedar Projeto ASP.NET no IIS na Própria Máquina

Question: Senhores, boa tarde.
Estou desenvolvendo uma aplicação em ASP.NET C#, e gostaria de hospedar esta aplicação no IIS da minha máquina.
A minha máquina é um windows 7, com IIS 7. Minha internet não é IP fixo, teria que configurar o roteador para aceitar acesso externo.
Gostaria de saber o que devo fazer para conseguir hospedar o meu projeto na minha própria máquina.
Alguém me ajuda?
Answer: Não sendo IP fixo, o jeito é usar um serviço de DNS dinâmico como o NO-IP ou Dyn DNS. A maioria dos roteadores já permite a configuração de um desses serviços direto pelo seu utilitário de configurações internas. Essa configuração muda de roteador para roteador, mas geralmente essa basta fornecer seu usuário e senha para que o roteador consiga informar ao serviço de DNS dinâmico quando há uma mudança de IP.
Além disso, no seu roteador, você terá que abrir a porta na qual o seu site estiver rodando (Port Forwarding). Essa configuração muda de roteador para roteador também, mas você terá que informar qual será o IP da máquina e a porta interna (na qual o IIS está rodando) e qual a porta externa (a porta que as máquinas externas à sua rede irão usar). Outro ponto importante é no seu roteador deixar um IP fixo amarrado com o MAC Address da máquina do IIS, de forma a evitar que o DHCP atribua um IP diferente a ela daquele configurado no Port Forwarding.
Também terá que abrir qualquer porta utilizada no Firewall do Windows e/ou do roteador se houver.
Comment: Marcus, tudo bem? Será que você pode me dar uma mãozinha para que eu possa configurar meu computador? Não sou muito bom quando é coisas relacionadas a segurança / infra, gosto mais é de desenvolver mesmo... Caso você queira / pode me ajudar, meu skype é: dimension.ds

PS: Quando eu tiver resolvido este problema, compartilho aqui pra todos!
Comment: To sem acesso ao skype no momento, quando eu tiver disponível, se você já não tiver solucionado, eu te chamo.
Comment: Brother, eu ainda não mexi... Peguei um DNS pra mim com o NO-IP, mas apenas isto... Não tenho mt confiança em mexer nesta parte, por isto posso te aguardar?
Comment: Liberei a porta no roteador, liberei no firewall do windows, criei a conta no no-ip, liberei a porta no modem e ainda continua bloqueado... tenho que liberar em mais algum lugar? To meio perdido ainda...
Comment: Acontece algum erro ou só não acessa?
Comment: Então, tentei acessar por um site que testa se a porta está aberta ou não, e ele sempre da closed... realmente não sei mais o que fazer
Comment: Qual porta está usando? Alguns provedores de internet bloqueiam determinadas portas.
Comment: To setando a porta 10000 como public e 80 como private