The limit of a fixed-point equation

Question: Consider the following fixed-point equation:
\begin{equation}
x = (1-x)^{1-\frac{2}{a+1}} - 1,
\end{equation}
where $x \in [0,1]$ and $a \in [0,1]$. If we write the solution of $x$ in terms of $a$ as $x(a)$, then, would it be possible to compute $\lim_{a \rightarrow 1} x(a)$ ?
Since there is no closed-form solution for $x$, I tried to numerically see what happens. Here is the result:
$a=0.5640 \Leftrightarrow x=0.9$;
$a=0.7399 \Leftrightarrow x=0.99$;
... ...
$a=0.9547 \Leftrightarrow x=0.9999999999999$.
But is there any analytic way to demonstrate $\lim_{a \rightarrow 1} x(a)$ ?
Answer: Moving -1 to the other side and taking logs yields
$$
\begin{split}
\ln(x+1) &= \left(1-\frac{2}{a+1}\right)\ln(1-x) \\
\frac{\ln(x+1)}{\ln(1-x)} &= 1-\frac{2}{a+1} \to 0 \text{ as } a \to 1
\end{split}
$$
so you are seeking the value of $x$ that will make the left-hand side $0$.
One options is to send the numerator to $0$, so $\ln(x+1) \to 0$ and thus $x+1 \to 1 \leftrightarrow x \to 0$ and so the LHS becomes 0/0, using L'Hospital's rule we can show that LHS is then $\frac{x-1}{x+1} \to -1$ so this way does not work.
Another way is to send the denominator to $\pm \infty$. Consider $-\infty$ first: so $\ln(1-x) \to -\infty$ and $1-x \to 0$ and $x \to 1$.
Finally, to $+\infty$: so $\ln(1-x) \to +\infty$ so $1-x \to +\infty$ and $x \to -\infty$, but that would make the numerator undefined.
In summary, the only choice is indeed $x \to 1$, which sends $\ln(1-x) \to -infty$ and the equality takes the form 0=0.
Answer: If you isolate $a$ in terms of $X$, the only possible solution as $\lim_{a\to 1} x(a)$ appears to be $x=0$...

The limit of a fixed-point equation


Network traffic accounting of Xen VMs

Question: How do I monitor network traffic usage on Xen virtual machines running on Debian GNU/Linux Squeeze?
I have a number of Xen virtual machines (domUs) running on a few physical machines (dom0s). Each domU can be started on or live-migrated to one of the physical machines.
I would like to monitor and account how much network traffic is used on each domU. That is, how many bytes are being sent and received per month, week, day, hour.
I thought this would be a pretty common task for system administrators using virtual machines on Linux, however, I have not been able to find any easy way of doing it.
I am looking forward to hearing your approaches to this.
Answer: If you are using iptables, you can config something like this.
iptables traffic accounting
Comment: ... and use a remote (or local) machine with something like [RRDtool](http://oss.oetiker.ch/rrdtool/) to log that data so a reboot doesn't take out your accounting data.
Comment: This introduces a lot of extra overhead that isn't necessary - the data's collected for you already in /proc, for example.
Comment: BeeDee: How would you go around to collect these data from /proc? Do you mean /proc on each individual VM? I cannot be sure that each VM behaves correctly.
Comment: Jeff Ferland: Can you give an example of how to do this with RRDtool on a remote machine?
Answer: We wrote a script that runs on every dom0 each minutes, gets stats from "xm top" and pushes them to a memcache queue. From there Cacti queries the memcache queue, and updates the graphs.
Comment: Matt: This sounds like what I need. Care to elaborate on how you do this? Will you share the script that captures data from xm top as well as cacti configuration?
Comment: Sorry I just found this post. I will see if I can get this for you next week, if you tell me you're still interested.
Comment: Matt, will you share the configuration?
Answer: If you want to centrally collect the information, and assuming the guests are trusted (ie, not client machines you're billing for) the most flexible way will probably be to install SNMP on the guests.  Then you have thousands of options for SNMP-based monitoring and collection.
If that's too much overhead, look in <code>/proc/net/dev</code>; I suppose you could parse that yourself and upload values to a central machine in some fashion.  If done on the dom0's, you would need to assign persistent vif names, etc.
Answer: You could also install the iptables NetFlow module, and export the NetFlow data to an analyzer such as WANGuard (it also IP Accounting/Billing).  It stores the data in a database so you have history, and you can configure all sorts of pretty graphs.  Top Talkers by IP Address, protocol, etc.

Network traffic accounting of Xen VMs


How does this converging function appear to diverge?

Question: I found something while trying to analyze the integral $\displaystyle\int_0^\infty \frac{\sin(mx)} {x}\mathrm  dx $
Let us suppose we already know that the value of the integral is $\pi/2$ when $m>0$, $0$ when $m=0$ and $-\pi/2$ when $m<0$.
Let $f(m)=\displaystyle\int_0^\infty \dfrac{\sin(mx)} {x} \mathrm dx$
Thus $f'(m)=\displaystyle\dfrac{\mathrm d}{\mathrm dm}\int_0^\infty \frac{\sin(mx)} {x} \mathrm dx=\int_0^\infty \frac{\partial}{\partial m}\dfrac{\sin(mx)} {x}\mathrm  dx=\int_0^\infty \cos(mx)\mathrm  dx=\lim\limits_{x \to \infty} \frac{\sin(mx)}{m}$, which does not converge.
However, $f'(m)$ should be $0$ where $m\neq0$, as value of the integral remains constant
So we get $0= \lim\limits_{x \to \infty} \dfrac{\sin(mx)}{m}$, where $m\neq0$
How does this happen? Please note that I am a high school student and do not know complex analysis.
Can we assign value $0$ to $\lim\limits_{x \to \infty}{\sin(x)}$ as the average value of Sine function remains zero even when $x$ approaches infinity?
Comment: f'(m) is not integral cos(mx). Are you trying to do lhopital rule? In that case, you also forgot the chain rule.
Comment: I am differentiating w.r.t .the parameter m.
Comment: I don't understand what you mean.
Comment: @Goldname I have edited.
Comment: I think it is something to do with uniform convergence of integral. You can only take differential operator inside in case the convergence is uniform.
Comment: @PrinceKumar Could you please elaborate it?
Answer: Say we have $$f(m) = \int_0^\infty \sin(mx)\frac{dx}{x}$$ and we want to compute the derivative at $m>0.$ We need to take $$\lim_{h\rightarrow0}\frac{f(m+h)-f(m)}{h}. $$ Since both integrals converge, we're free to combine them, and we get $$ f'(m) = \lim_{h\rightarrow0} \frac{1}{h}\int_0^\infty \left(\sin((m+h)x)-\sin(mx)\right)\frac{dx}{x}.$$
In order to come to the conclusion that this equals $\int_0^\infty\cos(x)dx,$ we need to be able to justify bringing the limit inside the integral.
The problem of when you can bring a limit inside an integral is well-studied, and some well-known sufficient conditions for when you can are the Dominated Convergence Theorem and the Monotone Convergence Theorem. Clearly (since the answer would be wrong), this is one case where you can't. This frequently happens in oscillating integrals, but also in lots of other cases as well. In this case, if your integral is relying on cancellation from oscillations to stay finite, taking a limit inside can screw up things.
When you take the limit inside the integral, you are assuming you can treat each point $x$ inside the integral uniformly as $h\rightarrow 0$. Sometimes, however, the global behavior of the integral is changed when you do this. This generally happens when, as $h\rightarrow 0,$ a range of $x$ that contributes significantly to the integral gets 'squeezed onto  the boundary', or 'pushed off to infinity'.
A nice example, a bit different from ours, but where it's easy to see what's going on is $\int_0^\infty hx e^{-\frac{1}{2}hx^2}dx.$ For any $h>0,$ the integral is $1$, which you can verify by substitution. Thus $\lim_{h\rightarrow 0^+}$ of the integral is $1.$ However, taking the limit inside the integral gives $0$ for all $x>0,$ so the integral of the limit is $0 \ne 1$. If you sketch the function for smaller and smaller values of $h$ it's easy to see what's going on. As $h\rightarrow 0^+,$ the function goes becomes a very tall spike, very close to $z=0,$ with area $1.$ When $h$ goes to zero, the spike that contains all the area gets pushed to the boundary at $x=0.$
For our integral, oscillatory cancellations are ' pushed to infinity' in a certain sense as $h\rightarrow 0,$ so taking the limit inside causes a divergence. To see how this works, we can rewrite $$\sin((m+h)x)-\sin(mx) = \sin(mx)\cos(hx)+\cos(mx)\sin(hx) -\sin(mx)$$ so that the integral is $$ \int_0^\infty\frac{\sin(mx)(\cos(hx)-1) + \cos(mx)\sin(hx)}{hx}dx.$$
When you take the limiting form $\sin(hx)\approx hx$ and $\cos(hx)-1)\approx \frac{1}{2}h^2x^2$as $h\rightarrow 0,$ you completely lose the fact that the functions oscillate. Thus the integral, whose convergence was controlled by this oscillating behavior at large periods $x \sim 1/h$ can have its convergence destroyed by taking the limit inside. You are letting $h\rightarrow 0$ at fixed $x$ without appreciating that the function's oscillations when $x$ gets above $1/h$ were the only thing making it converge in the first place. (You're pushing the oscillation period off to infinity, so it no longer actually oscillates.)
Thus when we take the limit $h\rightarrow 0$ inside the integral and get $\int_0^\infty \cos(x)dx,$ which no longer converges, we are no longer quite so surprised.
Going back to the expression $$ f'(m) = \lim_{h\rightarrow0} \frac{1}{h}\int_0^\infty \left(\sin((m+h)x)-\sin(mx)\right)\frac{dx}{x},$$
we can see another angle. Usually, our intuition says the integrand goes to zero like $h$ for $h\rightarrow 0,$ so we can pull the $h$ out of the integrand and be left with the derivative inside. However, as we know now, this only works when things are sufficiently uniform.
What happens in our case, is that even though the difference in $\sin((m+h)x)-\sin(mx)$ goes to zero like $h$ when $h\rightarrow0,$ the integral is actually always zero, for any $h$ (so long as $m+h$ stays positive).
To see this, if you go back to when the integrals were separate and write $$ f'(m) = \lim_{h\rightarrow 0}\frac{1}{h}\left(\int_0^\infty \sin((m+h)x)\frac{dx}{x} - \int_0^\infty \sin(mx)\frac{dx}{x}\right).$$ Since we know the integrals are both convergent, we can change variables. Because of the $dx/x$ they both go to $\int_0^\infty \sin(u)du/u$ which means they're the same and we have $$f'(m) = \lim_{h\rightarrow 0}\frac{1}{h}*0=0,$$ which is the correct answer.
Intuitively, stretching out the sine waves to get more area is exactly cancelled out by fact that the amplitude decays like $1/x$ when it stretches out.
Answer: What you have just encountered is an instance when it is not possible to differentiate under the integral sign.
There are many references where you can find conditions under which this is possible. Personally, I like the book  Probability With a View Towards Statistics by Hoffman-Jorgensen, which contains a huge amount of detailed and useful measure theory results.


casperjs: can I use node packages inside casperjs with 'require' keyword?

Question: I do use casperjs.
I need to use some ready to go node packagages with casperjs such as:
https://www.npmjs.com/package/csv-write-stream to create CSV files
inside my capserjs file I have:
var fs = require('fs'); // this works
var system = require('system'); // this works
var csvWriter = require('csv-write-stream'); // stops the script, no error, it  works fine with nodejs script
var writer = csvWriter()

It looks like some require are ok (system, fs), but not 'csv-write-stream'
I would like to understand if (I can/how I can) use require packages in casperjs ?
I found that:

CasperJS allows using nodejs modules installed through npm. Note that
  since CasperJS uses it's own JavaScript environment, npm modules that
  use node-specific features will not work under CasperJS.

So how to determine which module will work ?
Comment: Some works some fail for others. The only way to really know is to test
Comment: is there a repository for "working" packages ?
Comment: Both `fs` and `system` are PhantomJS' built-in modules. They have nothing to do with node.js.
Answer: From official documentation:

CasperJS allows using nodejs modules installed through npm. Note that
  since CasperJS uses it's own JavaScript environment, npm modules that
  use node-specific features will not work under CasperJS.

So, you can try any node module which you want to import and test it works or not...
As Artjom B pointed out, fs and system are phantomjs modules. And all phantomjs module is listed here.


Why does block add one more in overlapped P tags?

Question: In my code, there are two P tag in there.
And I gave them border.
I think there are two lightblue block in my code
beacuse there are two p tags.
But if I run this code, There are Three Blocks in there.
I want to know why.
Please help. Thanks for reading.

p {
        margin: auto;
        text-align: center;
        background: lightblue;
        height: 70px;
        width: 200px;
        border: solid 1px black;
        line-height: 70px;
   }

        <meta charset="utf-8" http-equiv="content-type">

dddddddddddoo

Comment: You can't nest a `` inside a ``, invalid HTML will cause you problems.
Comment: If I am not wrong its because you can't put a `p` inside another `p`. So UA is probably putting one close `` after the first opening `` and one opening `` before the last closing ``. So you get three.
Answer: Use your browser's element inspector to look at the actual DOM. The result is:

dddddddddddoo

A p within a p is invalid. When the browser encounters the second
, it implicitly closes the first p. Somewhere along the line a third p is being implicitly created from your invalid markup.
Answer: You can't nest a
 inside a another
 tag. This is invalid HTML. When HTML sees something like this,
It replaces your html with:-

dddddddddddoo

Answer: replace

dddddddddddoo

with

dddddddddddoo

Answer: You can't nest
 elements. The
 element represents a paragraph. It can't contain block-level elements (including
 itself). If you inspect it in your browser, you will see 3 paragraphs.

 however is a generic container where content can be inline e.g  or block-level. Hence
 can contain
 but not the other-way around.
See the updated fiddle: https://jsfiddle.net/862afpo5/1/


Crossing number lemma

Question:
Suppose that a simple graph $G$ on $n$ vertices drawn in the plane. Prove that if
every edge crosses at most one another edge, then the number of edges in $G$ is at most $4n − 8$

What I have tried: I tried to take a graph with finite vertices let's say 12 and drew it in a criss-cross manner so that every edge have at most one crossing. Here since it not planar then it won't satisfy the Euler formula or edge requirement conditions. So I thought of removing edges one by one it won't have any crossings. And then I can apply one of the edge conditions. But it did not result in a meaningful way. Then I do not know any other approach. Could you please help me to solve this?
Cheers!!
Comment: https://en.wikipedia.org/wiki/1-planar_graph#Edge_density
Comment: Can you discuss where you got this bound of $4n-8$?  I see that it works for $n=8$, by constructing a "box" and putting a "cross" on all 6 sides. The result can't hold for any smaller $n$ (because $n$ choose 2 would be less than $4n-8$), so I suppose the goal is to show it works for $n\geq 8$?  Is there an easy construction for larger graphs that have exactly this number of edges?
Comment: @BradElliott HI!.. I got this question as a part of the exercise.
Answer: For each edge $f = uv$ that crosses an edge $e$, if there are not already edges from the endpoints of $e$ to the endpoints of $f$, add them. (These edges can always be added without crossing other edges, since $f$ meets only $e$ on its path from $u$ to $v$.)

Thus we obtain a graph $H$ with (potentially) more edges than $G$.
Consider a planar subgraph $H'$ obtained by deleting one of each pair of edges that cross. $H'$ has at most $3n-6$ edges, and at most $2n - 4$ faces. Each removed edge crosses two faces of $H'$, and at most one of the removed edges appears in each face of $H'$, so there are at most $n - 2$ removed edges.

Crossing number lemma


Convergence of a sequence...

Question: Let $\{a_n\}$ be a sequence of real numbers. Define $\sigma_n = 1/n(a_1 + \dots + a_n)$. Suppose that $\lim a_n = a \in \mathbb{R}$. Show that $\lim \sigma_n = a$.
Here is my work so far...
Fix $\epsilon > 0$. We are given that for $N \in \mathbb{N}$ we have that $|a_n - a| < \epsilon/\alpha$ whenever $n \geq N$, and $\alpha$ will be choosen later. We must find $N \in \mathbb{\widehat{N}}$ so large such that $|\sigma_n - a| < \epsilon$ whenever $n \geq N$. Note that
$$|\sigma_n - a| = |1/n(a_1 + \dots + a_n) - a|...$$
Then I got stuck trying to work out the details. Should I try showing that the $\sigma_n$ is a Cauchy sequence, and somehow use the convergence of the $a_n's$? Thanks for your help.
Answer: Let's bring in another number $M=\max_{i=1..\infty}{|a_i-a|}$.
So
$$
|\sigma_n - a| = \frac{1}{n}| \sum_i(a_i -a)| \leq \frac{1}{n}\sum_i |a_i-a| \leq \frac{N}{n}M + \frac{n-N}{n} \epsilon
$$
Now define $N_2 = \frac{NM}{\epsilon}$
For all $n > N_2$
$$
|\sigma_n - a|  \leq \frac{N}{n}M + \frac{n-N}{N} \epsilon \leq \frac{NM}{N_2} + \epsilon = 2\epsilon
$$
Thus,  $\lim_{n\to\infty} \sigma_n = a$

Convergence of a sequence...


Show that $f_n \to 0$ everywhere but not in measure.

Question:
Let $f_n = \chi_{[n, n+1]}$. Show that the sequence $(f_n)$ converges everywhere to the $0$-function, but that it does not converge in measure.

For every $x \in \mathbb R$ there exists some $N \in \mathbb N$ such that $x \not\in [n, n+1]$ for all $n \ge N$. So clearly we have that for every $\varepsilon > 0$ $$|f_n (x) - 0| < \varepsilon$$ whenever $n \ge N.$ So $f_n \to 0$ everywhere.
Is this correct?
I am not sure how to show that it does not converge to $0$ in measure though. Can anyone please help?
Comment: Note that $f_n$ cannot converge in measure if $|f_n-f_m|$ does not converge to zero in measure. Write out this condition explicitly and you can solve this exercise.
Comment: @PaxKivimae . Thanks for the hint! Is my first part correct though? :)
Comment: Yes. First part is correct.
Answer: For every $n$, the measure of the set $\{|f_{n}|\geq 1/2\}$ is $1$, so the $f_{n}$'s cannot converge to $0$ in measure.


Exibir uma Imagem através de URL

Question: Tenho uma imagem no link http://18.104.22.168:8080/umamaoNovo/images/u184Tulips.jpg
Gostaria de saber se tira alguma função para exibir rápido pós preciso exibir imagens em uma ListView.
Answer: Você tem algumas opções de como implementar essa funcionalidade no seu projeto.
A primeira (a que eu particularmente prefiro) é utilizando o Universal Image Loader, uma biblioteca super fácil de implementar e você consegue implementar somente lendo a documentação. Se estiver com dificuldade, há diversos tutoriais.
A segunda é utilizando o ImageLoader e NetworkImageView do Volley. É bem tranquilo de implementar também, com a documentação oficial você consegue facilmente.
Comment: Tem também a lib https://github.com/square/picasso bem simples de implementar, tenho um exemplo que implementei:
https://github.com/analistacarlosh/listViewAndroidWebService

Exibir uma Imagem através de URL


I'm looking for a way to have both a servlet and a jax ws listener preferably in the same class

Question: I have a servlet that acts as controller for a jsp pages , and I want this servlet to able to listen to jax ws messages through the Provider interface , this would be an ideal solution. I also tried to have a different class that implements the Provider and with that class to pass messages to my servlet , but also it wasn't successful.
The last resort solution that i'm thinking of is to use some embeddable server (Jetty) and to embed it in my servlet , but it feels a bit stupid because i'm already having a server (tomcat) why should I use another component that basically the same.

Any input?
Answer: I wouldn't do this.  They aren't basically the same at all.  A servlet listens for HTTP requests synchronously; your JAX-WS listener is asynchronous.
Object-oriented design principles that say objects should do one thing well would advise you to not make these into one component.  What's it buying you, anyway?  You describe your idea as "ideal" and the alternative as "stupid", but I see no rigorous thought about pros and cons of each.  Maybe that will help you decide.
Comment: @Igor, the servlet and the JAXWS listener are both just top-layer components, they should handle translating the incoming message into whatever format you want to represent it and then call into the business logic layer of your app. Both servlet and WS listener can call into same "service" class so you don't duplicate logic.
Comment: Thanks , for a quick answer.
So how would you design an architecture where there should be component that should receive SOAP messages , and this messages need to be parsed and passed to servlet -> so they would be displayed in JPS's.And I prefer no to poll the server , but to have some kind of listening mechanism.
Comment: I'd emulate a design more like what Spring does.
Comment: @matt b - a great comment.  If you make it an answer I'd surely vote it up.
Comment: Duffy could please elaborate a bit , what do you mean by Spring design?
Matt -> I just need a component that can receive SOAP , and I don't want to use polling technique.So i'm working building a component that receives messages and transferring them to the servlet.And I would prefer to isolate the servlet from the communication logic.


Adding font-size and color buttons

Question: I work with Drupal 8.1.3 and my WYSIWYG editor lacks font-size and color buttons.
Is there a way to unlock these or should I install a total different editor (while trying to convince some in the community to bring these options back)?
Answer: You are looking for the ColorButton and CKEditor Font Size and Family plugins.
Follow the instructions on the project pages and you'll have the option to add those back to the toolbar.
Beware that because these plugins use inline styles, the effects will be removed by Drupal's XSS filtering mechanisms if the format has "Limit allowed HTML tags and correct faulty HTML" enabled.
There is currently no way (that I know of) to have both filtered markup and inline styles. There is currently no equivalent of D7's WYSIWYG Filter module for D8. Such a module would have to both implement a new filter of type Drupal\filter\Plugin\FilterInterface::TYPE_HTML_RESTRICTOR and the hook hook_editor_xss_filter_alter() to override the use of \Drupal\editor\EditorXssFilter\Standard in the Editor module (that class extends Drupal\Component\Utility\Xss and calls its filter method, which in turn is hard-coded to always remove style attributes.
Update: The htmLawed module does provide an alternative to Core's filter, so you can configure it to not strip style attributes during rendering. Ensuring that configuration safe is another matter, but just adding the 'span' tag in the list of allowed tags and removing 'style' from the list of disallowed attributes got me partially there.
I say partially because as soon as you try to edit the saved content or switch to another format and back, the style attribute will still be stripped by Editor module.
When you switch to a format with an editor enabled Editor module's script will make an AJAX call to the server and pass the contents of the original textarea to be filtered before sending it into the editor. (When an editor is attached on page load, this happens as part of generating the form so no AJAX call is needed until the format switch.)
It is during this process which the XSS filtering is still messing with the inline style attribute, as the call to Xss:filter() still blacklists it. The htmLawed module (or another module) would have to perform the aforementioned class replacement to get rid of this feature/problem completely.
So, as long as you re-apply inline styles each time you edit the content, and do not switch between editor formats while doing so, you can get font colors and sizes done, though it's currently a bit impractical and not very intuitive.
Answer: Open Administration -> Configuration -> Content authoring -> Text formats and editors admin/config/content/formats and Configure the text format you are using. Then drag and drop the buttons you want to use in your editor in the Toolbar Configuration section and click Save Configuration.
To add custom styles to the editor like different font colors & font sizes, drag the Styles-button to the toolbar. You will get a new tab below called Styles Dropdown.  In that tab you can add your own Style options. So if you want to add a possibility to add Heading 2 content in your editor, add the line h2|Heading 2. If you want to add text that is red color, add the line .color-red|Red color and then in your CSS file define .color-red { color: red; } and so on.
Comment: This buttons aren't included there. If they appear for you, please upload an image that shows that.
Comment: Ah yes, out of the box there's no font-size or color dropdowns. You'll need to add these yourself by dragging the Styles-button to the toolbar. You will get a new tab below called **Styles Dropdown**.  In that tab you can add your own Style options. So if you want to add a possibility to add **Heading 2** content in your editor, add the line `h2|Heading 2`. If you want to add text that is red color, add the line `.color-red|Red color` and then in your CSS file define `.color-red { color: red; }` and so on.
Comment: I can write CSS directly in the source code; I am not asking of a way to write CSS directly with the editor but rather on a way to bring back these buttons - Most preferably in a modular way.
Comment: Adding the Styles-dropdown doesn't add any CSS directly. It only allows you to specify CSS Classes and tags to your content that you can then style as you wish in your theme's CSS stylesheet.
Comment: It's quite different than what I aim to get.
Comment: Indeed, but it is a solution that gives the desired end result and can be accomplished out of the box. As far as I know there are no CKEditor Widget modules for D8 out there that accomplish what you want at the moment.
Comment: The styles drop down is there to avoid doing inline style.

Adding font-size and color buttons


Problem with teleporting Player to another scene

Question: I have 3 levels in my game, and the Door object to teleport player to another level(colliding with the door). The problem is that when i enter my door in some specific way(just moving forward without stopping), player teleports right to the third level. I think that is because OverlapCollider function detects some extra hits. How do i fix it? Here is my code and screenshot.
Door
public class Door : Collidable
{
    public string[] sceneNames;

    private static int sceneNumber = 0;

    protected override void OnCollide(Collider2D coll)
    {
        if(coll.name == "Player")
        {
            GameManager.instance.SaveState();

            //Teleport the player to next level
            sceneNumber++;

            if (sceneNumber >= sceneNames.Length)
            {
                return;
            }

            string sceneName = sceneNames[sceneNumber];
            SceneManager.LoadScene(sceneName);
        }
    }
}

Collidable
public class Collidable : MonoBehaviour
{
    public ContactFilter2D filter;
    private BoxCollider2D boxCollider;
    private Collider2D[] hits = new Collider2D[10];

    protected virtual void Start()
    {
        boxCollider = GetComponent<BoxCollider2D>();
    }

    protected virtual void Update()
    {
        //Collision work
        boxCollider.OverlapCollider(filter,hits);
        for (int i = 0; i < hits.Length; i++)
        {
            if (hits[i] == null)
                continue;

            OnCollide(hits[i]);

            //The array is not cleaned up, so we do it ourself
            hits[i] = null;
        }
    }

    protected virtual void OnCollide(Collider2D coll)
    {
        Debug.Log("OnCollide was not implemented in " + this.name);
    }
}

Door and player colliders
I tried to minimize door collider size, but it didnt work. I thought some extra hits appear because player collider is smaller.
Answer: There is a better way to load the next scene by utilizing the build index.
protected override void OnCollide(Collider2D coll)
{
    if(coll.name == "Player")
    {
        GameManager.instance.SaveState();
        SceneManager.LoadScene( SceneManager.GetActiveScene().buildIndex + 1);
    }
}

It doesn't matter how many times the collision occurs, it will always load the following scene. You only have to make sure that you've added your scenes in the correct order and that the last scene doesn't try to execute this code.


A nice conjecture about convexity

Question: Let $L : C([0,1]) \rightarrow \mathbb R$ linear continuous, with $L(id)=0$, $L(1)=0$ and $L(c)>0$
($c:x \rightarrow x^2$)
Is it true that $\forall f\in C([0,1])$ convex, $L(f) \geq 0$ ?
$C([0,1])$ with the uniform norm.
Comment: I currently try to build a counterexample. The point which I find strange (or 'interesting') is, that the condition is only a condition on a finite dimensional subspace $U := \mathrm{span}\{ \mathrm{Id}, 1, c \} \subseteq C( [0,1] $.
But the subspace of convex functions is larger, i.e. how could a condition on $U$ imply a condition for all convex functions...
Comment: @SteffenPlunder: you've essentially done it - any linear functional can be extended from a finitely-dimensional subspace of $C([0,1])$ to a continuous linear functional on the whole $C([0,1])$. Thus there is certainly an $L$ such that $L(x\mapsto x^3)=-1$, say.
Comment: Just to be sure: $L(\mathrm{Id})$ and $L(1)$ should be the zero-functions? And the image of the function $c$ should be a function that is non-negative and non-zero, or should it be nowhere zero?
Comment: Excuse me, it's a typo
Comment: Can you tell us what makes this conjecture seem "nice" to you?
Comment: If it's true, it's an intersting general result
Comment: OK, suppose it *is* true; can you say why it's "interesting"? And please, please, don't just say "because it's fascinating" or some other adjective. Explain to me (a person without much experience in analysis) why such a result would intrigue analysts.
Comment: There exists a theorem which only the conditions one some functions (square, identity and constant) give a general consequence, like here, but I don't remember the name of this result.
Comment: @Dattier: Do you mean the Korovkin theorems?
Comment: @metamorphy: Yes, that sound good. But I still struggle to find a concrete counterexample :D
Comment: @SteffenPlunder : yes, Korovkin result's
Answer: Take $L(f)=27f(0)-72f(1/3)+63f(2/3)-18f(1)$. You get
$$L(1) = L(\mathrm{Id}) = 0, \quad L(x\mapsto x^2) = 2, \quad L(x\mapsto x^3) = -2.$$
Comment: (I've removed my prior comments due to incorrect reasoning which caused a lengthy discussion. Here is the same counterexample with the reasoning fixed.) Take $L(f)=f(1)-3f(2/3)+3f(1/3)-f(0)$ (third-order finite difference). It is easy to check that $L(x\mapsto x^n)\geqslant 0$, with equality for $n<3$. Now $f(x)=3x^2-x^3$ is convex on $[0,1]$, but $L(f)=-2/9$.
Comment: What about the case $L(x\rightarrow 1)=L(x\rightarrow x)=0$ and $\forall n \in \mathbb N_{\geq 2} L(x\rightarrow x^n) \geq 0$ ?
Answer: By defining $L(1)=0$, $L(x)=0$, $L(x^2)=1$, and $L(x^3)=-1$; this gives a linear functional $L$ on the span of $\{1,x,x^2,x^3\}$ that is continuous on the span. The Hahn-Banach theorem provides a continuous extension. The function $x\mapsto x^3$ is convex, but its image is negative.

A nice conjecture about convexity


What's the meaning of the expansion coefficient of the AR model?

Question: I am trying to understand the meaning of the phi parameter of the AR modeling. A bit of background: I am digging into statistical parametric mapping (SPM) and the prewhitening method, used to get rid of the temporal correlation in the data.
SPM in particular models the noise with a AR(1) model, which means that the model takes into account the correlation between samples that are 1 lag apart, right?
In the specifications of the AR(1) model, phi is set to 0.2. There is no reference for this, only in a mailing list I found that this is an empirical value that is good for fMRI.
The topic of course is also explained on wikipedia:

But despite the readings and the research what I still don't get is: what's the exact effect of this parameter on the data?
When I change it in SPM, final results change drastically (in terms of statistical significance). How to assess which phi is the right phi?
Comment: AR models use lagged values of your series as explanatory variables. If you have an AR(1) model, then $X_t=\phi X_{t-1}+\varepsilon_t$. In this case, $\phi$ is the amount of $X_t$ that is explained by its past value, $X_{t-1}$. Note, however, that you first have to estimate $\phi$. You cannot simply say $\phi=0.2$. That is wrong! You have to estimate it and validate your model. In order to do that you need to know a little bit of the theory and use some statistics software.
Comment: Hello Guilherme, thanks a lot for your input, I guess I do have some lack here, can you please point me at some basic reference for me to understand how to estimate it and which statistics software to use?
Comment: You could get Time Series by Hamilton, but it might be a quite long read. Or try to absorb the maximum you can from this https://youtu.be/uBeM1FUk4Ps and they look for related videos on the topic. You could use R to do this estimation, but if you want something easier to deal with you should try Eviews or stata.
Answer: Not as much an answer to your question, but to the underlying misunderstanding:
SPM does not simply set $\phi = 0.2$, it approximates the autocorrelation of an AR(1) process by a 1st-order Taylor expansion at $\phi = 0.2$. The coefficients of the resulting variance components are estimated by SPM. For a reference, see K. Friston et al. (eds.), Statistical Parametric Mapping, 2007, chapter 10. The rationale is that variance components can be estimated by ReML, while proper AR estimation from residuals is difficult.
This approach has been shown to often not be sufficient (look at the publications by W. Olszowy). Newer versions of SPM implement another method, called "F.A.S.T.", which appears to overcome these limitations by adding more Taylor-expansion variance components. See Corbin N, Todd N, Friston KJ, Callaghan MF. Accurate modeling of temporal correlations in rapidly sampled fMRI time series. Hum Brain Mapp. 2018;00:1–14. link


fingers bending when playing the piano, what to do?

Question: My piano teacher has told me that my fingers bend in an unnatural way and this will be detrimental to my long term piano success. What are some good excersizes from prevent the tips of my fingers from laying flat on the piano and instead having arc.
Here is my attempt to show you how my fingers hit the keys vs how they should hit the keys.
How they should hit the keys (at an angle)
<code>      /
     /
    /
   /
</code>
How they hit the keys right now
<code>       /
      /
   _ /
</code>
the first joint in my finger goes flat to the piano which I have been told is bad for my form and sometimes can hurt to play. I don't have this issue EVERY time I hit a key but sometimes I end up hitting the keys this way and I want to not have issues in the longer term of playing the piano.
Any advice will help me greatly, thank you for taking the time to read this post. EDIT: any specific practice routines specifically will help me so much if anyone has resources for this issue, thanks again.
(ALSO, they angle is obviously pretty dramatic in the slashes but I hope you get what I am saying)
Comment: Does it hurt when your fingers touch the keys and go flat?
Answer: You need to look at the shape of your hand (and the position of your arm) as you address the keyboard.  Fingers are not expected to be flat but in an arc coming down from your hand.  Your elbows need to be raised slightly to allow you to use the weight of your forearms when striking the notes.
Your teacher should be able to help you with this and I'm sure you could find some images on the internet, possibly even as answers to other questions on this site.
As always, when you know what you need to do you will have to practise!
Good luck
Answer: Make sure your elbows are situated properly, which should be to the side, but slightly in front of your body. If your fingertips are collapsing down, try pushing your elbows and forearms slightly more forward so that the upper part of your hands moves closer to the back of the keys. This should raise your fingers so they are on the fingertips. Make sure your palm has a bit of a cup shape to it. Also pay close attention to how the tops of your hands feel. They should not feel strained or "pulled on", but relaxed. Also make sure you are sitting properly. You should be far enough away from the piano so that your elbows are slightly in front of your body. Do not sit straight up, but keep your back straight and lean slightly forward from the hips. Being too "straight up" actually encourages pulling away from the keys, which could lead to the arms pulling down on the hands, which could lead to your fingertips collapsing. It is all connected!
Answer: That end fulcrum is called a phalanx.  People break that phalanx when they press too hard into the keybed, they are playing from the fingers and not the arm, or they are sitting too high.
There are no exercises to stop doing it.  You need to make a concentrated effort to just stop doing it. You need to retrain your arm.
I'll be so bold as to say that you need a new teacher. First, if they didn't know that that was a phalanx, second, if they didn't correct it the first day they saw it, third, if they think you need a magical exercise to eradicate it and fourth, if they don't know that it is the arm that plays the piano and not the fingers . . . you've got a teacher who will cripple you with their ignorance.  Well, they will allow you to cripple yourself.
Barbara Lister-Sink created a video called "Freeing The Caged Bird" and there is a floor example she uses to help students find the weight of the arm and alignment of each fulcrum and the arm behind the finger.  You can do this yourself sitting at the piano but her example is very good.  I beleive much of her video is on Youtube.
Comment: Wait why are piano teachers supposed to know what a specific part of your body is called? Piano teacher usually majors in music, not biology, after all. (Of course if there was a piano teacher who happens to know a lot about how exactly one's hands work while playing the piano, it would certainly be helpful to their teaching to some extent)
Answer: Sounds like you may be pressing the keys too hard.  Remember, it's the speed with which the key travels that makes the note soft or loud, once it hits the bottom the job's done, no point in pressing.  (OK, some electric instruments have Aftertouch, but this is piano, right?)
You've noticed you're doing it.  Good, that's half the battle won already.  'Don't do that then'.
Comment: this is great advice! will apply this to my playing, thank you.


Cardinality of unnumerable set

Question: In the last class my professor asked us a question, which is:

If a set $X$ is uncountable and $Y$ is a countable set, then is $X\setminus Y$ countable or uncountable?

What I did was to think of the set $\mathbb{R}$ and subtract from it the set of $\mathbb{N}$. Since the set $\mathbb{R}$ is uncountable and $\mathbb{N}$ numerable, the set $\mathbb{R}$ is still uncountable because you cannot have injectivity but I am not sure about this answer, can someone give me a hint or tell me if my reasoning is correct please?
Comment: Hint: $X = Y \cup (X \setminus Y)$ and $Y, X\setminus Y$ are disjoint. What happens if you assume that $X \setminus Y$ is countable?
Comment: If $X\setminus Y$ are disjoint and countable I will have a empty set, right? @DominikKutek
Comment: What would be an empty set? I think I don't understand. What I meant, if you assume that $X \setminus Y$ is countable, then $X$ is an union of two countable sets (namely $Y$ and $X \setminus Y$). Why is this a contradiction with the assumption that $X$ is uncountable?
Comment: Sorry, I don't know why is a contradiction @DominikKutek
Comment: Somehow I've misread the question and thought that $Y$ is a subset. Anyway you have $X \subset Y \cup (X \setminus Y)$. If both $Y$ and $X\setminus Y$ are countable then their sum is countable, too, hence $X$ as a subset of countable set is countable (by countable I mean finite or bijective with $\mathbb N$)
Answer: Suppose $X\setminus Y$ is countable or finite. Since $X=(X\setminus Y)\cup (X\cap Y)$ and $X\cap Y$ is countable or finite as a subset of a countable set $Y$, $X$ would be a (disjoint) union of two countable or finite sets, hence at most countable, a contradiction.
Comment: The contradiction with your assumption that $X$ is uncountable.
Comment: Thank you but I have a doubt. I didn't understand this part "would be a union of two countable or finite sets, hence at most countable, a contradiction.". Could you please explain me that part, thank you. @markvs
Comment: What is it exactly that you do not understand? The fact that $X$ is the union of two (disjoint) subsets $X\setminus Y$ and $Y\cap X$? Or the fact that the union of two (disjoint) at most countable subsets is at most countable?
Comment: When you say "a union of two countable or finite sets, hence at most countable, a contradiction.". Why the union is a contradiction? @markvs
Comment: Hehe, for a moment I was lost. Thank you very much.

Cardinality of unnumerable set


e.startsWith Is Not A Function Error When Importing cURL Into Postman

Question: I'm trying to import this cURL example into Postman via Import > Raw Text:
<code>curl https://invoice-generator.com \
  -H "Accept-Language: fr-FR" \
  -d from="Invoiced, Inc." \
  -d to="Acme Corp." \
  -d logo="https://invoiced.com/img/logo-invoice.png" \
  -d number=1 \
  -d currency=eur \
  -d date="Feb 9, 2015" \
  -d due_date="Feb 16, 2015" \
  -d items[0][name]="Starter plan monthly" \
  -d items[0][quantity]=1 \
  -d items[0][unit_cost]=99 \
> invoice.pdf
</code>
(taken from here)
But I'm getting an error:

Error while importing Curl: e.startsWith Is Not A Function

I've seen posts about this error while running cURL in Postman but obviously this is a different situation and I'm not sure how to resolve this one?
Comment: .. where are you getting that error? looks like you're not running it in a unix terminal?
Comment: @hanshenrik as I mentioned in my post "I'm trying to import this cURL example into Postman via Import > Raw Text" so no I'm not running it in a Unix terminal
Answer: The last line of this cURL command exports the output to a file called invoice.pdf. Postman can't do that, at least, not in this way.
Postman's cURL import is, in my experience, flaky; make sure that all your quotes are double non-curly quotes, and delete all the 's as well as the > invoice.pdf and it might work OK.
Comment: Thanks! Turns out all I had to do there was remove the `> invoice.pdf` in this instance, I just didn't realise that Postman would try to do the last bit when doing an import.


Determining the Colorspace of a UIImage

Question: I'm wondering if there's an easy way to get the colorspace of an image (i.e. an image loaded into a UIImage)? For example, I have a TIFF image and I'd like to be able to determine if it uses the RGB colorspace or not. Is there an easy way to do this without manipulating pixel data? I know there's some CGColorSpace functions, but none of them seem to do this, just create colorspaces and manipulate them (and much more advanced functions).
Thanks in advance.
Answer: You have to get the color space through CGImage. You can do it with the following line of functions/properties:
@property(nonatomic, readonly) CGImageRef CGImage

CGColorSpaceRef CGImageGetColorSpace (
   CGImageRef image
);

So to get the color space of an image, you'd do:
CGColorSpaceRef colorspace = CGImageGetColorSpace([myUIImage CGImage]);

And of course, make sure to follow the get/create/copy rules for CG objects.
Answer: Swift
To obtain the color space of a UIImage:
let colorSpace = myUIImage.cgImage?.colorSpace

Example code that checks the color space type:
if colorSpace == CGColorSpace(name: CGColorSpace.sRGB) && colorSpace != nil {
  print("valid sRGB")
}

See Apple's CGColorSpace Documentation "Accessing System-Defined Color Spaces" for the complete list of color space types.

Determining the Colorspace of a UIImage


Probability of Intersection of any set (Union Bound Question)

Question: For any set $$A_k,1 <= k <=n$$ we have
[can we prove]
$$P(\bigcap_{k=1}^{n} A_k) >= \sum_{k=1}^n P(A_k) - (n-1)  $$
Comment: What do you mean by the product of sets $\prod_k A_k$? The title mentions intersection and union but that is (more commonly) denoted by $\cap_k A_k$ and $\cup_k A_k$ respectively. Can you clarify?
Answer: Hint: For any collection of events, $\ \left\{B_k\right\}_{k=1}^n\ $,
$$
P\left(\bigcup_\limits{k=1}^nB_k\right)\ge \sum_\limits{k=1}^nP\left(B_k\right)\ .
$$
Put $\ B_k = \Omega\setminus A_k\ $ and use the identities $\ \bigcup_\limits{k=1}^nB_k= \Omega\setminus\bigcap_\limits{k=1}^nA_k\ $, and  $\ P\big(\Omega\setminus E\big)=1-P(E)\ $ for any event $\ E\ $.


How many NHL natural hat tricks in a single period have been scored?

Question: How many natural hat tricks have been scored, with all of the goals occurring in the same single period, in NHL history?
Comment: The question doesn't ask for a list of all one-period natural hat tricks, only how many there have been, which should be a straightforward counting via a statistical database. That one answer has listed all of a small number doesn't make the question too broad.
Answer: Only having data for the 2017-2018 NHL season at my disposal:

81 hat-tricks were scored throughout the season
13 were natural
6 natural hat-tricks were scored in a single period (46.15% of all natural hat-tricks)

Jamie Benn (1st period)
Radek Faska (2nd period)
William Karlsson (2nd period)
Jason Zucker (3rd period)
Teuvo Teravainen (3rd period)
John Tavares (3rd period)


Openshift overrides email header 'from', 'reply-to' fields. How to send email without having to use SendGrid nor other paid email service.?

Question: I have django 1.6 and python 2.7 deployed on Openshift.  I notice that when the application sends emails out, Openshift overrides the email header by changing the 'From' field to 'email@example.com' and ignore all 'Reply-to' field that has been set in the application.
I have searched around and it seems like Openshift overrides the email header and recommendation is to use their email service partner which is NOT FREE.
Is there any other way to avoid this ie. deploy Django application on Openshift while still having the application sends email as per dictated in the program.  This exact program runs with no issues on test environment and localhost.
Any pointers are much appreciated.  Thank you.
Answer: I myself is looking for free SMTP library to just send emails. So far not much luck.
Tried java embedded SMTP library Aspirin. I am able to  send mails but not very comfortable working with it as I keep getting some unknown exceptions.
Apache James as another Java based SMTP server but don't think we can embed in the code yet.


Backup MongoDB database copying files in `dbpath`?

Question: I need a daily backup of all MongoDB databases in our single-instance server (without stopping the MongoDB service). Our server is in Rackspace so I'm wondering if a valid strategy could be just add all the database files (files in dbpath) to our automatic backup.
I've considered another options as well, but this will save us a lot of time and seems simpler and easier. The question is: is this solution reliable?
Comment: Asked and answered already here: http://dba.stackexchange.com/a/62853/6441
Answer:
without stopping the MongoDB service
  [...]
  is this solution reliable?

as is, no.
have a look at Backup by Copying Underlying Data Files
in order to have a consistent backup, the data you are backing up must not change during the whole backup process.
you said you can't stop the server so:

use LVM/filesystem snapshots

or

setup a replicaset, and perform backup with it. you'll be able to freeze/stop it as you want.
Comment: I'm very unsure, but I think mongodb could still start on corrupted data. considering it as a system crash and trying to recover what it can be with journaling.
if you use database references for example, it could be broken because the referenced document is missing
Comment: Is not reliable in which sense? The backup could miss some data? Or the backup could be corrupt and unrecoverable? Our data is not critical, we can assume some losses... (sorry, perhaps this should be a part of my question).


Desciprtion Function In Android

Question: I learning  android programming and in my first step I want to know what each function do
I discovered that all description about the function is found in activity.class.
IS my information right?
if it right I have a problem in activity.class in eclipse
and the error msg is the source attachment doesn't contain the source for the file Activity.class
what can i do ?
Answer: Here is all the information, that you need to know about activity http://developer.android.com/reference/android/app/Activity.html

Desciprtion Function In Android


Getting private attribute in parent class using super(), outside of a method

Question: I have a class with a private constant _BAR = object().
In a child class, outside of a method (no access to self), I want to refer to _BAR.
Here is a contrived example:
class Foo:
    _BAR = object()

    def __init__(self, bar: object = _BAR):
        ...

class DFoo(Foo):
    """Child class where I want to access private class variable from parent."""

    def __init__(self, baz: object = super()._BAR):
        super().__init__(baz)

Unfortunately, this doesn't work.  One gets an error: RuntimeError: super(): no arguments
Is there a way to use super outside of a method to get a parent class attribute?

The workaround is to use Foo._BAR, I am wondering though if one can use super to solve this problem.
Comment: Hi, check [this](https://stackoverflow.com/questions/56896131/why-cant-super-access-the-attribute-in-a-class-in-python) out.
Comment: Duplicate of https://stackoverflow.com/questions/26318836/getting-parent-private-or-protected-values-from-the-child-class ?
Answer: Inside of DFoo, you cannot refer to Foo._BAR  without referring to Foo. Python variables are searched in the local, enclosing, global and built-in scopes (and in this order, it is the so called LEGB rule) and _BAR is not present in any of them.
Let's ignore an explicit Foo._BAR.
Further, it gets inherited: DFoo._BAR will be looked up first in DFoo, and when not found, in Foo.
What other means are there to get the Foo reference? Foo is a base class of DFoo. Can we use this relationship? Yes and no. Yes at execution time and no at definition time.
The problem is when the DFoo is being defined, it does not exist yet. We have no start point to start following the inheritance chain. This rules out an indirect reference (DFoo -> Foo) in a def method(self, ....): line and in a class attribute _DBAR = _BAR.
It is possible to work around this limitation using a class decorator. Define the class and then modify it:
def deco(cls):
    cls._BAR = cls.__mro__[1]._BAR * 2  # __mro__[0] is the class itself
    return cls

class Foo:
    _BAR = 10

@deco
class DFoo(Foo):
    pass

print(Foo._BAR, DFoo._BAR) # 10 20

Similar effect can be achieved with a metaclass.
The last option to get a reference to Foo is at execution time. We have the object self, its type is DFoo, and its parent type is Foo and there exists the _BAR. The well known super() is a shortcut to get the parent.
I have assumed only one base class for simplicity. If there were several base classes, super() returns only one of them. The example class decorator does the same. To understand how several bases are sorted to a sequence, see how the MRO works (Method Resolution Order).
My final thought is that I could not think up a use-case where such access as in the question would be required.
Answer: Short answer: you can't !
I'm not going into much details about super class itself here. (I've written a pure Python implementation in this gist if you like to read.)
But now let's see how we can call super:
1- Without arguments:
From PEP 3135:

This PEP proposes syntactic sugar for use of the super type to
automatically construct instances of the super type binding to the
class that a method was defined in, and the instance (or class object
for classmethods) that the method is currently acting upon.
The new syntax:
super()

is equivalent to:
super(__class__, <firstarg>)

...and <firstarg> is the first parameter of the method

So this is not an option because you don't have access to the "instance".
(Body of the function/methods is not executed unless it gets called, so no problem if DFoo doesn't exist yet inside the method definition)
2- super(type, instance)
From documentation:

The zero argument form only works inside a class definition, as the
compiler fills in the necessary details to correctly retrieve the
class being defined, as well as accessing the current instance for
ordinary methods.

What were those necessary details mentioned above? A "type" and A "instance":
We can't pass neither "instance" nor "type" which is DFoo here. The first one is because it's not inside the method so we don't have access to instance(self). Second one is DFoo itself. By the time the body of the DFoo class is being executed there is no reference to DFoo, it doesn't exist yet. The body of the class is executed inside a namespace which is a dictionary. After that a new instance of type type which is here named DFoo is created using that populated dictionary and added to the global namespaces. That's what class keyword roughly does in its simple form.
3- super(type, type):

If the second argument is a type, issubclass(type2, type) must be
true

Same reason mentioned in above about accessing the DFoo.
4- super(type):

If the second argument is omitted, the super object returned is
unbound.

If you have an unbound super object you can't do lookup(unless for the super object's attributes itself). Remember super() object is a descriptor. You can turn an unbound object to a bound object by calling __get__ and passing the instance:
class A:
    a = 1

class B(A):
    pass

class C(B):
    sup = super(B)
    try:
        sup.a
    except AttributeError as e:
        print(e)  # 'super' object has no attribute 'a'

obj = C()
print(obj.sup.a)  # 1

obj.sup automatically calls the __get__.
And again same reason about accessing DFoo type mentioned above, nothing changed. Just added for records. These are the ways how we can call super.


Text in Text View not scrolling even i set ellipsize="marquee" in xml in android

Question: my xml code is
 <TextView
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_gravity="center_vertical"
 android:lines="1"
 android:singleLine="true"
 android:textColor="#ffffff"
 android:focusable="true"
 android:marqueeRepeatLimit="marquee_forever"
 android:ellipsize="marquee"
 android:typeface="serif"
 android:scrollHorizontally="true"
 android:focusableInTouchMode="true"</TextView>

and i set text in Activity in onCreate method as below
textView.setText("some text ");
textView.setSelected(true);
textView.setFocusable(true);
textView.setFocusableInTouchMode(true);

it is working but when close application pressing back button and again restart it text not scroll and also when i change activity and come to the activity where this text view present i wont scroll ?also i tried custom text view
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.TextView;

public class CustomTextView extends TextView {
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}

@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
if(focused)
super.onFocusChanged(focused, direction, previouslyFocusedRect);
}
@Override
public void onWindowFocusChanged(boolean focused) {
if(focused)
 super.onWindowFocusChanged(focused);
}
@Override
public boolean isFocused() {
return true;
}

}

but it wont work
Answer: You have to use android:scrollbars = "horizontal" in xml file, then use
tv.setMovementMethod(new ScrollingMovementMethod());

in your java code.
Answer: Change your layout as ScrollView
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
</ScrollView

Answer: Try changing this:
android:layout_width="fill_parent"

to this:
android:layout_width="80dp"

Answer: Sometimes you need to requestfocus on the TextView before it will scroll.
Comment: appreciate your answer buddy  ..but I had already accepted a answer for my question .. but keep it up to earn some points :-P
Answer: Your code is correct but you have to put text length greater than your device width.


Understand Cotangent Space as an Equivalence Class

Question: In my differential geometry class, my teacher defined the co-tangent space as follows. Let $M$ be a smooth manifold and $p$ is a point on $M$. Now define two sets of $C^\infty$ real-valued functions defined on $M$.

$\mathcal I_p := \left\{f\in C^\infty(M)\bigr|f(p)=0 \right\}.$ That is, the set of functions that vanish at $p$. This is not hard to imagine.
$\mathcal I_p^2 := \left\{\displaystyle\sum_{i=i}^n f_ig_i\bigr|f_i, g_i\in \mathcal I_p \right\}.$ I could not visualise what this set looks like. Is it a subset of $\mathcal I_p$ or a bigger set and why?

After the definition of these two sets comes the even harder concept of quotient as follows. My teacher defined the co-tangent space $T_p^*M$ as the quotient space $\mathcal I_p/\mathcal I_p^2$. I have difficulty in understanding quotient thing in general, especially I have no idea of what this quotient looks like. Is there an intuitive way to understand this concept, please? Thank you!
Comment: I have already came across something like that and I was confused as well (indeed I'm still confused=) Where did your teacher get the definition from?
Comment: I do not know. He wrote it down from his own notes.
Comment: Just a vague hint: $I_p$ is an ideal of $C^\infty(M)$ and $I_p^2$ is the product of this ideal with itself. You may find something about this kind of ideals in "Abstract Algebra" by D. S. Dummit and R. M. Foote..
Comment: Thank you for the suggestion.
Comment: Since he defined $\mathcal{I}_p / \mathcal{I}_{p}^{2}$, certainly $\mathcal{I}_{p}^{2} \subset \mathcal{I}_p$.
Comment: The cotangent space **not** a class but the quotient, that is the set of equivalence classes. Each element of this quotient looks like an element of $\mathcal I_p$ but we deem two such elements **equal** if their difference lies in $\mathcal I_p^2$. Alternatively, you may view elements of the quotients as sets $f + \mathcal I_p^2$ for $f \in \mathcal I_p$.
Answer: It is obvious that $\mathcal I_p^2 \subset \mathcal I_p$. Well, it is an easy exercise: simply use the definition of $\mathcal I_p$ to check that each element of $\mathcal I_p^2$ is in $\mathcal I_p$. Hint: 1) trivial: $a \cdot 0 = 0$ $\forall a \in \mathbb{R}$; 2) less trivial: products of smooth functions are smooth.
Straightforward verifications show the further necessary algebraic properties (being subspaces, ideals...) as the commenters have pointed out.
An important property of the space $\mathcal I_p^2$ is that each element of it has the vanishing differential at point $p$: $\forall f \in \mathcal I_p^2 \; \mathrm{d}f(p)=0$. Hint: use the product rule.
And the crucial fact: the quotient $\mathcal I_p / \mathcal I_p^2$ is a finite dimensional vector space. For a proof one uses the Taylor theorem (in the form that is also known as Hadamard's lemma).
The beauty of this construction is that we obtain a naturally defined finite dimensional vector space at each point of a smooth manifold without using coordinates!
It turns out that elements of this space can act on tangent vectors viewed at an appropriate angle (e.g. as derivations). The duality between vectors and covectors emerges immediately.
What is more important to get is that there is the notion of a cotangent space (of a smooth manifold at a point), and there are various definitions. The notion is something to visualize, the definitions being tools that allow us to work efficiently with the problems. Without a context everything will look unjustified and clumsy.
I hope that my remarks can help. For more details please see this and this notes. Actually, Wikipedia's articles on the tangent and the cotangent spaces are quite helpful too.
Comment: @ElíasGuisadoVillalgordo, thank you for your observation.
Comment: This can be understood as a consequence of a more general phenomenon. See the lemma from [here](https://mathoverflow.net/q/451294/101848) and sentence below.


How to reverse a string using a recursive function?

Question: I've seen lots of posts about reversing a string with recursion, but I like to use my own style of coding to properly understand it. Anyway here is the code I have.
private static String reverse (String s){

    String rev = "";
    int index = s.length()-1;
    if(index >= 0){

        rev += s.charAt(index);
        index--;
        rev += reverse(rev);

    }
        return rev;

    }

Basically index just keeps going for every single character when index is -1 the loop stops. it reads the last possible character of the string but there is an error in this line here.
rev += rev(str)

Here is iterative method
String dog = "dog";
String rev = "";

int index = dog.length()-1;
while(index >= 0){
    rev+=dog.charAt(index);
    index--;

}

out.println(rev);

Comment: Try adding `System.out.println(index);` before recursing to see if you can see the problem.
Comment: Yes I am using java.
Comment: I'm not fully comprehending.. I apologize I'm new to this recursion stuff. Let's say we have a string called "cat" the index starts at 2, then 1 then 0 so it's all printed out it does reach -1, but it wouldn't go through the loop because it is less than 0? so where is the program going wrong?
Comment: I changed it from rev += reverse(rev) to rev += reverse(s) but it didn't solve anything.
Comment: Add it before `rev += rev(str)`  You'll see why.
Answer: I believe when the method calls itself you reset the value of the index. Maybe a better approach would be to have an overloaded method where the original call passes in the string to process and then the remaining calls call a method where you pass in both the string you are building along with the remaining part of the that is being processed.
Comment: I know but it adds the letter before decrementing then when it goes back up the loop is skipped and it should return rev? right?
Answer: The recursive step doesn't contain the mutated string. You need to pass the substring of the original string.
rev = reverse(s.substring(0,index));
Comment: Ok this fixed it I just indexed too late it makes sense now thank you.
Answer: (Posted answer on behalf of the OP).
It's fixed now. Thank you so much, I was indexing too late and passing in negative numbers.
private static String reverse (String s) {

int index = s.length();
index--;
String rev = "";
if(index >= 0){
    rev += s.charAt(index);

    rev = rev + reverse(s.substring(0,index));
}

return rev;

}


Creating two dynamoDB tables in serverless.yml

Question: I'm try to add 2 tables to serverless.yml to link with DynamoDB.
A part of my code in serverless.yml:
...
 resources:
      Resources:
        ItemsTable:
          Type: "AWS::DynamoDB::Table"
          Properties:
            TableName: "InvoiceConfig"
            AttributeDefinitions:
            - AttributeName: "providerName"
              AttributeType: "S"
            KeySchema:
            - AttributeName: "providerName"
              KeyType: "HASH"
            ProvisionedThroughput:
              ReadCapacityUnits: 2
              WriteCapacityUnits: 2
            TableName: "DifferentTermsPages"
            AttributeDefinitions:
            - AttributeName: "id"
              AttributeType: "S"
            - AttributeName: "providerName"
              AttributeType: "S"
            - AttributeName: "productType"
              AttributeType: "S"
            - AttributeName: "language"
              AttributeType: "S"
            - AttributeName: "terms"
              AttributeType: "L"
            KeySchema:
            - AttributeName: "id"
              KeyType: "HASH"
            - AttributeName: "providerName"
              KeyType: "HASH"
            - AttributeName: "productType"
              KeyType: "HASH"
            - AttributeName: "language"
              KeyType: "HASH"
            - AttributeName: "terms"
              KeyType: "HASH"
            ProvisionedThroughput:
              ReadCapacityUnits: 10
              WriteCapacityUnits: 10

Is that correct??
My tables are:
InvoiceConfig: with columns: providerName (String)
DifferentTermsPages: id (String), providerName (String), productType (String), language (String), terms (list)

Do I need more changes in serverles.yml? what is the meaning of the expressions "ReadCapacityUnits" and "WriteCapacityUnits"?
Answer: There should be some separation between two resources (i.e. two DynamoDB tables).
Note:-
You can define only key attributes while creating the DynamoDB table. In other words, you don't need to define all other non-key attributes.
Try this:-
Resources:
ItemsTable:
  Type: "AWS::DynamoDB::Table"
  Properties:
    TableName: "InvoiceConfig"
    AttributeDefinitions:
    - AttributeName: "providerName"
      AttributeType: "S"
    KeySchema:
    - AttributeName: "providerName"
      KeyType: "HASH"
    ProvisionedThroughput:
      ReadCapacityUnits: 2
      WriteCapacityUnits: 2
DifferentTermsPages:
  Type: "AWS::DynamoDB::Table"
  Properties:
    TableName: "DifferentTermsPages"
    AttributeDefinitions:
    - AttributeName: "id"
      AttributeType: "S"
    KeySchema:
    - AttributeName: "id"
      KeyType: "HASH"
    ProvisionedThroughput:
      ReadCapacityUnits: 10
      WriteCapacityUnits: 10

Read and Write capacity units:-

You specify throughput capacity in terms of read capacity units and
  write capacity units:
One read capacity unit represents one strongly consistent read per
  second, or two eventually consistent reads per second, for an item up
  to 4 KB in size. If you need to read an item that is larger than 4 KB,
  DynamoDB will need to consume additional read capacity units. The
  total number of read capacity units required depends on the item size,
  and whether you want an eventually consistent or strongly consistent
  read. One write capacity unit represents one write per second for an
  item up to 1 KB in size. If you need to write an item that is larger
  than 1 KB, DynamoDB will need to consume additional write capacity
  units. The total number of write capacity units required depends on
  the item size.

Read and write capacity units
Answer: Short Answer:
Read and Write Capacity Units are the max size of data the db is allowed to processes per second, if you go over this amount in any second your request would throttle.
Alternative:
It might be easier to just use DynamoDB On-Demand and pay for the Db table usages rather than calculating WCU and RCU.
Example
Here is an example of 3 tables added in a formatted manner and without semiquotes:
resources:
  Resources:
    myDynamoDBTable1:
      Type: AWS::DynamoDB::Table
      Properties:
        TableName: Table1
        AttributeDefinitions:
          - AttributeName: ColumnName1
            AttributeType: S
          - AttributeName: ColumnName2
            AttributeType: N
        KeySchema:
          - AttributeName: ColumnName1
            KeyType: HASH
          - AttributeName: ColumnName2
            KeyType: RANGE
        ProvisionedThroughput:
          ReadCapacityUnits: 1
          WriteCapacityUnits: 1
    myDynamoDBTable2:
      Type: AWS::DynamoDB::Table
      Properties:
        TableName: Table2
        AttributeDefinitions:
          - AttributeName: ColumnName1
            AttributeType: S
        KeySchema:
          - AttributeName: ColumnName1
            KeyType: HASH
        BillingMode: PAY_PER_REQUEST
    myDynamoDBTableN:
      Type: AWS::DynamoDB::Table
      Properties:
        TableName: TableN
        AttributeDefinitions:
          - AttributeName: ColumnName1
            AttributeType: S
        KeySchema:
          - AttributeName: ColumnName1
            KeyType: HASH
        BillingMode: PAY_PER_REQUEST

Additional Explanation with Examples:
Back to Read/Write Capacity Mode:
Write Capacity Units (WCU) formula: Round up (DataSize / 1KB)
Example1:
imagine you foresee a traffic of writing 10KB of data per second into the db. Using the WCU formula, you would need (10KB / 1KB) = 10WCU.
Example2:
Expecting writing traffic of 7.5KB of data to the db, we would need: (7.5KB / 1KB) = 8WCU
Reading Capacity Units (RCU) depends on Strongly or Eventually Consistent models.
Strongly Consistent mode: Round up (DataSize / 4KB)
Eventually Consistent mode: Round up(DataSize / 4KB) / 2


Is it possible to find the return type of a boost::function from it's typedef?

Question: Is it possible to find the return type of a boost::function purely from its typedef?
Example:
typedef boost::function<bool (int, float)> CallbackType1;
typedef boost::function<float (int, float)> CallbackType2;

How to find the return type of the above function types?
I'm not sure if using c++0x features will be possible in my target build system, but any solution is welcome.
Many Thanks Guys,
Sak
Answer: Boost.Function has a typedef inside it called return_type that should do the trick:
typedef CallbackType1::result_type CallbackType1ReturnType;

No wizardry needed.


require_once não funciona

Question: Estou tentando dar require_once num Arquivo PHP que tem uma classe.
O Arquivo que estou tentando incluir no PHP com a classe possui apenas um array com dados de configuração, porém não consigo acessa-lo devidamente.

class CoreDatabase {

    public $database;

    public function __construct() {
        require_once('aps/config/database.php');
        $this->database = new PDO($db_data['default']['driver'] . ':host=' . $db_data['default']['host'] . ';dbname=' . $db_data['default']['name'], $db_data['default']['user'], $db_data['default']['password']);

        $statement = $this->database->prepare('select * from tablex');

        $statement->execute();
        echo var_dump($statement->fetch(PDO::FETCH_ASSOC));
        echo var_dump($this->database);
        echo var_dump($data);
        echo var_dump($statement);
    }

Editado
Galera, eu resolvi brevemente, desculpem o incomodo.
Enfim, eu fiz o require_once dentro do construtor da classe, e deu certo, agora eu atribuo $db_data para um atributo e tenho tudo dentro da classe.
Comment: PS: Quando leio os logs de erro, dizem que PHP Notice:  Undefined variable.
Comment: `$db_data` veio da onde?
Comment: Vem do require_once require_once('aps/config/database.php');
Comment: Comentário para a sua resposta: Se você quiser, você pode lidar com o erro verificando o retorno da função `require_once`.   `$retorno = require_once('aps/config/database.php');   if ($retorno === false) {  echo "Error." }`.
Comment: Você pode [responder sua própria pergunta e aceitá-la como resposta](https://pt.stackoverflow.com/help/self-answer). Assim, fica mais claro para quem ver sua pergunta mais tarde. E, ainda te possibilita a ganhar mais pontos.
Answer: Se $db_data é a variável de configuração que vem de aps/config/database.php ela deve ser passada como argumento no construtor dessa forma a classe consegue acessar ela.
Mude:
public function __construct() {

Para:
public function __construct($db_data) {

Na hora instanciar essa classe lembre de passar a variável.
$dbCore = new CoreDatabase($db_data);

Comment: Obrigado rray, é uma opção, porém eu não poderia estar passando como parâmetro, eu queria fazer algo mais parecido com a estrutura do CodeIgniter, sabe? Porém é uma opção, obrigado!
Comment: @instalaçãoplanejamento o CodeIgniter da um include dentro de um método olha o [código](https://github.com/bcit-ci/CodeIgniter/blob/develop/system/database/DB.php#L57)
Comment: Sim sim! Percebi isso agora! Obrigado!
Answer: Mano é fato que tem erro, só tem que o require_once produz um tratamento de erro que encerra o script, usa include_once no lugar que ele vai te exibir o erro e você vê o que tá errado e corrige, ex:
include_once "aps/config/database.php";

E tem mais, declare fora da class, ex:
include_once "aps/config/database.php";
class CoreDatabase {}

Comment: O `require_once` também produz uma mensagem de erro. A diferença que é que ele produz um erro **fatal** que parará o script (`E_COMPILE_ERROR`) enquanto que o `include_once` ou gerará apenas um aviso (`E_WARNING`).

require_once não funciona


The probability of observing the mean draw from binomial distribution

Question: I'm reading an article that considers the random variable $p$ that is uniformly distributed on the interval $[0,1]$. It attempts to express the probability of some observation of $p$ being the mean draw from $M$ trials. The argument goes:
Consider $M$ draws of the random variable $p$. $p$ is the mean(=median, given uniform dist) when $k$ draws are less than $p$ and $M-k$ are greater than $p$.* Since $p \in [0,1]$, the probability of observing $p$ is just $p$. Hence, the probability of $k$ draws being less than $p$ (= probability of draws being greater than $p$), is:
$$\int_0^1\binom{M}{k}p^k(1-p)^{M-k}=(M+1)^{-1}$$
I think $p$ is assumed to equal $0.5$ for this expression (I doubt this holds in general).
Is my interpretation of the above expression (as giving you the probability of the mean draw) correct? Secondly, how does $\int_0^1\binom{M}{k}p^k(1-p)^{M-k}$ equal $(M+1)^{-1}$?

*I guess this assumes that $M=2k$.
In case my explanation was confusing, see the following:
Answer: I don't think I recognise your description as being the same as the argument presented in the paper. A few points on your description:

You mention that it is about calculating observations of $p$ being the mean, but the article does not talk about the mean.
$p$ is also not a distribution: i.e. you refer to $M$ draws of $p$.
$p$ is random, so it is not being assumed to equal $0.5$, also in this interpretation what is the integral over? The integral should be interpreted as being in the variable $p$.

I will now try to expand on the description given in the paper.
Suppose we have $M+1$ random variables which are independently uniformly distributed $X_0\,X_1,\ldots, X_M \sim \text{Unif}[0,1]$. The paper is answering the following question:

What is the probability that $X_0$ is the $k$-th largest value of the $M+1$ random variables?

Let me denote this event  $A^{(0)}_k$, i.e. the event that $X_0$ is the $k$-th largest variable.
The paper now approaches this question from two angles: conditioning and symmetry. I will consider both arguments separately.
Conditioning Argument
In this argument we condition on the specific value taken by $X_0$, this is the value $p$. According to the law of total probability we have
$$\mathbf P[ A^{(0)}_k] = \int \mathbf P \left[A^{(0)}_k \, | \, X_0 = p \right] f_{X_0}(p) dp,$$
where $f_{X_0}$ is the probability density function of $X_0$; since $X_0$ is uniformly distributed, $f_{X_0} = 1$ on the interval $[0,1]$ and is $0$ elsewhere. Hence the integral above becomes
$$\mathbf P[A^{(0)}_k] = \int_0^1 \mathbf P[A^{(0)}_k \, | \, X_0 = p]dp.$$
Now we must consider the conditional probability term. Note that for a single uniform random variable $X$, and a fixed value $a \in [0,1]$, we have
$$\mathbf P[ X < a] = a, \qquad \qquad \mathbf P[x > a] = 1- a.$$
From the perspective of our conditional distribution this means
$$\mathbf P[X_1 < X_0 \, | \, X_0 = p] = p.$$
Note that this is equivalent to saying that conditioned on $X_0 = p$, the event $\{X_1 < X_0\}$ is Bernoulli distributed $\text{Ber}(p)$. Using independence of the $X_1,\ldots, X_M$ this extends to the statement that the event $A^{(0)}_k$, conditioned on $X_0 = p$ is Binomially distributed $\text{Bin}(M,p)$. In particular
$$\mathbf P[A^{(0)}_k\, | \, X_0 = p] = \binom{M}{k}p^k(1-p)^{M-k}.$$
Putting this together, we have
$$\mathbf P[A^{(0)}_k] = \int_{0}^1 \binom{M}{k}p^k(1-p)^{M-k} dp.$$
Symmetry Argument
This argument is much simpler. We note that since $X_0,X_1,\ldots, X_M$ all have the same distribution, they are all equally likely to be the $k$-th largest value.
That is if $A^{(m)}_k$ denotes the  event that $X_m$ is the $k$-th largest variable, then we have
$$\mathbf P[A^{(0)}_k] = \mathbf P[A^{(1)}_k] = \cdots = \mathbf P[A^{(M)}_k]$$
Moreover, since one of these has to be the $k$-th largest we have
$$\mathbf P[A^{(0)}_k] + \mathbf P[A^{(1)}_k] + \cdots + \mathbf P[A^{(M)}_k] = 1,$$
and together these imply
$$\mathbf P[A^{(0)}_k] = \frac{1}{M+1}.$$
And so combining the two arguments we have
$$\mathbf P[A^{(0)}_k] = \int_{0}^1 \binom{M}{k}p^k(1-p)^{M-k} dp = \frac{1}{M+1}$$
Answer: I don't think this interpretation is quite right because we are not drawing from $p$ and we are integrating over all possible values of $p$ (not assuming $p=0.5$).
This problem is part of Beta-Binomial Conjugacy. Suppose you knew that your data is distributed as binomial, but you do not know $p$. So you suppose that $p \sim Unif(0,1)$ (this is the same as $p \sim Beta(1,1)$), this is the prior distribution for $p$. Then if you observe $a$ successes and $b$ failures, Beta-Binomial conjugacy says that your posterior distribution for $p$ is $p \sim Beta(1+a, 1+b)$, i.e the distribution is still Beta.
This integral shows up in the following way: Suppose $X \sim Bin(n,p)$ but $p$ is unknown, so we model $p$ as $Unif(0,1)$. We want the unconditional probability that $P(X=k)$. Notice that by Law of total probability
$$P(X=k)=\int_{0}^{1}P(X=k|p)f(p)dp$$
But given $p$, $P(X=k)$ is a known binomial, so
$$P(X=k)=\int_{0}^{1}\binom{n}{k}p^k(1-p)^{n-k}dp$$
Surprisingly this integral equals $1/(n+1)$, regardless of what $k$ is. I think this is called Bayes' Billards Argument. Here is the intuition I use: $\textit{For the left hand side:}$ Suppose you randomly throw $n$ white darts and $1$ orange dart at the unit interval $[0,1]$. Call the position of the orange dart the random variable $p$. Its clear that $p \sim Unif(0,1)$. Let $X$ be the number of white darts to the left of the orange dart. If we knew $p$, then $X \sim Bin(n,p)$. Using LOTP
$$P(X=k)=\int_{0}^{1}P(X=k|p)f(p)=\int_{0}^{1}\binom{n}{k}p^k(1-p)^{n-k}$$
Now I will show that the $\textit{right hand side}$ is equivalent to this. Now suppose you have $n+1$ unpainted darts that you throw at the unit interval and $\textit{then}$ paint $n$ white and $1$ orange. The orange ball is equally likely to be at any position, so $P(X=k)=1/(n+1)$. So we have
$$\int_{0}^{1}\binom{n}{k}p^k(1-p)^{n-k}=1/(n+1)$$
This is the way it was taught in Stat 110. All the lecture videos and problem sets for the class are available online at stat110.net.


Calculate tonal tension of triads

Question: I'm trying to implement and calculate the tonal tension of a triad (and its harmonics) following the definition given here: https://pdfs.semanticscholar.org/f05e/56c9548fa18c64efeed248742e3a6afb0c02.pdf
The tension of a single triad is given by: t=v*exp[-((y-x)/alpha)^2], where y=log(f3/f2) and x=log(f2/f1) and f3>f2>f1 where f1,f2,f3 are the frequencies of the 3 components of the triad.
So far i've implemented this Matlab code:
    function [tension] = tension(f1,f2,f3)
       Fdif1 = log(f2/f1);
       Fdif2 = log(f3/f2);
       alpha = 0.60;
       tension = exp(-(((Fdif2 - Fdif1)/alpha))^2);
    end

Which seems right to me, but following the experimental data in the paper mentioned above (for example the tension for a single triad of 3 notes without overtones, so 3 simple sinusoids) I don't get at all the value mentioned in the graph (figure 6 of the paper).
What am i doing wrong? I thought it could be a mismatch of domain: the definition of tension works over a pure frequency difference, while (in figure 5 of the paper) the gaussian function of the tension works over semitones difference.
Could it be the problem?
PS: I took inspiration from this answer: Is there a way to measure the consonance or dissonance of a chord? and i wanted to extend the search implementing the other algorithms mentioned in the various papers.
Comment: (I see two authors. http://www.res.kutc.kansai-u.ac.jp/~cook/   https://scholar.google.com/citations?user=x19zNuAAAAAJ&hl=ja)
Comment: As interesting as this is it is not a fair question for either stack exchange and I'd be surprised if you got a straight answer.  You state simply that you used the data in the paper and the equation but don't get figure 6.  Did you try replicating other results first?  How exactly did you use the data and how was the Gaussian model incorporated?  You are asking someone to go through the paper and implement the whole thing to validate your work.  It would help if you provided more detail and possibly your version of the graph for comparison.
Comment: If you don't get an answer here, you could try https://dsp.stackexchange.com/
Comment: @YourUncleBob Done! I hope someone can help me, i cannot figure out what is the problem, and the only source i found are based on this paper (so they basically explain and exploit the same process).
Comment: "I don't get at all the value mentioned in the graph (figure 6 of the paper)."

(Ask the author.)
Comment: I'm sorry, I do realize my question is written poorly. Unfortunately I tried to be as short as possible with my question, I implemented all the functions in the paper with 3 different algorithms for each one and different domains.
My doubt was about the coherence of what it's written in the paper. If it's more useful to provide all the code I wrote with all the consideration I did, I'll update the question as soon as possible.
Comment: What exactly does `alpha` stand for?
Comment: @Pyromonk alpha is a parameter that gives how "wide" is the gaussian. What we're actually doing is modeling the gaussian of tension (figure 5 in the paper), the value has been chosen by the researchers based on sperimental data (basically an "average" of values taken by people listening to different types of chords).
Comment: Anyway i've almost reach a conclusion for this topic, i'm working on some extra code and implementation. As soon as i've finished i'll share the code and the details answering to my own question. Maybe it will be useful for somebody
Answer: I don't know if OP is still working on this, but this seems to be a simple error in the formula given in the paper.  The OP was on the right track with the "mismatch in domain."  That is, the value of alpha (~0.6) that the authors state seems to be based on x and y in their equation being the number of semitones for each interval, as they then use in their scale on their graphs.
The formulas for x and y are wrong for that value of alpha and those graphs.  I think what they actually mean is: x  = 12*log2(f2/f1) and y = 12*log2(f3/f2).  You need base 2 logarithms to convert frequencies to standard pitch scales based around repetition at the octave, and you need the factor of 12 to convert those fractions of an octave to numbers of semitones.
I haven't tried to see whether this matches their model for overtones as well, but it seems to be very close to (if not exactly) what their basic gaussian curve for only fundamental frequencies is based on (in figure 5 and the "F0 only" lines in figures 6-8).

Regardless, I don't find this model of tension to pass even the most basic test for reasonableness.  The entire model is based around the equal tempered semitone, which means that an equal tempered major triad with only fundamentals sounding would have a tension of about 0.06, while a justly tuned 4:5:6 major triad would have a tension of about 0.25.  Note also that the most dissonant triads according to the model are the augmented triad and diminished triad and have a tension of 1.0 by definition (assuming only fundamentals).  That makes absolutely no sense, with the equal tempered triad having basically "no tension," while the purely tuned triad is about 1/4 of the way toward "maximum tension" for pure tones.  These errors would accumulate and get even worse as you add overtones (which is why I'm not even vaguely interested in trying to see whether I can replicate the model).
I'd say if you want to calculate the tonal tension of triads, find a better model.  (There are plenty of attempts out there.)
Comment: @MattiaSurricchio - No, I personally don't think the given model reflects a realistic understanding of musical tension. Basically, it only seems to work at all within equal temperament and the fact that the authors only mention cases where the lower interval of a triad is fixed at 3, 4, or 5 ET semitones.  If you start calculating tension with any other intervals (including slightly detuned non-ET intervals), the results seem very counterintuitive. As for the rest, there are lots of mathy models of "dissonance" or musical "distance" out there; all of them have benefits and drawbacks.
Comment: @MattiaSurricchio: Yes, it relies on a 12-tone equal tempered scale, but the problem is that the "tension" curves they provide in their paper appear to give tension values to the frequencies in-between those scale steps. And my point is that when you begin to adjust what they call the "1st interval" to other values other than the integers 3, 4, and 5 that they use in their graphs, the model gives really weird results. (Honestly, the graphs for 3, 4, and 5 also don't model dissonance/tension well either, from my perspective; they just happen to line up well for a handful of intervals.)
Comment: Interesting point of discussion. I've been working on it and I solved all the problems/incoherence between domains, i'll update my code with explanations as soon as possible.

Regarding the second part, i did not actually "test" the model proposed, i'm a simple college student (i don't even know how would i do that to be honest). Do you think it's not valid? Do you have any suggestions for better models? It would be great
Comment: Regarding dissonance, there's a psychoacoustic model, which is based on the "bandpass filters" of the ear, but doesn't explain phenomenon like triads ecc... it only relies on the physical meaning of dissonance (we're not capable of separate frequencies that are too close to each other).
I thought that the paper i mentioned above, relied on the assumption of 12 semitones scale (the common one in western culture). Isn't it enough as assumption?
Comment: For example: Look at fig. 7. Assume the lower pitches are C-E. Fig. 7 has a peak for the aug. triad C-E-G#, which makes sense. It has local min. at C-E-G for triad. That's good. But the "minor 1st. inv." minimum occurs not at C-E-A; the curve goes down so the min. is between A and Bb, which makes little sense. C-E-Bb is "tense," though only (?) about as tense as a minor triad (C-E-A), but C-E-B is even less tense than C-E-A(!?). Basically, the graphs show the very tiny number of vaguely correct places the model sort of works, while ignoring the vast majority of situations where it wouldn't.
Comment: Another place the model fails even basic intuition is if you just consider fundamentals without harmonics (as you appear to be trying to do). Their gaussian is designed to simply fall off once the two intervals are no longer equal, so your model without the harmonics will be useless. Going back to C-E for the 1st interval, C-E-G# would have maximum tension, C-E-G would be less, but C-E-F# would be even less, C-E-F even less. On the other side, C-E-A would have low tension, but C-E-Bb less, C-E-B even less. Those values would make absolutely no sense for rating chords.
Answer: They used six partials and you only use the fundamental. That's the problem. Anyway, their approach doesn't make any sense to me. The basic assumptions are not supported by any evidence and unnecessarily complicated. The elusive partial tones, which do not have to exist in reality, introduce a high degree of ambiguity. If I understand it right, "tension" is an artifact they introduced in order to get their wrong model to behave like reality for the case of three tone intervals. In their model, the central note of a triad behaves different to the outer tones, which is just absurd. So the question is anyway, what their concept of tension means musically. I quess it doesn't mean anything.
The consonance of an interval indeed depends on the overtone intensity distribution, but I found adding the sums of the prime factors of nominator and numerator for an interval gives a reasonable estimation for its dissonance. A chord's dissonance is the average of dissonance of its composite intervals.
E.g. the major triad = 4:5:6 = 3:2 + 5:4 + 6:5 = 3:2 + 5:(2*2) + (3*2):5
Dissonance = (3+2 + 5+2+2 + 3+2+5)/3 = 8
Not applicable for extremely dissonant chords though, as the while sound more consonant due to the similarity to nearby more consonant chords. This is a result of our ear's limited frequency resolution. One can get extend the model essentially by calculating the consonance as the inverse of the dissonance and applying a smoothing and get a smooth n-dimensional consonance function for a chord containing n+1 notes.

Calculate tonal tension of triads


Using function based index (oracle) to speed up count(X)

Question: I've a table Film:
CREATE TABLE film (
film_id NUMBER(5) NOT NULL,
title varchar2(255));

And I wanted to make the query, which counts how many titles start with the same word and only displays ones with more than 20, faster using a function based index. The query:
SELECT FW_SEPARATOR.FIRST_WORD AS "First Word", COUNT(FW_SEPARATOR.FIRST_WORD) AS "Count"
FROM (SELECT regexp_replace(FILM.TITLE, '(\w+).*$','\1') AS FIRST_WORD FROM FILM) FW_SEPARATOR
GROUP BY FW_SEPARATOR.FIRST_WORD
HAVING COUNT(FW_SEPARATOR.FIRST_WORD) >= 20;

The thing is, I created this function based index:
CREATE INDEX FIRST_WORD_INDEX ON FILM(regexp_replace(TITLE, '(\w+).*$','\1'));

But it didn't speed anything up...
I was wondering if anyone could help me with this :)
Comment: How many rows are in your table?  Are the statistics on the table accurate?  What is the actual query plan?  Unless the index is substantially smaller than the table, it may well be more efficient to do a full scan on the table than to do a full scan on the index.
Comment: You make a full scan - your index is useless. Oracle optimizer considers indexes to accelerate the selection of appropriate rows.
Comment: My table has 20000 entries and the table actually has more info, I just thought I'd spare you guys of it because it's not important at the moment.
Answer: Add a redundant predicate to the query to convince Oracle that the expression will not return null values and an index can be used:
select regexp_replace(film.title, '(\w+).*$','\1') first_word
from film
where regexp_replace(film.title, '(\w+).*$','\1') is not null;

Oracle can use an index like a skinny version of a table.  Many queries only contain a small subset of the columns in a table.  If all the columns in that set are part of the same index, Oracle can use that index instead of the table.  This will be either an INDEX FAST FULL SCAN or an INDEX FULL SCAN.  The data may be read similar to the way a regular table scan works.  But since the index is much smaller than the table, that access method can be much faster.
But function-based indexes do not store NULLs.  Oracle cannot use an index scan if it thinks there is a NULL that is not stored in the index.  In this case, if the base column was defined as NOT NULL, the regular expression would always return a non-null value.  But unsurprisingly, Oracle has not built code to determine whether or not a regular expression could return NULL.  That sounds like an impossible task, similar to the halting problem.
There are several ways to convince Oracle that the expression is not null.  The simplest may be to repeat the predicate and add an IS NOT NULL condition.
Sample Schema
create table film (
film_id number(5) not null,
title varchar2(255) not null);

insert into film select rownumber, column_value
from
(
    select rownum rownumber, column_value from table(sys.odcivarchar2list(
    q'<The Shawshank Redemption>',
    q'<The Godfather>',
    q'<The Godfather: Part II>',
    q'<The Dark Knight>',
    q'<Pulp Fiction>',
    q'<The Good, the Bad and the Ugly>',
    q'<Schindler's List>',
    q'<12 Angry Men>',
    q'<The Lord of the Rings: The Return of the King>',
    q'<Fight Club>'))
);

create index film_idx1 on film(regexp_replace(title, '(\w+).*$','\1'));

begin
    dbms_stats.gather_table_stats(user, 'FILM');
end;
/

Query that does not use index
Even with an index hint, the normal query will not use an index.  Remember that hints are directives, and this query would use the index if it was possible.
explain plan for
select /*+ index_ffs(film) */ regexp_replace(title, '(\w+).*$','\1') first_word
from film;

select * from table(dbms_xplan.display);

Plan hash value: 1232367652

--------------------------------------------------------------------------
| Id  | Operation         | Name | Rows  | Bytes | Cost (%CPU)| Time     |
--------------------------------------------------------------------------
|   0 | SELECT STATEMENT  |      |    10 |    50 |     3   (0)| 00:00:01 |
|   1 |  TABLE ACCESS FULL| FILM |    10 |    50 |     3   (0)| 00:00:01 |
--------------------------------------------------------------------------

Query that uses index
Now add the extra condition and the query will use the index.  I'm not sure why it uses an INDEX FULL SCAN instead of an INDEX FAST FULL SCAN.  With such small sample data it doesn't matter.  The important point is that an index is used.
explain plan for
select regexp_replace(film.title, '(\w+).*$','\1') first_word
from film
where regexp_replace(film.title, '(\w+).*$','\1') is not null;

select * from table(dbms_xplan.display);

Plan hash value: 1151375616

------------------------------------------------------------------------------
| Id  | Operation        | Name      | Rows  | Bytes | Cost (%CPU)| Time     |
------------------------------------------------------------------------------
|   0 | SELECT STATEMENT |           |    10 |    50 |     1   (0)| 00:00:01 |
|*  1 |  INDEX FULL SCAN | FILM_IDX1 |    10 |    50 |     1   (0)| 00:00:01 |
------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter( REGEXP_REPLACE ("TITLE",'(\w+).*$','\1') IS NOT NULL)

Comment: Thank you, it worked perfectly, cut the time by half! =D


Array of ranges stores the same range. Why?

Question: I have the following code in Word:
Function findRanges(keyword) As Variant()
    Dim foundRanges(), rngSearch As Range
    Dim i, foundCount As Integer

    i = 0
    foundCount = 0

    Set rngSearch = ActiveDocument.Range
    With rngSearch.Find
        Do While .Execute(FindText:=keyword, MatchWholeWord:=True, Forward:=True) = True
            foundCount = foundCount + 1
            rngSearch.Collapse Direction:=wdCollapseEnd
        Loop
    End With

    ReDim foundRanges(0 To foundCount - 1)

    Set rngSearch = ActiveDocument.Range
    With rngSearch.Find
        Do While .Execute(FindText:=keyword, MatchWholeWord:=True, Forward:=True) = True
            Set foundRanges(i) = rngSearch
            MsgBox "rngSearch / " & rngSearch.End
            MsgBox "foundRanges / " & foundRanges(i).End
            i = i + 1
            rngSearch.Collapse Direction:=wdCollapseEnd
        Loop
    End With

    For j = LBound(foundRanges) To UBound(foundRanges)
        MsgBox j & "foundRanges / " & foundRanges(j).End
    Next j

    findRanges = foundRanges
End Function

When I use this function, ranges stored in the array "foundRanges" are different (I check it by their End position). BUT as soon as my find loop ends, ranges become all the same (they have the same End position) and I can't get why.
What I want to do is to store locations of each found keyword in an array and change the keywords later to a user input.
Answer: You need to duplicate the range before storing it - otherwise you keep storing a reference to the same range, and this range keeps changing as you call .Find() repeatedly.
Something like this:
Function findRanges(keyword, Optional SearchIn As Range) As Variant()
    Dim foundRanges(), i As Integer

    If SearchIn Is Nothing Then Set SearchIn = ActiveDocument.Range

    Do While SearchIn.Find.Execute(FindText:=keyword, MatchWholeWord:=True, Forward:=True)
        ReDim Preserve foundRanges(i)
        Set foundRanges(i) = SearchIn.Duplicate
        SearchIn.Collapse Direction:=wdCollapseEnd
        i = i + 1
    Loop

    findRanges = foundRanges
End Function

Comment: Thanks! It works except "redim preserve" part as the array doesn't have dimesnsions at the first loop step. I solved it by adding "ReDim foundRanges(0)" before the find loop and "ReDim Preserve foundRanges(UBound(foundRanges) - 1)" after it. Is it ok or is there a better way?
Comment: This is exactly right, that was a bug in my code. Thanks! :)
Comment: You should  find that using a collection (or better a Scripting.Dictionary) is much simpler than using a variant array.
Comment: Collections are a bit easier to fill (call `.Add()` instead of calling `ReDim Preserve`), but arrays are a bit easier to iterate with a `For Each` loop. There is no need to re-write working code that uses arrays.