Using a form and a button to call a method in view

Question: beginner rails question here. I created a web scraper to populate my model with information and I wanted to call this method with a button from a view. More importantly, I wanted to pass the contents of a form as a parameter to this method. I'm kinda lost on how to this using forms, but so far I have:
I placed the method into the directory app/helpers/admin_pages_helper.rb
module AdminPagesHelper
  def populate(term)
  .
  .
  end
end

I then have a view located at app/views/admin_pages/index.html.erb
I'm unsure of how to go about this using the form_tag/text_field_tag/submit_tag for a parameter; most of examples I've seen involve database queries using forms instead. Thanks
Comment: What is `term` - a single parameter as a string?
Answer: The simplest form of usage would be something like this - firstly you need a route that your form can submit to:
# in your routes.rb
match "/admin_pages/my_action" => "admin_pages#my_action", as: "my_admin_pages_action"

This will route a request to "/admin_pages/my_action" to the "my_action" action in your AdminPagesController.  It also gives you several helper methods you can use to build this url string in your views and/or controllers.
# in your view
<%= form_tag my_admin_pages_action_path do |f| %>
  <%= text_field_tag :term %>
  <%= submit_tag "Submit" %>
<% end %>

When this form is submitted it will route to the AdminPagesController#my_action method:
class AdminPagesController < ApplicationController
  def my_action
    term = params[:term]          # this contains the contents of the text_field
    something = populate(term)    # call your helper method passing in the term
  end
end

Comment: I'm getting a "can't convert Symbol into Integer" on the form_for line in view. Any suggestions?
Comment: Are you sure you used `text_field_tag` instead of `f.text_field` on the next line?  Also, try adding a label to the submit button like this: `<%= f.submit "Submit" %>`
Comment: I'm using the text_field_tag. Double checked any typos too.
Comment: Updated to avoid using `form_for` - it's actually intended for building up a model which isn't needed/used here.  I'm not sure why it's not working, but it isn't necessary to fix in this case since you can just replace it with `form_tag`.


'How much would you pay to play this game' question

Question: 'We play a game: I pick a number $n$ from 1 to 100. If you guess correctly, I pay you $n^2$ dollars and zero dollars otherwise. How much would you pay to play this game?'
I know the answer for the case where you are paid $n$ dollars if you guess correctly, and just want to see if I am correct for this other case.
The idea was to pick $k$ with probability $\frac{C}{k}$ where $C = \left(\sum_{j=1}^{100}\frac{1}{j}\right)^{-1}$.
So then $\mathbb{E}[\text{winnings}] = \sum_{j=1}^{100}j^2 \mathbb{P}(\text{winnings} = j) = \sum_{j=1}^{100} j^2 \frac{1}{100}\frac{C}{j} = \frac{101}{2}C$. So I'd be happy to pay any amount less than or equal to $\frac{101}{2}C$. Is this correct? I'm worried it's a little too large as a value.
Answer: I think your $\frac{101}{2}C \approx 9.735$ looks far too large if the bank can just choose $1$.  It rather depends on whether the bank has to choose uniformly at random or has a deliberate choice. Let's assume it is a deliberate choice or strategy chosen by the bank but unknown to the player. I suspect

the game-theoretic optimal strategy by the player is then, for each $k\in \{1,2,\ldots,100\}$, to bet on $k$ with probability $\dfrac1{k^2\, H_{100,2}}$ where $H_{100,2} = \sum\limits_{n=1}^{100} \frac1{n^2}\approx 1.635$, a generalised harmonic number
if the banker has chosen a particular $n$ then the expected amount paid by the banker to the player is then $\frac{n^2}{n^2\, H_{100,2}}= \frac1{H_{100,2}} \approx 0.6116$ and is the same for all $n$
so $\frac1{H_{100,2}} \approx 0.6116$ is the most the player should be willing to pay to play the game.

If the banker changed the rules to remove the $100$ maximum so there was no limit on the positive integer chosen, then this amount would decrease slightly to $\frac6{\pi^2} \approx 0.6079$.
If the banker had to choose uniformly at random from $\{1,2,\ldots,100\}$, then the best strategy for the player would be to always bet on $100$, with an expected amount paid by the banker to the player of $\frac1{100}100^2 =100$.  A better game-theoretic strategy for the banker would be the same as the optimal strategy as the player, picking $n$ with probability $\dfrac1{n^2\, H_{100,2}}$.


Is there a shiny way to make Windows shares web accessible?

Question: I'm new here, and I hope this isn't too much of a shopping question.
I'm the under-qualified director of technology at a small college that may be acquired by a larger school. We have Office 365 email and Office 2010 on our Windows 7 desktops. We have used AD with network drives for many years to manage all our department files, and it's worked well.
However, the larger school uses Google Apps and Drive, and we're now constantly getting requests for internal data. Today, for example, I found out with less than an hour's lead time that their marketing department wants to view all our marketing department's photos. That's about 400 GB sitting on a network share.
Is there any way to make external shares accessible? (With some controls, of course.) We're low on money, which is why we're likely being acquired, and I cannot buy a big boxed product. What I want to prevent is getting pushed into Google Apps overnight.
I suspect Sharepoint might be the answer. However, my predecessor tried MOSS 2007 and it was horrible. Are the newer versions better? Are there any other decent ways to do this? Shinier is better, because this is more about trying to not annoy a bunch of executives than anything else.
Comment: Yes, you want to create a site to site VPN before establishing the trust.
Comment: Would a VPN between your companies work? It'd be slow, though. An external RDP session would likely work better.
Comment: How about a trust between the two forests, then limit access to the specific groups that need the access?
Comment: @Davidw, would that be in addition to the VPN proposed by @NathanC? I could see that being a good long-term solution.
Answer: One possible hack is to set up a Remote Desktop User that has access to the shares, then let the outside user RDP in and they can view them. That seems like would be the quickest and easiest for something that you won't be using long term.
Answer: While there is some risk you could certainly install IIS on your file server and create 'web shares'.  The web shares basically use webdav (http/https) to remotely access the filesystem.
It is really important to have your NTFS permissions set correctly, since you won't have the share-level permissions as an additional layer of protection.  Also you really need SSL if this is going to be authenticated.  Ideally this would be across a VPN, since you almost certainly want to protect that file server.
Answer: FTP might be the simplest way to enable access web access for multiple people. It's easy to set up and configure, easy to secure, very efficient, map-able to a drive letter, and already included with IIS. The 'web shares' idea mentioned in one of the answers is good as well, but WebDAV can be ridiculously slow sometimes.
For information on securing IIS sites (FTP or otherwise), see this TechNet article.
Comment: You can enable Windows authentication for the site with literally one checkbox. I'd call that pretty easy.
Comment: Except that the credentials fly over the Internet in plain text for everyone to see. That's definitely easy but not secure.
Comment: Only if you're using basic authentication. Windows authentication uses Kerberos. No plaintext passwords. IIS offers both, you can choose which to enable. Pull up the authentication page on any IIS instance and check it out.
Comment: @AndréDaniel For reference, see http://technet.microsoft.com/en-us/library/cc754628(v=ws.10).aspx
Comment: My bad, didn't know about that. Please edit your answer (add the reference link, some might find that useful) so I can remove my downvote.
Comment: I added the link.
Comment: Great. Downvote removed, sorry about that.
Answer: My recommendation would be to create a trust over a site to site VPN between the two AD Forests, and use selective authentication to give the specific groups that need access to the information that they need.
Comment: Today I received a similar request for mass-sharing photos, and I pointed the user to OneDrive for Business, which comes with our Office365 for Education subscription and offers 1 TB of storage per-user. With how fast Office365 has been changing, I'd barely noticed that Microsoft added it and no-one has been using it here (until now).

In the long term, I will aim for Davidw's solution. Thanks, everyone!


Unit tests failing in xunit.runner.console but passes locally

Question: Our TFS CI build uses dotCover for running xUnit tests. However some of the tests are failing there but locally they passes.
I downloaded dotCover.CommandLineTools and xunit.runner.console from nuget. unpacked the packages and tried to locally run dotCover cover command as is executed in TFS pipeline:
.\tools\dotcover.exe cover /TargetExecutable=".\..\xunit-runner\tools\net461\xunit.console.exe"
/TargetArguments="c:\Projects\MySolution\Sources\MyTestProject\bin\Debug\MyTestProject.dll -xml c:/temp/testResultFile.xml"
/Output="c:/temp/coverageResultFile.dcvr"
/Filters='-:module=xunit.*;-:module=*UnitTests*'

Get the same errors as in CI. From my investigation of errors that dotCover output showed in failing tests it seems that mock data are not the same when running tests locally from VS and running them with dotCover.
Does anybody faced such problem? Any solution for it?
EDIT: Just tried one more thing, ran command
.\xunit.console c:\Projects\MySolution\Sources\MyTestProject\bin\Debug\MyTestProject.dll and found that this gives me same errors as on CI so the cause of problems is not CI, nor dotCover but xunit.runner.console.
Any new points to this?
Answer: According to your description and analysis. This issue seems not related to TFS side(such as configuration of build task/pipeline. Since it's the same result when you directly run dotCover cover command locally as TFS build server.
Take a look at this similar issue check if it's helpful: Unit tests are failing when run from dotCover

It seems that the problem is related to the fact that my build uses an
  XML file to hold certain data values. This XML file is found by VSTest
  when run under TFS but not by dotCover.
When dotCover runs it creates a TestResults folder which it then
  copies all the necessary files to required to run the unit tests. All
  files are copied except the XML file. I have set the file to "Copy
  always" so can't understand why this file isn't copied. I tried
  copying the file manually as a batch file but the folder structure is
  created by dotCover so it doesn't exist until I actually run the code
  coverage

Another method if it is failed by the file copying: Shadow-copying in dotCover: if your NUnit tests fail during continuous testing .
Comment: Thanks, I will check it. Please, edit the first link you stated, it refers to this question :)
I think our mocks are imported from jsons so I thought that problem could be in using files. I need to check. I'm quite new to the project, so I'm not so familiar with it yet.
Comment: @Gondil Sorry for the mistyped. Have corrected and updated. Also not familiar with dotcover to me, can't help to dig into the root cause. Only could give some suggestions and directions.
Comment: Thanks, for edit. I understand that you are not familiar with dotCover, me neither :D I'm also just assuming what is wrong with it and that's why I was asking here, more heads, more experiences :) I will try to focus on dotCover and the files used and try to find the solution.
Comment: Other team member helped me.. He created something like kind of lets say Mocking FW so I was little bit lost in it. Don't know to this time (I think my colleague neither) why it wasn't working properly with xunit.runner.console. There was made some kind of general initialization of mocks using C# Attributes and it wasn't working when running through xunit.runner.console. So probably this question could be closed even when it don't have a general solution.


Como enviar messagens de uma aplicação cliente (Dash.js) para um Switch Openflow

Question: Tenho uma aplicação cliente chamada Dash.js, player de vídeo, que roda em um ambiente que emula uma rede SDN, com switches e um controlador openflow.
Essa aplicação adapta a qualidade do video de acordo com a largura de banda da rede do usuário.
A classe que determina se o cliente vai solicitar a troca de segmento para se adaptar a largura de banda disponível é a AbrController.js.
MediaPlayer.dependencies.AbrController = function () {
    "use strict";

    var autoSwitchBitrate = true,
        qualityDict = {},
        confidenceDict = {},

        getInternalQuality = function (type) {
            var quality;

            if (!qualityDict.hasOwnProperty(type)) {
                qualityDict[type] = 0;
            }

            quality = qualityDict[type];

            return quality;
        },

        setInternalQuality = function (type, value) {
            qualityDict[type] = value;
        },

        getInternalConfidence = function (type) {
            var confidence;

            if (!confidenceDict.hasOwnProperty(type)) {
                confidenceDict[type] = 0;
            }

            confidence = confidenceDict[type];

            return confidence;
        },

        setInternalConfidence = function (type, value) {
            confidenceDict[type] = value;
        };

    return {
        debug: undefined,
        abrRulesCollection: undefined,
        manifestExt: undefined,
        metricsModel: undefined,
        metricsBaselinesModel: undefined,

        getAutoSwitchBitrate: function () {
            return autoSwitchBitrate;
        },

        setAutoSwitchBitrate: function (value) {
            autoSwitchBitrate = value;
        },

        getMetricsFor: function (data) {
            var deferred = Q.defer(),
                self = this;

            self.manifestExt.getIsVideo(data).then(
                function (isVideo) {
                    if (isVideo) {
                        deferred.resolve(self.metricsModel.getMetricsFor("video"));
                    } else {
                        self.manifestExt.getIsAudio(data).then(
                            function (isAudio) {
                                if (isAudio) {
                                    deferred.resolve(self.metricsModel.getMetricsFor("audio"));
                                } else {
                                    deferred.resolve(self.metricsModel.getMetricsFor("stream"));
                                }
                            }
                        );
                    }
                }
            );

            return deferred.promise;
        },

        getMetricsBaselineFor: function (data) {
            var deferred = Q.defer(),
                self = this;

            self.manifestExt.getIsVideo(data).then(
                function (isVideo) {
                    if (isVideo) {
                        deferred.resolve(self.metricsBaselinesModel.getMetricsBaselineFor("video"));
                    } else {
                        self.manifestExt.getIsAudio(data).then(
                            function (isAudio) {
                                if (isAudio) {
                                    deferred.resolve(self.metricsBaselinesModel.getMetricsBaselineFor("audio"));
                                } else {
                                    deferred.resolve(self.metricsBaselinesModel.getMetricsBaselineFor("stream"));
                                    //self.debug.log("GET STREAM.");

                                }
                            }
                        );
                    }
                }
            );

            return deferred.promise;
        },

        getPlaybackQuality: function (type, data, availableRepresentations) {
            var self = this,
                deferred = Q.defer(),
                newQuality = MediaPlayer.rules.SwitchRequest.prototype.NO_CHANGE,
                newConfidence = MediaPlayer.rules.SwitchRequest.prototype.NO_CHANGE,
                i,
                len,
                funcs = [],
                req,
                values,
                quality,
                confidence;

            quality = getInternalQuality(type);

            confidence = getInternalConfidence(type);

            //self.debug.log("ABR enabled? (" + autoSwitchBitrate + ")");

            if (autoSwitchBitrate) {
                //self.debug.log("Check ABR rules.");

              self.getMetricsFor(data).then(
                  function (metrics) {
                    self.getMetricsBaselineFor(data).then(
                      function (metricsBaseline) {
                        self.abrRulesCollection.getRules().then(
                            function (rules) {
                                for (i = 0, len = rules.length; i < len; i += 1) {
                                    funcs.push(rules[i].checkIndex(quality, metrics, data, metricsBaseline, availableRepresentations));
                                }
                                Q.all(funcs).then(
                                    function (results) {
                                        //self.debug.log(results);
                                        values = {};
                                        values[MediaPlayer.rules.SwitchRequest.prototype.STRONG] = MediaPlayer.rules.SwitchRequest.prototype.NO_CHANGE;
                                        values[MediaPlayer.rules.SwitchRequest.prototype.WEAK] = MediaPlayer.rules.SwitchRequest.prototype.NO_CHANGE;
                                        values[MediaPlayer.rules.SwitchRequest.prototype.DEFAULT] = MediaPlayer.rules.SwitchRequest.prototype.NO_CHANGE;

                                        for (i = 0, len = results.length; i < len; i += 1) {
                                            req = results[i];
                                            if (req.quality !== MediaPlayer.rules.SwitchRequest.prototype.NO_CHANGE) {
                                                values[req.priority] = Math.min(values[req.priority], req.quality);
                                            }
                                        }

                                        if (values[MediaPlayer.rules.SwitchRequest.prototype.WEAK] !== MediaPlayer.rules.SwitchRequest.prototype.NO_CHANGE) {
                                            newConfidence = MediaPlayer.rules.SwitchRequest.prototype.WEAK;
                                            newQuality = values[MediaPlayer.rules.SwitchRequest.prototype.WEAK];
                                        }

                                        if (values[MediaPlayer.rules.SwitchRequest.prototype.DEFAULT] !== MediaPlayer.rules.SwitchRequest.prototype.NO_CHANGE) {
                                            newConfidence = MediaPlayer.rules.SwitchRequest.prototype.DEFAULT;
                                            newQuality = values[MediaPlayer.rules.SwitchRequest.prototype.DEFAULT];
                                        }

                                        if (values[MediaPlayer.rules.SwitchRequest.prototype.STRONG] !== MediaPlayer.rules.SwitchRequest.prototype.NO_CHANGE) {
                                            newConfidence = MediaPlayer.rules.SwitchRequest.prototype.STRONG;
                                            newQuality = values[MediaPlayer.rules.SwitchRequest.prototype.STRONG];
                                        }

                                        if (newQuality !== MediaPlayer.rules.SwitchRequest.prototype.NO_CHANGE && newQuality !== undefined) {
                                            quality = newQuality;
                                        }

                                        if (newConfidence !== MediaPlayer.rules.SwitchRequest.prototype.NO_CHANGE && newConfidence !== undefined) {
                                            confidence = newConfidence;
                                        }

                                        self.manifestExt.getRepresentationCount(data).then(
                                            function (max) {
                                                // be sure the quality valid!
                                                if (quality < 0) {
                                                    quality = 0;
                                                }
                                                // zero based
                                                if (quality >= max) {
                                                    quality = max - 1;
                                                }

                                                if (confidence != MediaPlayer.rules.SwitchRequest.prototype.STRONG &&
                                                    confidence != MediaPlayer.rules.SwitchRequest.prototype.WEAK) {
                                                    confidence = MediaPlayer.rules.SwitchRequest.prototype.DEFAULT;
                                                }

                                                setInternalQuality(type, quality);
                                                //self.debug.log("New quality of " + quality);

                                                setInternalConfidence(type, confidence);
                                                //self.debug.log("New confidence of " + confidence);

                                                deferred.resolve({quality: quality, confidence: confidence});
                                            }
                                        );
                                    }
                                );
                            }
                        );
                    }
                );
               }
             );
            } else {
                self.debug.log("Unchanged quality of " + quality);
                deferred.resolve({quality: quality, confidence: confidence});
            }

            return deferred.promise;
        },

        setPlaybackQuality: function (type, newPlaybackQuality) {
            var quality = getInternalQuality(type);

            if (newPlaybackQuality !== quality) {
                setInternalQuality(type, newPlaybackQuality);
            }
        },

        getQualityFor: function (type) {
            return getInternalQuality(type);
        }
    };
};

MediaPlayer.dependencies.AbrController.prototype = {
    constructor: MediaPlayer.dependencies.AbrController
};

O que eu quero é que toda vez que ocorre uma solicitação para troca de segmento, uma mensagem seja disparada para o switch openflow, para que ele possa enviar um packetin para o controlador e o controlador tomar uma ação.
Para mim, agora, o problema está nessa troca de comunicação entre o cliente e o Switch Openflow.
Alguém saberia como disparar essa mensagem e receber no switch openflow?
Obrigada!
Answer: Pelo que entendi, o AbrController tem um método que é chamado pelo player para determinar qual é o tamanho da banda, internamente ele faz o calculo e retorna um Promise.
Nesse caso, você pode modificar o escopo que está chamando o método getPlaybackQuality do AbrController para te retornar um promise ou usar o próprio promise do getPlaybackQuality para você saber se a qualidade mudou ou não. O legal é você continuar usando o promise para obter essa atualização.
Eu não gosto de mudar o código fonte de terceiros mas open source é pra isso né? Então um outro passo mais simples seria você disparar um evento assim que a qualidade mudou.
Da uma olhada nesse Dispatcher ele é bem simples de usar e não se importa com a hirearquia de objetos, então você pode disparar um evento de qualquer lugar e captura-lo em qualquer lugar.
Mas de novo, isso pode te ajudar mas ao mesmo tempo pode sujar um pouquinho seu código já que o método que te retorna a qualidade, te retorna um promise.


Proof about converging absolutely with respect to equivalent norm

Question: If series converges absolutely with respect to some norm, then it also converges absolutely with respect to any kind of equivalent norm.
I need to prove this assertion, but I have no idea from where to start.
Answer: Let $\|\cdot \|_1$ and $\|\cdot \|_2$ be equivalent norms on a normed vector space $S.$ That is, the norms generate the same topology. Then the norms are uniformly equivalent : There exist positive $A, B$ such that for all $v\in S$ we have $A\|v\|_1\leq \|v\|_2\leq B\|v\|_1$.
Otherwise, with $(i,j)=(1,2)$ or $(i,j)=(2,1) ,$ there exists $T=\{v_n\}_{n\in N}\subset S$ with $\|v_n\|_i=1$ and $\|v_n\|_j<1/n$ for each $n\in N.$   With respect to the $j$-norm, the vector $0$ belongs to $\overline T,$ but with respect to the $i$-norm, $0\not \in \overline T,$ so the norms are not equivalent.
That should be enough to solve the problem.


Showing equality between a vector space and the direct sum of two subvector spaces.

Question: Let $\mathit{F} = \{ P \in \mathbb{K}[X] : P(1)=P(-1)=0 \}$
the exercise starts by asking to prove that $\mathit{F}$ is a sub-vector space of $\mathbb{K}[X]$, which easy to prove, but then also to show that $\mathbb{K}[X] = \mathit{F} \oplus \mathbb{K}_1[X]$.
Trivially, we have that $\mathit{F} \oplus \mathbb{K}_1[X] \subseteq \mathbb{K}[X]$ , but I'm stuck at showing $\mathbb{K}[X] \subseteq \mathit{F} \oplus \mathbb{K}_1[X]$.
Comment: Fixed, thanks for poiting it out.
Comment: Use `$F=\{ x\}$` for $F=\{ x\}$. [Here's a MathJax tutorial](https://math.meta.stackexchange.com/q/5020/104041) :)
Answer: Being in $F$ may be translated in terms of divisiblity by a polynomial. Use euclidean division in $\mathbf{K}\left[X\right]$ to conclude.


Where do you store the variables in jinja?

Question: I've got five pages with the same page layout and structure, but some different colors, text, etc, so this is an ideal environment for templating. I've decided to use Jinja2 and probably flask. I've read through the documentation, and some tutorials online, which explain lots about what you can do with templates on a page but not much about how to send variables to the page.

Where do you store the page-specific variables?
How does the code know which page has been requested and which variables to load?
Comment: Flask is a good choice. And its tutorial more or less answers your questions: http://flask.pocoo.org/docs/quickstart/#rendering-templates . Also note how `@app.route` defines the URL.
Comment: Thanks - so I would have a python script for each page, declare the variables within each python script, and then pass them to template.render?
Answer: Here's the basic usage:
First create a template
>>> from jinja2 import Template
>>> template = Template('Hello {{ name }}!')

Then render it passing the variables
>>> template.render(name='John Doe')
u'Hello John Doe!'

Usually you will want to load templates from files instead of code. That's more efficient and optimized, and allows template inheritance:
from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('yourapplication', 'templates'))

That will look for templates inside the templates folder of the yourapplication Python package, as installed in the Python path. You could use other loaders to load from a specific filesystem or other places too.
Then you can load a template:
template = env.get_template('mytemplate.html')
print template.render(the='variables', go='here')

When using Flask it is all configured for you, so you can just use Flask's render_template function and it will already look for a templates subfolder of your application:
from flask import render_template

@app.route('/hello/')
def hello(name=None):
    return render_template('hello.html', name=name)

Note the template variable (also known as context) being passed to render_template
Jinja has pretty good documentation. Please read it. Feel free to ask further questions.
Answer: Edit: I've googled the interweb in search for an answer and I've found some articles that could help (pretty sure they've helped me)
http://dbanck.de/2009/01/13/using-jinja2-with-django/
http://www.hindsightlabs.com/blog/2010/03/15/jinja2-and-django-4ever/ (dead)
http://djangosnippets.org/snippets/1061/
Comment: A selection of links without any explenation is not helpful, -1 from me.
Comment: @jwbensley Awww, not helpful because copy-pasting is disabled? Here's an explanation: read ... But also your down vote is legit, because I was lazy or in a hurry (can't remember which)
Comment: Just pasting a load of links leads to link rot, which is evident as you have now marked one of those links as dead.


How do I solve $5x=x^2+8$?

Question: How do I solve the following equation for x?
$$5x=x^2+8$$
Comment: The quadratic @David Quinn speaks about is $x^2-5x+8=0$. Maybe, **you haven't yet learned the general formulas giving the solutions of a quadratic**. In this case, let us write this equation under the form $(x^2-2*2.5x+2.5^2)+1.75=0$ (do you agree ?) then $(x+2.5)^2+1.75=0$, but this has no solution because the square of any "real" number is positive, and when added to 1.75 cannot be 0.
Comment: And what does this have to do with "similarly of triangles"?
Comment: @gerrymyerson I didn't post the whole question only what I needed help with, but the section I'm learning about is called similar triangles.
Comment: Fine, but doesn't it make sense to give a title that actually corresponds to the question? Won't that make it easier on the next person to come along?
Comment: Yes you are most definitely correct my sinceriously apology for not knowing how to use this app, but  now are you going to help or just criticize the title?
Comment: This quadratic has no real roots so there may be something wrong with your work leading up to this
Comment: I *am* helping by criticizing the title, and you're *not* helping by refusing to change it. Also, I believe that at the time I posted my comments there was an earlier comment that showed you what to do with the mathematics, but that comment is gone now. In any event, I hope the comments from David Quinn and JeanMarie have helped you.
Comment: somethings wrong. the numbers you give us lead to no solution.
Comment: The best answer so far is JeanMaries comment. You can and should always solve this via "completing the square" (s. e.g. https://en.wikipedia.org/wiki/Completing_the_square). Meaning try to write this as $a(x-b)^2+c=0$ and first solve this for $(x-b)^2$ and then solving that for $x$. All the other concrete formulas are hard to remember and just applied of this stuff above.
Answer: $x^2-5x+8 = 0$
$\left(\frac{-b +\sqrt {b^2-4ac}}{2a}\right)$
and
$\left(\frac{-b -\sqrt {b^2-4ac}}{2a}\right)$
plugging in $a = 1, b = -5, c = 8$.
$x = 2.5 + 1.3228756555323i, x =
2.5 - 1.3228756555323i$.
I am quite confident thats not what you need for your problem.
Comment: Um... $(x=3)(x-2)\neq x^2-5x+8$. You just simply *cannot* have that identity.
Comment: @Frank I've fixed it now. Lmao
Answer: Completing the square:
$$\left(x - \frac{5}{2}\right)^{2} = -8 + \left(\frac{5}{2}\right)^{2}$$
I need to add $\left(\frac{5}{2}\right)^{2}$ to RHS because if we expand LHS we will have an extra term of $\left(\frac{5}{2}\right)^{2}$. Simplify the RHS and we get
$$\left(x - \frac{5}{2}\right)^{2} = -\frac{7}{4}$$
then take the square root to get
$$\left(x - \frac{5}{2}\right) = \sqrt\frac{7}{4} \times \sqrt{-1} \implies \left(x - \frac{5}{2}\right) = \sqrt\frac{7}{4} \times i$$
use that $\sqrt{ab} = \sqrt{a}\sqrt{b}$ and we have $-1 \times  \frac{7}{4}$. The square root of $-1 = i$ so we have
$$x = \frac{5}{2} \pm \sqrt\frac{7}{4} \times i$$
Comment: Please don't post only formulas without any explanation. This yields nearly never a good answer. Try extending this with some explanations of what you are doing/why these equations holds.
Comment: I will add some explanation.
Comment: @ctst I have added some explanation.
Answer:
Concept: A good way to see how many solutions a quadratic has is to look at its Discriminant $D=b^2-4ac$. \begin{align*} & \text{When } D>0:\text{The quadratic has }2\text{ real solutions}\\ & \text{When }D=0:\text{ The quadratic has 1 real solution}\\ & \text{When }D<0:\text{ The quadratic has no real solutions}\end{align*}

Looking at the quadratic, $x^2-5x+8=0$, we see that $a=1,b=-5,c=8$. So the discriminant is $$D=b^2-4ac=25-32<0$$
Implying that the quadratic has no real solutions.

Perhaps something went wrong when you did the Geometry?

How do I solve $5x=x^2+8$?


Algorithm to find all fields of orders $p^n$ for fixed $n$ and all primes $p$ simultaneously?

Question: Is there an efficient way (an algorithm) to find, given a fixed $n\in\mathbb{N}_+$, all fields of order $p^n$ for all primes $p$ simultaneously?
There's no background behind this question, just an idea.
Given a prime $p$ and $n\in\mathbb{N}_+$ we can find a field of order $p^n$ using an irreducible polynomial $f$ of degree $n$ over $\mathbb{Z}_p[x]$ and considering the quotient $\mathbb{Z}_p[x]/(f)$. Can we achieve something like this but universally for all primes?
By that I mean, if we are able to find certain "thing" in finite time so that that thing will give us a description of all finite fields of order $p^n$ where $n$ is fixed.
Comment: I guess you should be a bit more specific about *for all primes simultaneously*. If the hope is that a clever choice of $f\in \Bbb{Z}[x]$ would work for all primes, then I'm afraid that is impossible. There are obstructions from algebraic number theory. Like Chebotarev's density theorem. I suspect (but won't bet on it) that the best possible choice of $f(x)$ would be one that has a cyclic Galois group of order $n$. Chebotarev says that this $f(x)$ remains irreducible for the fraction $\phi(n)/n$ of primes. Should $n$ be a prime itself, this is a relatively high percentage, but still $<1$.
Comment: @JyrkiLahtonen no need for algebraic number theory; just consider any prime factor of any $n\in\operatorname{im}(f)\setminus\{\pm 1\}$ :)
Comment: @Jakobian ah, that's a very interesting variation on the problem!! I am fairly sure the answer is still no, but I can't think of a proof off the top of my head, and I suspect such a proof will require more advanced tools. however, I do have a proof for the case $n=2$. I've written both the general question and the proof up [here](https://math.stackexchange.com/questions/3944986/if-n1-are-there-f-1-dots-f-k-in-mathbbzx-of-degree-n-such-that-for), if you're interested
Comment: Well, not necessarily an irreducible polynomial. But I don't know of any other possible description of a finite field. @AtticusStonestrom
Comment: Like $x^3-3x+1$ is irreducible modulo a prime $p\neq3$ unless $p\equiv\pm1\pmod9$.
Comment: @JyrkiLahtonen Thank you. I think that's the best answer I could ask for, really.
Comment: @Jakobian as a side note, imo your question has an interesting subtlety with respect to "possible descriptions of a finite field"... in some sense, any finite field of order $p^n$ can be described as "the unique field of order $p^n$", and this characterizes it completely... but of course this isn't a satisfying answer, because that description is not very tractable for computations, etc. so I think there's an interesting question there as to what we consider a satisfactory "description" for the purposes of this question
Comment: if the question means expressing $\mathbb{F}_{p^n}$ as a quotient of $(\mathbb{Z}/p)[x]$ by an irreducible polynomial of degree $n$, then the answer to it is no, but perhaps there is a suitable weakening of the question that makes the answer yes while still retaining what we want in a tractable "description" of an algebraic object
Comment: Well, it doesn't have to be one polynomial. It can be a finite set of them depending on $n$, right.
Answer: I interpret your question as asking whether there is a polynomial $f\in\mathbb{Z}[x]$, of degree $n>1$, such that $\overline{f}$ is irreducible of degree $n$ in $(\mathbb{Z}/p)[x]$, for every prime $p$; unfortunately the answer to this is no. To see this, let $f\in\mathbb{Z}[x]$ be arbitrary. Find some $n\in\mathbb{Z}$ such that $\pm 1\neq f(n)=:m$, and let $p$ be any prime factor of $m$. Then $\overline n$ is a root of $\overline f$ in $(\mathbb{Z}/p)[x]$, since $\overline f(\overline n)=\overline m=\overline 0$, and thus $x-\overline n$ is a factor of $\overline f$, which is hence reducible (or of degree $\leqslant 1$) mod $p$.
Comment: Yeah. As they say in bridge circles to the players throwing curveballs to their unsuspecting partners, *KISS* (= Keep It Simple, Stupid). Chebotarev and friends are more of a tool for analyzing how often a given polynomial workds.
Comment: @JyrkiLahtonen that makes sense! :) probably a more satisfying answer for OP too, since it gives a best case


Disable support for LOW encryption ciphers for glassfish port no 3920

Question: Qualis team found a vulnerability with our glassfish with port no 3920 .

glassfish version :- glassfish-184.108.40.206
Port no :- 3920,3820
Below are the details from Qualis
Messages encrypted with LOW encryption ciphers are easy to decrypt.
  Commercial SSL servers should only support MEDIUM or HIGH strength
  ciphers to guarantee transaction security.
Impact :- An attacker can exploit this vulnerability to decrypt secure
  communications without authorization.

Let us know , how to fix this vulnerability for port 3920 and 3820 in Glassfish-220.127.116.11 .
Answer: The SSL/TLS standards don't mandate a single specific encryption cipher, but allow the client and the server to negotiate to select one they both support.
To improve interoperability most server implementations support - by default - the largest possible range of ciphers, including some which are now considered weak (e.g. RC4). That's what triggers Qualis.
In your Glassfish server you can override the defaults and restrict the list of supported encryption ciphers in the configuration. Check the create-ssl directive and set for instance:
create-ssl --ssl2enabled=false --ssl3enabled=true --tlsenabled=true ....

Answer: In case others are trying to perform this task, the following information can be found within the DTD for the domain (glassfish/lib/dtds/sun-domain_1_3.dtd):
ssl3-tls-ciphers
    A comma-separated list of the SSL3 ciphers used, with the
    prefix + to enable or - to disable, for example
    +SSL_RSA_WITH_RC4_128_MD5. Allowed SSL3/TLS values are those
    that are supported by the JVM for the given security provider
    and security service configuration. If no value is specified,
    all supported ciphers are assumed to be enabled.

The following command line can then be used to set the ciphers:
WARNING, the ciphers being used are an example, make sure you set them to something that will work in your enviroment.
asadmin set 'configs.config.server-config.network-config.protocols.protocol.http-listener-2.ssl.ssl3-tls-ciphers=+SSL_RSA_WITH_RC4_128_MD5,-SSL_RSA_WITH_NULL_MD5'
Enter admin user name>  admin
Enter admin password for user "appservd">
configs.config.server-config.network-config.protocols.protocol.http-listener-2.ssl.ssl3-tls-ciphers= SSL_RSA_WITH_RC4_128_MD5,-SSL_RSA_WITH_NULL_MD5
Command set executed successfully.

NOTE: The output that gets echoed is incorrrect, grepping the domain.xml shows that its set properly:
grep SSL_RSA ~/domains/domain1/config/domain.xml
            <ssl key-store="keystore.jks" ssl3-tls-ciphers="+SSL_RSA_WITH_RC4_128_MD5,-SSL_RSA_WITH_NULL_MD5" classname="com.sun.enterprise.security.ssl.GlassfishSSLImpl" trust-store="cacerts.jks" cert-nickname="s1as"></ssl>

Alternatively, use asadmin get to retrieve the config:
asadmin get 'configs.config.server-config.network-config.protocols.protocol.http-listener-2.ssl.*'                                  Enter admin user name>  admin
Enter admin password for user "appservd">
configs.config.server-config.network-config.protocols.protocol.http-listener-2.ssl.allow-lazy-init=true
configs.config.server-config.network-config.protocols.protocol.http-listener-2.ssl.cert-nickname=s1as
configs.config.server-config.network-config.protocols.protocol.http-listener-2.ssl.classname=com.sun.enterprise.security.ssl.GlassfishSSLImpl
configs.config.server-config.network-config.protocols.protocol.http-listener-2.ssl.client-auth=
configs.config.server-config.network-config.protocols.protocol.http-listener-2.ssl.client-auth-enabled=false
configs.config.server-config.network-config.protocols.protocol.http-listener-2.ssl.key-store=keystore.jks
configs.config.server-config.network-config.protocols.protocol.http-listener-2.ssl.key-store-password-provider=plain
configs.config.server-config.network-config.protocols.protocol.http-listener-2.ssl.ssl-inactivity-timeout=30
configs.config.server-config.network-config.protocols.protocol.http-listener-2.ssl.ssl2-enabled=false
configs.config.server-config.network-config.protocols.protocol.http-listener-2.ssl.ssl3-enabled=false
configs.config.server-config.network-config.protocols.protocol.http-listener-2.ssl.ssl3-tls-ciphers= SSL_RSA_WITH_RC4_128_MD5,-SSL_RSA_WITH_NULL_MD5
configs.config.server-config.network-config.protocols.protocol.http-listener-2.ssl.tls-enabled=true
configs.config.server-config.network-config.protocols.protocol.http-listener-2.ssl.tls-rollback-enabled=true
configs.config.server-config.network-config.protocols.protocol.http-listener-2.ssl.tls11-enabled=true
configs.config.server-config.network-config.protocols.protocol.http-listener-2.ssl.tls12-enabled=true
configs.config.server-config.network-config.protocols.protocol.http-listener-2.ssl.trust-max-cert-length=5
configs.config.server-config.network-config.protocols.protocol.http-listener-2.ssl.trust-store=cacerts.jks
configs.config.server-config.network-config.protocols.protocol.http-listener-2.ssl.trust-store-password-provider=plain
Command get executed successfully.


Unsuccessful XDebug installation

Question: I'm trying to install XDebug on my local machine with Win 7, Apache 2, PHP 5.3.6 TS VC9 build (server manually installed, no package). I've followed instructions at http://xdebug.org/find-binary.php:
I've downloaded dll, moved to dir with other extensions, added following code to C:\Windows\php.ini, restarted server and - in contrary to my expectations - xdebug is neither installed nor listed in phpinfo page.
<code>zend_extension="E:\www\server\php\ext\php_xdebug-2.1.2-5.3-vc9.dll"
</code>
Altough I've gone trough my phpinfo and XDebug site several times I still have no idea what can cause this problem. Do you have any suggestions how to get XDebug working please?
Thank you
Comment: Have you check apache's logs?
Comment: greg0ire: Yes, I don't see anything suspicious here. I've restarted the server and this is new: http://pastebin.com/ExzxYvke
Comment: Did you enable xdebug in php.ini? `xdebug.default_enable=1`
Comment: According to documentation xdebug.default_enable has value 1 by default. Of course I've tried it, but it didn't help. Thanks anyway
Answer: According to netbeans manual you have to add the xdebug configuration file to the apache php ini directory and not the local php ini directory to make it work with anykind of wamp.
1) http://wiki.netbeans.org/HowToConfigureXDebug
2) Definition of wamp: http://en.wikipedia.org/wiki/WAMP
Comment: As I have mentioned in my first post, I am not using WAMP ("server manually installed, no package"). Thanks anyway
Comment: I'm not using either but you use Windows.
Comment: Sorry, I thought of WAMP as of the concrete package with the this name, not in general. But I still have the problem, altough I have copied php.ini into windows/ folder, apache/bin/ folder and php/ folder.
Comment: I've even used PHPINIDir E:/.../apache/bin in my VirtualHosts settings (and it reflected into phpinfo), but still no result with xdebug. FYI I'm using Apache from http://www.apachelounge.com/
Comment: I'm using lighttpd with xdebug. But my xdebug isn't working either.
Answer: try zend_extension**_ts**=...
and the in a console fire php -m to see whats in. No need to restart server
Answer: I "solved" the problem by updating from 5.3.6 to 5.3.8. I dont know where the problem was, but update and it will work fine. (I used http://xdebug.org/find-binary.php)

Unsuccessful XDebug installation


Scaling a LAMP stack

Question: Once you move beyond 100k hits/month, what would people in this community say is the biggest hurdle?
My situ:
Tons of static media (audio/video/images) being served off of S3/CDN, but being stored locally as backup (not served though). Everything that can be cached, is cached, with about 8 gigs of memory scalable to 32.
We're currently handling about 100k hits without a problem, and would love to know what problems others have run into: load balancing? memory issues? disk i/o?
Thanks for any tips. I've looked through the related questions, and they answered them well, but just wanted to get some more feedback.
Comment: 100,000 hits per month is about 125 requests per hour, or about 2 per minute. You shouldn't even need to *think* until you've got 100 times that traffic unless each request is really heavy.
Comment: You'll probably get a better answer over at http://www.serverfault.com/
Answer: Hardware is so cheap these days that increasingly few people even get to the point where they need more than one machine. $10,000 will buy you:

16-32GB of RAM;
2 quad core Xeons;
RAID5 disk array.

That kind of machine can serve over 10,000 concurrent users on an even mildly optimized site for all but the most resource intensive applications.
Basically there are two approaches to scalability:

Vertical: basically buying the biggest machine you can so you don't need more than one;
Horizontal: doing things in a way that lends itself to parallelism. Only needed on the most intensive of applications.

Look at StackOverflow: its basically run on a Web server plus a database server and it does in excess of 6 million hits a month.
That being said, scalability is about finding and addressing your bottleneck.

If your database is slowing things down either give it more resources or use some form of in-memory caching to take the load off;
If disk I/O is your problem then the same applies;
If you're running out of memory to the point where it's causing too many page faults and thus causing a disk I/O problem, add more memory;
Does your application and it's data lend itself to partitiioning across servers? If so, that's one way of scaling horizontally;
If bandwidth is an issue and you're delivering large files then perhaps a CDN is the answer;
And so on.

Ultimately though, 100k hits/month is not that large. I suspect that these days on a typical Web site you'd need to get beyond 10 million/month before you had real problems, assuming you don't do things badly (eg if you don't index your database searches then of course you'll be having problems with that but they're nothing to do with hits/month).
I would say redundancy is a far bigger headache than scalability. The issues involved in having redundant links, monitoring processes for system failure, having and maintaining a DR (disaster recovery) site, dealing with the issues that entails (like split-brain clustering), etc are far more difficult and tedious.
Comment: Upvoted for bringing up reliability and redundancy -- arguably more important that capacity.  Well done.
Comment: Thanks for the in-depth write up. The static media is already coming off a 3rd party cdn, so that def. won't be the issue.
I assumed our current setup could handle 2-3m without too big of an issue, but I wanted to be fully aware of what I could expect when we got beyond that.

Our needs are entirely db based. Our hits are to very dynamic, very active pages, which are similar to message boards in the type of content being spit out.
Comment: That being the case, in-memory caching will probably be your next hurdle I would guess. That is assuming you're already effectively caching and serving static content like Javascript/CSS/images.
Comment: You should be warned... Bigger machines = bigger SPOF :-)
Answer: Use Varnish or Squid. Both are web accelerators and both are excellent for static media files.
If you scale out, you can even have 1 machine for web cache and 1 machine for the dynamic content
Alternatively, you could try tweaking apache by using the mods:
mod_expires, mod_headers, mod_cache, mod_file_cache, mod_mem_cache.
Answer: Depends a little bit on what sort of database handling your doing - if you are serving static content or near static content; you will scale well beyond 100K/mo with very modest hardware.
Complex database driven sites such as forums can be a larger problem, you will need to look into database replication, reverse proxies on the main website to act as additional caches, and additional load-balanced webservers. Most 'heavy' DB-using software also supports things such as memcached, which can be used to reduce the load on the database on common requests.
Frankly though, I think you are probably overestimating demand right now - 100K is within the realm of handling on a single machine just fine. Once you break 10M, then you need to look at more complex solutions such as the ones I have outlined above.
My personal advice is to always favour parallel machines over single complex ones - not only does it end up being cheaper, but it gives you a lot more room to grow when the time comes. Expanding already expensive hardware gets you into the realm of $25,000 servers - where 'bang for buck' disintegrates.
Answer:
Once you move beyond 100k hits/month

Is NOTHING!!! If you have troubles serving 100k hits per month you are in trouble. Generally you should not have problems with most dumbest systems serving 100K per day.
This is about LAMP... and CMS systems

My situ: Tons of static media (audio/video/images) being served off of S3/CDN

There are very good web servers for these purposes: lighttpd -- it serves YouTuble media
streaming, nginx is good as well.
These are lightweight web servers that scale extremely well with high loads.
Even switching Apache module from mod-prefork to mod-worker would help (even lighttpd are still much better).
Bottom line: these loads are far from being high.
Answer: Other have pointed out that 100K hits is not a problem though I suspect they missed your point that you were already serving that many hits without issue...
Given that your content includes video I would suggest that network bandwidth would be your first problem, followed by I/O requests once you have enough concurrent requests for large objects. If you have more RAM than data then I/O will be less of a problem, once everything is sat in cache (though it'll take a while to prime the cache after any server shutdown).
One thing that you must specify when trying to size requirements like this is what distribution your hits have. Are they evenly distributed over the month or more bursty? For instance a site hosting information about a national lottery might see 80% or more of its weekly traffic in a two hour window after the draw time - 80% of 100K requests in two hours is 2.7 per second (assuming a 4 week month), still not massive but getting there depending on the size/complexity or the responses. Other less predictable bursts are possible too, such as what happens if a video on your site hits the front-page of Digg or similar.
Answer: The biggest hurdles are probably

getting your application in shape for a loosely coupled architecture which drops ACID and other strong constraints to allow for asynchronous operation and short-term inconsistencies. See Brewer's CAP Theorem for a broad overview of this topic.
Deal with proper management of many nodes. This includes basic system administration tasks like Package management as well as testing and rolling out change requests. When you've got 50 webservers you can't just "restart all the apache servers"; some thought has to be brought into these tasks
which brings me to my last point - understand the effects which can be seen in large systems. Thundering Herd is one of the things you're going to see. This article on Audiogalaxy also describe a few problems of large systems.

Scalable Internet Architectures and The art of capacity planning are two books on this topic which I can warmly recommend.
Answer: I'm a scaling guy, I have one rule: always leave yourself the option of buying yourself out of a performance problem.
Anything that can't be fixed by spending money has no fixed 'time to resolve', so always try to code/confit your way out of a problem but always leave yourself with the option to throw cores/cycles/memory/storage/bandwidth/whatever at the issue - they can always be FedEx'ed :)
Answer:
Once you move beyond 100k hits/month, what would people in this community say is the biggest hurdle?

Over thinking the problem, over engineering the platform, and over complicating the system.
100k/month is nothing.  Your entire goal at that point should be spending as little of your time as humanly possible focusing on it.

Scaling a LAMP stack


solr's suggester gives "SolrException: Unknown Search Component: spellcheck at org.apache.solr.core.SolrCore"

Question: I tried using Solr's Suggester component but it gives exception Unknown Search Component: spellcheck. I am using solr version 3.6. I made changes in solrconfig.xml so it looks like this
<searchComponent class="solr.SpellCheckComponent" name="suggester">
 <lst name="spellchecker">
      <str name="name">suggester</str>
      <str name="field">name</str>
      <str name="classname">org.apache.solr.spelling.suggest.Suggester</str>
      <str name="lookupImpl">org.apache.solr.spelling.suggest.tst.TSTLookup</str>
      <float name="threshold">0.005</float>
      <str name="buildOnCommit">true</str>
      <str name="spellcheckIndexDir">spellchecker</str>
 </lst>
</searchComponent>

<requestHandler class="org.apache.solr.handler.component.SearchHandler" name="/suggester">
  <lst name="defaults">
  <str name="spellcheck">true</str>
  <str name="spellcheck.dictionary">suggester</str>
  <str name="spellcheck.count">10</str>
  </lst>
  <arr name="components">
  <str>suggester</str>
  </arr>
</requestHandler>

Now i saved it and started solr but it gives a 500 error. There is a long stack trace which goes like this
HTTP Status 500 - Severe errors in solr configuration. Check your log files for more detailed information on what may be wrong. If you want solr to continue after configuration errors, change: <abortOnConfigurationError>false</abortOnConfigurationError> in solr.xml ------------------------------------------------------------- org.apache.solr.common.SolrException: No cores were created, please check the logs for errors at org.apache.solr.core.CoreContainer$Initializer.initialize(CoreContainer.java:172) at org.apache.solr.servlet.SolrDispatchFilter.init(SolrDispatchFilter.java:96) at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:295) at

---lot of lines---
and some more
Caused by: org.apache.solr.common.SolrException: Unknown Search Component: spellcheck at org.apache.solr.core.SolrCore.getSearchComponent(SolrCore.java:893) at org.apache.solr.handler.component.SearchHandler.inform(SearchHandler.java:118) at org.apache.solr.core.SolrResourceLoader.inform(SolrResourceLoader.java:527) at org.apache.solr.core.SolrCore.<init>(SolrCore.java:594) ... 32 more

According to the stack trace Solr is not able to find the spellcheck component but according to the Solr wiki this component comes with Solr version > 1.4.
Answer: You seem to have named your search component suggester, and your requestHandler refers to it correctly, so that's probably not where the issue is. Can you check in the rest of your solrconfig.xml whether some other requestHandler refers to a component named spellcheck in its last-components section or elsewhere? That would throw an error since it can no longer find a component with that name (it's been renamed to suggester).
The thing with solrconfig is that it comes with a lot of preconfigured search handlers, and if you change the default name of one item it could cause issues with handlers that refer to it.
Comment: Thanks. i found a `requestHandler` with name `/browse` which has a last-component `spellcheck`. But should i remove that `spellcheck`. Or is there some other way around it?
Comment: You can change that to `suggester`, or you could comment out the entire requestHandler if you don't use it. I suggest the first :)
Comment: I changed that `requestHandler` name to `suggester` but the same error. I tried one more thing and that was i changed the `browse` requestHandler's `last-components` to `components`. In that way it should not ignore later `requestHandlers` which use `spellcheck`. But even that does not solve the problem.
Comment: I didn't mean to change the requestHandler's name to suggester, I meant to replace the occurrence of `spellcheck` in the last-components section to `suggester`.


What is tie-break for match in tennis?

Question: In US-Open 2015 mixed doubles final I saw tie-break instead of the third set.
What is that ?
Is it applied only in mixed doubles?
When this rule is applied in tennis?
Is it applicable for all tournaments?
Comment: yes @Ale I am talking about US-Open Mixed doubles final
Comment: [Wikipedia](https://en.wikipedia.org/wiki/Tennis_score#Scoring_a_tiebreak_game) gives some basic information about this. (And also about [tiebreakers](https://en.wikipedia.org/wiki/Tiebreaker) in other sports.)
Comment: Are you talking about "tie-break" or "super tie-break"?
Comment: Are you talking about US-Open Mixed doubles final?
Answer: First of all, Mixed Doubles competition is played only in the 4 Grand Slams. There is no mixed doubles event except in Olympics which falls outside the ITF. The rule came into effect in 2001(I think). It is known as Super Tiebreak. Before that, mixed doubles competition used to play best of 3 set matches.
If the teams have won 1 set each, instead of playing the deciding 3rd set, they play a super tiebreak of 10 points, ie. first to reach 10 points with a lead of 2 points wins the 3rd set & hence the match.
The rule was brought in to speed up the Mixed doubles competition & make it more attractive
Comment: I have also heard the term "match tie-break". Actually coming from the mouth of an official referee (who I know) in my country
Answer: What: if you are talking about "Super Tie-break" the appendix V of ITF rules of tennis you can see info about Match tie-breaks (10 points): this is a tie-break to 10 points, a shorter solutions played instead of third (final) set
When: suggested by ITF in 2001, experimental in 2002, it becames a rule from the year 2003 source
Applied: it is applied also to double matches (men and women) and also in other tournaments out of Gran Slam circuit:
ATP 250 men doubles
ATP 500 men doubles
ATP Master1000 men doubles

What is tie-break for match in tennis?


How can I refresh a fancybox popup?

Question: enter code hereI have a fancybox popup that has the list of cities on it, and a textbox. Once a user enters another city name into the textbox and clicks "Save", I am able to save the new city into the database, but how can I also reload just the popup, so that the new city appears in the list as well?
My popup is an ASPX page, and all I would have to do is somehow execute the Page_Load event, so that it would display the datagrid with all the cities.
Is there any way I can do that? Somehow reload the popup? PLEASE HELP!!!
Here is the fancybox code that opens my popup:
$(document).ready(
                function () {
                    $("#location").fancybox({
                        onClosed: function () {
                            __doPostBack('BodyContent', '');
                        },
                        ajax : {
                        'cache': false,
                        'titlePosition': 'inside',
                        'overlayShow': true,
                        'overlayColor': '#000',
                        'transitionIn': 'elastic',
                        'transitionOut': 'elastic'
                      }
            });

        });

Comment: I guess your function is not well formed, you shouldn't put the fancybox options inside the ajax call. As far as I can tell, your function only binds fancybox to the selector "#location" but it doesn't trigger fancybox (unless there are other parts of your code you are not publishing here)
Answer: If I understood well, you should do this: within the server event that gets executed when you close the popup, make sure that you rebind the grid (feed it with the updated data and call its DataBind method again.
Comment: No, I want to reload my popup, not my parent. I want my popup to re-execute the page_load event
Comment: so, after the postback, you want the popup to show immediately after the page loads? I see that `__doPostBack('BodyContent', '');` statement that looks like it gets executed when the popup closes, so my conclusion is that a POST happens? Or, is that an AJAX call?
Comment: That is for when I close the popup, but if i don't close the popup I want to be able to refresh my popup by clicking on a button or a hyperlink (that is on the popup) for example.
Comment: Well, couldn't you add HTML that relates to the new record that you just sent to the server? so, when AddCity ajax call returns, add HTML for the new city (it's probably a TR element and a few TD's).
Comment: I didn't think about it like that, I suppose it could be done.... But still - is there a way to simply refresh an open popup? There has to be a way, wouldn't you think?
Comment: If the popup is built based on what markup exists on the page, then you'd have to update that markup (via js or page-refresh) and then close-open the popup. If page refresh is your choice, then you'd have to render some js variable, based on which you'd re-open the popup.

How can I refresh a fancybox popup?


Dúvida consulta no SQL Server - Associação de Informações

Question: Meus caros, boa noite! Estou precisando realizar uma consulta em um banco de dados utilizando SQL Server e fiquei empacado em um problema por isso peço, por favor a ajuda de vocês.
Segue um resumo exemplificativo do problema:

Tenho uma tabela que contém o nome de pessoas (chamarei de TABELA 1);
Tenho uma tabela que agrupa certas pessoas da TABELA 1 e estabelece quem é a pessoa principal e quem são as secundárias desse agrupamento (chamarei de TABELA 2);

A TABELA 1 é mais ou menos assim:
IdP   Nome
1    João
2    Maria
3    José

A TABELA 2 é mais ou menos assim:
IdG  IdP  Prcp
1    1    1
1    2    0
1    3    0

Ou seja, neste exemplo, as 3 pessoas estão agrupadas no mesmo grupo e João é o principal e os demais são secundários... Eu gostaria de construir uma consulta que retornasse:
Nome   NomePrincipal
João   João
Maria  João
José   João

Eu tentei a consulta a seguir, mas sem sucesso:
select T1.Nome as 'Nome', T1P.Nome as 'NomePrincipal' from TABELA2 T2
inner join TABELA1 T1 on T2.IdP = T1.IdP
left join TABELA1 T1P on T2.IdP = T1P.IdP AND T2.Prcp = 1

Estou obtendo o seguinte resultado:
Nome   NomePrincipal
João   João
Maria  NULL
José   NULL

Obrigado!
Answer: Tente da seguinte forma: http://www.sqlfiddle.com/#!9/f9a09c/3
A DDL abaixo é opcional,
CREATE TABLE Tabela1
(
  IdP INT NOT NULL PRIMARY KEY,
  Nome NVARCHAR(5) NOT NULL
)
GO

CREATE TABLE Tabela2
(
  IdG INT NOT NULL,
  IdP INT NOT NULL,
  Prcp INT NOT NULL,
  PRIMARY KEY PK_Tabela2 (IdG, IdP),
  FOREIGN KEY FK_Tabela2_Tabela1 (IdP) REFERENCES Tabela1 (IdP)
)
GO

A DML para reproduzir o conteúdo da base de dados é opcional, também,
INSERT INTO Tabela1 VALUES (1, 'João')
GO
INSERT INTO Tabela1 VALUES (2, 'Maria')
GO
INSERT INTO Tabela1 VALUES (3, 'José')
GO

INSERT INTO Tabela2 VALUES (1, 1, 1)
GO
INSERT INTO Tabela2 VALUES (1, 2, 0)
GO
INSERT INTO Tabela2 VALUES (1, 3, 0)
GO

Segue a DML:
SELECT t1.Nome, t1a.Nome Principal
FROM Tabela1 t1
JOIN Tabela2 t2 ON t2.IdP = t1.IdP
JOIN Tabela2 t2a ON t2a.IdG = t2.IdG AND t2a.Prcp = 1
JOIN Tabela1 t1a ON t1a.IdP = t2a.IdP
GO

Obs.: o fiddle está feito no MySQL porque, aparentemente, o SQL Server 2017 disponível no site estava em manutenção.


LVM: "Couldn't find device with uuid" yet blkid finds the UUID

Question: I have a SLES 11.2 PPC (3.0.58-0.6.6-ppc64) system that lost track of its volume group (containing LVs with data that is not critical but would be rather nice to get back).  The disks are connected via two fibre paths from a SAN.
The problem started when I rebooted it before a planned power outage last Friday.  I didn't have time to troubleshoot before bringing it down again.  The volume group had previously been used successfully for about two years.
vgscan and pvscan return nothing:
# pvscan -vP
Partial mode. Incomplete logical volumes will be processed.
 Wiping cache of LVM-capable devices
 Wiping internal VG cache
 Walking through all physical volumes
No matching physical volumes found
# vgscan -vP
Partial mode. Incomplete logical volumes will be processed.
  Wiping cache of LVM-capable devices
  Wiping internal VG cache
Reading all physical volumes.  This may take a while...
  Finding all volume groups
No volume groups found

vgcfgrestore reports it can't find the PVs:
# vgcfgrestore vgclients
Couldn't find device with uuid PyKfIa-cCs9-gBoh-Qb50-yOw4-dHQw-N1YELU.
Couldn't find device with uuid FXfSAO-P9hO-Dgtl-0Ihf-x2jX-TnHU-kSqUA2.
Cannot restore Volume Group vgclients with 2 PVs marked as missing.
Restore failed.

Yet blkid can find those UUIDs:
# blkid -t UUID=PyKfIa-cCs9-gBoh-Qb50-yOw4-dHQw-N1YELU
/dev/mapper/3600a0b800029df24000011084db97741: UUID="PyKfIa-cCs9-gBoh-Qb50-yOw4-dHQw-N1YELU" TYPE="LVM2_member"
/dev/sdl: UUID="PyKfIa-cCs9-gBoh-Qb50-yOw4-dHQw-N1YELU" TYPE="LVM2_member"
/dev/sdw: UUID="PyKfIa-cCs9-gBoh-Qb50-yOw4-dHQw-N1YELU" TYPE="LVM2_member"
# blkid -t UUID=FXfSAO-P9hO-Dgtl-0Ihf-x2jX-TnHU-kSqUA2
/dev/mapper/3600a0b800029df24000017ae4f45f30b: UUID="FXfSAO-P9hO-Dgtl-0Ihf-x2jX-TnHU-kSqUA2" TYPE="LVM2_member"
/dev/sdg: UUID="FXfSAO-P9hO-Dgtl-0Ihf-x2jX-TnHU-kSqUA2" TYPE="LVM2_member"
/dev/sdr: UUID="FXfSAO-P9hO-Dgtl-0Ihf-x2jX-TnHU-kSqUA2" TYPE="LVM2_member"

/etc/lvm/backup/vgclients has all the right info and does not say the PVs are missing:
# egrep "(N1YELU|kSqUA2|dm-|ALLOC)" /etc/lvm/backup/vgclients
                    id = "PyKfIa-cCs9-gBoh-Qb50-yOw4-dHQw-N1YELU"
                    device = "/dev/dm-7"    # Hint only
                    status = ["ALLOCATABLE"]
                    id = "FXfSAO-P9hO-Dgtl-0Ihf-x2jX-TnHU-kSqUA2"
                    device = "/dev/dm-12"   # Hint only
                    status = ["ALLOCATABLE"]

I confirmed on the SAN that the volumes dedicated (and named) for LVM on this server are presented, and the identifier (ends in f30b or 7741) matches on the SAN and on the server:
# multipath -ll | egrep -A5 "(f30b|7741)"
3600a0b800029df24000017ae4f45f30b dm-7 IBM,1814      FAStT
size=575G features='1 queue_if_no_path' hwhandler='1 rdac' wp=rw
|-+- policy='round-robin 0' prio=6 status=active
| `- 6:0:0:1   sdr  65:16  active ready running
`-+- policy='round-robin 0' prio=1 status=enabled
  `- 5:0:0:1   sdg  8:96   active ghost running
--
3600a0b800029df24000011084db97741 dm-12 IBM,1814      FAStT
size=834G features='1 queue_if_no_path' hwhandler='1 rdac' wp=rw
|-+- policy='round-robin 0' prio=6 status=active
| `- 5:0:0:7   sdl  8:176  active ready running
`-+- policy='round-robin 0' prio=1 status=enabled
  `- 6:0:0:7   sdw  65:96  active ghost running

Neither device has a partition table (by design):
# fdisk -l /dev/dm-7 /dev/dm-12 | grep table
Disk /dev/dm-7 doesn't contain a valid partition table
Disk /dev/dm-12 doesn't contain a valid partition table

I am able to read from the devices directly:
# dd if=/dev/dm-7 of=/tmp/a bs=1024 count=1
1+0 records in
1+0 records out
1024 bytes (1.0 kB) copied, 0.00121051 s, 846 kB/s
# strings /tmp/a
LABELONE
LVM2 001FXfSAOP9hODgtl0Ihfx2jXTnHUkSqUA2

I have tried rebooting and also deleting sd(r|g|l|w) and dm-(7|12) and rescanning, to no effect.
I've tried recreating the PV using the backup values, but it still says it can't find them.
# pvcreate --uuid "PyKfIa-cCs9-gBoh-Qb50-yOw4-dHQw-N1YELU" --restorefile /etc/lvm/backup/vgclients /dev/mapper/3600a0b800029df24000011084db97741 -t
  Test mode: Metadata will NOT be updated and volumes will not be (de)activated.
  Couldn't find device with uuid PyKfIa-cCs9-gBoh-Qb50-yOw4-dHQw-N1YELU.
  Couldn't find device with uuid FXfSAO-P9hO-Dgtl-0Ihf-x2jX-TnHU-kSqUA2.
  Device /dev/mapper/3600a0b800029df24000011084db97741 not found (or ignored by filtering).

Here is my lvm.conf, though as far as I know the only change I've made is to increase the log level:
# egrep -v "^( *#|$)" /etc/lvm/lvm.conf
devices {
    dir = "/dev"
    scan = [ "/dev" ]
    preferred_names = [ ]
    filter = [ "a|^/dev/sda$|", "r/.*/" ]
    cache = "/etc/lvm/.cache"
    write_cache_state = 1
    sysfs_scan = 1
    md_component_detection = 1
    ignore_suspended_devices = 0
}
log {
    verbose = 0
    syslog = 1
    overwrite = 0
    level = 2

    indent = 1
    command_names = 0
    prefix = "  "
}
backup {
    backup = 1
    backup_dir = "/etc/lvm/backup"
    archive = 1
    archive_dir = "/etc/lvm/archive"

    retain_min = 10
    retain_days = 30
}
shell {
    history_size = 100
}
global {

    umask = 077
    test = 0
    units = "h"
    activation = 1
    proc = "/proc"
    locking_type = 3
    fallback_to_clustered_locking = 1
    fallback_to_local_locking = 1
    locking_dir = "/var/run/lvm/lock"
}
activation {
    missing_stripe_filler = "/dev/ioerror"
    reserved_stack = 256
    reserved_memory = 8192
    process_priority = -18
    mirror_region_size = 512
    readahead = "auto"
    mirror_log_fault_policy = "allocate"
    mirror_device_fault_policy = "remove"

    udev_rules = 1
    udev_sync = 1
}
dmeventd {
    mirror_library = "libdevmapper-event-lvm2mirror.so"
    snapshot_library = "libdevmapper-event-lvm2snapshot.so"
}

So what gives?  Where'd my VG go and how do I get it back?
Answer: vgreduce --removemissing helped in my case when I was having the same issue.
This is how I created this issue.
I was going to extend an existing logical volume but midway through that that from another terminal I run fdisk on the device that was going to be used for extension. It had some previous partition table that I thought of deleting. Since I had already added this disk to the volume group (just not extended the logical volume itself yet) but that physical volume no more existed so the issue of missing UUID happened.
To solve that I rand the vgreduce --removemissing  and then it was ok.
Comment: This worked for me, but from the `dracut` emergency shell (on Fedora 28) I had to prefix the command with `lvm`. Figured this may be useful for some running Fedora - even though the question is tagged SLES.
Answer: A document in the Novell knowledge base seems to apply here: It explains that on SLES, LVM by default doesn't scan multipath devices, and so will never see them in this situation.
To resolve the issue, you can implement the workaround Novell gives:
In /etc/lvm.conf in the devices section, change the filter to read:
filter = [ "a|/dev/sda.*|", "a|/dev/disk/by-id/dm-uuid-.*mpath-.*|", "r|.*|"]

(This is for SLES 11. For other versions, see the KB article linked.)
Answer: Modify /etc/lvm/backup/<vg_name> file. Fix the messed up stuff, specially remove the missing UUIDs.
Then execute:
vgcfgrestore <vg_name>

Comment: `sudo vgcfgrestore ubuntu-vg` says `Do you really want to proceed with restore of volume group "ubuntu-vg", while 1 volume(s) are active? [y/n]: ` ?


How do I specify a Forena PDO data source in settings.php?

Question: I would like to override my Forena data sources in a local settings file for development. I would also like them in settings.php on production for database independent deployment.
I have checked the documentation but a full example is not provided. Can anyone provide a full example?
Answer: A sample of what you are looking for can be found in Forena subfolder repos/sample/settings.php, it looks like so (and is for 7.x-4.x):
<?php
/*
 * Sample Repository configuration file
 */

/*
 * Security provider:  Specify the class name that is used to provide security
 */
$conf['access callback'] = 'user_access';

/*
 * Data provider:
 * Specify the class name that will be used to interpret data block files.
 * Note that data blocks in a repository
 *
 */
$conf['data provider'] = 'FrxPDO';

/*
 * URI:
 * The format of the uri depends on the type of data engine that's being used.
 * In database engines it might be the connection string to the db.  In the file
 * engine it would be the path to the directory containting the files
 */
$local_path = realpath(dirname(drupal_get_path('module','forena').'/forena.info'));
$conf['uri'] = 'sqlite:'. $local_path . '/repos/sample/sample.db';
$conf['debug'] = FALSE;
/**
 * Uncomment the following line to specify a particular path in which to save reports.
 * The default value would be controlled by Forena configuration page. If you'd like users
 * to be able to define their own reports in this repository then you need to make sure that this
 * is writable by the web user (e.g. apache).
 */
// $conf['report_path'] = 'sites/files/reports'

Disclosure: I'm a Forena co-maintainer.
Comment: Thanks. I didn't accept your answer because I was looking for a way to handle multiple repositories. The version I provided below works to some extent but recently caused problems when migrating reports from one Drupal install to another. Maybe because I am missing both access_callback and user_callback?
Answer: I have found a format that works in settings.php. It is actually shown in snippet form in the linked documentation but not fully expanded on.
global $_forena_repositories;
$_forena_repositories['source1'] =
  [
    'path' => 'sites/all/forena_repos/source1',
    'title' => 'Source1',
    'data provider' => 'FrxPDO',
    'uri' => 'mysql:host=mydb.site.localhost;dbname=source1;charset=UTF8',
    'user' => 'root',
    'password' => 'changeme',
  ];
$_forena_repositories['source2'] =
  [
    'path' => 'sites/all/forena_repos/source2',
    'title' => 'Source2',
    'data provider' => 'FrxPDO',
    'uri' => 'mysql:host=mydb.site.localhost;dbname=source2;charset=UTF8',
    'user' => 'root',
    'password' => 'changeme',
  ];


Statement of result for binomial confidence intervals

Question: Confidence intervals for binomial proportions have irregular coverage over the range of possible population parameters (e.g. see Brown et al. 2001 <Link>). How can I formally and usefully describe the properties of the confidence intervals?
Say I toss a coin ten times and obtain seven heads. Are the following statements accurate?
For the Clopper-Pearson method:
The interval 0.3475–0.9333 has been generated by a method that will on at least 95% of occasions, for any true population proportion, contain the true population proportion. The long-run frequency with which this method would yield confidence intervals containing the true population proportion pertaining to this particular experiment is at least 95%.
For the Wilson's scores method:
The interval 0.3968–0.8922 has been generated by a method that will on 95% of occasions, averaged over all population proportions, contain the true population proportion. The long-run frequency with which this method would yield confidence intervals containing the true population proportion pertaining to this particular experiment may be more or less than 95%.
Comment: Those statements sound fine to me.
Comment: I do not think that the second statement is correct, because it is not defined what "average over all population proportions" means. Actually this formulation makes an implicit assumption about an a priori probability of the true value (assumed to be uniform). This is essentially a Bayesian approach and, as you make an a priori assumption anyway, the use of a Bayesian HPD interval makes more sense (incidentally it even has better coverage probability than the Wilson interval).
Answer: You ask how to 'formally and usefully' present your conclusions
Formally: Your answer is an accurate summary of some of the results from Brown et al. as I understand them.  (I note you do not offer their preferred small n method).
Usefully: I wonder who you audience is.  For professional statisticians, you could state your two intervals directly with only citations to the original papers - no further exposition needed.  For an applied audience, you would surely rather pick an interval on whatever substantive grounds you (or they) have, e.g. a preference for conservative coverage or good behavior for small proportions, etc., and just present that interval alone, noting its nominal and perhaps also its actual coverage much as you do above, perhaps with a footnote to the effect that other intervals are possible.
As it stands you offer a choice of intervals but not much explicit guidance for an applied audience to make use of that information.  In short, for that sort of audience I would suggest either more information about the implications of choice of interval.  Or less!
Comment: I'm writing a paper for a broad audience an wish to contrast those statements with the equivalent statement for the interval containing 95% of the population proportions that are likely to yield the observed number of successes. That interval is easily accessible from the cumulative beta function, Beta(x+1,n-x+1), and has exact coverage given the observed successes. It is fully frequentist, being a fiducial interval and is at the same time a Bayesian interval with a uniform prior. (Ross 2003,
Comment: Then I can see why you don't mention the Jeffreys interval:  Although I can't access the article itself, from the abstract it seems that Ross 2003 offers a Jeffreys' interval with a Beta(1,1) prior, rather than the same interval with a Beta(.5,.5) prior that Brown et al. examined.  It would seem odd if the coverage properties were wildly different for these two, but without the article it's hard to say.
Comment: The coverage properties with a uniform prior and the Jeffrey's prior are indeed very similar when expressed over all possible population parameter values. However, the uniform is superior when the coverage is expressed as conditional on the observed proportion. In that case it is exact. Not 'exact' in the Clopper-Pearson sense, by exactly exact. The Jeffries prior is not quite as good. It is important to note that intervals from the method do not have to be interpreted in the Bayesian manner, as it is entirely derivable as a fiducial interval.
Answer: When using confidence intervals, my response is always as follows:
In repeated sampling % of intervals so constructed will contain _. Thus, we have % confidence that the true  lies within __-_.
One example is
In repeated sampling, 95% of all intervals so constructed will contain Mu, the true population mean. Thus we have 95% confidence that the population GPA lies between 2.72 and 3.07.
I don't see anything particularly wrong with your response, except I would imagine the last sentence should be 95%, not more or less, or at least.
Comment: The issue here lies in the distinction between *actual* coverage and *nominal* coverage.  You seem to assume the two are equal, but for most discrete distributions they are not.  Worse, the actual coverage depends on the proportion one is trying to estimate!  Before considering the question further, you might want to research the two methods @Michael Lew mentions.


Eiffel: REAL_32.to_double gives a strange value

Question: Trying to transform a real_32 to real_64, I'm getting
real_32: 61.55
real_64: 61.54999923706055

Am I wrong with the to_double function?
Answer: This is expected. In the particular example, the binary representation of the decimal 61.55 with single and double precision respectively is:
REAL_32: 0    10000100 11101100011001100110011
REAL_64: 0 10000000100 1110110001100110011001100110011001100110011001100110

As you can see, the trailing pattern 0011 is recurrent and should go ad infinitum to give a precise value.
When REAL_32 is assigned to REAL_64, the trailing 0011s are not added automatically, but filled with zeroes instead:
REAL_32: 0    10000100 11101100011001100110011
REAL_64: 0 10000000100 1110110001100110011001100000000000000000000000000000

In decimal notation, this corresponds to 61.54999923706055. What is essential here, 61.54999923706055 and 61.55 have exactly the same binary representation when using single precision floating numbers. You can check it yourself with print ({REAL_32} 61.55 = {REAL_32} 61.54999923706055). In other words, the results you get are correct, and the two values are the same. The only difference is that when REAL_32 is printed, it is rounded to lower number of meaningful decimal digits.
This is the reason why accounting and bookkeeping software never uses floating-point numbers, only integer and decimal.
Comment: @Pipo There is no way to transform real_32 to real_64 without having the issue. If it's important to keep a specified precision, decimal arithmetic should be used instead. For example, the class `DECIMAL` from the library `decimal`.
Comment: Thx for the explanation I learned a lot, is there a way to solve that with Eiffel? you mentioned integer and decimal... I still don't see how to solve this issue even if it is expected
Comment: @Pipo If the original value always comes as a decimal number with known precision, either an integer with a scaling factor or a decimal number can represent it without loosing precision. This is known as [fixed-point arithmetic](https://en.wikipedia.org/wiki/Fixed-point_arithmetic).
Comment: thx which classes of eiffel should I use for decimal and floating-point?
Comment: Giving me the explanation doesn't give me the solution how to transform a real_32 to a real_64 without having this issue...
Answer: As a workaround working for getting from JSON into typescript deserialization, the following worked:
 a_real_32.out.to_real_64

Comment: This may or may not work, depending on a particular input value. BTW, you are reading the number to make some operations on it, not just to output it immediately, right? Just try the "workaround" with some operation, e.g. `a_real_32.out.to_real_64 + 0.01` to see what's going on.


$x_n$ is the $n$'th positive solution to $x=\tan(x)$. Find $\lim_{n\to\infty}\left(x_n-x_{n-1}\right)$

Question:
$x_n$ is the $n$'th positive solution to $x=\tan(x)$. Find $\lim_{n\to\infty}\left(x_n-x_{n-1}\right)$.
Comment: It certainly converges, since there is a root in every interval $[ n\pi,(n+1)\pi]$. Thus $x_{n}-x_{n-1}<\pi$ for all $n$. It seems that the limit is $\pi$, but I can't think how to show it rigorously.
Comment: Do you see the solution, intuitively ?
Comment: @GitGud Whoops.
Comment: See this answer: http://math.stackexchange.com/a/18733/312
Answer: HINT
Show that $n \pi < x_n < n \pi + \dfrac{\pi}2$, where $x_0 = 0$ by considering the function $f(x) = x - \tan(x)$, which is continuous in the interval $n \pi < x_n < n \pi + \dfrac{\pi}2$.
Now consider $y_n = n \pi + \dfrac{\pi}2 - x_n$. We have $y_n \in (0,\pi/2)$. Since $x_n = \tan(x_n)$, we have $$n \pi + \dfrac{\pi}2 - y_n = \cot(y_n) \in \left(n \pi, n \pi + \dfrac{\pi}2\right) \implies \underbrace{\tan(y_n) \in \left(\dfrac1{n \pi + \dfrac{\pi}2}, \dfrac1{n \pi}\right) \implies y_n < \dfrac1{n \pi}}_{\text{Because $0 < y_n < \tan(y_n)$}}$$
Hence, we have
$$\left \vert x_n - \left(n \pi + \dfrac{\pi}2\right) \right \vert < \dfrac1{n \pi}$$
Conclude what you want from this.
Answer: HINT: Sketch $x = \mathrm{tan}(x)$ and think about the asymptotes of tan$(x)$.


Axon Framework: Convert XStream serialized events to Jackson Serializer in existing application

Question: We have an application that was written using the Axon Framework. Based on the issues we are having with XStream, the idea of converting to the Jackson serializer has been proposed.
Is it possible to convert the current events in the event store to a JSON representation using configuration options in Axon or are we going to have to handle this manually?
Answer: Axon Framework, nor any of the extensions, provide something out of the box to achieve this.
The most straightforward way to rewrite an event store is to write a basic event handling application that reads from store one and writes (with the desired adjustments) to store two.
From an effort perspective, that's something like this:

Construct basic Axon Framework application, reading from current XML store.
Configure the second EventStore in your application separately from Axon's Configurer. This second store's EventStorageEngine should receive the JacksonSerializer, whereas the default store should use the XStreamSerializer
Write an event handler that handles all events, keeping things like the timestamp (very important) intact. This handler should 'append' events into store two.
Start the application. The default Streaming Event Processor will read everything, give it to your Event Handler, that'll provide them to the second store.
Comment: how to define the secondary event store, Currently I am also facing the same issue ( converting xml to jackson serializer). Reason to change the serializer is, When a property is removed from entity we are getting error while deserializing.
Comment: Assuming you're not using Axon Server, your best bet is checking out the "Embedded Event Store" section of the Reference Guide. It shows the builder paradigm the framework uses for all infrastructure components. So, it showcases how you can construct a JPA or JDBC EventStorageEngine. The section in the guide is here, btw -> https://docs.axoniq.io/reference-guide/axon-framework/events/event-bus-and-event-store#embedded-event-store


system property -Dspring.profiles.active not available in spring boot test config in gradle build

Question: I have a spring boot gradle application. when I run gradle builds, I want to run against different environments.
Ex : ./gradlew clean build -Dapp.env=QA1. In the test code, I want to check for this property and gather test data accordingly. What I observed is that property (app.env) is not available.
The build should fail since the test checks for the system property. but the build is succcessful. I also do not see println statements in console.
if you want to clone repo:
git clone https://email@example.com/SpringDevSeattle/gs-rest-service.git
Here is my test code:
src/test/java/hello/GreetingControllerTests.java
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@ContextConfiguration(classes={hello.TestConfig.class,hello.AppConfig.class})
@WebAppConfiguration
public class GreetingControllerTests {

    @Autowired
    TestEnv testEnv;

    @Autowired
    Status status;

    private String env;

    @Before
    public void init(){
        System.out.println(status.getName());
        env=testEnv.getEnv();
    }

    @Test
    public void should_fail(){
        if (env.equalsIgnoreCase("DEV")){
            assertThat(false).isFalse();
        }
        if (env.equalsIgnoreCase("QA1")){
            System.out.println("failing the test");
            fail();
        }
    }

}

src/test/java/hello/TestConfig.java
@Configuration
public class TestConfig {

    @Bean
    public TestEnv testEnv(){
        Properties properties = System.getProperties();
        String env = properties.getProperty("app.env");
        System.out.println(env);
        if (env==null){
            env="dev";
        }
        return new TestEnv(env);
    }
}

src/test/java/hello/TestEnv.java
public class TestEnv {

        private String env;

        public TestEnv(String env){
            this.env=env;
        }

        public String getEnv() {
            return env;
        }

        public void setEnv(String env) {
            this.env = env;
        }
}

src/main/java/hello/AppConfig.java
@Configuration
public class AppConfig {

    @Value("${app.version}")
    private String version;
    @Value("${app.name}")
    private String name;

    @Bean
    public Status status(){
        return new Status(name,version);
    }

}

My ultimate goal is to set 'spring.profiles.active' for tests based on -Dapp.env that gets passed. but I currently do not see the system property picked up in gradle run.
EDIT
even with ./gradlew clean build -Dspring.profiles.active=QA1, I do not see it working.
The test changed accordingly to this.
@Autowired
Environment envi

@Before
    public void init(){
        System.out.println("*********-IN THE INIT METHOD **********"); //new line added
        System.out.println(status.getName());
        env=envi.getActiveProfiles()[0];
    }

@Test
    public void should_fail(){
        if (env.equalsIgnoreCase("DEV")){
            assertThat(false).isFalse();
        }
        if (env.equalsIgnoreCase("QA1")){
            System.out.println("failing the test");
            fail();
        }
    }

The build fails in either case -Dspring.profiles.active=DEV or -Dspring.profiles.active=QA1
Answer: Gradle executes tests in a separate JVM. Therefore, system properties specified at the command line are used in the build JVM and are not propagated to the testing JVM. This is done on purpose to isolate the test process from the build process. You can explicitly specify system properties specifically for the test process like so.
test {
    systemProperty 'key', 'value'
}

Alternatively you can simply pass all system properties to the test process, which will allow you to specify them on the command line via the -D syntax.
test {
    systemProperties = System.props
}

Comment: yes, after adding this in my build.gradle, I am seeing expected behavior. but I do not see see println on console. any idea why? `System.out.println("failing the test");` in the method `should_fail`?   thanks
Comment: you can see added a print statment `System.out.println("*********-IN THE INIT METHOD **********")` in init() method. That should execute always. but I do not see in console. where does those lines go in gradle build?
Comment: You should be able to see this in the test report located in build/reports/tests/test/index.html.
Comment: can you help with this question. it is more gradle based. Thanks. http://stackoverflow.com/questions/38752485/how-to-skip-placeholder-value-if-not-supplied-in-properties-file-in-spring-boot


More control over highcharts legend style

Question: With the highcharts tooltip I'm able to use custom html tags and have almost complete control over the look and feel of the tooltip.
Does anybody know if it's possible to do the same with the legend? At the moment I use the following for the tooltip
headerFormat: '
{point.key}

',
pointFormat: '' +
                '{point.y}
',
footerFormat: '

',

I would love to be able to do the same with the legend, the only thing I've been able to do with the legend is
labelFormatter: function () {
  return '
' + this.name + '
';
                        }

Any help would be great, thanks
Edit: Or would it even be possible to maybe have two tooltips? One static that acts as a legend only displaying the series names and the other as a regular tooltip, and removing the legend all together?
Answer: In a legend you can use only legendFormatter, similar to tooltip, which has also formatter (http://api.highcharts.com/highcharts#tooltip)
Comment: thanks, so with this are you able to control the markers in the legend in the same way as the tooltip?
Comment: Unfortunately not, it is not simple way, to achieve this you need to add "fake" series with custom marker, which will be shown in legend but not in the chart.
Comment: that's a shame, you'd think there would at least be the same amount of control as the tooltip. you don't think it's possible to do as I described in my edit in my post?


Derivation of IV estimator?

Question: Assume, the model we are trying to estimate is:
$Y=\beta_ß+\beta_1X+U$
where x and u are correlated: $Cov(X,U)\neq 0$
Then OLS is inconsistent:
$\beta_1^{OLS}=\frac{Cov(Y,X)}{Var(X)}=\frac{Cov(\beta_0+\beta_1X+U,X)}{Var(X)}=\beta_1\frac{Cov(X,X)}{Var(X)}+\frac{Cov(X,U)}{Var(X)}=\beta_1+\frac{Cov(X,U)}{VaR(X)}\neq 0$
If we introduce an instrumental variable, for which it holds:
$Cov(Z,X)\neq 0$
$Cov(Z,U) = 0$
One can show, that OLS is consitent, so that
$\beta_1^{IV}=\beta_1+\frac{Cov(Z,U)}{Cov(X,Z)}=\beta_1$
I wanted to proof this. Therefore I tried the following:
$\beta_1^{OLS}=\frac{Cov(Y,Z)}{Var(Z)}=\frac{Cov(\beta_0+\beta_1X+U,Z)}{Var(Z)}=\beta_1\frac{Cov(Z,X)}{Var(Z)}+\frac{Cov(Z,U)}{Var(Z)}=?$
This does not lead to a nice solution (first of all $\frac{Cov(Z,X)}{Var(Z)}\neq 1$ and I have $Var(Z)$ in the denominator and not $Cov(X,Z)$)? Why, where is my mistake and how can I proof this?
Answer: I think you tried to prove consistency of the IV estimator but started the proof with the OLS estimator instead. If you write:
$$\newcommand{\Cov}{\operatorname{Cov}}\beta_{1}^{\mathrm{IV}} = \frac{\Cov(Z,Y)}{\Cov(Z,X)} = \frac{\Cov(Z,\beta_{0}+\beta_{1}X+U)}{\Cov(Z,X)}$$
you should get your desired result
$$\beta_{1}\frac{\Cov(Z,X)}{\Cov(Z,X)} + \frac{\Cov(Z,U)}{\Cov(Z,X)}$$
and then by the assumption that $\Cov(Z,U) = 0$ you will be left with $\beta_{1}$.
Have a look here on page 3 just to double-check.
Concerning the question about the formula of the IV estimator:
For your model $$Y = \beta_{0} + \beta_{1}X_{1} + U$$ take the covariance of all terms with the instrument $Z$, which gives $$\Cov(Z,Y) = \beta_{1}\Cov(Z,X) + \Cov(Z,U)$$
Then $\Cov(Z,U) = 0$ by assumption and dividing by $\Cov(Z,X)$ gives
$$\beta_{1}^{\mathrm{IV}} = \frac{\Cov(Z,Y)}{\Cov(Z,X)}$$
Comment: +1 and thanks a lot for your answer, but why do you use Cov(Z,Y)/(Cov(Z,X)) and not Cov(Z,Y)/(Var(X)) ? Where did you get this first equation, that beta = Cov(Z,Y)/(Cov(Z,X)) ?
Comment: I edited the answer and added the explanation you asked for in the comment.

Derivation of IV estimator?


What does pdflush attempt to do when a CentOS server runs out of memory and does not have a swap partition?

Question: I noticed one of our CentOS machines was very close to 100% memory usage last night.  The load average on the machine shot up to ~16 and I noticed that there were several pdflush processes that were blocked on Disk IO (run state D in top).  I thought pdflush was used to swap data from memory to disk (os memory paging), but that particular server didn't have a swap partition mounted.  So what was pdflush actually doing in this case?
Answer: pdflush's primary duty is flushing the disk buffer cache (AFAIk this is its only duty, but a Linux guru may correct me on this).  The cache it flushes includes files that have been written to but not yet committed to disk.
If I recall correctly kswapd is the virtual process responsible for dealing with swap space & shuffling memory pages from RAM to disk & back again.

For the health of your system, please set up a swap partition for your server (or swapon the one you have)
Unix-like systems expect to be able to swap.  Bad Things can happen when there is no available swap (like the disk buffer cache getting squeezed down to a tiny bit of memory, which can really make pdflush have a bad day).
Even if you'll "never" use the swap space, disk is cheap enough that you can throw 2G at it.


MongoDB agregation with filtering in array

Question: I need to count records grouped by tags and have filtered bofore including in ones
// in db
{tags: ['video', 'Alex'], ... },
{tags: ['video', 'John'], ... },
{tags: ['video', 'John'], ... },
{tags: ['text', 'Alex'], ... },
{tags: ['text', 'John'], ... },

client.db('mydb').collection('Files').aggregate(
        [
          { $group: { _id: { tags: '$tags' }, total: { $sum: 1 } } },
          { $match: { tags: 'video' } },
        ],
      ).toArray()

But sadly I got zero docs. If remove $group section I got 3 docs.
In original request I anticipated 2 docs
{ _id: ['video', 'Alex'], total: 1 },
{ _id: ['video', 'John'], total: 2 }

Answer: In aggregation the order of pipeline is important, as output of previous stage is fed to the next one.
Your query is almost there basis the expected output. Just move $match stage before the $group stage.
Query:
db.collection.aggregate([
  {
    $match: {
      "tags": "video"
    }
  },
  {
    $group: {
      _id: {
        tags: "$tags"
      },
      total: {
        $sum: 1
      }
    }
  }
]);

Working Example