what can we say about $G(.)$?

Question: Given $c \in R$, a deterministic probability density $f(x)$ and its cumulative distribution  $F(c)$, what can be said about $G(c)$ where:
$G(c)=\int f(x)F\left( x+c\right) dx $
The question specifically is:
A) Whether $G(x)$ is concave or convex in $c$?
B) Whether $G(0)=0$ (i.e. $G(c=0)=0.5$)?
C) The sign of the first and second order derivatives wrt $c$.
Any suggestion will be highly appreciated.
Comment: "Cumulative density" is an oxymoron: the word "cumulative" contradicts the word "density".  I presume you mean the cumulative distribution function.  That's what you ought to write.
Comment: you are right, I got it wrong
Answer: There is not enough information to answer all of your questions; it depends on the behaviour of $f$. Perhaps useful is the observation that:
$$F(x) = \int_{-\infty}^x f(y)\ \mathrm dy, G(c) = \int_{\Bbb R}\int_{-\infty}^{x+c} f(x)f(y)\ \mathrm dy \mathrm dx$$
Assuming a sufficiently smooth density $f$ is used, we also have:
$$G'(c) = \int_{\Bbb R} f(x)f(x+c) \ \mathrm dx$$
Since $f(x) \ge 0$, $G'(c) \ge 0$ for all $c$. Note that it is not even a priori clear that this integral will exist.
Upon differentiating this expression again we get a term $f'(x+c)$ which can behave in arbitrary ways. Noteworthy is that since $0 \le F(x) \le 1$ for all $x$, we must have $0 \le G(c) \le 1$ for all $c \in \Bbb R$.
Now let us look at the domain of the double integration for $G(c)$. We have that it is:
$$\{(x,y) \in \Bbb R^2: y \le x + c\} = \{(x,y) \in \Bbb R^2: x \ge y - c\}$$
Thus we can rewrite the integral to:
$$\int_{\Bbb R} \int_{y - c}^\infty f(x)f(y) \ \mathrm dx \mathrm dy$$
but since $x,y$ are dummy variables, this is the same as:
$$\int_{\Bbb R} \int_{x - c}^\infty f(x)f(y) \ \mathrm dy \mathrm dx$$
If $c = 0$, we obtain:
$$2 G(0) = \int_{\Bbb R} \int_{-\infty}^x f(x)f(y) \ \mathrm dy \mathrm dx + \int_{\Bbb R} \int_x^\infty f(x)f(y) \ \mathrm dy \mathrm dx = \int_{\Bbb R} \int_{\Bbb R} f(x)f(y) \ \mathrm dy\mathrm dx = 1$$
Comment: won't it be possible to tell about the sign of the derivatives and the value of the function at $c=0$ with the information already provided? The PDF and CDF are not explicitly defined, as you mentioned they satisfy the general features of such functions.
Comment: For the derivative $G''(0)$ we can observe $f(x)f'(x) = \dfrac12 (f^2)'(x)$ to obtain that $G''(0) = \displaystyle \frac12\left(\lim_{x \to \infty} f^2(x) - f^2(-x)\right)$. It may be that you are allowed to assume this is zero.
Comment: I cannot thank you enough. I missed one point, though. I couldn't understand what exactly does "$x,y$ are dummy variables" mean and how it lead to that equivalence.
Comment: It means that replacing, say, $x$ consistently with another symbol (e.g. $\xi$) wouldn't influence the meaning of the expression. I employed it to interchange the symbols $x$ and $y$ everywhere. PS: You may thank me by accepting or upvoting the answer :).
Comment: I will be glad to do that, may you tell me how to. I am a new user of this site.

what can we say about $G(.)$?


Including a baseline covariate in a linear mixed-effects model

Question: I have a question on modelling a big data set (about 5000 subjects). I want to model a random intercept+slope, many of the subjects have only two observations (baseline and one follow-up), but some have more observations.
I want to include baseline as a covariate and I am wondering whether I have to remove the observations in t=0 or if I can use them "twice" by leaving them in the data set but also using them for estimating the coefficient of baseline...
hopefully my problem became clear!
The second thing concerns the scaling of the variables- I am using R and just implementing it in the formula by scale(Time), scale(Baseline) etc. However, I am a bit confused about interpreting the results, would it be better to somehow do scaling by hand in advance?
Thanks a lot!
Answer: If you are going to include the value of your outcome at baseline as a covariate, then indeed, you should not also leave this baseline value in the response variable.
Nonetheless, if you are going to fit a mixed model, you are not required to include the baseline value as a covariate. Especially when you have more than two measurements, doing so implies that the baseline value is equally correlated with all subsequent measurements, which is often not the case.
Comment: Thanks a lot for your reply! Actually the baseline covariate was chosen because we are interested in showing that this value has a large impact on the outcome. However, if we remove the baseline value from the response as it would be technically correct, the model, incorporating a random slope, can't be fit anymore as there are numerous subjects with only one observation. So you would recommend to remove the baseline covariate instead? But how can we then interpret the effect of this baseline value on the response?
Comment: @Dimitris Rizopoulos I have the same question can you perhaps explain it more? is it correct to adjust for baseline if you also include baseline (t = 0 ) in your response in linear mixed model?
Comment: @Frank Harrell your comment is valuable.


SmartScreen (or other) blocking legitimate software?

Question: We have Symantec Wise Package Studio to build simple custom MSI files (Yes I know the product is beyond end-of-life but for our needs it serves it's purpose)
It used to work fine but now when we try to run it , the main executable "PackageStudio8.exe" gets blocked by something which seems to be SmartScreen maybe?
<code>Translation : This application has been blocked for your protection.
An administrator prevents you from running this application. To know more, contact the administrator.
</code>

Could it be some kind of GPO I don't know about?
Based on web findings I tried setting the following values :
<code>[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer]
"SmartScreenEnabled"="Off"

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\System]
"EnableSmartScreen"=dword:00000000
"ShellSmartScreenLevel"=-
</code>
But it doesn't change anything, it still gets blocked and that window still appears. Turning off SmartScreen (disabled) in the Windows 10 GUI still doesn't make it go away.
Interesting thing I noticed is if you open a shell (cmd or powershell) AS AN ADMINISTRATOR and run the exe, it runs fine and everything works. So for now we make do by running it as administator, but it's not ideal.
What gets bypassed when you run as admin and how can I find and adjust what creates this prompt?
Much appreciated.
Comment: Turns out it's UAC actually. I found out that the only way to get rid of that prompt is to completly disable UAC for example :

 HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System  (set value ' EnableLUA' to 0)

but of course it's a security risk.

I guess the safer way is to run it as administrator simply, instead of getting rid of UAC completly just for that program!

Wondering why UAC blocks it though? Is it because the app has "EDITOR/PUBLISHER : UNKNOWN" ?
Answer: Turns out it's UAC actually. I found out that the only way to get rid of that prompt is to completly disable UAC for example : HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System (set value ' EnableLUA' to 0) but of course it's a security risk. I guess the safer way is to run it as administrator simply, instead of getting rid of UAC completly just for that program! Wondering why UAC blocks it though? Is it because the app has "EDITOR/PUBLISHER : UNKNOWN" ?


Drupal Commerce add to cart is no longer working for anonymous users

Question: I just updated to Commerce Kickstart 7.x-2.52 and add to cart is no longer working for anonymous users. It shows the success add to cart message but nothing is added to the cart. If I log in it works fine. I've tried:

I checked out and UID 0 is still in the DB
Disabled honeypot module
emptied the cache_from table
enabled "disable SQL rewrite" on the cart view
check permissions for the anonymous user
cleared the cache

UPDATED
The order entity is being created but nothing shows in the cart.
Answer: Commerce Kickstart added these lines to the /profiles/commerce-kickstart/.gitignore which prevented new files from being added to git and thus not getting pushed to production.
libraries
modules/contrib
themes/contrib
https://www.drupal.org/project/commerce_kickstart/issues/2937535


$X$ metric separable then $C(X)$ separable

Question: Is it true, that if $X$ is a separable metric space, then the space of all continuous functions on $X$ with the supremum metric is also separable?
Comment: I don't think it necessarily is. Consider the discrete metric space on $\Bbb N$. Then the set of bounded continuous functions is the space of bounded sequences $\ell^{\infty}$ which, if I remember correctly, is not separable.
Comment: See http://mathoverflow.net/questions/118442/reference-for-x-compact-c-bx-separable-x-metric-space
Answer: No. Consider triangle-shaped function
$$
\varphi(x)=\max(1-2|x|,0)
$$
then for each binary sequence $s:\mathbb{N}\to\{0,1\}$ we define
$$
f_s(x)=\sum\limits_{n=1}^\infty s(n)\varphi(x-n)
$$
One can show that $\{f_s:s\in\{0,1\}^\mathbb{N}\}$ is uncountable set of functions with the property
$$
s'\neq s''\implies \Vert f_{s'}-f_{s''}\Vert_{C(\mathbb{R})}\geq 1
$$
This implies that $C_b(\mathbb{R})$ is not separable.
Comment: Thanks very much, I'm asking because I read answer to this question http://at.yorku.ca/cgi-bin/bbqa?forum=ask_a_topologist_2008;task=show_msg;msg=1613.0002 and it seems to me that the compactness is used only to show that the base for X is countable, so separability of X should be sufficient to prove my original proposition (which you disproved), what am I missing?
Comment: @Josef: The linked post applies Stone-Weierstrass to deduce density. This theorem needs compactness for $C(X)$ or local compactness for the space $C_0(X)$ of functions vanishing at infinity. A further point you are missing is that the sup-metric is not really defined on all of $C(X)$, but on the bounded functions only.
Comment: @Martin: Aaaa, that explains it. Thanks very much. So in the case when X is compact, the proposition holds. I found it prooved also in a book by R. M. Dudley, but the proof seemed a bit more complicated. To the second remark, I think on a compact space all continuous functions must be bounded so I guess it shouldn't be a problem there, but you were right I was missing that in the more general case.  http://course.zjnu.cn/hnc/shibian/Dudley-Real-Analysis-and-Probability.pdf - Corollary 11.2.5


mysql database how to select column with repeated entires after inner join

Question: I have a database with 3 tables

article with the fields: id: int name: varchar(255) text: text
tag with the fields: id: int name: varchar(255))
article_tag with the fields: id: int article_id: int (foreign key =>
  article.id) tag_id: int (foreign key => tag.id)

I want to be able to look for articles associated with multiple tags.
If I do:
SELECT article.name FROM article
JOIN article_tag ON article.id = article_tag.article_id
JOIN tag  ON tag.id = article_tag.tag_id
WHERE tag.name  IN ('science', 'technology', ... );

I get back every article*(the number of tags it has); which was expected.
My question: is there a way to refine it so that it lists in descending order of frequency of article.id (with the effect being the more requested tags that it matches the higher it is in list) and or so that it only returns records that match all tags (number of occurrences in result = number of tags).
Thanks, and sorry this question wasn't better formatted
Answer: Get the count of repeated articles and order them
SELECT article.name ,COUNT( article.name) AS acount FROM article
JOIN article_tag ON article.id = article_tag.article_id
JOIN tag  ON tag.id = article_tag.tag_id
WHERE tag.name  IN ('science', 'technology', ... )
GROUP BY article.name
ORDER BY acount DESC

Answer: If I understand the question correctly, this should do the trick:
SELECT
  article.id,
  article.name,
  COUNT(*) AS TagCount
FROM article
JOIN article_tag ON article.id = article_tag.article_id
JOIN tag  ON tag.id = article_tag.tag_id
WHERE tag.name  IN ('science', 'technology', ... )
GROUP BY
  article.id,
  article.name
ORDER BY
  TagCount DESC


How to run JSP files on Android and iOS browsers?

Question: I tried to run JSP files on my Android, but it is showing this message:

Error loading the web page

How can I make it work on smartphones?
Answer: I feel you can't run JSP pages on smartphones. Not only on smart phones and also in any normal browser without getting translated to html
Comment: So how can I translation it to html?
Comment: you can deploy that in server like tomcat etc and then call the URL from any desktop/mobile browser
Comment: you cant do it manually JSP is dynamically generated web pages based on HTML, XML, or other document types. Any browser doesnt understand JAVA code


How can I get $\lim2^na_n$? : $a_{n+1}=\frac{\sqrt{a_n^2+1}-1}{a_n}$

Question: How can I get $\lim2^na_n$, for $a_1=1$ and $a_{n+1}=\frac{\sqrt{a_n^2+1}-1}{a_n}$?
I've tried using $b_n=a_n^{-1}$ and I got $b_{n+1}=\sqrt{b_n^2+1}+b_n$, but I cannot get a better idea or further step.
Let $\frac {b_n}{2^n}=c_n$ and $\lim c_n=C$, then I get $C=\frac C2+\frac C2$, a trivial equation.
Any help is welcomed...
Comment: is $ n\to \infty$?
Comment: @PierreCarre it looks like $\frac{\pi}{2}$ ;)
Comment: [Find $\lim_{n\to\infty} 2^n a_n$ where $a_{n+1} = \frac{\sqrt{a_{n}^2 + 1} - 1}{a_n}$ and $a_1 = 1$](https://math.stackexchange.com/questions/3557438/find-lim-n-to-infty-2n-a-n-where-a-n1-frac-sqrta-n2-1-1) is the same question, which uses a tangent substitution to solve the problem. The answer is indeed $\frac \pi 2$. Found with [SearchOnMath](https://www.searchonmath.com/)
Comment: Of course, @RamanujanXV I learned that I can skip $n\to\infty$ because most of them are $n\to\infty$ when I find the limit of the sequence, but is it not true that I learned?
Comment: Well,frankly speakin I haven't heard of such a thing but it may exist.We have to wait till someone more knowledgeable would tell us about this.
Comment: @RamanujanXV I think the limit does exist ($\approx 1.5707963267948981$). However, from the numerical point of view, it is preferable to consider the equivalent formulation
$$
a_{n+1} = \dfrac{a_n}{\sqrt{a_n^2+1}+1}.
$$
Answer: Using the equivalent recursion formula
$$
a_{n+1} = \dfrac{a_n}{1+\sqrt{a_n^2+1}},
$$
it is easy to see that $a_n \to 0$, $a_n$ is decreasing, and also that $a_{n+1} < \frac 12 a_n$. Additionally, since
$$
2^{n+1}a_{n+1} - 2^n a_n=2^{n}(2a_{n+1}-a_n) < 0,
$$
we can establish that $2^n a_n$ is decreasing and, therefore  $0 < 2^n a_n < 2$. A bounded and decreasing sequence is convergent. The limit seems to be $\frac{\pi}{2}$ but I did not prove this.


Finding the basis of the null space for $y''''=a^4y$

Question: I'm attempting to prove that for $$y''''=a^4y, y(0)=0, y'(0)=0, y(L)=0, y'(L)=0$$
to have a nontrivial solution, we must have that $\cos(aL)\cosh(aL)=1$.
I've been given a hint, that is to prove that the null space of this this D.E. is $[\sin(ax),\cos(ax),\sinh(ax),\cosh(ax)]$.  I began by substituting $y=e^{mx}$ and found a basis of $[e^{ax},e^{-ax},\cos(ax),\sin(ax)]$.  I'm thinking that to get $\sinh(ax), \cosh(ax)$ in my null space I would need to use their exponential forms, ie, $\sinh(x)=\frac{e^x-e^{-x}}{2}$, but I'm unsure how to proceed in proving this, as well as how I would need to use this to prove that $\cos(aL)\cosh(aL)=1$ for a nontrivial solution.  Any help is appreciated, thank you.
Answer: Factor the associaated polynomial, $\lambda^4 -1 = (\lambda -1 )(\lambda + 1)(\lambda^1 + 1).$
You get the four functions $y_1 = e^x$, $y^2 = e^{-x}$, $y_3 = \cos(x)$, $y_4 =
\sin(x).$   These span the solution space of your ODE.
You can also use $\cosh(x)$ and $\sin(x)$ instead of the exponentials because the transformation $(e^x, e^{-x})\mapsto(\cosh(x), \sinh(x))$ is an invertible one.
Comment: I already put in my question that I know these to be the solutions, but I'm unsure how to proceed with showing $\cosh(ax),\sinh(ax)$ are part of the basis.  Is it as simple as saying that $\cosh(ax),\sinh(ax)$ are linear combinations of $e^{ax}, e^{-ax}$?
Comment: Yes, and vice versa. That's all folks.
Answer: It would be easier to use the basis $y_1=\sin(ax)$, $y_2=\cos(ax)$, $y_3=\sinh(ax)$, $y_4=\cosh(ax)$.
Let $y=\sum_{j=1}^4 c_jy_j$. Use $y(0)=0$ to show $c_2+c_4=0$. Use $y'(0)=0$ to show $c_1+c_3=0$. Now $y=c_1(\sin(ax)-\sinh(ax))+c_2(\cos(ax)-\cosh(ax))$. Lay out the system of linear equations
$$0=y(L)=c_1(\sin(aL)-\sinh(aL))+c_2(\cos(aL)-\cosh(aL))$$
$$0=y'(L)=c_1(\cos(aL)-\cosh(aL))+c_2(-\sin(aL)-\sinh(aL)).$$
It has a nontrivial solution, so the determinant must vanish. Compute it and you're done.
Comment: The determinant of this system of linear equations in the variables $c_1$ and $c_2$. It is $(\sin(aL)-\sinh(aL))(-\sin(aL)-\sinh(aL))-(\cos(aL)-\cosh(aL)^2$. It's messy, but comes out as $2-2\cos(aL)\cosh(aL)$, which you set to 0 to show the result.
Comment: Which determinant precisely are you speaking of?  The Wronskian? Or with $y(0), y'(0), y(L), y'(L)$?


Javascript regex with word boundary includes word with special characters

Question: I want to make a word boundary \b check for matching words that also work if there are certain special characters in the word getting matched, such as Ø, but preferably not characters like ! or ?. Since the special character is at the end of the word, the \b sees it as being "open space" and therefore matches the word without it actually being a free-standing word.
Is this possible to do?
Right now this check matches both words, but i would like it to only match the word with "Ford".

const nodes = [{
  textContent: "Ford is the best"
}, {
  textContent: "Fordørgen is the best"
}];

const variable = 'Ford';
const regex = new RegExp('\\b' + variable + '\\b');

const matches = nodes.filter(function(node) {
    return regex.test(node.textContent);
});

console.log(matches);
Comment: Try: `const regex = new RegExp('\\b' + variable + '(?!\\S)');`
Comment: @anubhava this also seems to work, so now im left to wonder if there's a performance difference between these two solutions, or if it really matters which one i choose
Answer: \b only works for ascii, you have to use unicode properties to handle non-ascii word boundaries, for example:

const nodes = [{
  textContent: "Ford is the best"
}, {
  textContent: "Fordørgen is the best"
}];

const variable = 'Ford';
const regex = new RegExp('(?<!\\p{Alpha})' + variable + '(?!\\p{Alpha})', 'u');

const matches = nodes.filter(function(node) {
    return regex.test(node.textContent);
});

console.log(matches);

(?<!\\p{Alpha}) xxx (?!\\p{Alpha}) means xxx, unless preceded or followed by a unicode alphabetic character.
Docs: Unicode Property Escapes
Comment: This looks like exactly what i needed, thanks a lot. I'll accept the answer once i am able to. Do you know if there's any difference in performance between the '\\b' + variable + '(?!\\S)' and this kind of Regex?
Comment: @Reaver: I don't know, but I doubt this part is going to be a bottleneck in your program.


javascript revealing module pattern ignored on server

Question: I've been looking for answers why my javascript code is totally on my webhost. I have existing javascript functions that used to work fine until I tried to modify them using the revealing module pattern in javascript because from what I gathered this is good practice to reduce polluting the global namespace. There are no function calls outside this scope so I did not use return to point to functions. It worked okay in different browsers while testing from Visual Studio.
Is there something maybe in godaddy server that I need to configure? I tried to call them for support but no help. Below is sample of my code. I actually have more functions in this scope but kept it short for this question. Thanks in advance.
myModule = (function () {

    //add upDate
    function timeOfUpdate {
    var timeOfUpdate = new Date(document.lastModified);
        $("#lastUpdate").append(timeOfUpdate);

    }
    //add some more functions
    function modTwo {
    //add code to execute..
    }
})();

Answer: I'm not sure exactly what you're trying to do with that module definition, but you aren't returning anything from the module so the functions inside the module are local within the module and can't be used from outside the module.  If you look at this reference on the revealing module pattern, you will clearly see that they are returning an object with methods on it and that is what is assigned to the module variable.
Perhaps what you meant to do was this:
var myModule = (function () {

    return {
        //add upDate
        timeOfUpdate: function {
            var timeOfUpdate = new Date(document.lastModified);
            $("#lastUpdate").append(timeOfUpdate);

        },
        //add some more functions
        modTwo: function {
            //add code to execute..
        }
    }
})();

This returns an object from the IIFE so that myModule becomes an object that has your methods timeOfUpdate() and modTwo() as properties on the object.
Then, you could access your functions as:
myModule.timeOfUpdate();
myModule.modTow();

If you're not trying to use any of these functions from outside the module, then you'll have to help us with more details about what you're trying to do and what errors you see.  You can wrap a bunch of code in an IIFE like you were doing just fine and that will cause no problems.  There is ZERO point in assigning to a module name as in myModule = ... if you aren't returning anything from that IIFE so it appears to me like you're at least going in a wrong direction there, but without understanding what you're trying to do with this module or what errors you are running into, we can't really help further.

Also, your example shows some local function definitions, but doesn't show calling any functions so nothing would happen until you insert some code that actually calls your functions.
Comment: Yes jfriend00. Thank you. My script is working now. Calling the main object and attaching the timeOfUpdate() was the part I am missing. I was locked into the thought that because I had the self-invoking operator at the end of myModule value would auto invoke the methods I had inside its scope without making a call. I appreciate your pointing me to that problem.
Comment: @smundoKo2 - since it appears you may be new to StackOverflow, are you aware that when you get your question answered, you can indicate the "best answer" to your question by clicking the green checkmark to the left of the answer.  That will earn both you and the person who provided the answer some reputation points here at StackOverflow.  An accumulation of reputation points will earn you more privileges here.


StartExecPost calling the service itself

Question: I have a service defined as bellow:
Unit]
Description=My Service
After=network.target

[Service]
ExecStart=/usr/local/bin/myservice
KillMode=process
Restart=on-failure
ExecStartPost=/usr/local/bin/script.sh

[Install]
WantedBy=multi-user.target

and script.sh contains commands like:
while ! $(systemctl is-active --quiet myservice) ; do echo "waiting.."; sleep 5; done

(and other calls to the service)
The problem is that it doesn't work.
I think it's a chicken-and-egg issue. I'm waiting for the service to be up in the service start itself. This obviously can't work.
So my question is:
How can I run script.sh automatically when myservice is up?
Thanks
Comment: You're trying to use `ExecStartPost` with a service that doesn't play nice since it doesn't notify systemd when it has finished starting up, you're most likely stuck with trying whatever it is you need `ExecStartPost` until it works.
Answer: From manual

ExecStartPost= commands are only run after the commands specified in
ExecStart= have been invoked successfully, as determined by Type=
(i.e. the process has been started for Type=simple or Type=idle, the
last ExecStart= process exited successfully for Type=oneshot, the
initial process exited successfully for Type=forking, "READY=1" is
sent for Type=notify/Type=notify-reload, or the BusName= has been
taken for Type=dbus).

So ExecStartPost will executed only after ExecStart= have been invoked successfully.
Your script doesn't work may be due to wrong options choose in unit file.
Comment: I investigated a bit more. Actually, having service in `running` state is not enough. The service needs to start a server and listen on port X. This can take a bit of time. Thus, ExecStartPost starts too quickly, before the server to be started. What I don't understand is that I tool this in account in my script.sh (wait for port to be open) but it's waiting forever


TypeError: unsupported operand type(s) for /: 'tuple' and 'int'

Question: I'm having trouble with dealing with this error unsupported operand type error and I'm not sure what I'm doing wrong in this case. Any help would be appreciated!!
def closest_pair(list):
if (len(list) <= 3):
    return min_distance(list)
else:
    left, right = split_into_two(list)
    left_min = closest_pair(left)
    right_min = closest_pair(right)
    if(left_min[2]>right_min[2]):
        return right_min
    else:
        return left_min

def split_into_two(list):
    med_val = statistics.median(list)
    med_x = med_val[0]
    left = []
    right = []
    for i in list:
        if (i[0]<med_x):
            left.append(i)
        else:
            right.append(i)
    return left, right

and printing closest_pair gives out:
Traceback (most recent call last):
  File, line 109, in <module>
    print(closest_pair(text_file))
  File, line 61, in closest_pair
    left_min = closest_pair(left)
  File, line 62, in closest_pair
    right_min = closest_pair(right)
  File, line 60, in closest_pair
    left, right = split_into_two(list)
  File, line 44, in split_into_two
    med_val = statistics.median(list)
  File, line 358, in median
    return (data[i - 1] + data[i])/2
TypeError: unsupported operand type(s) for /: 'tuple' and 'int'

Comment: [`list`](https://docs.python.org/3/library/functions.html#func-list) is a bad variable name
Comment: please fix indentation, and provide a [mcve]
Answer: The error message is very explicit:
    return (data[i - 1] + data[i])/2
TypeError: unsupported operand type(s) for /: 'tuple' and 'int'

It says that the program is trying to divide a tuple by an int. So, data[i - 1] + data[i] is a tuple, and that means that each of data[i - 1] and data[i] are tuples and not numbers as you may be expecting.
Note that the error occurs inside the statistics.median function. Check that you are passing arguments with the right type to this function.


How to send message/content in fb messenger to user never been in messenger?

Question: I have an FB app which is a bot app. It subscribes as a primary responder of a page.
I get a callback when any user comments/like in any post of the page through the user never been in the messenger. on the basis of this kind of comment and likes, BOT wants to send messages to the user from the page.
But I can't send messages to the user if the user has not been in messanger at least once.
Answer: find this api :
Private Replies allows Businesses to reply to Post Comments and Visitor Posts made on their Page with a single message on Messenger.
The message is sent just like any regular message using the Send API but referencing either the Page Post of comment that will be replied.
When using this feature, the user will get a reference with a link to the post or comment that is getting the reply.
Private replies to posts or comments are allowed within 7 days of the creation date of the user post or comment.
https://developers.facebook.com/docs/messenger-platform/discovery/private-replies


Can the shot speed of an airsoft sniper rifle be reduced without cutting the spring?

Question: I am getting a sniper for airsoft, but my shot speed limit is 350 fps. Could I buy a sniper shooting at 450 fps and lower it to around 350 fps?
If so, how could I do that without cutting the spring?
Answer: Yes, you can change the speed, there are a few ways to do this.

You can change the weight of the BBs you use. The heavier the BB, the lower the speed. Please keep in mind most fields do not measure by speed in fps but by energy in joules, as the "force" or how much the BB will hurt, is dependent on joules not fps, so check where you're playing to see what their limit is.
You can change the inner spring, obviously the weaker the spring the lower the speed in fps, please don't cut your spring; that will ruin it. Just buy a lower power one, they go by units of measure for example m110 meaning a velocity of 110 metres per second using 0.20g BBs.

I personally recommend doing both, as the heavier the BB the less the wind and air pressure will affect it equating to a more accurate shot, but changing the BB weight will not change the force exerted by the BB so you should also change out the spring if you want it to hurt less.
Comment: I can suggest you to link a source to make your answer stronger


How to design my C# jQuery API such that it isn't confusing to use?

Question: I'm making a jquery clone for C#. Right now I've got it set up so that every method is an extension method on IEnumerable<HtmlNode> so it works well with existing projects that are already using HtmlAgilityPack. I thought I could get away without preserving state... however, then I noticed jQuery has two methods .andSelf and .end which "pop" the most recently matched elements off an internal stack. I can mimic this functionality if I change my class so that it always operates on SharpQuery objects instead of enumerables, but there's still a problem.
With JavaScript, you're given the Html document automatically, but when working in C# you have to explicitly load it, and you could use more than one document if you wanted. It appears that when you call $('xxx') you're essentially creating a new jQuery object and starting fresh with an empty stack. In C#, you wouldn't want to do that, because you don't want to reload/refetch the document from the web. So instead, you load it once either into a SharpQuery object, or into an list of HtmlNodes (you just need the DocumentNode to get started).
In the jQuery docs, they give this example
$('ul.first').find('.foo')
  .css('background-color', 'red')
.end().find('.bar')
  .css('background-color', 'green')
.end();

I don't have an initializer method because I can't overload the () operator, so you just start with sq.Find() instead, which operates on the root of the document, essentially doing the same thing. But then people are going to try and write sq.Find() on one line, and then sq.Find() somewhere down the road, and (rightfully) expect it to operate on the root of the document again... but if I'm maintaining state, then you've just modified the context after the first call.
So... how should I design my API? Do I add another Init method that all queries should begin with that resets the stack (but then how do I force them to start with that?), or add a Reset() that they have to call at the end of their line? Do I overload the [] instead and tell them to start with that? Do I say "forget it, no one uses those state-preserved functions anyway?"
Basically, how would you like that jQuery example to be written in C#?

sq["ul.first"].Find(".foo") ...
Downfalls: Abuses the [] property.
sq.Init("ul.first").Find(".foo") ...
Downfalls: Nothing really forces the programmer to start with Init, unless I add some weird "initialized" mechanism; user might try starting with .Find and not get the result he was expecting. Also, Init and Find are pretty much identical anyway, except the former resets the stack too.
sq.Find("ul.first").Find(".foo") ... .ClearStack()
Downfalls: programmer may forget to clear the stack.
Can't do it.
end() not implemented.
Use two different objects.
Perhaps use HtmlDocument as the base that all queries should begin with, and then every method thereafter returns a SharpQuery object that can be chained. That way the HtmlDocument always maintains the initial state, but the SharpQuery objects may have different states. This unfortunately means I have to implement a bunch of stuff twice (once for HtmlDocument, once for the SharpQuery object).
new SharpQuery(sq).Find("ul.first").Find(".foo") ...
The constructor copies a reference to the document, but resets the stack.
Comment: IMO 5) is the best option.  It's certainly readable and intuitive for the queries to begin from `HtmlDocument`, and as for the duplicate work -- hopefully you can implement it so that only the method signatures are duplicated, but not the actual logic.  (Chaining the calls to some common class that does the work.)  I also like option 1) and personally don't see it as an "abuse" of the brackets. :)
Comment: @Kirk: `[]` generally indicates an `O(1)` operation... like the data is already indexed. In this case, it actually has to do a full search.
Comment: Nevertheless, I'm leaning towards (1) now. Actually, I've started coding it this way. This prevents users from jumping right in with `.Find()` because the context isn't set until they call `[]`. i.e., `.Find()` simply won't find anything because it has nothing to search. `[]` resets the context to the document node and then they can begin searching.
Answer: I think the major stumbling block you're running into here is that you're trying to get away with just having one SharpQuery object for each document. That's not how jQuery works; in general, jQuery objects are immutable. When you call a method that changes the set of elements (like find or end or add), it doesn't alter the existing object, but returns a new one:
var theBody = $('body');
// $('body')[0] is the
theBody.find('div').text('This is a div');
// $('body')[0] is still the

(see the documentation of end for more info)
SharpQuery should operate the same way. Once you create a SharpQuery object with a document, method calls should return new SharpQuery objects, referencing a different set of elements of the same document. For instance:
var sq = SharpQuery.Load(new Uri("http://api.jquery.com/category/selectors/"));
var header = sq.Find("h1"); // doesn't change sq
var allTheLinks = sq.Find(".title-link") // all .title-link in the whole document; also doesn't change sq
var someOfTheLinks = header.Find(".title-link"); // just the .title-link in the
; again, doesn't change sq or header

The benefits of this approach are several. Because sq, header, allTheLinks, etc. are all the same class, you only have one implementation of each method. Yet each of these objects references the same document, so you don't have multiple copies of each node, and changes to the nodes are reflected in every SharpQuery object on that document (e.g. after allTheLinks.text("foo"), someOfTheLinks.text() == "foo".).
Implementing end and the other stack-based manipulations also becomes easy. As each method creates a new, filtered SharpQuery object from another, it retains a reference to that parent object (allTheLinks to header, header to sq). Then end is as simple as returning a new SharpQuery containing the same elements as the parent, like:
public SharpQuery end()
{
    return new SharpQuery(this.parent.GetAllElements());
}

(or however your syntax shakes out.)
I think this approach will get you the most jQuery-like behavior, with a fairly easy implementation. I'll definitely be keeping an eye on this project; it's a great idea.
Comment: Ahh..clever! I was thinking about returning a new object, but then I couldn't figure out how I would maintain the stack. Keeping a reference to the parent... so simple >.<
Comment: Big update: http://sharp-query.googlecode.com/svn/trunk/HtmlAgilityPlus/ Uses this method for chaining now.
Answer: I would lean towards a variant on option 2.  In jQuery $() is a function call.  C# doesn't have global functions, a static function call is the closest.  I would use a method that indicates you're creating a wrapper like..
SharpQuery.Create("ul.first").Find(".foo")

I wouldn't be concerned about shortening SharpQuery to sq since intellisense means users won't have to type the whole thing (and if they have resharper they only need to type SQ anyways).
Comment: They can name it whatever they want.. `sq` would be an instance of `SharpQuery`. `SharpQuery.Create` won't work as a static method because you have to load the document first... unless you want to make the document static too, but then you can only work with one document at a time; an arbitrary restriction.


Complex integral on a smooth curve contained in an open set

Question: Thm 5.19 (exactly) says: Let $\gamma\colon[a,b]\rightarrow \mathbb{C}$ be piecewise smooth. Let $F$ be a complex function defined on an open set containing $\gamma^*$, and suppose that $F'(z)$ exists and is continuous at each point of $\gamma^*$. Then $$\int_\gamma F'(z)dz=F(\gamma(b))-F(\gamma(a)).$$
The homework asks to determine all possible values of $$\int_C \frac 1{z^2+1}dz,$$ where $C$ is piecewise smooth from $z=-1$ to $z=1$, but does not include $z=i$ or $z=-i$.
Part of our answer is that if $C_1$ is straight from $-1$ to $1$ (or deformable into such a line), then the integral must equal $\arctan(1)-\arctan(-1)=\frac \pi 2$. Note that $C_1$ passes between the two singularities.
Why doesn't thm 5.19 apply to a curve which passes over (or under), both singularities (and doesn't loop either)?
If $C_2$ passes over both singularities, then it is piecewise smooth. $F$ is still defined on an open set containing $C_2$ (it's not an open disc, and it would have to be drawn carefully so as not to include either singularity, but it is open). And $F'(z)$ still exists and is continuous on the curve.
If my friend (and the perfect grade he got on his homework!), is correct, then if a curve passes over both singularities, it is equal to $\frac \pi2$.
P.S. No need to inform me about loops of the singularities. We've handled that situation using Cauchy's Integral Formula.
Answer: You know what the integral is around the loop given by traversing $C_2$ and then traversing $C_1$ backwards (by the Cauchy integral formula, on which you're sold) and you know what the integral is along $C_1$, so you can deduce the integral for $C_2$ by subtracting, even if you're squeamish about the branch cut used in defining the arc tangent.
Answer: There is a way  to make your theorem 5.19 applicable to arbitrary paths $\gamma$ connecting $z=-1$ with $z=+1$ that are disjoint from the segment $\sigma:=[-i,i]$, in particular paths that "pass over the singularity at $z=i$":
Let $\Omega:={\mathbb C}\setminus\sigma$. The Möbius transformation $z\mapsto{z-i\over z+i}$ maps $\sigma$ onto ${\mathbb R}_{\leq 0}\subset{\mathbb C}$, therefore
$${z-i\over z+i}\notin {\mathbb R}_{\leq 0}\qquad(z\in\Omega)\ .$$
It follows that the function
$$F(z):={1\over 2i}{\rm Log}{z-i\over z+i}$$
is analytic in $\Omega$, and one easily computes $F'(z)={1\over z^2+1}$. Therefore by theorem 5.19 for any $\gamma$ of the described kind one has
$$\int_\gamma{dz\over z^2+1}=F(1)-F(-1)={1\over 2i}\Bigl({\rm Log}{1-i\over 1+i}-{\rm Log}{-1-i\over -1+i}\Bigr)=-{\pi\over2}\ .$$
Answer: As countinghaus points out, there's a branch cut so $F$ is not holomorphic for the theorem to apply, hence the need to subtract an overhead contour out of a loop to compute that particular integral.
$\hskip 2.3in$
This is a picture of the complex $\arctan(z)$ function from Wikipedia.
Answer: You write that you already know how to deal with loops around the singularities. But that is actually all you need to know. For example if you have a path that passes above both singularities from $-1$ to $1$, you can extend it with one that goes back along the real line to $-1$ and then doubles back (forward) to $1$:

The two parts of the extensions will cancel out each other, so they don't change the integral around the entire path. On the other hand, the extended path can now also be viewed as a sum of a loop around $i$ and the straight path you have already computed.
In this way, any path however wild from $-1$ to $1$ can be decomposed into some number of loops around the singularities (possibly in various directions), plus a single copy of the straight baseline path.

The theorem you quote does apply to the original (unextended) $\gamma$, but you cannot use the same antiderivative as you used to find the integral of the straight path. That's because this $\gamma$ crosses a branch cut you needed to make to define that antiderivative, and you can't extend the domain of the antiderivative all the way to the branch cut from both sides and still have it be continuous on its domain.
On the other hand, the theorem doesn't apply to the extended path in my diagram, because there is no antiderivative that can cover the entire loop around $i$ without any discontinuities.


Log de erros com Selenium WebDrive em C#

Question: Boa noite!
Estou organizando minha suíte de testes e procurando os melhores meios de criar um relatório de erros quando um teste falha. Implementei já um log em .txt com o nome do teste que é executado (utilizando o TestContext), o tempo de execução do teste, o status dele (Passou, erro, timeout...), e salvando prints caso o teste falhe.
Porém, Caso o teste falhe, também gostaria de salvar o motivo do erro, bem como o Visual Studio aponta quando debuga, ou aparece a razão da falha na própria suíte de testes. O caso é que farei um serviço rodar os testes de madrugada, e não terei acesso aos motivos escritos da falha.
Pensei em algumas possíveis soluções, só não as implementei porque acredito que haja meios melhores. Por exemplo, uma das possibilidades que imaginei fui tratar todos os testes com try/catch, e salvar o erro dentro dos catchs.
Estou usando a última versão estável do Selenium WebDriver em um projeto C#, com estrutura baseada no Microsoft.VisualStudio.TestTools.UnitTesting. Obrigado desde já!
Comment: E qual é sua dúvida? O que já fez? Onde está enfrentando problema?
Comment: 1) A melhor forma pra registrar o erro quando o teste falha. 2) Coloquei try/catchs em alguns testscases para registrar a exception. 3) Acredito que haja outro modo de capturar o erro lançado quando um teste falha, de modo que o código fique mais organizado e fácil de dar manutenção. Estou procurando esse meio
Comment: Existem diferentes maneiras de logar erros do Selenium: 1) tirar um screenshot da tela no momento do erro. 2) salvar as informações de erro do log do navegador. 3) salvar as informações de erro do próprio selenium, como mencionou.
Comment: Dherik, estou tentando fazer o que você exatamente falou no fim, salvar as informações de erro do próprio selenium, porém sem usar try/catch em todos os testcases. Os outros casos já implementei na suíte
Comment: Como o Selenium no C# pode usar o Nunit, o [NUnit Addins API](http://jimmykeen.net/2015/02/28/logging-test-results-with-nunit) deve ser o que você precisa, pois ele loga os erros do Nunit em um arquivo. É isto que procura? Se for, eu coloco como resposta.
Comment: Chegando em casa, vou conferir ele. É possível usá-lo junto com o UnitTesting da Microsoft? Senão terei que fazer uma mudança gigantesca no projeto de testes
Comment: @Dherik , usarei o seu conselho, pode colocar como resposta
Answer: Acredito que o seu problema não seria gravar em log os erros do Selenium em si, mas em como gravar em log os erros do seus testes unitários.
Se estiver usando NUnit, uma opção para o que almeja fazer é o Nunit Addins API, no qual você consegue gravar as exceções de um teste em um arquivo separado para posterior consulta.
Dependendo da versão do NUnit, existem outras alternativas ainda. Se estiver usando o NUnit 3.x é possível fazer de uma maneira e com o NUnit 2.x é possível fazer de outra. Infelizmente, a documentação para estes casos me pareceu bem precária, mas vale conferir.
Comment: Retirei um link da resposta porque ele não funciona mais e estava redirecionando para um site aparentemente malicioso. Qualquer coisa, quem quiser procurar o link original ou sugerir um novo link, pode olhar no histórico de edições.


How to send e-mails using a contact form on Symfony?

Question: I created my website with Symfony and I am deploying it now. I used my contact form. When I use it I am supposed to receive messages to my email address. But currently, I didn't receive any message.
Here is my code.
I am using this line in my .env file :
MAILER_DSN=smtp://firstname.lastname@example.com:firstname.lastname@example.com:465?encryption=ssl&auth_mode=login
ContactController.php
<?php

namespace App\Controller\Front;

use App\Form\Front\ContactType;
use Symfony\Component\Mime\Email;
use App\Repository\UserRepository;
use App\Form\Front\ContactFromUserType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;

class ContactController extends AbstractController
{
    #[Route('/contact', name: 'contact')]
    public function index(
        Request $request,
        UserRepository $userRepository,
        MailerInterface $mailer): Response
    {
        if ($this->getUser()) {
            $connected = $this->getUser();
            $useremail = $connected->getUserIdentifier();
            $user = $userRepository->findOneBy(['email' => $useremail]);

            $form = $this->createForm(ContactFromUserType::class);
            $form->handleRequest($request);

            if ($form->isSubmitted() && $form->isValid()) {
                $contactFormData = $form->getData();
                $message = (new Email())
                    ->from($user->getEmail())
                    ->to('firstname.lastname@example.com')
                    ->subject('Vous avez reçu un email d\'un utilisateur de Go Zpeak : ' . $user->getFirstname() . ' ' . $user->getLastname())
                    ->text(
                        $contactFormData['message'],
                        'text/plain'
                    );
                $mailer->send($message);

                $this->addFlash('success', 'Merci. Ton message a bien été envoyé !');

                return $this->redirectToRoute('contact');
            }

            return $this->render('front/home/contact.html.twig', [
                'form' => $form->createView()
            ]);

        } else {

            $form = $this->createForm(ContactType::class);
            $form->handleRequest($request);

            if ($form->isSubmitted() && $form->isValid()) {
                $contactFormData = $form->getData();

                $message = (new Email())
                    ->from($contactFormData['email'])
                    ->to('email@example.com')
                    ->subject('Vous avez reçu un email d\'un visiteur de Go Zpeak !')
                    ->text(
                        'Nom du visiteur : '.$contactFormData['name'].\PHP_EOL.
                        $contactFormData['message'],
                        'text/plain'
                    );
                try {
                    $mailer->send($message);
                } catch (TransportExceptionInterface $e) {
                    $this->addFlash('error', $e);
                    return $this->redirectToRoute('contact');
                }

                $this->addFlash('success', 'Merci. Ton message a bien été envoyé !');

            }

            return $this->render('front/home/contact.html.twig', [
                'form' => $form->createView()
            ]);
        }
    }
}

Where might be the problem ?
Answer: Which Symfony and Mailer versions are you using ? Your controller and form seems to be correct, have you check the log files of the app if any error messages from the mailer ?
To check the MAILER_DSN config, you can create a tiny Php project with only the Mailer if SMTP or SMTPS, login/password, catch Mailer events...


How to get header.php drupal 7

Question: I have the next files .tpl.php in my drupal7:

page-front.tpl.php
page.tpl.php
page-taxonomy.tpl.php

I want include a header.php and footer.php  with the follow way but is not working:
<?php include_once($theme_path.'/include/header.php');?>

How can I get common files from a tpl.php?
Comment: Using template_preprocess_page sounds like a better way to add content to pages. Am I wrong?
Comment: Hi rreiss,  sorry but I am new with drupal, I´ve worked with wordpress but drupal is my first time to work.

why do you think is best choice using template_preprocess_page??
how it should be implemented?

Kind regards!
Comment: It depends on the things you're adding in those files, but I assume that we're taking about elements that are related to the appearance of those pages and not to its functionality (module vs. theme). In Drupal if you want to add page logic you should use template_preprocss_page, for example - you can add new variable (probably a renderable array) to the page variavles ($vars['foo']) and print it in the template file if it exists. Hope that's clear enough
Answer: Use drupal_get_path(), e.g.
<?php include_once drupal_get_path('theme', 'MYTHEME') . '/include/header.php'; ?>

include_once isn't a function so no need for parentheses.

How to get header.php drupal 7


How to add active class to a specific menu only, while ignoring other menus?

Question: I have 2 conflicting menus I need to solve by adding an active class to a targeted menu only, they are a user menu and a profile and account settings menu which have overlapping links.

User Menu (in the header section of every page):

[username] (links to Profile2 page)

Account Settings  (i.e. change password, etc.)
Log out

Profile and Account Settings menu (appears in the sidebar of the profile2 and account pages):

View Profile (links to Profile2 page also)
Edit Profile
Account Settings (same link destination as "Account Settings" of User Menu)
Order History

Since I'd like to convey to my users that whenever they are in any page linked by the Profile and Account Settings menu (eg. Edit Profile)I tried using Context to set an .active class for "User Menu>Profile", which worked.
However, now that "User Menu>Profile" is active when I'm in "Edit Profile", since "View Profile" shares the same link destination as "User Menu>Profile", both "View Profile" and "Edit profile" are have an .active class, which is very undesirable.
Hence, I would like to know, if there is a way to use Context or any hooks to set an .active class for the User Menu only when I'm in the "Edit Profile" page?
Comment: Are you using pathauto?
Comment: Yes I'm using pathauto :)
Comment: try using jquery to check the path against all links on the page and $(element).addClass('active') on the matching elements
Comment: Thanks. I'm, not familiar with using jquery. I'd like to know if there's a way to check the path against links in only a specific menu on the page before adding the class?
Answer: Try the  following modules
1)Menu Position

Often times site builders want certain types of content to appear in a specific position in the navigational menu. The simplest solution, adding all of that content individually to the menu system, has performance and usability issues. (Imagine hundreds of menu items added to one spot in the menu.)
This module allows for the creation of rules that will dynamically add the current page into the menu system at the requested spots.

I've used Menu Position module for one of my project and it works great!
OR
2) Menu Trail By Path

Menu Trail By Path sets the active-trail on menu items according to the current url.
For example if you are at yoursite.com/blog/category1/article1
  Menu Items with these paths will get the active-trail class on them and expand accordingly.
blog
blog/category1
blog/category1/article1
Comment: Yess!! I was about to give up on Menu Position until I went to Settings> Mark the rule's parent menu item as being "active". Thanks!  (deleted the previous comment because I wrote Menu Trail by Path instead of Menu Position)
Comment: @ashash Great! glad to hear that :)


Is there always a superlinear function which "strongly dominates" a given superlinear function?

Question: Consider the class $\mathcal{F}$ of functions $f:[0, \infty) \to [0, \infty)$ with the following properties
$(1)$ $f$ is strictly increasing with $f(0) = 0$.
$(2)$ $f \in \omega(x)$ as $x \to \infty$. That is to say, $$\lim_{x \to \infty} \frac{f(x)}{x} = \infty$$, or $f$ is superlinear.
The latter condition ensures that $f(x)$ is much larger than $x$ for large $x$, and hence  iteratively composing any $f \in \mathcal{F}$ with itself any number of times will produce a function which grows at least as fast as $f$ asymptotically.
Define $$f^{[n]}(x) \stackrel{\text{def}}{=}  (\overbrace{f \circ f \circ f \cdots \circ f}^{n \ \text{times}})(x)$$
For any two $f,g \in \mathcal{F}$, we say $f$ $\textbf{strongly dominates}$ $g$ if for all $n \in \mathbb{N}$, $f \in \omega(g^{[n]}(x)) $ as $x \to \infty$. (this is "strong" domination as opposed to weak domination, which is just $f \in \omega(g)$).
Problems:

Let $f \in \mathcal{F}$ be arbitrary. Does there exist a $g \in \mathcal{F}$ such that $g$ strongly dominates $f$? Additionally, does there exist an $h \in \mathcal{F}$ such that $f$ strongly dominates $h$? And can both $g,h$ be explicitly constructed?
Comment: @Michael For the second question, why doesn't $x^2$ strongly dominate $x$? Note if $f(x) = x$, then $f^{[n]}(x) = x$.
Comment: @Michael And the example for the first question is perfect.
Comment: The function $e^x-1 \in \mathcal{F}$ strongly dominates any polynomial function in $\mathcal{F}$, it would be interesting to find a function that strongly dominates $e^x-1$.
Comment: I think the answer to the first question is "yes," no time to prove it but here is the idea:  Take $f \in \mathcal{F}$.  There is an $M$ such that $f(x)\geq x$ for all $x \geq M$.  Define $g(x)$ in pieces: Take $g(x) = f(x)$ for $x \in [0, M+1]$.  Take $g(x) = f^{[2]}(x)$ for $x \in (M+1, M+2]$, $g(x) = f^{[3]}(x)$ for $x \in (M+2, M+3]$ and so on.
Comment: Thanks, you were right about my first (incorrect) comment, which I have now deleted.  I now have a proof that both questions have "yes" answers (see below).  What is the context of this exploration? How did you come to be interested in this problem?
Answer: My previous comment gives a "yes" answer to the first question.  This answer shows "yes" also is true for the second.
Fix $f \in \mathcal{F}$.  We want to construct $h \in \mathcal{F}$ such that $f$ strongly
dominates $h$.  We construct $h$ piecewise linear over a sequence of switching times
$\{S_k\}_{k=0}^{\infty}$ that satisfy
$$ 0 < S_0 < S_1 < S_2 < S_3 < … $$
and $\lim_{k\rightarrow \infty} S_k = \infty$.  For a given sequence $\{S_k\}_{k=0}^{\infty}$ (to be precisely defined later), define $h:[0,\infty)\rightarrow\mathbb{R}$ by:
$$ h(x) = \left\{ \begin{array}{ll}
x &\mbox{ if $x \in [0, S_0)$} \\
kx & \mbox{ if $x \in [S_{k-1}, S_k)$, $k \in \{1, 2, 3, ...\}$}
\end{array}
\right.$$
Claim 1:
For any such sequence $\{S_k\}_{k=0}^{\infty}$, the $h$ function defined above satisfies $h \in \mathcal{F}$.
Proof:  By construction, $h(0)=0$ and $h$ is increasing. For $x \geq S_0$ we can write
$h(x) = k_x x $, where $k_x$ is defined as the index $k \in \{1, 2, 3, \ldots\}$ such that
$x \in [S_{k-1},S_k)$. Then
$$\frac{h(x)}{x} = \frac{k_x x}{x} = k_x \rightarrow \infty$$
$\Box$
Claim 2:
If $f \in \mathcal{F}$, then $\sqrt{x f} \in \mathcal{F}$ and
$$ \lim_{x\rightarrow\infty} \frac{\sqrt{xf(x)}}{f(x)} = 0$$
Proof: The function $\sqrt{xf(x)}$ is increasing, sends $0\rightarrow 0$, and
\begin{align}
\frac{\sqrt{xf(x)}}{x} &= \sqrt{f(x)/x} \rightarrow \infty\\
\frac{\sqrt{xf(x)}}{f(x)} &= \sqrt{x/f(x)}\rightarrow 0
\end{align}
where the limits hold because $f(x)/x\rightarrow \infty$.
 $\Box$
Now define $\phi:[0,\infty) \rightarrow\mathbb{R}$ by:
$$ \phi(x) = \left\{ \begin{array}{ll}
0 &\mbox{ if $x=0$} \\
\inf_{y \in [x, \infty)} \frac{\sqrt{y f(y)}}{y}   & \mbox{ if $x>0$}
\end{array}
\right.$$
Claim 3:
The function $\phi$ is nondecreasing and satisfies
$$ \lim_{x\rightarrow\infty} \phi(x) = \infty$$
Proof: We have
$$ \lim_{x\rightarrow\infty} \phi(x) = \lim\inf_{x\rightarrow\infty} \frac{\sqrt{xf(x)}}{x}=\infty   $$
where the limit holds because $\sqrt{xf(x)}\in \mathcal{F}$ so $\frac{\sqrt{xf(x)}}{x}\rightarrow\infty$.
$\Box$
It remains to choose the sequence $\{S_k\}_{k=0}^{\infty}$ such that the resulting $h$ function is strongly dominated by $f$.  Formally define $S_{-1}=0$.
For $k \in \{0, 1, 2, …\}$ and with knowledge of $S_{k-1}$, choose $S_k$ as any real
number that satisfies:

Property 1: $S_{k-1} < S_k$.
Property 2: $(k+2)^{k+1} \leq \phi(S_k)$
Property 3: $S_{k-1}k^{k-1} < S_k$ (only required if $k\geq 2$).

It is always possible to choose such a sequence $\{S_k\}_{k=0}^{\infty}$. In particular, the condition of the second bullet can be satisfied because $\phi(x)$ is nondecreasing and $\lim_{x\rightarrow\infty} \phi(x) =\infty$ (so we can always choose $S_k$ larger than the thresholds required in Properties 1 and 3 and sufficiently large to satisfy Property 2).
Claim 4:
Fix $k$ as a positive integer.  If $x \in [S_{k-1}, S_k)$ then
$$ x(k+1)^k \leq \sqrt{x f(x)}  $$
Proof: We have
\begin{align}
x(k+1)^k &\overset{(a)}{\leq} x\phi(S_{k-1}) \\
&\overset{(b)}{=} x \inf_{y \in[S_{k-1}, \infty)} \frac{\sqrt{y f(y)}}{y}\\
&\overset{(c)}{\leq} x \frac{\sqrt{xf(x)}}{x} \\
&= \sqrt{x f(x)}
\end{align}
where (a) holds by Property 2 (applied to $k-1 \in \{0, 1, 2, …\}$);
(b)  holds by definition of $\phi$; (c) holds because $x \in [S_{k-1}, \infty)$.
 $\Box$
Claim 5:
Fix $n$ as a positive integer. Fix $x \geq S_{n-1}$.  Let $k$ be the index such
that $x \in [S_{k-1}, S_k)$ (note that $k\geq n$).  Then
$$ h^{[n]}(x) \leq x(k+1)^k $$
Proof: Postponed until later (see details below). $\Box$
Claim 6:
The function $f$ strongly dominates $h$.
Proof:  Fix $n$ as a positive integer. Consider any $x \geq S_{n-1}$.  Let $k\geq n$ be the index such that $x \in [S_{k-1}, S_k)$. We have:
\begin{align}
\frac{h^{[n]}(x)}{f(x)} &\overset{(a)}{\leq} \frac{x(k+1)^k}{f(x)} \\
&\overset{(b)}{\leq}  \frac{\sqrt{x f(x)}}{f(x)} \rightarrow 0
\end{align}
where (a) holds by Claim 5; (b) holds by Claim 4; and the limit holds by Claim 2. $\Box$

Proof of Claim 5: Fix $n$ as a positive integer and fix $x \geq S_{n-1}$.  Let $k \geq n$ be the index such that $x \in [S_{k-1}, S_k)$. Then
$$ (k+1)^k x \leq (k+1)^kS_k < S_{k+1} $$
where the final inequality holds by Property 3 (applied to $k+1 \geq 2$). Thus

$h(x) = kx \leq (k+1)x < S_{k+1}$.  So $h(x) \in [S_{k-1}, S_{k+1})$.
$h(h(x)) \leq (k+1)h(x) \leq (k+1)^2x < S_{k+1}$.  So $h(h(x)) \in [S_{k-1}, S_{k+1})$.
... and so on...
$\underbrace{(h \circ \ldots  \circ h)}_{\mbox{k times}}(x) \leq (k+1)^kx < S_{k+1}$.
$\Box$


cobbler in multi vlan environment

Question: I am trying to use cobbler for automated cent OS deployment.
we have a multi vlan ( about 5 vlans) network environment.
We do not have remote consoles to most of these servers so we cant see pre install server status or PXE boot status
how should be dhcp bootp services utilized ? should we need to have a dhcp server on each vlan/subnet ?
Any pointers about how should i go ahead deploying cobbler?
Answer: I'm doing this on our network.  If your switch/router supports it, just relay the dhcp to the cobbler server with dhcp-agent or equivilent on the router.
That way you don't have to have mulitple nic's etc on the cobbler server and make your life all confusing.
Cobbler's default setup should do the rest once you have things up and running.  Although you may have to setup a stub zone for the network for dhcp only clients if you haven't pre-populated the mac addresses of your machines.
Answer: You need to have at least one DHCP server listening in each vlan, remember that vlans are logically separated and DHCP won't cross over magically, the easiest way to do this if it's temporary is to have one linux box with a switching trunk to all those 5 networks with 5 subinterfaces configured and one DHCP running them all, although the dhcp config will be a bit complicated it'll get all the work done.
Comment: sorry that's not true at all. you can use the 'ip helper-address' feature on the gateway router for each subnet to forward DHCP requests to a single interface on your central dhcp server. If you don't have control of your routers, you still don't need an interface on every VLAN, you can just use the 'dhcrelay' program running on a given system.
Comment: Sure Eric, but that not only complicates things but in my own experience is quite flaky
Comment: thanks thats the approach i was considering second will be having new machines on same vlan as of cobbler server and then moving them in another vlan after setup + little puppet magic
Answer: You may want to use a DHCP agent on each VLAN which will forward the traffic to the DHCP server...  See the below link on how to configure this on a Cisco switch/router;
http://www.cisco.com/en/US/docs/ios/12_4t/ip_addr/configuration/guide/htdhcpre.html

cobbler in multi vlan environment


How can I return to my loop after an exception?

Question: I have the code below:
import urllib.request
import json

flag_servidor = 0
flag_salva_txt = 0
numero = 0

#codigo para verificar se há conexao como servidor e caso nao
#haja ele criar um arquivo txt com as infos

while 1:
    try:
        url = urllib.request.urlopen('http://IP/CAMINHO/get_infos.php')
        x_ = url.read()
        y_ = json.loads(x_.decode('utf-8'))
        get_turno_ = y_["turno"]
        print(get_turno_)

        #salva as infos do txt dentro do banco de dados
        if flag_salva_txt == 1: #significa que temos infos para serem salvas
            arquivo = open('novo-arquivo1.txt', 'r')
            for linha in arquivo:
                linha = linha.rstrip()
                valor = linha.split(";")
                print(valor[0])
            flag_salva_txt = 0
        continue
    except Exception as e:
        print("Servidor indisponível.Erro:", e)
        if flag_salva_txt == 0:
            #após salvar txt
            flag_salva_txt = 1
            numero = numero +1
            arquivo = open('novo-arquivo'+str(numero)+'.txt', 'w')
            arquivo.write('nova linha;123;1pop' + '\n')
            arquivo.close()
        continue

The problem is that: when an exception happened for the first time it shows me message error but when it happens for second time my code stop running and doesn´t show anything.
Comment: What exactly are you trying to do? It's hard to follow the logic of your code here... Also, what do you mean "it stops running and doesn't show anything"? There is no way the `while 1:` loop can just stop.
Comment: What exception(s) are you expecting to catch here? You are probably hurting yourself by casting too wide a net by using the generic `Exception` which is probably obscuring other errors in your code. Try focusing on a more narrow exception first while allowing others to be raised so you can see tracebacks for them and debug as necessary. (In fact, as currently written, neither of the `continue` statements in your code are actually necessary--if you catch an exception without re-raising it then execution should continue after the `except:` block).
Comment: I guess that the program is arrested in a try function, it trys to make a connection but how can not connect it doens´t leave there
Comment: Still, what is your program actually supposed to do? The way I see it, it gets some data over HTTP, prints it and does nothing further with it... and if there had been an error during this process, it writes some static data into a new file, then sets a flag to read a file after the next HTTP request... I can't make heads or tails of it :)
Comment: @Iguananaut the function try has a delay?
Comment: @AKX I want to try connecation, verify ih has connection all the time before execute some functions
Comment: "try" isn't a function. It's a "block-level statement"--all the code in the "block" under the `try:` statement is always executed each time you go through the loop, and if an exception occurs in *any* of those lines the execution will jump to the `except:` block and skip any of the remaining code in the `try:`.  You will probably solve your own problem by first experimenting with some simpler code by trying to write a [Complete, Minimal, Reproducible example](https://stackoverflow.com/help/minimal-reproducible-example).
Comment: Also, try localizing the `try/except` just immediately around the code that you expect might fail.  For example put `except:` immediately after `urllib.request.urlopen` or maybe after trying to parse the JSON, in order to minimize the amount of code your `except:` is covering.
Answer: I'm still not quite crystal clear about what your program is supposed to do, but maybe something like this helps.
I refactored your program to a separate function to get the data, and printing it out (or whatever you like to do) is in the main loop.
In addition, to not hit the server as fast as your script can, there's a delay of 5 seconds between every request, successful or not.
import datetime
import time
import urllib.request
import json

def get_turno():
    url = urllib.request.urlopen("http://IP/CAMINHO/get_infos.php")
    data = json.loads(url.read().decode("utf-8"))
    return data["turno"]

while True:
    try:
        turno = get_turno()
    except Exception as exc:
        print("Retrieving turno data failed: {}".format(exc))
    else:
        current_time = datetime.datetime.now().isoformat()
        print("Time: {} - Turno: {}".format(current_time, turno))
    time.sleep(5)


Tables with identical styles have different widths

Question: I am trying to style two tables similarly. However, the column widths are different between the two tables even though the styles are the same. There seems to be invisible padding or spacing in the second table's first column.

document.getElementById('displayDateTime').innerHTML = Date();
html,
body {
  height: 100%;
}
body {
  margin: 0 auto;
  max-width: 960px;
  padding: 0 20px;
  font-family: 'Roboto', sans-serif;
}
h1 {
  font-size: 48px;
  margin-bottom: 5px;
}
h2 {
  font-size: 36px;
}
h3 {
  font-size: 24px;
  color: green;
}
table {
  width: 100%;
}
pre {
  font-family: 'Ubuntu Mono', monospace;
  padding: 20px;
  line-height: 1.5em;
}
.input {
  background-color: lightgrey;
}
.lineno {
  background-color: grey;
  padding-right: 15px;
}
.output {
  background-color: lightgrey;
  padding: 20px;
  line-height: 1.5em;
}

Displaying Date & Time

Input

1
2
3

<script type="text/javascript">
   document.getElementById('displayDateTime').innerHTML = Date();
</script>

Output

>

Comment: I would argue this is not an appropriate use for a `table` as you are not presenting tabular data at all.
Answer: You may need to add this:
table {
  width: 100%;
  table-layout: fixed;
}

References:

The table-layout property ~ MDN
17.5.2 Table width algorithms: the table-layout property ~ W3C

document.getElementById('displayDateTime').innerHTML = Date();
html,
body {
  height: 100%;
}
body {
  margin: 0 auto;
  max-width: 960px;
  padding: 0 20px;
  font-family: 'Roboto', sans-serif;
}
h1 {
  font-size: 48px;
  margin-bottom: 5px;
}
h2 {
  font-size: 36px;
}
h3 {
  font-size: 24px;
  color: green;
}
table {
  width: 100%;
  table-layout: fixed;
}
pre {
  font-family: 'Ubuntu Mono', monospace;
  padding: 20px;
  line-height: 1.5em;
}
.input {
  background-color: lightgrey;
}
.lineno {
  background-color: grey;
  padding-right: 15px;
}
.output {
  background-color: lightgrey;
  padding: 20px;
  line-height: 1.5em;
}

Displaying Date & Time

Input

1
2
3

<script type="text/javascript">
   document.getElementById('displayDateTime').innerHTML = Date();
</script>

Output

>

Comment: Yup that did it! Thank you!
Comment: Thanks, I did not know about `table-layout: fixed`. However, I would not like them to be 50% width. I would like the left column to only take the space of the text + 15px padding on both sides.
Comment: You can adjust the widths. Check the references.


Bayes by Backprop applied to Regression

Question: I have been reading the Bayes by Backprop paper "Weight Uncertainty in Neural Networks" from 2015 (https://arxiv.org/pdf/1505.05424.pdf). I think I have a decent understanding of the content of the paper up until the part where it is applied to a regression problem. My issue is that to do the backpropagation we have to do computations involving the likelihood term $P(\mathcal{D}|w)$ where $\mathcal{D}$ is the data. This is based on the model specified by our network so in the classification case I believe this expression for any of our data points is just the probability predicted by the forward pass through the network.
After working on MNIST as a classification example in the paper (which I believe I understand assuming the above is correct) the authors move on to a regression example where they just generate some data from a simple function and attempt to fit it with their method and an ordinary neural network. They mention that the two networks are fit by minimising a conditional Gaussian loss and I'm not sure what is meant by this. The only thing that seems reasonable to me is that in the case of both networks the underlying model is that $Y|_X$ is Gaussian. I believe this would mean in the ordinary network we are treating the network output as an estimate for the mean of $Y|_{X_i}$ and therefore we use a squared error loss for training. In the Bayes by Backprop case then we would want $P(\mathcal{D}|w)$ to correspond to the likelihood for the target value so this would be the likelihood for a Gaussian with mean $\hat{Y}_i$ evaluated at the data $(X_i, Y_i)$, where $\hat{Y}_i$ is the value predicted by the network.
My first two questions are as follows:

Is my understanding set out above correct?

For the Bayes by Backprop regression above, we have no variance specified but we need to calculate the likelihood. How is this dealt with?

The results for this part are displayed by plotting the fits with confidence bands. I'm unsure on exactly how the confidence bands are being obtained. Firstly for the Bayesian approach, the result of fitting the network is a posterior probability distribution for each weight so the distribution for $\hat{Y}|_X$ is determined by these, however I'm not sure how practical it would be to use this to compute confidence bands due to fact that this distribution will generally have a complicated dependence on the weight distributions. Since prediction is achieved by sampling weights and averaging multiple predictions $\hat{Y}$ maybe it would make more sense to use these predictions to compute a confidence band too, but then we would need to make some sort of assumption on the posterior for $\hat{Y}|_X$ or justify using the central limit theorem. Secondly for the ordinary neural network there are also confidence regions on the plot. I'm not sure where these come from as my motivation for why this Bayesian approach was important is because on its own an ordinary neural network doesn't give us error estimates. Based on these points then:

What exactly are the displayed confidence bands for the Bayes by Backprop network fit? Is it one of the two approaches I mentioned?
How are confidence regions being obtained for the ordinary neural network? I was wondering if this is linked to the second of my first two questions since that involved specifying a variance for $Y|_X$ but that would be constant and the bands in the plot are not of constant width.
Comment: This website works best if you ask one question at a time. Feel free to post each of these as separate questions.
Comment: They're all related to one subsection of the same paper, do they still need to be separated? They would probably each have to almost the full length to explain the context.
Comment: It's helpful for getting faster answers. Several people may have the time or expertise to answer one part, but not the complete question. A partial answer to the uber-question doesn't properly qualify as an answer here.
Answer: I agree the authors didn't do a great job of clarifying this. My best guess is that the regression model looks like: $y_i \sim \mathcal{N}(\mu=f(x_i), \sigma^2 = g(x_i))$ where $f$ and $g$ are neural networks (or more precisely, probably two branches of the same neural network).
I'm not sure I understand your concern about the uncertainty bands on the BBB network. It seems that you can just

sample $\theta$ from the variational posterior,
given $x$, sample $y$ according to the above model,
repeat the previous some large number of times,
compute the 25 and 75% percentile of the sampled $y$.
Comment: I have seen other approaches where something like the network producing estimates for both $\mu$ and $\sigma^2$ is done, so I guess that seems likely.
Comment: My comment on the confidence bands was based on the fact that the distribution of $y$ for a given $x$ is also determined by this method (as well as the weights distributions). As a result I'm not sure why we would use sampling of $y$ to come up with a confidence region when we actually know the form of the distribution for $y$ so we don't need to do this empirically.
Comment: you know the conditional $p(y|x,\theta)$ but not the marginal $p(y|x)$. so either you integrate (intractable), or you just sample, which is by far easier
Comment: @EGN123 could you elaborate on that? where have you seen this? i'm looking for a way to apply bayes by backprop to regression and having estimates for both $\mu$ and $\sigma^2$ is exactly the outcome i want.

Bayes by Backprop applied to Regression


How to create Scald Atoms media library for each content type?

Question: I need to categorize the "Atoms Library" items in a way that there would be a "Atoms Library" for each content type. How  could create a Atoms Library for each conten type? or How I could categorize the items in "Atoms Library" according to content type?
Is this possible to create a "Atoms Library" for each content type?
Comment: check this https://drupal.org/project/scald
Answer: There are two Views that come with Scald:

scald_library - Which, for our purposes, is what controls the format of the menu in the editor.
scald_atoms - Which controls the format of the Scald Library at /admin/content/atoms.

Both are fully editable views.
For the admin page, clone the View and assign each one a unique filter for Atom:Type and give each View a unique path URL. Add these URLs to an admin menu somewhere to make them findable.
The editing menu is a little more complicated. Cloning and filtering the View is the same, but I believe using them would require adding new functionality to either the editor or Scald. Though people editing content can still filter by type in the Scald search pane.


How to play notes over one octave at once in one voice on a piano?

Question:
In the bass voice, I am supposed to play notes spanning from C to the next but one G at once. Is this even possible with one hand? Should I use the other hand for that G?
I could barely hit the two outer keys with my fingers, but then there is no finger to play the other C...
Comment: Ignore that friend's advice - or ask for clarification.
Comment: Once you get past numbering the fingers over the score, the clefs no longer indicate which hand, only which note. Use the other hand, it's an easier reach.
Comment: I never numbered the fingers, but a friend once told me that the voices should be played with their respective hand
Comment: I'm having trouble understanding the question. I assume you mean the G on top of the left hand staff, on the last note?
Comment: it's a G on the bass voice, not F, sorry. Fixed it.
Comment: Your friend is wise, but you can't trust the clefs to always be the same voices. In this case I would consider the B and D in the left hand to both be moving to C, while the D above is moving down to G.
Answer: Simplest is to think the top l.h. (bass) note (G) should really have been written under (and belonging to) the treble clef. Then use your right thumb to play it. That's realistically how it ought to have been written.
Comment: Agreed with Tim here - this must be a typo editing-wise as the G3 should be put in RH.
Answer: There's an inner melody of a sort at the top of the LH notes.  It could be  emphasized by spreading that last chord.  Or you could accept the notation as showing the musical intention but cheat the G with the RH.   The second way may seem 'easier'.  I suspect the first way could be more effective.
Comment: The first way would be more effective if it was playable with normal hands! And either way, it'll be a thumb.


Can I alias all directory requests to a single file in nginx?

Question: I'm trying to figure out how to take all requests made to a particular directory and return a json string without a redirect, in nginx.
Example:
curl -i http://example.com/api/call1/

Expected result:
HTTP/1.1 200 OK
Accept-Ranges: bytes
Content-Type: application/json
Date: Fri, 13 Apr 2012 23:48:21 GMT
Last-Modified: Fri, 13 Apr 2012 22:58:56 GMT
Server: nginx
X-UA-Compatible: IE=Edge,chrome=1
Content-Length: 38
Connection: keep-alive

{"logout": true}

Here's what I have so far in my nginx conf:
location ~ ^/api/(.*)$ {
    index /api_logout.json;
    alias /path/to/file/api_logout.json;
    types { }
    default_type "application/json; charset=utf-8";
    break;
}

However, when I try to make the request the Content-Type doesn't stick:
$ curl -i http://example.com/api/call1/
HTTP/1.1 200 OK
Accept-Ranges: bytes
Content-Type: application/octet-stream
Date: Fri, 13 Apr 2012 23:48:21 GMT
Last-Modified: Fri, 13 Apr 2012 22:58:56 GMT
Server: nginx
X-UA-Compatible: IE=Edge,chrome=1
Content-Length: 38
Connection: keep-alive

{"logout": true}

Is there a better way to do this? How can I get the application/json type to stick?
EDIT: Solution!
I figured out you can just send manual strings in the return statement, so I did that instead of using aliases!
Final code I used:
location /api {
    types { }
    default_type "application/json";
    return 200 "{\"logout\" : true"}";
}

Answer: You could use a rewrite instead to get the catchall behaviour.
location /logout.json {
    alias /tmp/logout.json;
    types {
        application/json json;
    }
}
rewrite ^/api/.* /logout.json;

Comment: Doesn't this redirect you to /logout.json? I'm trying to avoid sending a 302 redirect response.
Comment: No, that's an internal [rewrite](http://wiki.nginx.org/HttpRewriteModule#rewrite). Redirects are only sent if an absolute location is specified or a `redirect` or `permanent` flag is specified.
Answer: Very simple. The whole configuration could be:
# default.conf
# Add file here: /etc/nginx/html/logout.json

server {
  listen 80;
  rewrite ^.*$ /logout.json last;
}


How to determine where selected row is closed or open on itemClick event in AdvancedDataGrid

Question: I have an AdvancedDataGrid with Hierarchical data in it. On itemClick I have to identify if the row I clicked is expanded or collapsed.
Any ideas?
Answer: The AdvancedDataGrid has a member function isItemOpen(item:Object):Boolean.  Pass it the data for the row and it will return true if the item is open, false otherwise.


Does the ability of reading and writing music on staff help with learning music fundamentals?

Question: As I see it, notation on sheet music is a tool for translating musical ideas into something that can be read/interpreted by others and played back, given they understand the same set of rules.
I assume also that the way one approaches to music or the instrument played makes thinking about music itself very different. So when it's time to write or create some music, maybe someone trained to see through the lenses of musical notation would come up with some sort of "patterns" or ideas that another person more used to digital creation would have different. It's like if the tool was shaping the craft somehow.
Some time ago I've came across a bass workshop by Victor Wooten that made me think about music in a different way. He explains music as made of 10 elements (notes, rhythm, space, dynamics, articulation...). He believes that all of these are equally important to make music, not even good or bad music, simply music, because you can find them in every melody or song.
Introduction made, now the question. On my personal journey to learn music I've tried guitar playing with no attention to music theory and after that some time in an music school. I'm not reluctant to theory, in fact I like it, but what I fail to see it's the point of making the staff the center of my learning when I don't want to be a classical nor professional interpreter.
I want to understand music, its elements and details to be able to express myself with no more limitations than my abilities. Beyond some basic knowledge of notation that certainly is good to have, is there any fundamental element that is better learned using music written on a staff? I'm thinking in rhythm but not sure.
Comment: There is a difference between _sight reading_ and the ability to read and write music on the staff. Sight reading is the ability to play a piece as-written on the first viewing. The ability to read and write, without the skill of sight-reading, is valuable in itself. Which skill do you mean?
Comment: Just my personal experience: you say you went to _"music school"_ and then that you _"don't want to be a classical nor professional interpreter"_. I'd say this is the root cause of your confusion. As my clarinet teacher told me just a few weeks before I dropped out from conservatory: _"You're gifted but you're not taking this seriously. You're not paying tuition to learn a hobby; you can do that by yourself at home. You're here to become a full-time, professional musician. If you don't want to make a career in Music, this might not be your place."_ He was right.
Comment: @Topomoto point is wonderful viz notation fluency makes you better in the paradigm that the notation is natural to and makes more inaccesible distant paradigms. As an exercise try and notate this [Indian classical lecture](https://youtu.be/NijvuJnrazo) into staff notation!
Answer: (This answer addresses the original posted question, not the subsequent edit.)
I don't see how sight reading would help with learning the fundamentals of music theory, but there is a very strong case of the converse: a better understanding of music theory makes you a better sight reader.
So much of the "Classical" repertoire is built around fundamental patterns of scales and triads. When a pianist simply knows their scales, sight reading a Mozart piano sonata becomes much easier. Instead of tallying a string of 50 straight sixteenth notes, a student adequately trained in music theory will recognize those sixteenths notes as patterns of the A-major scale; the music then almost plays itself.
In the world of jazz, a string of nine chord changes might look completely foreign to someone untrained in music theory. But the adequately trained student recognizes it as a string of ii–V–I progressions; now suddenly the student hearkens back to their training and the improvisation flows naturally.
Keep in mind too that "music theory" isn't just written theory; it also involves ear training. Musicians that "don't want to be a classical nor professional interpreter" often prefer to play by ear. In such cases, the knowledge of common chord patterns makes playing by ear (not to mention composing) much easier and much more successful.
Comment: That's a bit my point or idea. Investing more time on ear training to recognize pitch, chords, intervals, etc. than in reading music on a staff.
Comment: Note that the question was slightly modified from a specific "sight reading" to "ability to reading and writing music" after this answer, in case the answer needs some adjustment.
Answer: I can read English. I could read a thesis about nuclear science, or whatever, but it wouldn't make a lot of sense to m, although anyone listening may be able to understand what was being read.
Sight-reading is a great skill to have, but I don't think that that, in itself, will particularly give you a great insight into music, or music theory. Learning how to sight-read may well help, as there are certain premises and facts that are important to know and understand whilst learning how to sight-read.
So, studying theory - with the all important practical playing in tandem to make it make sense - is your better route, learning how to sight-read on the way will help, but purely sight-reading things won't necessarily give you much insight into music. Apart from being able to pick up anything, and play it, so bringing that sheet music to life, and perhaps meeting other genres that, if you can't sight-read, may be denied.
Comment: Thanks for the reply. I've rephrased a bit my question because the point was not really clear. The things is if "reading music on staff" is any useful to help acquiring basics of music theory or even composing.
Answer:
I want to understand music, its elements and details to be able to
  express myself with no more limitations than my abilities.

The trouble is, we DO limit ourselves to our abilities.  If our musical journey is limited to 'monkey see, monkey do'  we're only going to understand music that we can play, on our chosen instrument, at our level of technique.
It's useful to see music as notation.  It can also be quite an eye-opener to see it as graphic display on a sequencer screen (but that's 'notation' too!) particularly when it's a performance not a quantized construction.
And yes, even a skilled, reading pianist has to consciously break away from writing stuff that lies under 10 fingers on a keyboard! (But he can, quite easily.  His technique isn't a disability.)
Answer: Standard notation inherently relates to a certain model of what music is - for example

The idea that music is made of 'notes' and 'rests'
The idea of rhythms as being constructed of units of time that are hierarchical subdivisions of a bar
the idea that a piece of music is assumed to be diatonic and can be said to be in a certain key

(There's no reason you have to think of music as being made of 'notes', or having a 'key' - that's just a particular model, albeit a very common one).
The more used to standard notation you are, the better you will be at thinking of music from the perspective of the model that is implied by standard notation. But if thinking of music in that way is already straightforward for you, then it might be that there isn't any major new musical concept that sight-reading or reading music is going to teach you.
That isn't to say that reading music might not be an incredibly valuable skill, of course. But then learning Chinese, or real estate law, or welding could also be incredibly valuable too. You have to focus your efforts where it seems the return will be greatest.
Answer: There is no simple answer here as it really depends on what you really want to achieve in music, and in what type of music and also what's your strenghts and weak spots.
Obviously Victor Wooten's example shows clearly you can be at the top of the game and rely solely on your ears. Tommy Emmanuel is another example, George Benson and many others.
But it also has to be said that they all have something in common - they naturally absorbed and learned music from the very very early age. Their "knowledge" of music is very visceral - a bit like a spoken native language. For those who didn't have a chance to absorb music this way the learning method is a bit different - a bit more like learning a second language. And that's where being able to read might help. It might help as it allows you to quicker absorb and analyse small detail in music, understand complex sequences, get your head around the form.
Pat Metheny said he always strived to be the best reader he can be for that reason. To understand and absorb more. I'd imagine it's also a tool to free up your memory if there's a ton o musical material to remember.
Bach, Debussy, they were writing and reading all their lives.
So there are different approaches and they are all fine. There's also different proportions of visceral/intelectual in different types of music, that's why again there's no simple answer.
Comment: I think any musical material that is complex and not only classical gets complex. Example: listen to 'First Circle' by Pat Metheny, try to memorize and repeat the clapping pattern. With the help of the score it should take you a couple of minutes. Going just by ear you'll most likely waste lots of time. And at the end of the day we're talking about time investment here.
Comment: Ok. So we can agree that certain reading skills would be beneficial to follow theory books or access to more repertoire, as others have said. Can you elaborate a bit what kind of areas will require more reading abilities? For example regarding to composing non classical material.
Comment: One last thing regarding composing. Do you see any differences between using sequencers or similar tools vs. writing on staff? I think the medium used for creation conditions the way we think about music itself.
Comment: Sure I agree. But conversely the more different ways of looking at the music we absorb the more possibilities we see. Composers writing scores might not be as obsessed with grooves and texture as modern djs, conversely modern dj could definitely gain some interesting insigths by studying for example counterpoint.
Answer:
I want to understand music, its elements and details to be able to express myself with no more limitations than my abilities. Beyond some basic knowledge of notation, is there any fundamental element of music that sight reading would help me to understand better? I'm thinking in rhythm but not sure.

After reading your waste introduction I assume that you actually mean understanding sheet music as you mention just some basic knowledge of notation and the 10 elements of music ...
Reading and understanding of sheet music will be of an interactive benefit for the process of understanding music theory, listening, analyzing and also for the skill of sight reading. Each moment you are investigating to improve your skills for reading scales, intervals, triads and all sorts of chords, rhythm, solfège, clefs and scores will have agreat benefit for all other occupations with music, also for someone who comes from computer music or any instrument.
Don't forget that all the genius performers who were musical analphabethists were not those genies because they were lacking of reading knowledge, they didn't know to read sheet music because they were poor and didn't have the opportunity to learn it.
Answer: Reading is pretty basic to understanding theory, because we name things differently based on the notation (e.g. an augmented fourth sounds the same as a diminished fifth).  Reading also gives a notation to rhythm, and articulation through slurs, legato lines, staccato dots, etc.
In any field it's useful to have some kind of nomenclature.  It gives you something to wrap your head around and communicate with others.  You could get along by demonstrating what you mean if you don't have a language to describe it, but notation gives you a faster and clearer method.
That said, "sight" reading means being able to interepret a piece that you haven't seen before.  I think it's a useful skill for the work I do as a guitarist, but it's certainly not essential for all guitarists, and the speed at which you can recognize things like intervals and chords isn't much of a barrier to understanding music theory - if you can follow and understand the written examples in theory texts, you're reading skills are sufficient, and reading faster won't help al that much.
Answer: You have to see that musical sheets gives to you only 2 things:

WHAT to play/execute;
HOW to play/execute.

For the first one the sheets will brings to you all the notes or elements which are contained in the song. Is valid reforce that music is not made only of sound and notes but it is made by silence as well. Then this part brings this elements for you.
Once you know what you need to play (or even sing) the song now you have to know how to perform these elements and this will took by the second topic. If you know all notes and silences you have to do, the sheet music will teach you the durations, expressions, dynamics or even feeling.

Knowing this you see that sheets can not teach you any music rules or theory, but you don't have to quit from its learning.
Why?
Answering: you need to know that sheets are the VISUAL form of a sound. We only can LISTEN to a sound, but we can't see it. The sheet is the way that humans can to SEE the song.
Then, if you really want be a person that understand music you really have to do it completelly, and learn sheet reading is a part of this knownledge.
Answer: While the primary purpose of sheet music may be a way to communicate musical works so that a musician can play the piece that the composer intended,
it is also a (practically) universal language among musicians to describe notes, scales, chords, and other elements of music.
You could probably express a lot of the ideas of music theory in a digital format, or even in guitar tablature, but the number of people who would be able to read it (or write more theory in the same format) is much more limited.
If you want to learn theory, you'll need a teacher (or teachers) and you'll need to be able to receive instruction about music in a form in which they know how to deliver it. It's possible to learn quite a bit of theory merely by ear, without writing any notes, but to really learn a substantial amount of theory I think you need some way for people to be able to notate the ideas for you, and standard music notation is the way most teachers understand. So it's probably a good idea to learn enough of it to follow the theory lessons.
To borrow an analogy from another answer, there are fields of study where almost all current material is published in English. You could learn some of one of those fields in a different language, but if you want to really be up to date in the field, it pays to learn English. Knowing English won't make you a good nuclear physicist, but not knowing English might prevent you from becoming a good nuclear physicist.
Answer: It is hugely beneficial for learning to be able to read and write. Without this ability you're illiterate. You could develop your own writing system, but then you would have to teach that system to anybody else you want to communicate with, and most probably your system would suffer from many first-generation deficiencies. Using the same common system of written language as other people is hugely beneficial too. Traditional Western musical notation has been developed through centuries of practice by countless people, for communicating music-related ideas to other people. Performers, composers, arrangers, theorists. And not just any ideas and aspects, but those ideas and aspects that all the people have deemed to be actually relevant, in a way that they have deemed to be actually practical.
Learning a language enables you to interact with a culture, people using the language. If you think you're a self-sufficient entity and don't need to be in touch with the part of musical culture and history that uses musical notation... Okay. :)
If you're not convinced yet, it would be possible to list all the useful technical properties of musical notation, but it would be an endless list. I think it should suffice to say "just learn it or otherwise you're illiterate". Though on the other hand, of course nowadays we have Youtube videos, speech recognition and everything, so we can gradually fade away this awkward reading and writing thing. ;)