Endomorphism is normal and idempotent iff it is an orthogonal projection.

Question: I've searched for answers for this question here for some time but haven't found an applicable answer because I could only find related questions, but not this one in particular.
Suppose $V$ is a finite dimensional (real or complex) inner product space, and $f: V \rightarrow V$ an endomorphism. Then $f$ is an orthogonal projection on $im(f) = U$ iff $f$ is normal and idempotent. Here orthogonal projection means that $f(v) = u$ with the unique decomposition $v = u + u'$, where $u \in U, u' \in U^{T}$.
The first direciton is straight forward, because you immediately get an orthonormal basis of $U$, fill it up with an orthonormal basis of $U'$ and use that all these vectors are eigenvectors.
The problem is the other direction, how do I proceed here? I know that essentially I have to show that $\forall u' \in U^{T}: f(u') = 0$, because an idempotent implies identity on it's image, but I don't know where to use that $f$ is normal. I have somehow gotten an argument without using that $f$ is normal, but this one has to be wrong I guess.
Any help is appreciated!
Answer: Let $f^*$ denote the adjoint of $f$. Let $u' \in U^\bot$. Then
$$\langle f(u'), f(u')\rangle = \langle u', f^*(f(u'))\rangle = \langle u', f(f^*(u'))\rangle = 0.$$
The second equality follows from normality, the third holds because $f(f^*(u')) \in U$ and $u' \in U^\bot$.
Comment: Oh, that was easy. Thanks!
Answer: Being idempotent implies that $f$ is a projection, without the normality assumption. You already know it implies $f$ is the identity on its image; it follows that $v = fv + (1-f)v$ (valid for any linear map) splits $v$ into $u\in\operatorname{im} f$ and $u'\in\ker f$. (Note that $(1-f)v\in \ker f$ as $f(1-f) v = fv-f^2v = fv-fv=0$.) It follows that every element of $V$ is represented as a sum of an element of $U=\operatorname{im}f$ and $U'=\ker f$, and that $f$ sends $v$ to the former, forgetting the latter. The representation is unique because $\ker f \cap \operatorname{im} f = 0$ since if $v$ is in the image then $v=fv$, but if also in the kernel then $fv=0$.
You need the normality to conclude that the projection is orthogonal, i.e. that $U = \ker f$ and $U' = \operatorname{im} f$ are orthogonal to each other. You can get this from McFry's answer.


How to calculate Log Predictive Probability Desnity?

Question: I am trying to follow example in the book Statistical Rethinking (Page 210, code 7.13 and 7.14) for calculating LPPD of a simple model.
The given example code in the book is:
set.seed(1)
logprob <- sim( m7.1 , ll=TRUE , n=1e4 )
n <- ncol(logprob)
ns <- nrow(logprob)
f <- function( i ) log_sum_exp( logprob[,i] ) - log(ns)
( lppd <- sapply( 1:n , f ) )

I assumed ll=TRUE provides the logprobability, I tried calculating it as (in julia)
 begin
    m=10
    # Take random samples from posterior of parameters
    quap_sample = sample_from_model()

    # evaluate mean from sampled parameters
    sim_samples = quap_sample.a .+ quap_sample.b * mass_std'

    # log of samples, I think this part am doing wrong as it is the log of mean I am evaluating and not logprob?
    sim_samples = log.(sim_samples)

    nr,nc = size(sim_samples)
    lppd_sample = zeros(nc)
    for i = 1:nc
        lppd_sample[i] = logsumexp(sim_samples[:,i]) - log(nr)
    end
    lppd_sample
end

Of course results are not matching, Am not totally sure what is ll=TRUE doing (source code accessible here), and previous discussion were also not much helpful
Answer: I figured it out. ll=TRUE returns the log probabilities. I took "hints" from PyMC3 version of Statistical rethink book. Which implements it bit more clearly (it can be found here).
Corresponding Julia code would be:
 begin
    m=10000

    # draw m samples from posterior.of model q71.
    # model :
    #   lsigma ~ Normal(0,1)
    #   b ~ Normal(0,10)
    #   a ~ Normal(0.5,1)
    #   μ = a .+ b .* mass_std
    #   brain_std ~ MvNormal(μ, exp(lsigma))

    quap_sample = DataFrame(rand(q71.distr,m)',q71.params)

    # calculate the mean from drawn samples of a, and b
    sim_samples = quap_sample.a .+ quap_sample.b * mass_std'

    # calculate log probabilities of the actual data, brain_std
    # using the sampled mean and lsigma
    ll = logpdf.(Normal.(sim_samples, exp.(quap_sample.lsigma)), brain_std')

    # calculate lppd = \sum_i log 1/s \sum_s p(y_i|theta_s)
    nr,nc = size(sim_samples)
    lppd_sample = zeros(nc)
    for i = 1:nc
        lppd_sample[i] = logsumexp(ll[:,i]) - log(nr)
    end
end
```


What are good criteria for performance evaluation of algorithms in a regression problem?

Question: I'm classifying different algorithms on the wine quality dataset. The quality ranges from between 0 - 10 based on 11 other attributes. Here is the data.
I'm treating this as a regression problem.
When I run the Decision tree algorithm (w/ a 10 fold cross validation) and confidence factor of 0.5 on the dataset I get the following output:
Correctly Classified Instances        3808               58.6117 %
Incorrectly Classified Instances      2689               41.3883 %
Kappa statistic                          0.3808
Mean absolute error                      0.0787
Root mean squared error                  0.2562
Relative absolute error                 64.3868 %
Root relative squared error            103.6923 %
Total Number of Instances             6497

When I run the same thing with confidence factor of 0.125 I get the following output
Correctly Classified Instances        3790               58.3346 %
Incorrectly Classified Instances      2707               41.6654 %
Kappa statistic                          0.3722
Mean absolute error                      0.0817
Root mean squared error                  0.253
Relative absolute error                 66.8975 %
Root relative squared error            102.4069 %
Total Number of Instances             6497

Questions

What should I be using to evaluate the performance of the algorithm? RMSE? or Correctly classified instances?
What if I was comparing output of different algorithms? e.g. Decision Tree vs. KNN..etc.
What if the problem for classification and not regression?
Comment: Did you look at [ROC](http://en.wikipedia.org/wiki/Receiver_operating_characteristic)?
Comment: I experimented with ROC Curve in Weka but it seems it seems it has to be for a class variable. i.e. if my class has values between 0 - 10 then I can make curve for only one of them at a time. See screenshot here: https://dl.dropboxusercontent.com/s/zlwn2we5ymqeuqi/Screen%20Shot%202014-12-23%20at%2010.43.34%20AM.png?dl=0
Comment: "Criteria" (plural) sounds right here rather than a grammatically incorrect "a criteria".
Answer: First of all, there may be some confusion wrt terminology here. Decision trees are classification routines, despite being commonly known as CART models (or classification and regression trees) and, as such, they aren't truly regression models (I'm sure someone will take issue with this statement. No problem), particularly since they are non-parametric and distribution-free techniques.
That said, the kinds of performance metrics possible can differ between regression models and decision trees but the fundamental issues being addressed do not change. Ever since the late, great Leo Breiman in the 90s (author of the original book about CART), the statistical industry has enshrined optimizing predictive accuracy (PA, alternatively, minimizing the mean squared error) as the gold standard metric for performance evaluation and model validation.
That PA has evolved to this status is understandable: it's easily calibrated and for the most part is a consistent statistic for internal model validation. However, all too often it is the sole criterion for model value, without thought given to wider business impact, and despite its being prone to p-hacking, gaming, and analyst fraud.
The 2008 Netflix Prize provides an object lesson in these challenges. Netflix offered a reward to any statistician or team able to improve upon the MSE of their recommender system The eventual winners used a complex ensemble of 107 different models. As Netflix learned however, the real problem was that, from a fully loaded cost perspective, the actual improvement over their incumbent model was a 0.005% reduction in the real 5 point rating scale. Moreover the IT costs in maintaining this ensemble of 107 models more than nullified any gains from the error reduction. Netflix abandoned the pursuit of MSE and no more Netflix Prizes have been awarded.
Regardless, other competitions – e.g., Kaggle, Crowdanalytix – have enshrined PA. However, to be fair, the era of crowd-sourcing problems as data-mining contests was brand new when NetFlix launched it. The organizers and sponsors of such events are now learning to be more careful in how they pose the problem and data-mining contests are evolving towards more practical and more usable solutions. This year or next, we may see contests where using a designated AWS sand-box (or equivalent) will be part of the scoring. "The official provisioned contest virtual-server will be 8-CPUs rated at XXXX MHz and with 128-GB of RAM. Solutions that run more than 4 hours will be penalized 10% per hour (pro-rated) for excess run-time. Solutions that run more than 10 hours, or that fail due to exceeding available resources, will be disqualified." But this hasn't happened yet.
My real point is that PA is not the only metric for model validation. Should the analyst be willing to sacrifice some PA by factoring in other considerations? Which combination of possible metrics will satisfy constraints wrt PA and derive the strongest strategic insights and confidence in the predictions in the face of truly out-of-sample information and the uncertainty inherent in all future projections?
Integration With Business Financials
Among applied analysts, having domain expertise and a general sense of how their business makes money can result in much greater alignment between purely statistical considerations such as PA and strategic objectives. These insights, as Netflix shows, are not always obvious. Recent articles in the strategic mgmt literature point to PA as a red herring that can be misleading, particularly with respect to strategic planning under uncertainty.
Descriptive vs Predictive Models
Descriptive models find a reduced set of predictors that provide independent information from one to the next, are intuitively interpretable to lay people for the greatest strategic insights. Pricing models are an example where independence is desirable since the goal is to understand how price alone impacts the outcome. Predictive models, one the other hand, usually optimize PA and are sometimes described as "black boxes" that are opaque or even counter-intuitive to lay understanding.
Model Validation
PA is not unidimensional and the distinctions between internal versus external or truly out-of-sample validation can be lost or blurred:

Historic: PA from a randomly drawn holdout or k-fold cv sample(s) from the same data
Forecast: assumes the data is in the form of a time series. Validation is between predicted and actual values based on "today's" observations projected into the future
Prospective: external validation on truly out-of-sample data, can be an "in-market" experiment achieved by making predictions regarding the future then waiting a period of time to evaluate the model relative to actual events. Software such as Unica can also provide this evidence

Model Stability
Parameter estimates can be notoriously unstable out-of-sample. Given a fixed set of model predictors, how stable are they across fixed, k-fold cv data sets? Also, how stable are the predictors across k-fold cv data based on the variable selection method? Do differing methods provide similar results?
Additional Metrics
Model complexity is usually expressed terms of the number of parameters in a model and relies on measures such as the AIC, BIC or Hannan-Quinn. Other metrics are possible. For instance, metrics exist to assess qualitative aspects of model performance that may not improve PA but can be related to descriptive power. These include Mandelbrot's D for fractal dimensionality, Hurst's H exponent for "wild" randomness, entropy, interestingness, conformal confidence, diversity, novelty, etc.
Answer: Since you used cross-validation, MSE is the error you want to look at because it's the error from your testing set, and approximation of the true testing error.
If you use other algorithms with cross-validation, MSE is still appropriate.
You would only want to use an adjustment to MSE--like AIC, BIC, adj. R^2--if you only ran your models on the training set without any sort of validation.
For classification use the error rate, which is the average of $I(y_i \neq \hat{y_i})$.
Source: "An Introduction to Statistical Learning" by Gareth James
Comment: is MSE same as RMSE? I dont see any MSE as output in Weka


JavaScript - Condicional if else

Question: Estou pondo em prática a última aula que fiz de JavaScript e me deparei com um erro em um código que escrevi no VSCode.
Acredito que seja referente a comparação de numeros de dois digitos com números de 1 digito.
Quando comparei o número 9 com o 10, ele volta com o if, ao invés do else if. Isso só acontece com o uso do input através do 'readline-sync'.
Alguém teria uma solução e explicação.
Agradeço!
Exemplo:
<code>import teste from 'readline-sync'

let num1 = teste.question("Digite um numero: ")
console.log(num1)

let num2 = teste.question("Digite outro numero: ")
console.log(num2)

if (num1 > num2) {
console.log(num1 + " é maior que " + num2)
}

else if (num1 < num2) {
console.log(num1 + " é menor que " + num2)
}

else {
console.log(num1 + " é igual ao " + num2)
}
</code>
Comment: Isso está acontecendo porque você está comparando strings. Converta as entradas em numérico antes de as comparar.
Comment: Então...foi isso que me veio a mente, por que o VSCode me diz que string, mas eu não sei como fazer essa conversão de tipos, ainda. Grato pela resposta!
Comment: Esse conflito ocorre pq readline-sync usa a função Number() que transforma os inputs  um número e quando comparado um número de 1 dígito com um de 2 dígitos. ficando assim 9 para 9.0, tente substituir para `parseInt(teste.question("Digite um numero: "))`
Answer: Use o parseInt para converter as string em inteiros
segue exemplo:
var numInt = parseInt(num1);
var numInt2 = parseInt(num2);
E ai depois e so fazer os If.

JavaScript - Condicional if else


how to give two value for a string

Question: import re
mysentence = 'have a dog a cute cat and a big cow '
myanimal = 'dog', 'cat' , 'cow'
print re.finditer('have(.*?)myanimal',mysentence)

this is not working , as my animal strings are not taken . Any idea to make it work ?
Comment: Can you share some more detail what do you expect as output here..
Answer: Q> my animal strings are not taken
As you have myanimal inside the quotations ('have(.*?)myanimal') it would be considered as part of the string, it's actual values won't be substituted.
A regex needs to be formed, and since myanimal is list:
for animal in myanimal:
    regex = re.compile('have a .*%s'%animal)
    for m in re.finditer(regex, mysentence):
        print m.group()

output:
have a dog
have a dog a cute cat
have a dog a cute cat and a big cow

May be this could help....
Answer: >>> import re
>>> mysentence = 'have a dog a cute cat and a big cow '
>>> myanimal = 'dog', 'cat' , 'cow'
>>> m = re.match(r'have a (?:%s)' % '|'.join(map(re.escape, myanimal)), mysentence)
>>> m.group()
'have a dog'

how to give two value for a string


Kubernete / Openshift: Config map contains keys that are not valid environment variable names / xxx.yml is not a valid variable

Question: Is this supported by Kubernete / Openshift 3? I use a yaml file after data: and got error from Openshift:
Config map app-config contains keys that are not valid environment variable names. Only config map keys with valid names will be added as environment variables.

And:

Strangely, it says operatorconfig.yml is not a valid variable, but it's not a variable, it's a file.
Before, it was operator-config.yml, but now after removing -, it still does not work.
The definition is like this:
  - apiVersion: v1
    kind: ConfigMap
    metadata:
      name: app-config
    data:
      appconfig.yml: |
        swarm:
          resource-adapters:
            resource-adapters:
              activemq-rar:
                config-properties:
                  ServerUrl:
                    value: {{ some_url }}
                  UserName:
                    value: {{ some_user }}
        anothercomponent:
          url: {{ some_url }}
      operatorconfig.yml: {{ APP_OPERATOR_CONFIG | to_nice_yaml(width=99999) | trim | to_yaml(width=99999) }}

Neither does appconfig.yml nor operatorconfig.yml works, none got their property values recognized by the service.
I noticed that if it's property file, or properties file without file extension, it works in the official page. Does this mean yaml is not supported?? https://docs.openshift.com/container-platform/3.11/dev_guide/configmaps.html
Answer:
Config map app-config contains keys that are not valid environment
variable names

Above error denotes that ConfigMap used for a container inside pod is loaded as environment variables.  its an issue with environment variable key name used. Variables with "." is not supported naming convention for environmental variables ex: test.var, operatorconfig.yml and appconfig.yml
Comment: Configmap can be created in four different ways.  If you are using configmap map to load it as environment variables inside pod then the variable key name shouldn't have "." For other options of configmap you can have it.  https://kubernetes.io/docs/concepts/configuration/configmap/ When environment option is used in that case inside container when referencing $appconfig.yml won't work.  The same error you are experiencing
Comment: So you mean I should change configMap ref name, or the file name of yaml? I think changing yaml file name does not work.
Comment: Variable Key name used inside configmap are "appconfig.yml" and "operatorconfig.yml" this has to properly defined without "."
Comment: OK you mean I cannot include . in the file name, so I must remove file extension. But why `foo.properties` file works? Please check the link in the OP, I see `game.properties` used there.
Comment: This is good info, thanks a lot. I will read that page and try to understand better.
Answer: At last I found out that in the previous version of app, we load the yaml file content with mountedVolume, then app read that yaml file from the volume, not by loading yaml content in config map as environment variables; seems it's not supported. But to mount to a volume, you need a config map. That's why it was done like this in the beginning; having a config map does not mean you need to load it as environment variables.
My conclusion is that files specified after "data:" can only be properties file; i.e., with each line of "key=value" format; yaml is not.
So I use QUARKUS_CONFIG_LOCATIONS environment variable to point to the mount volume yaml files, and it works.


linear algebra and variance

Question: Please help me understand the following concept.
Let A be a matrix of constants and Y is a random vector.
Var(AY) = AVar(Y)A', where A' is A transpose.
I understand that AA' = A^2.
What I don't understand is why A' goes in the end, instead of AA'Var(Y).
Is there some kind of property in linear algebra that would help me understand the correct order?
Thank you!
Answer: By definition, ${\rm Var}(Y) = \mathbb{E}[YY^\top] - \mathbb{E}[Y]\mathbb{E}[Y]^\top$. Recall that $\mathbb{E}$ is a linear map. Let's compute ${\rm Var}(AY)$ directly: $$\begin{align} {\rm Var}(AY) &= \mathbb{E}[AY(AY)^\top] - \mathbb{E}[AY]\mathbb{E}[AY]^\top \\ &=  \mathbb{E}[AYY^\top A^\top]  - (A\mathbb{E}[Y])(A\mathbb{E}[Y])^\top \\ &= A\mathbb{E}[YY^\top]A^\top - A\mathbb{E}[Y] \mathbb{E}[Y]^\top A^\top \\ &= A(\mathbb{E}[YY^\top] - \mathbb{E}[Y]\mathbb{E}[Y]^\top)A^\top \\ &= A{\rm Var}(Y)A^\top,\end{align}$$as required. The key property you seem to have missed is that the transpose of a product of matrices is the product of the transposes, in the reverse order: $(AB)^\top = B^\top A^\top$.
Comment: Thank you !!!!! I was so confused that I actually forgot to try and derive it from the scratch.
Appreciate it.

linear algebra and variance


DataTable contain no rows after loading

Question: I am trying to load a DataTable with SQLDataReader but then it shows that it has no rows. I check the reader to see if it counts correctly with the while loop and it is correct which means data has been retrieved from database:
NpgsqlConnection sqlcon = new NpgsqlConnection(ConnectionString);
NpgsqlCommand sqlquerry = new NpgsqlCommand(sqlcmd, sqlcon);
sqlcon.Open();

NpgsqlDataReader reader = sqlquerry.ExecuteReader();

int i = 0;
while (reader.Read())
{
    i++;
}
DataTable dt = new DataTable();
dt.Load(reader);

var count = dt.Rows.Count;

Answer: You should decide: either you're using repeated reading from datareader and populating table manually in your loop  while (reader.Read()) or you're populating DataTable with Load method from datareader, but not both options simultaniously.
In fact, your loop "empties" datareader but does nothing useful, so there is nothing to load after it finished. Simpliest solution - is just remove this loop.
Comment: Thanks! it solved my problem. I was thinking that the reader keeps the data

DataTable contain no rows after loading


Why ng-switch-when will not work when we use ng-controller?

Question: I am a beginner to coding. Please help me in finding an issue in below code.
In below code When i write ng-controller, all the 3 radio options are displayed and when i remove ng-controller then ng-switch-when works fine.

<form>
Choose any topic:
<input type="radio" ng-model="selectedValue" value="cars">Cars
<input type="radio" ng-model="selectedValue" value="books">Books
<input type="radio" ng-model="selectedValue" value="pets">Pets
</form>

{{cars}}

        <select ng-options="x for (x,y) in books"></select>
            <input type="text" ng-model="test">
            Title
            Author

                {{books.x.title | filter: test}}
                {{books.x.author | orderBy: varOrder}}

            Hello pets

Answer: Place your ng-controller at the root level,
DEMO

var app=angular.module('myApp',[]);
app.controller('myCtrl',function($scope){
$scope.cars=["ford", "ferrari", "audi"];
$scope.books = {
                "book1":{"title":"CAT", "author":"xyz"},
                "book2":{"title":"Novel" ,"author":"pqr"},
                "book3":{"title":"MAths", "author":"abc"},
                "book4":{"title":"Java", "author":"java"}
                };
$scope.funOrder = function(x){
    $scope.varOrder = x;
};
});

<form>
Choose any topic:
<input type="radio" ng-model="selectedValue" value="cars">Cars
<input type="radio" ng-model="selectedValue" value="books">Books
<input type="radio" ng-model="selectedValue" value="pets">Pets
</form>

{{cars}}

        <select ng-options="x for (x,y) in books"></select>
            <input type="text" ng-model="test">
            Title
            Author

                {{books.x.title | filter: test}}
                {{books.x.author | orderBy: varOrder}}

            Hello pets


Is there a piece of music that "inaugurated" Beethoven's middle period, and thus the Romantic era?

Question: Since Beethoven's early works are considered part of the Classical era, and his later works are considered part of the Romantic era, is there, by scholarly consensus, a single piece of his that indicates the changeover?
I've heard a technical explanation of Romantic harmony as an expansion of Classical harmony to include erstwhile dissonances such as the dominant 9th chord. So I imagine this first piece (if it exists) should introduce the power of the dominant 9.
Comment: This is pretty subjective as it's worded now; I think if you limited your scope to Beethoven and asked about scholarly consensus you might lose yourself those downvotes.
Answer: In order to answer your question, the question itself needs to be modified.  To correct your thought, the Romantic Period did not occur specifically during Beethoven's lifetime, so it could therefore not have happened during his "middle" period.
It is important to understand that when talking about labeling a period of music is to label a zeitgeist of thought, and because of that, it is fairly impossible to distinguish a particular moment or instance in which the shift occurred.  That said, with every musical period there are events which reinforce the current zeitgeist.  This is consistent throughout history.  These events are related to the people that we end up studying in school; such as Beethoven.
Beethoven himself is seen as one of the strongest (and the most famous) connections between the Classical period and the Romantic period.  However, it is generally considered that for music, what would become the Romantic period began to seriously gain momentum in the early 1830's, a few years after Beethoven's death in 1827.
It is because of this that there cannot be scholarly consensus on a single piece of music that would influence and create and entirely new musical period.  At best, a single piece like that would have been seen as an intriguing outlier and imitated by less famous composers.
Regarding the technical explanation that you have heard, that is just not true.  Long before Beethoven's time, Mozart and other composers were using 13th chords, non-functional harmony, chromatic passing tones, and non-local harmonic modulations.  Beethoven would often use unresolved, harmonically non-functional fully-diminished chords as a means of sustain tension throughout a passage.  In comparison to a dominant 9th chord, it's like whipped cream.
In addition to expanded harmony, the Romantic period was a result of composers playing with conventions - both with formal organization, with listeners' expectations, and the beginning of the composer as a self-developing artist.
At the risk of turning this into a paper, I think I'll stop there.
I hope that answers your question.
Comment: Please take no offense that I changed acceptance. BTW didn't you have more rep than that?
Comment: @luserdroog No worries - if this kind of thing bothered me I'd have a terrible life. To answer your question, no. This Beethoven question was actually the first thing I ever answered here, and I had email/login issues immediately after I posted this answer. I left the account alone and started a new one.
Answer: One piece which is often mentioned is Beethoven's 3rd symphony. I don't think harmony alone could be a defining factor. Bach already has some pretty wild stuff. There's an extremely dissonant chord-progression piece (or section of a piece) by him, but I don't remember what it is (it's not the chromatic fantasie and fugue).
Comment: Orlande de Lassus and Carlo Gesualdo also dabble in wild chromaticism some years before the 19th century rolls around...
Answer: The defining point lies somewhere between the Third Symphony and the Fifth Symphony.
In particular, I would argue that it's the Fourth Piano Concerto where Beethoven makes the most radical break from Classical to Romantic music, inasmuch as the harmonic freedom exploited in late Mozart and in Beethoven's earlier works is combined with breaking structural "norms"—the soloist comes in before the orchestra for the first time, the middle movement features piano versus orchestra (instead of the "first among equals" model that predominated until that time), and the "rebalancing" of the work making the allegro-sonata opening as long as the remaining movements combined.


Free Web Forwarding without Nameservers

Question: I have a site running Google App Engine and using CloudFlare (a free CDN proxy, using its own nameserver).
This leaves me with no options for the root domain.
App Engine does not support naked domains, and CloudFlare doesn't support web forwarding.
All forwarding options that I've seen, including my registrar's, only work if the domain's nameservers are set to them.
Does anyone know of a free service that will send HTTP 301 (or 302) redirects without forcing me to change my nameservers?
(I'd make an A record for @ pointing to their server)
Answer: I think it can be done trough .htaccess file
Comment: Read the question. I'm aware of that.  I don't have any servers that I can associate with the naked domain.

Free Web Forwarding without Nameservers


Como salvar a id de um relativeLayout?

Question: Olá, boa tarde. Sou novo em programação Android e não estou conseguindo salvar a ID de um relativeLayout para ser comparado.
Exemplo:
 <RelativeLayout
        android:id="@+id/idAmc"
        android:layout_width="match_parent"
        android:layout_height="65dp"
        android:layout_marginBottom="15dp"
        android:background="@drawable/shadow_grey"
        android:clickable="true"
        android:onClick="selecionaMenuTec">

        <ImageView
            android:id="@+id/ic_amc"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_marginLeft="5dp"
            android:layout_marginTop="15dp"
            app:srcCompat="@drawable/ic_amc" />

        <TextView
            android:id="@+id/amc"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/amc"
            android:textAlignment="center" />

        <TextView
            android:id="@+id/empresaAmc"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginStart="12dp"
            android:layout_toEndOf="@+id/ic_amc"
            android:text="ABC Empresa"
            android:textAppearance="@style/TextAppearance.AppCompat.Body2"
            android:textSize="15sp" />

        <TextView
            android:id="@+id/mediaAmc"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/empresaAmc"
            android:layout_marginLeft="180dp"
            android:text="@string/media" />

        <TextView
            android:id="@+id/mediaValorAmc"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingLeft="5dp"
            android:text="0%"
            android:textSize="25sp"
            android:layout_alignParentBottom="true"
            android:layout_toEndOf="@+id/mediaAmc" />

    </RelativeLayout>

Como faço para pegar o ID desse relativeLayout e salvar em uma variável para futura comparação?
Já tentei utilizar o findViewById() mas não de certo.
Quero fazer algo do tipo: `
public class menuTec extends AppCompatActivity{

public void selecionaMenuTec(RelativeLayout view)
{
    RelativeLayout layoutMenuTec = view;

    if( view == R.id.idAmc){

    }

}

}
Comment: Você quer receber esse valor: idAmc?
Comment: Vc está em um Fragment?
Comment: Quero receber esse idAmc. A ideia é verificar esse idAMc em um if. E chamar um fragment. @Luc
Comment: Quero receber esse idAmc. A ideia é verificar esse idAMc em um if. E chamar um fragment @LeonardoDias
Answer: O seu código não está funcionando porque você está comparando uma View com um inteiro.
O correto seria pegar o Id da view que o método recebe como parâmetro, assim:
public void selecionaMenuTec(View view){
    if (view.getId() == R.id.idAmc) {
        // faça alguma coisa
    }
}

Comment: Entendi, eu fiz um relativeLayout clicavél, quando o usuário clicar nele vai abrir um fragment. Como que eu pego a id desse layout e compraro ela com outras? Na minha função selecionaMenuTec () quero receber esse layout, depois pegar o id desse layout e salvar em uma variavel para ser comprada com os outros ids, para ver qual fragment abrir. @Luc
Comment: Editei a resposta
Comment: Isso eu fiz direto no XML  android:onClick="selecionaMenuTec". Meu problema é quero salvar a id desse layout. Edeitei minha pergunta. @Luc
Comment: Mude o parâmetro RelativeLayout para View.
Comment: Editado de acordo com  tua pergunta, já que a resposta anterior não era relacionado com o que você quer.
Comment: Muio obrigado @Luc

Como salvar a id de um relativeLayout?


Can't parse domain into IP in C#?

Question: I have this code:
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(txtBoxIP.Text), MainForm.port);
When I have an IP in the txtBoxIP (192.168.1.2) for example, it works great.
But if I want to put a DNS? like I'm putting (my.selfip.com) I get:
System.FormatException: An invalid IP address was specified.
at System.Net.IPAddress.InternalParse(String ipString, Boolean tryParse)

How can I make it support both IP and DNS ?
Comment: I've removed the [tag:parsing] tag as the conversion of a hostname into an IP is known as "address resolution" rather than "parsing".
Answer: IPAddress ipAddress;
if (!IPAddress.TryParse (txtBoxIP.Text, out ipAddress))
   ipAddress = Dns.GetHostEntry (txtBoxIP.Text).AddressList[0];
serverEndPoint = new IPEndPoint(ipAddress, MainForm.port)

Don't forget the error handling.
Comment: Yeah, a lot better with `TryParse` :-)
Answer: A DNS name isn't an IP address. Look at Dns.GetHostEntry() for DNS resolution.
Edited to add: Here's what I've done:
public static IPEndPoint CreateEndpoint( string hostNameOrAddress , int port )
{
  IPAddress addr    ;
  bool      gotAddr = IPAddress.TryParse( hostNameOrAddress , out addr ) ;

  if ( !gotAddr )
  {
    IPHostEntry dnsInfo = Dns.GetHostEntry( hostNameOrAddress ) ;

    addr = dnsInfo.AddressList.First() ;

  }

  IPEndPoint instance = new IPEndPoint( addr , port ) ;
  return instance ;
}

Answer: DNS to IP List
IPHostEntry nameToIpAddress;
nameToIpAddress = Dns.GetHostEntry("HostName");
foreach (IPAddress address in nameToIpAddress.AddressList)
    Console.WriteLine(address.ToString());

Then you can use the IP's in the AddressList.
Here is a great article
Comment: You use [one of] the IPAddress(es) that the DNS name resolves to. Use IPAddress.TryParse(). If it succeeds, you've got an IP address. If it doesn't, the name is a DNS name (or should be), then you need to resolve the name via DNS.GetHostEntry().
Comment: Yes, but how can i makei t support both inputs, DNS and IP ?
Comment: If the input is not an IP address you convert it to one first. Then continue as you did before.
Answer: var input = txtBoxIP.Text;
IPAddress ip;

// TryParse returns true when IP is parsed successfully
if (!IPAddress.TryParse (input, out ip))
    // in case user input is not an IP, assume it's a hostname
    ip = Dns.GetHostEntry (input).AddressList [0]; // you may use the first one

// note that you'll also want to handle input errors
// such as invalid strings that are neither IPs nor valid domains,
// as well as hosts that couldn't be resolved

var serverEndPoint = new IPEndPoint (ip, MainForm.port);

Answer: Note: No, it is not déjà vu, this answer is the exact same I provided on another duplicate question... I wanted to make the author of this one aware of the other so the best way I've found was to add it again here as just linking to other answers is frowned upon on Stack Overflow.
I've got a very neat extension method for just that!
I takes into account that an IPV6 may be returned as the first address in the list of addresses returned by the DNS class and allows you to "favor" an IPV6 or IPV4 on the result. Here is the fully documented class (only with the pertinent method for this case for reasons of brevity):
using System;
using System.Linq;
using System.Net;
using System.Net.Sockets;

///
/// Basic helper methods around networking objects (IPAddress, IpEndPoint, Socket, etc.)
///
public static class NetworkingExtensions
{
    ///
    /// Converts a string representing a host name or address to its <see cref="IPAddress"/> representation,
    /// optionally opting to return a IpV6 address (defaults to IpV4)
    ///
    /// <param name="hostNameOrAddress">Host name or address to convert into an <see cref="IPAddress"/></param>
    /// <param name="favorIpV6">When true will return an IpV6 address whenever available, otherwise
    /// returns an IpV4 address instead.</param>
    /// <returns>The <see cref="IPAddress"/> represented by <paramref name="hostNameOrAddress"/> in either IpV4 or
    /// IpV6 (when available) format depending on <paramref name="favorIpV6"/></returns>
    public static IPAddress ToIPAddress(this string hostNameOrAddress, bool favorIpV6=false)
    {
        var favoredFamily = favorIpV6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork;
        var addrs = Dns.GetHostAddresses(hostNameOrAddress);
        return addrs.FirstOrDefault(addr => addr.AddressFamily == favoredFamily)
               ??
               addrs.FirstOrDefault();
    }
}

Don't forget to put this class inside a namespace! :-)
Now you can simply do this:
var server = "http://simpax.com.br".ToIPAddress();
var blog = "http://simpax.codax.com.br".ToIPAddress();
var google = "google.com.br".ToIPAddress();
var ipv6Google = "google.com.br".ToIPAddress(true); // if available will be an IPV6

Answer: You'll have to look up the IP of the hostname yourself:
string addrText = "www.example.com";
IPAddress[] addresslist = Dns.GetHostAddresses(addrText);

foreach (IPAddress theaddress in addresslist)
{
   Console.WriteLine(theaddress.ToString());
}

Edit
To tell the difference between the two (BTW this uses some features of C# that may be in 3.5 and above):
bool isDomain = false;
foreach(char c in addrText.ToCharArray())
{
   if (char.IsLetter(c)){
     isDomain = true;
     break;
}

if (isDomain)
   // lookup IP here
else
   // parse IP here

Comment: Yes, but how can i makei t support both inputs, DNS and IP ?
Comment: I think this has problems with ipv6 addresses, since their string representation can contain letters.

Can't parse domain into IP in C#?


Oracle Query to Select minimum and maximum date of each day by employee

Question: My DB record and TIME_IO is time Stamp field of oracle db.

I need a query to select record in this format, the query should return minimum and maximum TIME_IO for each day and for each employee.
Answer: Start with this
<code>select TRUNC(timeio) as day_timeio, min(timeio) as min_timeoi,
        max(timeio) as max_timeoi
 from table
        group by TRUNC(timeio)
</code>
Comment: ... you probably need to select (and group by) userid as well ?
Comment: Yes. Looks like OP edited the question after my answer


MFC Rich Edit TOM -- InsertTable; cannot add more than one column?

Question: May you please help, I can only insert a table with any number of rows, but not columns; I get an E_INVALIDARG when cols > 1 in ITextRange2::InsertTable(cRow,cCol,AutoFit)??
IRichEditOle* pREOle = NULL; // rCtrl is my derived CRichEditView in MFC
HRESULT hr = rCtrl.SendMessage(EM_GETOLEINTERFACE, 0,
(LPARAM)&pREOle);
CComQIPtr<ITextDocument2> pITextDoc;
hr = pREOle->QueryInterface(__uuidof(ITextDocument2), (void*)&pITextDoc);
CComPtr<ITextRange2> range;
pITextDoc->Range2(start, start, &range);
hr = range->InsertTable(3,3, 1); // get hr = E_INVALIDARG here

Comment: Could you provide us with your test environment? hr = pREOle->QueryInterface(__uuidof(ITextDocument2), (void*)&pITextDoc); IRichEditOle is an incomplete class type for me
Comment: Have you tried passing 0 for `AutoFit`? Also which version of RichEdit control are you using?
Comment: Hey Guys - I figured this out after a few days and help from someone from MS Docs. The solution is rather windows APIish
Comment: If you have resolved your issue please [mark](https://meta.stackexchange.com/a/5235) it as accepted.
Answer: Below is code, that will insert a table for editing rows or inserting a new table. The function is declared in my derived view class CMHMView. I added fields such as ITextRange2* m_ptr2, HRESULT m_hr.
Initialization is done in my CRichEditView::OnInitialUpdate:
CRichEditCtrl& re = GetRichEditCtrl();
m_pREOle = re.GetIRichEditOle();
m_hr = m_pREOle->QueryInterface(IID_PPV_ARGS(&m_ptd2));

This is the function I use to add the table(s)
void CMHMView::InsertTableRow(long index, long& start, long& end, long ncells,
long cellwidths[], long skip, LPCTSTR* sText, BOOL bAppend){

if (SUCCEEDED(m_hr))
{
    long lDelta{};

    CComPtr<ITextFont> pFont;

    m_hr = m_ptr2->GetFont(&pFont);

    CComPtr<ITextRow> pRow;
    CComPtr<ITextFont> pFontDuplicate;

    m_hr = m_ptr2->GetRow(&pRow);
    m_hr = pFont->GetDuplicate(&pFontDuplicate);

    if (pRow && pFontDuplicate)
    {
        CComPtr<ITextPara> pPara, pParaDuplicate;
        m_ptr2->GetPara(&pPara);
        pPara->GetDuplicate(&pParaDuplicate);

        pFontDuplicate->SetName(CComBSTR(L"Courier New"));
        pFontDuplicate->SetSize(12.0f);

        m_ptr2->MoveStart(tomTable, start, &lDelta);
        m_ptr2->Collapse(tomEnd);
        if (bAppend)
        {
            pRow->SetCellCount(ncells);
            for (int i = 0; i < ncells; i++)
            {
                pRow->SetCellIndex(i);
                pRow->SetCellWidth(cellwidths[i]);
            }

            pRow->Insert(1);
            m_ptr2->SetIndex(tomTable, index, 0);

            for (int i = 0; i < skip; i++)
            {
                if (i > 0)
                    m_ptr2->MoveStart(tomCell, 1, &lDelta);
                m_ptr2->SetText(CComBSTR(L""));
            }
            for (int i = 0; i < ncells; i++)
            {
                if (i > 0)
                    m_ptr2->MoveStart(tomCell, 1, &lDelta);

                m_ptr2->SetText(CComBSTR(sText[i]));
                m_ptr2->SetFont(pFontDuplicate);
                m_ptr2->SetPara(pParaDuplicate);

            }

            m_ptr2->EndOf(tomTable, tomMove, &lDelta);

            m_ptr2->GetEnd(&end);
        }
        else
        {
            m_ptr2->SetText(CComBSTR(L"\r"));
            m_ptr2->Collapse(tomEnd);

            pRow->SetCellCount(ncells);
            for (int i = 0; i < ncells; i++)
            {
                pRow->SetCellIndex(i);
                pRow->SetCellWidth(cellwidths[i]);
                /*pRow->SetCellMergeFlags(tomHStartCell)*/
            }

            pRow->Insert(1);
            m_ptr2->SetIndex(tomTable, index, 0);

            for (int i = 0; i < ncells; i++)
            {
                if (i > 0)
                    m_ptr2->MoveStart(tomCell, 1, &lDelta);

                m_ptr2->SetText(CComBSTR(sText[i]));
                m_ptr2->SetFont(pFontDuplicate);
                m_ptr2->SetPara(pParaDuplicate);

            }

            m_ptr2->EndOf(tomTable, tomMove, &lDelta);
            m_ptr2->GetEnd(&end);

        }
    }
}
m_pREOle->Release();}

I hope this will help others!


Checking independence of variables in a Bayesian network

Question: I need a little help with Bayesian Networks. Consider given the following network (all variables are binary) and we need to check conditional independence of $A$ and $C$ if $X$ and $Z$ are given.
Any suggestions?
The network is:

Thanks in advance.
Answer: I have some online software that might help you:
www.causality.org.uk
Shameless plug aside, you want to be able to say that $A$ and $C$ are $d$-separated by $X$ and $Z$ (because $d$-separation is a good proxy for statistical independance under certain assumptions).
The basic idea is to check the paths (without cycles) ignoring the arrows. So you have two paths
$$(I) \;\;\; A\rightarrow Z \leftarrow Y \leftarrow X \leftarrow C$$
$$(II) \;\;\; A\rightarrow Z \leftarrow B \rightarrow X \leftarrow C$$
The idea then is to check that both paths are blocked by conditioning on $X$ and $Z$. I find this definition easy to work with, a path is blocked if

the path contains a chain $P \rightarrow Q \rightarrow R$ or a fork
$P \leftarrow Q \rightarrow R$ with $Q$ being conditioned, OR
the path contains a collider $P \rightarrow Q \leftarrow R$ with neither $Q$ nor any descendant of $Q$ being conditioned.

The first one roughly corresponds to our intuition about common causes, and the second one roughly corresponds to our understanding of Simpson's paradox.
The "or" is very important. Because (I) satisfies 1 but not 2. But (II) does not satisfy either. What is happening here is you are (potentially) introducing a correlation between $A$ and $C$ by your conditioning on $X$ and $Z$ via their link to $B$ (Simpson's paradox).
Note
Conditioning on either $X$ or $Z$ would give you independence, it's just doing both that makes it fail.
Conditioning on $X$ introduces a correlation between $A$ and $B$, which is fine on its own, conditioning on $Z$ introduces a correlation between $B$ and $C$, which is fine on its own. But doing both introduces a correlation between $A$ and $C$ because $A$ is correlated with $B$ and $B$ is correlated with $C$.
Comment: Thanks, it is rather helpful, but I need to show it analytically.
Comment: It has a tutorial part, but the whole d-separation bit is incomplete.
Comment: I will add how to work it out by hand...
Comment: Thanks, I will check carefully.
Comment: @RomanDryndik actually, it seems I haven't uploaded it at all. Sorry :(
Comment: @RomanDryndik Is that more helpful? I can expand it if need be.
Comment: @RomanDryndik to show it analytically you just have to find a suitable probability dist on the graph; knowing that the answer is that they are dependent in general, just make a distribution where they really are dependent to prove it.
Comment: @guy, he was responding to my original answer which was just "I have a website".
Comment: @Lucas thanks. It was helpful, now it is clear. Appreciate.


Continuous and bounded - Check my proof please

Question: Let $f : [0, ∞) → \mathbb{R}$ be continuous such that $\lim_{x→+∞} f(x) = 0$. Prove that $f$ is bounded on $[0, ∞)$
By our hypothesis and the definition of continuity, given $ c \in [0, \infty), \space \forall \space \epsilon>0, \exists \space \delta >0 \space s.t \space |x-c| \leq \delta \implies |f(x) - f(c)| \leq \epsilon  $
Since $f(c) = 0$, then $|f(x)| \leq \epsilon$ and thus $f$ is bounded on $[0, \infty)$
I am scared because here our $x \to c \implies x \to + \infty$ and so $|x-c| \leq \delta \implies |x - \infty| \leq \delta$ wouldn't make sense?
Comment: How is it that you know that $f(c)=0$?
Comment: First find $M>0$ with $|f(x)|<1$  for $x\ge M$. Then find a bound for $|f|$ on $[0, M]$. One step to go after that ...
Comment: @TimRaczkowski Good point! Why did I assume $c = \infty$ when clearly I stated $c \in [0, \infty)$ =_=

Thanks Davild, I'll give it another attempt
Answer: As $\lim_{x\to\infty}f(x)=0$, there exists some $N\in\mathbb{R}$ such that, for all $x>N$, we have $|f(x)|<1$.
Now consider $[0,N]$. This is a closed and bounded subset of $\mathbb{R}$, so it is compact. Since $f(x)$ is continuous on this compact set, there exists some $c$ in $[0,N]$ such that $|f(c)|\geq |f(x)|$ for all $x$ in $[0,N]$.
Thus for $x$ in $[0,N]$, $|f(x)|\leq |f(c)|$, and for $x>N$ we have $|f(x)|<1$. Let $M=\max\{|f(c)|,1\}$. Then $f(x)$ is bounded on $[0,\infty)$, as
$$
-M\leq f(x)\leq M.
$$
Answer: Are you saying $c= \infty$? I looks strange, even if your idea is correct. I would say this: $\lim_{x \rightarrow \infty}f(x)=0$ means that for say $\epsilon =1$ there is an $M$ such that  for all $y > M$ is true that $\vert f(x)\vert <  \epsilon =1$. On the other hand, take the closed interval $[0,M+1]$, here the function is bounded, cause it is continuous over a compact.


confusing error thown while trying to match templates

Question: I've the below XML line of code.
<entry colname="col3" align="left" valign="top"><para>grandchild, cousin, <content-style font-style="italic">etc</content-style>., shall be described as "lawful" and "one of the next-of-kin" or "only next-of-kin".</para></entry>

and below XSL
<xsl:template match="entry" name="entry">
  <xsl:choose>
    <xsl:when test="./@namest">
      <xsl:variable name="namest" select="@namest" />
      <xsl:variable name="nameend" select="@nameend" />
      <xsl:variable name="namestPos" select="count(ancestor::tgroup/colspec[@colname=$namest]/preceding-sibling::colspec)" />
      <xsl:variable name="nameendPos" select="count(ancestor::tgroup/colspec[@colname=$nameend]/preceding-sibling::colspec)" />

        <xsl:apply-templates select="child::node()[not(self::page)]" />

    </xsl:when>
    <xsl:otherwise>

        <xsl:if test="./@morerows">
          <xsl:attribute name="rowspan">
            <xsl:value-of select="number(./@morerows)+1" />
          </xsl:attribute>
        </xsl:if>
        <xsl:if test="./@align">
          <xsl:attribute name="align">
            <xsl:value-of select="@align" />
          </xsl:attribute>
        </xsl:if>
        <xsl:if test="./@valign">
          <xsl:attribute name="valign">
            <xsl:value-of select="@valign" />
          </xsl:attribute>
        </xsl:if>
        <xsl:for-each select="para">

            <xsl:choose>
              <xsl:when test="../@colname='col3' and contains(./text(),'.')">
                <xsl:variable name="strl">
                  <xsl:value-of select="fn:string-length(fn:substring-before(.,'.'))" />
                </xsl:variable>
                <xsl:choose>
                  <xsl:when test="$strl < '6'">

                      <xsl:value-of select="./text()" />

                  </xsl:when>
                  <xsl:otherwise>
                    <xsl:apply-templates />
                  </xsl:otherwise>
                </xsl:choose>
              </xsl:when>
              <xsl:otherwise>
                <xsl:apply-templates />
              </xsl:otherwise>
            </xsl:choose>

        </xsl:for-each>

    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

and when i run this on my XML in the above mentioned line(the XML given in the sample), it is throwing me an error. and the error is as below.
Wrong occurrence to match required sequence type -   Details: -     XPTY0004: The supplied sequence ('2' item(s)) has the wrong occurrence to match the sequence type xs:string ('zero or one')

here what i actually was trying to achieve is, i have another table(which is basically a TOC), where in there is some linking needed, and below is such sample entries.
<entry colname="col3" align="right" valign="top"><para>A.1</para></entry>
<entry colname="col3" align="right" valign="top"><para>A.2</para></entry>

here i'm searching if the colname is col3 and if this has a . in it, and the above two cases mentioned are passing and are getting linked successfully, where in the case mentioned in the top is throwing the error, can anyone please suggest some better method to differentiate these two cases, and i use XSLT 2.0.
Thanks
Answer: The problem is
contains(./text(),'.')

./text() is not "the text of the current element" but rather the sequence of all text node children of the current element.  In the case of
<para>grandchild, cousin, <content-style font-style="italic">etc</content-style>., shall be described as "lawful" and "one of the next-of-kin" or "only next-of-kin".</para>

there are two such nodes, one containing everything between the <para> and <content-style> tags ("grandchild, cousin, " including the trailing space) and the other containing everything between the </content-style> and the </para>.  But the contains function expects its first argument to be a single string, not a sequence of two nodes.
Instead of testing ./text() you probably just need to test .:
contains(., '.')

which is interpreted as the string value of the whole para element, i.e. a single string consisting of the concatenation of all the descendant text nodes (so the whole text "grandchild, cousin, etc., shall be described...").
Comment: @user2423959 if you _only_ want the entries of the form `A.1` (or whatever) then I'd replace the `contains(., '.')` test with something more specific, e.g. `matches(., '^[A-Z0-9]+(\.[A-Z0-9]+)*$')`
Comment: Hi @IanRoberts, can you please let me know if there is a better way to differentiate both the cases? Thanks


double sequence of real numbers

Question: Which of the following statements are true?

Let $\{a_{mn}\}, m ,n \in \mathbb{N}; $be an arbitrary double sequence of real numbers.
Then  $$\sum^ \infty_{m=1} \sum^ \infty_{n=1} a^3_{mn} = \sum^ \infty_{n=1} \sum^ \infty_{m=1} a^3_{mn} $$
Let $\{a_{mn}\}, m ,n \in\mathbb{N}; $be an arbitrary double sequence of real numbers.
Then  $$\sum^ \infty_{m=1} \sum^ \infty_{n=1} a^2_{mn} = \sum^ \infty_{n=1} \sum^ \infty_{m=1} a^2_{mn} $$
Let $\{a_{mn}\}, m ,n \in \mathbb{N}; $be an arbitrary double sequence of real numbers such that $|a_{mn} |\leq \sqrt{\frac{m}{n}}    $
Then  $$\sum^ \infty_{m=1} \sum^ \infty_{n=1} \frac{a_{mn}}{m^2n} = \sum^ \infty_{n=1} \sum^ \infty_{m=1} \frac{a_{mn}}{m^2n} $$
Comment: the last one seems to [converge absolutely](http://www.wolframalpha.com/input/?i=Sum[Sum[1%2Fn^%283%2F2%29*1%2Fm^%283%2F2%29%2C+{n%2C+1%2C+Infinity}]%2C+{m%2C+1%2C+Infinity}])
Comment: If the terms are positive (your second question), see here: http://math.stackexchange.com/questions/89814/positivity-and-interchange-of-summation
Answer: Some HINTS:

Let $a_{nn}=n$ and $a_{n+1,n}=-n$ for $n\in\Bbb Z^+$, and let $a_{mn}=0$ in all other cases.
This is true, assuming that you allow $\infty$ as a sum; how you prove it will depend on what you already know.
$\dfrac{\sqrt{m/n}}{m^2n}=\dfrac1{\sqrt{m^3n^3}}=\dfrac1{m^{3/2}n^{3/2}}$, so for fixed $m$ the series $\displaystyle\sum_{n\ge 1}\frac{a_{mn}}{m^2n}$ is absolutely convergent, and for fixed $n$ the series $\displaystyle\sum_{m\ge 1}\frac{a_{mn}}{m^2n}$ is absolutely convergent.
Comment: still not getting...
Comment: @Prasanta: Which part?
Comment: both 1 and 2...
Comment: @Prasanta: For (1) just evaluate the two sums for the double series that I suggested. For (2) and (3) you need to know that equality holds if the double series is absolutely convergent.
Comment: Maybe you intended a different sequence for 1. With your choice both sums equal $0$. Am I right?
Comment: @Pambos: Not if I calculated correctly. One sum is $0$; the other diverges.
Answer: Use the Fubini–Tonelli theorem.  We have that $a_{mn}\leq\sqrt{\frac{m}{n}}= m^{\frac{1}{2}}\cdot n^{-\frac{1}{2}}$ implies $\frac{a_{mn}}{m^{\frac{1}{2}}\cdot n^{-\frac{1}{2}}}$ and
$$
\frac{a_{mn}}{m^{2}\cdot n^{1}}
=
\frac{a_{mn}}{ m^{\frac{1}{2}}\cdot n^{-\frac{1}{2}}}
\cdot
\frac{ m^{\frac{1}{2}}\cdot n^{-\frac{1}{2}}}{m^2n^1}
\leq
\dfrac{1}{m^{\dfrac{3}{2}}}\cdot\dfrac{1}{n^{\dfrac{3}{2}}}
$$
Note that  $\displaystyle\sum_{n=1}^{\infty}\frac{1}{  n^{3/2}   }< \infty $ and $\displaystyle\sum_{m=1}^{\infty}\frac{1}{  m^{3/2}   }< \infty $ implies  $\displaystyle\sum_{n=1}^{\infty}\frac{1}{m^{3/2}  n^{3/2}   }< \infty $ and $\displaystyle\sum_{m=1}^{\infty}\frac{1}{  m^{3/2}n^{3/2}   }< \infty $ for all $m,n\in\mathbb{N}^*$.
Set the measures in $\mathbb{N}$:
$$
\mu(\{m\})=\frac{1}{m^{2}} \mbox{ and } \nu(\{n \})=\frac{1}{n}.
$$
The above observations it follows that the hypotheses of the theorem Fubini-Tonelli theorem are satisfied. Therefore we have the following.
\begin{align}
\sum^ \infty_{m=1} \sum^ \infty_{n=1} \frac{a_{mn}}{m^2n}=
&
\int_{\mathbb{N}}\int_{\mathbb{N}} a(m,n) d\mu(m) d\nu(n)
\\
=
&
\int_{\mathbb{N}}\int_{\mathbb{N}} a(m,n)  d\nu(n) d\mu(m)
\\
=
&
\sum^ \infty_{n=1} \sum^ \infty_{m=1} \frac{a_{mn}}{m^2n}
\end{align}

double sequence of real numbers


Calculate confidence interval from point estimate and standard error

Question: Im having a problem with calculating a confidence interval for an incidence rate ratio between two populations. Using PROC STDRATE from SAS, I've obtained the Incidence Rate Ratio (the difference in incidence rate between two time periods), the log rate ratio, the standard error and the z-value.
I wonder (1) why on earth did SAS not provide confidence intervals for the rate ratio?
(2) How can I myself calculate these?
I've read: http://www.ncbi.nlm.nih.gov/pmc/articles/PMC1255808/
But this is not a mean, which is why the simple formula: SE = SD/√(sample size), probably isnt correct.
Many thanks in advance for help!
Answer: They do give you a standard error and a $z$ value, which suggests that the SAS developers thought it reasonable to use the normal distribution to approximate the sampling distribution of the statistic involved. So, if you can confirm that your $z$ statistic is equal to the estimated log rate ratio (call it $LRR$) divided by the standard error, then I would be comfortable in using $LRR \pm 2\times SE$ as an approximate 95% CI for the true log rate ratio. Supposing that this results in an interval $(\ell,u)$, then the interval $(e^\ell, e^u)$ provides a 95% CI for the incidence rate ratio itself.
Comment: Dear Professor Lenth,
Many thanks for Your answer, it surely was helpful.

Have I understood it correctly, as follows:

to calculate upper reference limit, I use the formula: exp(LRR + 2*SE)
to calculate lower reference limit, I use: exp(LRR - 2*SE)

I've tried it; the estimates land on each side of the point estimate, but the ones I've tried return a lower estimate quiet close to the point estimate.

Many thanks for Your time
Comment: The lower confidence limit will be *closer* to the point estimate than the upper one. But "quite close" has me concerned if you mean it's practically the same value. BTW, I'd say "confidence limit", not "reference limit".
Comment: The majority of my events have a reasonable upper and lower limit compared to the point estimate (although one event has a lower limit of 1.14, point estimate of 1.17, and upper limit 1.57).
Theres one more thing thats troubling me. In some events 2 *SE is greater then the log rate ratio (LRR). So if i have LRR +/- 2*SE with a negative lower limit and use that estimate in the exp function, i receive a value below zero for the lower limit, the point estimate and upper limit for the same event is above zero (e.g stroke has a point estimate of 1.17, upperlim 1.40, lower limit0.89). continues ->
Comment: -> -> Now what I've done to solve this is, if LRR-2*SE = <0 then I've simply multiplied this value with (-1) before using the exp function. In these cases i obtain a reasonable upper and lower limit compared to the point estimate, is this incorrect and should i then simply accept a lower limit below zero when point estimate and upper limit is above zero in those events.
Comment: **NO** - leave it negative! $e^x$ is still positive when $x<0$.
Comment: Fine. Do you suppose that those events with a lower limit >0 and <1 with point estimate and upper limit >1 are mostly those events were the trend is non-significant?
Comment: This is the first I've heard of a trend, so I don't know what you mean. But that's beside the point anyway, I think. Aren't you trying to estimate the ratio of two quantities, say $IR_1/IR_2$? If $IR_1IR_2$, the log of the ratio is positive. So if, on the log scale, your lower confidence limit is negative and the upper one is positive, it means you can't exclude the possibility that $IR_1=IR_2$. Is that what you were asking?
Comment: Yes. I think that i misguided you when saying that my lower limit was negative, I was actually meant to say that it was simply less than 1 but more then 0. Once again many thanks for all the help!
Answer:
It is not reasonable to multiply (or perform any other operation) with certain values that appears odd.
Just like hazard ratio, odds ratio, relative risk etc, an incidence rate ratio can never be negative (as far as I know...). Higher risk will be expressed as risk >1.0, while lower risk will be expressed as ratio <1.0. I cannot recall that there exists negative relative risks.
Comment: But it's log can be negative. That's the context


How remove border around image in css?

Question: I try to display a span when the cursor of the mouse is on a help icon.
It works, but nevertheless, I don't manage to remove the border around the icon.
My CSS :
.info{
    position:absolute;
    border:none;
}

a.info{
    position:absolute;
    z-index:24;
    background:none;
    color:#000;
    text-decoration:none
}

a.info:hover{
    z-index:25;
    background-color:#FFF;
    cursor:help;
}

a.info span{
    display: none
}

a.info:hover span{
    display:block;
    position:absolute;
    cursor:help;
    bottom:0px;
    left:26px;
    width:150px;
    padding:4px;
}

cd
Comment: try using `div` instead of `img` tag
Comment: If you want to remove the border around the image, why don't you just remove the border around the image? `.info img {}`
Comment: @DaveJarvis: This is not a duplicate, it was asked earlier.
Comment: possible duplicate of [ inside  gets blue border](http://stackoverflow.com/questions/2922858/img-inside-a-gets-blue-border)
Answer: Another thing - remember that if you have an  with an empty src attribute, then none of these suggestions will work, a border will still get shown.

Comment: also src="" will cause a good browser to make a second request to your page as it is short hand for request the current url with an accepts header for images.
Comment: For me this works well
Answer: Try this:
img{border:0;}

You can also limitate the scope and only remove border on some images by doing so:
.myClass img{border:0;}

More information about the border css property can by found here.
Edit: Changed border from 0px to 0. As explained in comments, px is redundant for a unit of 0.
Comment: Am going to use "limitate" somewhere.
Comment: In terms of optimization  border: 0    no need for the 'px'
Comment: @uberneet : that's true. I like adding px so that it's easy to change in firebug in case I want to increase the size later dynamically. I edited my answer  to mention it thought
Comment: `border: 0px` is the way for removing borders (instead of `border: none`)!
Comment: All browser and all mobile are not 100%! check my replies
Answer: img need src to use border is remover, i no know a why css is crazy
data:image/gif;base64,R0lGODlhAQABAPcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAP8ALAAAAAABAAEAAAgEAP8FBAA7

So try example with SRC:

img.logo {
 width: 200px;
    height: 50px;
 background: url(http://cdn.sstatic.net/Sites/stackoverflow/img/sprites.svg) no-repeat top left;
}
<img class="logo" src="data:image/gif;base64,R0lGODlhAQABAPcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAP8ALAAAAAABAAEAAAgEAP8FBAA7">

So try example without SRC:

img.logo {
 width: 200px;
    height: 50px;
 background: url(http://cdn.sstatic.net/Sites/stackoverflow/img/sprites.svg) no-repeat top left;
}

lol... css crazy! good fun
Comment: This was the only solution that worked for me. Thank you
Comment: Thanks. It solved my problem too but I still don't grasp its logic.
Answer: it's a good idea to use a reset CSS.
add this at the top of your CSS file
img, a {border:none, outline: none;}

hope this helps
Comment: border:none; Did not helped me. I needed outline:none; Thanks, master pixeltocode
Answer:

Answer: I faced similar problem with img tag
I had added following line with img tag.

And this is the css class
.my-class{
    background-image: url('add.gif');
    background-repeat: no-repeat;
    display: inline-block;
    width: 27px;
    height: 27px;
}

I changed the img tag to span tag with same css class. Border is not visible now.

Answer: Use:
div {
  background: url()
}

instead of .
There is no borders in the div with background image.
Answer:

if image dont have src or image url is not returning image, border will be there, so you have to set a empty but valid image , here is a example which will load a default image on image loading error

Answer: maybe add border:none to under a.info:hover span or text-decoration:none
Answer: I realize this is a very old post, but I encountered a similar issue in which my displayed image always had a border around it. I was trying to fill the browser window with a single image. Adding styles like border:none; did not remove the border and neither did margin:0; or padding:0; or any combination of the three.
However, adding position:absolute;top:0;left:0; fixed the problem.
The original post above has position:absolute; but does not have top:0;left:0; and this was adding a default border on my page.
To illustrate the solution, this has a white border (to be precise, it has a top and left offset):

This does not have a border:

Hopefully this helps someone finding this post looking to resolve a similar problem.
Answer: img {
  text-indent: -20000px; /*some large value*/
}

did the trick for me (for Chrome). This will remove the alt icon as well, something to note.
Answer: What class do you have on the image tag?
Try this

Answer: I usually use this on the top of css file.
img {
   border: none;
}

Answer: Thank for the answers,
The border is removed for Internet Explorer, but this there for Firefox.
So, I added this class to the img:
.clearBorder{border:none;}

And it worked!
Answer: Here's how I got rid of mine:
.main .row .thumbnail {
    display: inline-block;
    border: 0px;
    background-color: transparent;
}

Answer: Also, in your html, remember to delete all blanks / line feeds / tabs between the closing tag and the opening tag.
  will always display a space between the images even if the border attribute is set to 0, whereas  will not.
Answer: I do believe you need to add the border: none style to your icon element as well.
Answer: Try this

Comment: The question asks for this to be done with CSS.

How remove border around image in css?


Using a ROC Plot to interpret specific scores

Question: I have a binary classifier which outputs a given score to differentiate normal (low score) from abnormal (high score) cases. The score itself however is non-interpretable to others.
I know a ROC plot is typically used to select a threshold to map these continuous scores onto binary decisions. The threshold is selected based on the desired TPR/FPR tradeoff.
My question is: Can this process be done "in reverse", where instead of selecting a binary threshold and them presenting the end user a decision (normal/abnormal), I present the end user the score and say "cases with this score or higher have the following sensitivity (TPR) and specificity (1 - FPR)"
Comment: Why do you think you wouldn't be able to do that?
Answer: Your model presumably can provide the probability of being in the "abnormal" class as a function of your "non-interpretable" score. A plot of probability versus score would be more useful to users than forcing them to wrap their heads around sensitivity and specificity estimates.
If a user is really forced to make a class assignment based on this single score, then the probability cutoff is based on the relative costs of false-positive and false-negative assignments. If there are other types of information available, the probability based on this score will be most useful to combine with them.
Frank Harrell discusses problems with specificity and sensitivity, and the advantages of direct probability estimates, here.
Comment: (1) the model itself provides a score (not bounded to [0,1]). I am not sure of any clear-cut way to go from this score to a "probability of being in the "abnormal" class"
(2) this is in medical context so specificity/selectivity very standard to users.
Comment: @DankMasterDan if all you have is accuracy/specificity/sensitivity for a classifier, the model runs several risks, particularly in the medical context. See the Harrell link in the answer, [this Cross Validated page](https://stats.stackexchange.com/q/312780/28500), and [this post](https://www.fharrell.com/post/class-damage/).
Comment: @DankMasterDan [this post](https://www.fharrell.com/post/mlconfusion/) shows the dangers of relying on ROC in the medical context.
Answer: If you only have the scores and no ground truth targets, and you would assign targets according to a chosen threshold for those scores and use those labels as ground truth labels, then you would always get a perfect ROC score equal to one. For the ROC curve to make sense, you need ground truth targets.
The standard situation is that you are given ground truth labels, that you have learned a binary classifier from those ground truth labels via supervised learning, and that this classifier provides you with a score. Then the ROC score is independent of the threshold you choose for predicting the label of future observations. The ROC curve only depends on the ordering given by the score and on the ground truth variables.
Now to your question: Yes, you can create a binary classifier with any threshold and then report the sensitivity and specificity thereof. This is often done and helps users to choose the classifier they prefer (some might favor high recall, others are more afraid of false positives).
Comment: to be clear I am doing the latter: I train a classifier with ground truth labels. Then I apply that classifier on a sample for which I dont have ground truth and get an output score. Based on the previously obtained ROC, I would like to make a statement about the specificity/sensitivity of declaring this sample positive.


Coefficients linear and log-linear regression model

Question: I performed both a linear and log-linear regression to predict the price of a smartphone based on its characteristics.
Now I have a question concerning the coefficients between the two models.
In the linear regression model, the dummy variable GPS included or not is 37,7.
This means that smartphone users pay on average 47.7 euro more for a smartphone
with a GPS built in than one without, while holding other variables in the model constant.
lm <- lm(Price ~ ., data=data_price2)
summary(lm)

Call:
lm(formula = Price ~ ., data = data_price2)

Residuals:
Min      1Q  Median      3Q     Max
-702.43  -46.68   -6.49   37.59 1522.53

Coefficients: (38 not defined because of singularities)
                     Estimate Std. Error t value Pr(>|t|)
(Intercept)              44.62802   70.21355   0.636 0.525128
Screensize               -6.78973    7.14553  -0.950 0.342155
Multitouch               11.20542   12.62356   0.888 0.374861
nbrCores                 14.58104    2.67044   5.460 5.53e-08 ***
Processorspeed           46.84652    9.54521   4.908 1.02e-06 ***
Memory                  -24.12829    6.02706  -4.003 6.54e-05 ***
nbrSims                  -9.23095    8.00187  -1.154 0.248842
CameraBack                3.10923    0.62724   4.957 7.94e-07 ***
CameraFront              10.69124    2.45340   4.358 1.40e-05 ***
Autofocus               -20.51415    9.40548  -2.181 0.029326 *
Flitsertype              10.63140    7.10996   1.495 0.135043
5-GHzOndersteuning             NA         NA      NA       NA
GPS                      47.68043   11.81778   4.035 5.73e-05 ***
....
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 102.3 on 1556 degrees of freedom
Multiple R-squared:  0.7766,    Adjusted R-squared:  0.7613
F-statistic: 51.02 on 106 and 1556 DF,  p-value: < 2.2e-16

Next, when we take a look at the log-linear regression model, the coefficient for the GPS variable is 2.249e-02, which means that the smartphone retail price increases with 2.52% = (e2.249e-02 − 1) when GPS is included, while holding other variables in the model constant.
lm3 <- lm(log(Price) ~ ., data = data_price2 )
summary(lm3)

Call:
lm(formula = log(Price) ~ ., data = data_price2)

Residuals:
Min      1Q  Median      3Q     Max
-2.3367 -0.1964 -0.0008  0.1896  3.1645

Coefficients: (38 not defined because of singularities)
                     Estimate Std. Error t value Pr(>|t|)
(Intercept)             3.268e+00  2.598e-01  12.575  < 2e-16 ***
Screensize              4.878e-02  2.644e-02   1.845 0.065255 .
Multitouch              2.155e-02  4.672e-02   0.461 0.644685
nbrCores                5.670e-02  9.883e-03   5.737 1.16e-08 ***
Processorspeed          7.306e-02  3.533e-02   2.068 0.038787 *
Memory                  8.273e-03  2.231e-02   0.371 0.710761
nbrSims                -3.488e-02  2.961e-02  -1.178 0.239022
CameraBack              9.779e-03  2.321e-03   4.213 2.67e-05 ***
CameraFront             5.348e-02  9.080e-03   5.890 4.73e-09 ***
Autofocus               1.061e-02  3.481e-02   0.305 0.760654
Flitsertype             1.080e-01  2.631e-02   4.105 4.26e-05 ***
5-GHzOndersupport              NA         NA      NA       NA
GPS                     2.249e-02  4.374e-02   0.514 0.607221
....
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.3785 on 1556 degrees of freedom
Multiple R-squared:  0.7974,    Adjusted R-squared:  0.7835
F-statistic: 57.76 on 106 and 1556 DF,  p-value: < 2.2e-16

The average price for a smartphone in my model is 232€. So, in the log-linear model 2.52% of 232€ is +- 5.85€. How come this value is so different in comparison with the result obtained from the linear regression model?
Comment: Please clarify what you mean by "log-linear regression," as that term can have a [technical meaning](http://stats.stackexchange.com/a/86722/28500) that is not the same as a linear regression with a log-transformed outcome variable. It would help a lot to see more details of the data (maybe some plots), the summaries of the regression outputs, and so forth.
Comment: I've added the regression outputs from both the linear regression and the regression with the log-transformed outcome variable
Comment: Why do you have so many singularities?
Answer: It's not just GPS, whose coefficient is "significant" in the linear price model but not in the log-price model. Many of your predictors change in apparent "significance" between the two models: screen size, memory, auto focus, flitsertype, too.
This is probably due to significant correlations among sets of your predictors, called multicollinearity. In that situation, exactly which predictor gets "credit" for an influence on outcome (in terms of a significant regression coefficient) depends strongly on peculiarities of the data sample at hand. Best guess is that the log transformation of price simply changed which variables among the multicollinear set happened to get that "credit." The distressingly large number of coefficients "not defined because of singularities" might even represent perfect correlations among some predictors.
Depending on what you're trying to accomplish, you might be better off using ridge regression, which better handles multicollinearity as it tends to treat correlated predictors together. But first look closely at the relations among your predictors, remove any that are perfectly correlated to other predictors, and think hard about how you want to deal with sets of highly correlated predictors.


Pegar o Id do cliente de uma linha selecionada do DataTable

Question: Como pegar o Id do cliente de um DataTable sendo que essa coluna está oculta ?
Quando eu clicar na linha do DataTable vou precisar desse ID para exibir em outra View com os detalhes do Cliente.
Tenho o seguinte código
  @model IEnumerable<Dominio.Entidade.TBCliente>

@{
    ViewBag.Title = "CLIENTE";
    Layout = "~/Areas/Administrativo/Views/Shared/_AdministrativoLayout.cshtml";
}

            ID
            NOME
            TIPO

@section Scripts {

    <link href="//cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css" rel="stylesheet" />

}

ACTION
public JsonResult BuscarCliente()
    {
        string echo = Request.Params["sEcho"].ToString();
        string iColumns = Request.Params["iColumns"].ToString();
        string sColumns = Request.Params["sColumns"].ToString();
        int iDisplayStart = int.Parse(Request.Params["iDisplayStart"].ToString());
        int iDisplayLength = int.Parse(Request.Params["iDisplayLength"].ToString());
        string mDataProp_0 = Request.Params["mDataProp_0"].ToString();
        string sSearch = Request.Params["sSearch"].ToString();
        string iSortCol_0 = Request.Params["iSortCol_0"].ToString();
        string sSortDir_0 = Request.Params["sSortDir_0"].ToString();
        string iSortingCols = Request.Params["iSortingCols"].ToString();
        string bSortable_0 = Request.Params["bSortable_0"].ToString();
        int regExibir = iDisplayLength;
        int startExibir = iDisplayStart;

        List<TBCliente> lClienteFiltrado = new List<TBCliente>();
        List<TBCliente> lTotalCliente = _IRepositorio.ListarCliente();

        if (!string.IsNullOrWhiteSpace(sSearch))
        {
            lClienteFiltrado = lTotalCliente.Where(x => x.NMCLIENTE.ToUpper().Contains(sSearch.ToUpper())).ToList<TBCliente>();
        }
        else
        {
            lClienteFiltrado = lTotalCliente;
        }

        if (iDisplayStart > lClienteFiltrado.Count)
            startExibir = 0;
        if (iDisplayStart + iDisplayLength > lClienteFiltrado.Count)
            regExibir = lClienteFiltrado.Count - startExibir;

        if (sSortDir_0 == "asc")
        {
            if (iSortCol_0 == "0")
                lClienteFiltrado = lClienteFiltrado.OrderBy(x => x.TBCLIENTEID).ToList<TBCliente>();
            if (iSortCol_0 == "1")
                lClienteFiltrado = lClienteFiltrado.OrderBy(x => x.NMCLIENTE).ToList<TBCliente>();
            if (iSortCol_0 == "2")
                lClienteFiltrado = lClienteFiltrado.OrderBy(x => x.TPCLIENTE).ToList<TBCliente>();
        }
        else
        {
            if (iSortCol_0 == "0")
                lClienteFiltrado = lClienteFiltrado.OrderByDescending(x => x.TBCLIENTEID).ToList<TBCliente>();
            if (iSortCol_0 == "1")
                lClienteFiltrado = lClienteFiltrado.OrderByDescending(x => x.NMCLIENTE).ToList<TBCliente>();
            if (iSortCol_0 == "2")
                lClienteFiltrado = lClienteFiltrado.OrderByDescending(x => x.TPCLIENTE).ToList<TBCliente>();
        }

        var Resultado = new
        {
            sEcho = echo,
            iTotalRecords = lTotalCliente.Count,
            iTotalDisplayRecords = lClienteFiltrado.Count,
            //iDisplayLength = 10,
            aaData = lClienteFiltrado.ToList<TBCliente>().GetRange(startExibir, regExibir)
        };
        return Json(Resultado, JsonRequestBehavior.AllowGet);
    }

Comment: Os dados da datatable estão vindo como? Paginado pelo servidor? Você gera tudo no HTML e depois converte em datatable? Existem algumas maneiras de fazer isso e o modo como a tabela é gerada pode influenciar.
Comment: Erick o processamento está sendo feito no servidor, eu adicionei na pergunta a Action que retorna os dados para o DataTable.
Answer: Olá, uma maneira de fazer isso é utilizar fnGetData
Para isso depois de declarar sua table você declara o evento de get data para cara linha (row) da sua tabela.
table.$('tr').click( function () {
    var data = table.fnGetData( this );
    // a variavel data vai conter ou um array ou objeto contendo todos os dados da sua row
  } );

Documentação oficial http://datatables.net/api#fnGetData
Editado
Outra coisa, o mais correto seria você fazer
var table = $("#tblCLiente").DataTable({
                "bProcessing": true,
                "bServerSide": true, ....

E não chamar depois o var table = $("#tblCLiente").DataTable() é como se você tivesse recriando o DataTable.
Comment: Obrigado Erick mas não funciona
Comment: @AdrianoCordeiro Da algum erro? Retorna vazio? O que acontece quando você usa o fnGetData?
Comment: Tem razão Erick sobre a variável table eu já alterei, porém estou na mesma, ou seja: Não da erro e nem retorna nada, simplesmente qdo clico na linha do DataTable não acontece nada.
Answer: Encontrei a solução e fic ai pra quem passar pela mesma situação que eu, a solução foi adicionar o valor do id cliente para o atributo "id" para do parâmetro "rowCallback": da requisição ajax:
           "rowCallback": function (row, data) {
                $(row).attr("id", data.TBCLIENTEID);
            },
            "sPaginationType": "full_numbers"ódigo aqui

e depois recuperar no click da linha:
$('#tblCLiente tbody').on('click', 'tr', function () {
            var id = this.id;
            if ($(this).hasClass('selected')) {
                $(this).removeClass('selected');
            }
            else {
                table.$('tr.selected').removeClass('selected');
                $(this).addClass('selected');
            }
        });

        $('#button').click(function () {
            table.row('.selected').remove().draw(false);
        });


How to write complete "sed"command

Question: I tried sed command at Mac's terminal but it is showing ">" and couldn't execute the command.
<code>username$ oc get secret all-icr-io -n default -o yaml | sed 's/default/my-project/g' | oc create -n my-project -f -
>
</code>
I got this command from
here
(③Copy the all-icr-io image pull secret from the default project to the project of your choice. The new image pull secrets are named <project_name>-icr--io.)
What I am trying to do is to copy OpenShift secret to from one namespace to another.
"my-project" is existing project.
Answer: Don't use the "smart quotes", use the ASCII ones only. The shell thinks the quoted string hasn't been closed.
<code>'s/default/my-project/g'
                       ~
</code>
Comment: It worked well by changing as you told me .Thank you very much.

How to write complete "sed"command


Find power series solution of ${x^{2}y''-xy'+py=0}$ about x=1, p is a constant.

Question: The recurrence relation I ended up getting doesn't match with the final answer. Did a couple of revisions of the thing but nothing changes.
I get the recurrence relation as
 $${a_{r+2}=\frac{-[(r^2-2r+p)a_r+(r+1)(2r-1)a_{r+1}]}{(r+2)(r+1)}}$$
My attempt at a solution
The original equation can be written as
$${y''-\frac{xy'}{x^{2}}+\frac{py}{x^{2}}=0}$$
Put $(x-1)=t$
Notice that $y''$ and $y'$ don't make a difference
Therefore we have $${y''-\frac{(t+1)y'}{(t+1)^{2}}+\frac{py}{(t+1)^{2}}=0} \qquad (1)$$
where $P(t)=-\frac1{(t+1)}$ and $Q(t)=\frac{p}{(t+1)^{2}}$, which have $t=0$ as an ordinary point
Now we can write $$y =\sum{a_rt^r},$$
$$y' =\sum{ra_rt^{r-1}},$$
$$y'' =\sum{(r-1)ra_rt^{r-2}}$$
Using these in the (1) we get
$${\sum{(t+1)^{2}(r-1)ra_rt^{r-2}}-\sum{(t+1)ra_rt^{r-1}}+p\sum{a_rt^r}=0}$$
$$\implies{\sum{(t^2+2t+1)(r-1)ra_rt^{r-2}}-\sum{(t+1)ra_rt^{r-1}}+p\sum{a_rt^r}=0}$$
$${\implies\sum{(t^2+2t+1)(r-1)ra_rt^{r-2}}-\sum{(t+1)ra_rt^{r-1}}+p\sum{a_rt^r}=0}$$
$${\implies\sum{(r-1)ra_rt^{r}}+2\sum{(r-1)ra_rt^{r-1}}+\sum{(r-1)ra_rt^{r-2}}-\sum{ra_rt^{r}}-\sum{ra_rt^{r-1}}+p\sum{a_rt^r}=0}$$
Equating coefficients of $t^r$ on both sides, we have
$${(r-1)ra_r+2{(r+1-1)(r+1)a_{r+1}}+(r+2-1)(r+2)a_{r+2}-ra_r-(r+1)a_{r+1}+pa_r=0}$$
$$\implies{((r-1)r-r+p)a_r+{(2r(r+1)-(r+1))a_{r+1}}+(r+1)(r+2)a_{r+2}=0}$$
$$\implies{(r^2-2r+p)a_r+{(r+1)(2r-1)a_{r+1}}+(r+1)(r+2)a_{r+2}=0}$$
$$\implies{(r+1)(r+2)a_{r+2}=-[(r^2-2r+p)a_r+{(r+1)(2r-1)a_{r+1}}]}$$
which gives the recurrence relation
$${a_{r+2}=\frac{-[(r^2-2r+p)a_r+(r+1)(2r-1)a_{r+1}]}{(r+1)(r+2)}}$$
However when I use the above mentioned relation for the solution, the coefficients don't come out to be correct as per the answer key.
The solution supposedly is http://s11.postimg.org/4zm9oouf6/IMG_20150708_190227.jpg
I can't post images yet, so the link.
Answer: We may notice that the original ODE is solved by $x^{\alpha}=\exp(\alpha \log x)$, provided that:
$$ \alpha(\alpha-1) -\alpha + p = 0,\tag{1} $$
so two independent solutions are given by $\exp\left[\left(1-\sqrt{1-p}\right) \log x\right]$ and $\exp\left[\left(1+\sqrt{1-p}\right)\log x\right]$. Assuming:
$$ y(x) = \sum_{n\geq 0}a_n (x-1)^n \tag{2}$$
we have:
$$\begin{eqnarray*} 0=x^2 y''(x) - x y(x) + p y(x) =\\ =  (x-1)^2 y''(x) + 2(x-1)y''(x)+y''(x)-(x-1)y'(x)-y'(x)+py(x)\tag{3}\end{eqnarray*}$$
hence for any $n\geq 0$:
$$ n(n-1) a_n + 2n(n+1) a_{n+1}+(n+2)(n+1)a_{n+2}-na_n-(n+1)a_{n+1}+p a_n = 0$$
or:
$$ (n+2)(n+1) a_{n+2} + (2n^2+n-1)a_{n+1} + (n^2-2n+p)a_n = 0.\tag{4} $$
Comment: I added my attempt of the solution. I don't understand Step 3.
Comment: @MohammadNairAalam: $$ x^2=((x-1)+1)^2 = (x-1)^2 + 2(x-1)+1. $$
Comment: Shouldn't it be $ (2n^2+n-1)a_{n+1}$?
Comment: Our solutions match up. So, I must be right then.


VS2015: Default Universal App template causes XAML designer crash

Question: When I create a Universal App template project in VS2015, it throws an unhandled exception in the designer view (telling me that often times, 'excluding code' will cause less hiccups), then proceeds to give me the following exception:
<code>System.OperationCanceledException

The registration of the app package required by the designer took too long
to complete and was canceled. Reload the designer to try again.
</code>
I've tried rebooting Windows 10, and repairing VS2015. Nothing works! Looking at the 'similar questions' tab makes me think that Microsoft rushed this a little too much..
Answer: I had the same issue with VS2015 community edition on Windows 10.
The following fixed my issue:

Disabling developer mode in Windows.
Restart.
Enabling developer mode.


Related Measures

Question: ($\Omega, F,P) $ is a measure space, $\ Q \ll P $ ($Q$ is related to $P$) i.e. $\ Q(A)= \int 1_ADdP $ where $\ D=dQ/dP$.
Then $X$ is integrable wrt $Q$ if and only if $XD$ is integrable wrt $P$ and $\int XdQ = \int XDdP$.
How do I prove this? I can only do it for $X$ a simple Borel function, not a general one.
Answer:
Let $X$ integrable wrt $Q$. Write $X=X^+-X^-$, where $X^+$ and $X^-$ are the positive and negative parts of $X$. Let $X_n$ a sequence of step functions which converge pointwise to $X^+$ and $X_n\leq X^+$. We can show by Fatou's lemma that
$$\int X^+DdP=\int \liminf_n X_nDdP\leq \liminf_n\int X_nDdP=\liminf_n\int X_ndQ\leq \int X_n^+dQ,$$
hence $DX^+$ is $P$ integrable. Do the same for $X^-$ to get the result. Use the same idea to get the converse, using the fact that $D$ is non-negative.
You got $\int XdQ=\int XDdP$ for each $X$ simple. By a monotone convergence argument, you have to show that this equality holds if $X\geq 0$ and is integrable. Then you will deduce the general case.
Comment: Ok, so for the second one I can say that for any non negative borel function X there exits a monotone sequence Xi where Xi are simple for all i such that $\ X=Sup_i(X_i)$ then $\int X dQ =  \ int sup_iX_i dQ =sup_i \ intX_idQ$ via monotone convergence which is then $\sup_i \ intX_iDdP$ But now what can I do with this?
Comment: You can write a Borel-measurable function as a difference of two measurable non-negative functions.

Related Measures


Formulating the likelihood in an LRT involving geometric and exp distribution

Question: Here is a question from old exam papers I am having trouble with:

Suppose the lifetime of a bulb is distributed exponentially with mean life $\theta$ (in hours). Let $X_i$ be the number of trials required to get a bulb surviving at least $t$ (known) hours for the first time in the $i$th lot, where lot sizes are large enough. Discuss a likelihood ratio test for testing $H_0:\theta\ge\theta_0$ against $H_1:\theta<\theta_0$.

I am not sure what exactly my observed sample is supposed to be. So I am stuck at setting up the problem correctly.
Say I have $k$ lots of bulbs, the $i$th lot having size $n_i\,, i=1,2\ldots,k$.
Then is the observed sample some $\mathbf X=(X_1,X_2,\ldots,X_k)$, where  $X_i=(X_{ij})_{i=1,\ldots,k\,;\,j=1,\ldots,n_i}$ is again a vector for each $i$ ? I am using $X_{ij}$ to denote the number of trials needed to get the $j$th bulb surviving for at least $t$ hours for the first time in the $i$th lot.
If I assume $X_1,X_2,\ldots,X_k$ are all independent samples, then my likelihood function should be
$$L(\theta\mid \mathbf x)=\prod_{i=1}^k\prod_{j=1}^{n_i}p(\theta)(1-p(\theta))^{x_{ij}-1}\quad,\,\theta>0$$
, where $p(\theta)=\int_t^{\infty}\frac{1}{\theta}e^{-z/\theta}\,dz=e^{-t/\theta}\,,t>0$ is the success probability.
But this might be wrong since I am supposed to have a sample consisting of only $X_1,\ldots,X_k$ where each $X_i$ denotes number of trials (so not vectors by themselves). In the above setup, this does not seem to be the case.
If this formulation is wrong, I would like a hint on how to arrive at the correct one. And also, where exactly am I supposed to apply a large sample approximation with large $n_i$s? Is this referring to Wilks' theorem on the asymptotic distribution of the log-likelihood ratio statistic?
(I am not looking for a solution to the actual problem.)
Answer: I would formulate your likelihood based on the geometric distribution.  What you are trying to estimate is $p(\theta, t)$, where $p$ is the probability of a bulb surviving at least $t$ hours given the parameter $\theta$ of the exponential distribution, as you have realized.  Given this formulation, you are observing $x_i$, the number of "failures" before your first (and only) success for each of $k$ lots; that's your data.  Since your last trial within each lot is the success (as the last bulb tried is the one that survives for at least $t$ hours), the number of failures is just the number of trials $-1$.
The likelihood function for the $i^{th}$ lot is:
$$\mathcal{L}(p;x_i) = (1-p)^{x_i}p$$
and the likelihood for $k$ lots is just the product of the $k$ individual likelihoods (since the parameter $p$ is the same and the lots are independent):
$$\mathcal{L}(p; x) = (1-p)^{\sum_{i=1}^k x_i}p^k$$
Note that this is actually the likelihood function for a negative binomial $(k,p)$ distribution, because you have $k$ independent lots.
Hints: You can easily convert the likelihood ratio test for $\theta$ to one for $p$, since the relationship between $p$ and $\theta$ is strictly monotonic, or you can construct a likelihood ratio test for $p$ and transform it into one for $\theta$.  You can use a large sample approximation for the distribution of the MLE of $p$ if $k$ and $\sum x_i$ are large enough, say, both $> 5$ (as a possibly-discredited rule of thumb), to simplify this latter approach to the more common Normal distribution problem.
Comment: I've edited the question, hopefully answering your questions.
Comment: Thanks. Is $k$ also supposed to be the total lot size as in my question? So I should not consider individual lots but only the entire lot as a whole?
Comment: And how does the number of trials $x_i$ become the the number of failures?


Kanban com Bootstrap

Question: Bom dia a todos!
Preciso montar um Kanban, de preferencia com Bootstrap.
Vocês conhecem algum projeto (opensource) pra baixar ele e implementar?
Answer: Após uma pequena pesquisa no google, achei um que deve te agradar, dado que a resposta do @Flavio não agradou.
Eu achei ele no site bootsnipp, com este link direto.
Comment: Muito obrigado pela ajuda...... eu tinha visto este projeto também pelo Google.
Só tem um detalhe.... eu não tenho acesso a servidor pra hospedar css e javascript..... tem q estar tudo no html.
Comment: CSS e Javascript você pode fazer dentro do arquivo HTML também. Só é pior pra fazer manutenção, mas poder pode. Só colocar uma tag `

Kanban com Bootstrap


Dom4J alternatives for XML processing in Java

Question: We wanted to upgrade our project in order to use some up-to-date dependencies. In the moment we use jaxb for XML reading and writing. This is working very good.
In some cases we do not have an xsd or dtd in order to generate the java classes (via xjc). In those cases we use dom4j for creating xml documents or dom4j with xpath for reading xml documents.
The version 1.6.1 is over ten years old and as far as I understand, dom4j needs jaxen as the X-Path library. Jaxen 1.1.6 is also 4 years old. Also we removed from our project xerces 2.40 (also 12 years old).
What XML API is state of the art in the moment? It should support XPATH expressions and should create and read xml documents.
Also I am wondering about xerces. When we use JAXB for reading xml documents, sometimes we have an object values instead of a string, date or something else.
The reason for that is that somebody messed up the xsd and forgot do define a datatype for some elements. XJC creates simple object properties inside the generated java class. The strange thing is, that I needed to cast the object to an "ElementNSImpl" object. This object comes from the xerces project.
I am a little bit confused. Our solution for removing xerces was to define each element with a proper datatype. Unfortunately those XSDs are third party XSD and we have to fix that each time the XSD will change. But why do I have to cast the object in ElementNSImpl?
Thanks for your help.
Comment: My preferred options would be JDOM2 or XOM, but you haven't given a convincing reason for moving that would justify the cost and disruption. If you want a more modern XPath engine, Saxon works with DOM, JDOM2, DOM4J, XOM, and Axiom, as well as its own internal tree model.
Answer: Just because something is 'old' doesn't mean it's not useful. DOM4J is still my favorite tool for ad-hoc XML processing. dom4j has been updated since 1.6.1, but note that it is still dependent on an underying XML parser (such as Xerces).
Answer: dom4j version 1.6.1 has an XML Injection security vulnerability: https://nvd.nist.gov/vuln/detail/CVE-2018-1000632.
It appears to have been fixed in 2.1.1, released in July of 2018.


Why can't the uncentered $R^2$ be negative?

Question: In vectorized OLS, let $\mathbf{y}$ and $\hat{\mathbf{y}}$ be the observations and predictions, and define the residuals as $\mathbf{e} = \mathbf{y} - \hat{\mathbf{y}}$. Then the uncentered $R^2$ is
$$
R^2_{uc} = 1 - \frac{\mathbf{e}^{\top} \mathbf{e}}{\mathbf{y}^{\top} \mathbf{y}}.
$$
Now in his econometrics textbook, Hayashi writes:

Since both $\hat{\mathbf{y}}^{\top} \hat{\mathbf{y}}$ and $\mathbf{e}^{\top} \mathbf{e}$ are nonnegative, $0 \leq R^2_{uc} \leq 1$.

However, this restriction that $R^2_{uc}$ is nonnegative does not make senes to me. $R^2_{uc}$ should be negative when $\mathbf{e}^{\top}\mathbf{e} > \mathbf{y}^{\top}\mathbf{y}$. This is true when
$$
\begin{aligned}
\hat{\mathbf{y}} &> 2\mathbf{y}
\\
\hat{\mathbf{y}}^{\top} \hat{\mathbf{y}} &> 2\mathbf{y}^{\top} \hat{\mathbf{y}}
\\
\mathbf{y}^{\top} \mathbf{y} + \hat{\mathbf{y}}^{\top} \hat{\mathbf{y}} - 2\mathbf{y}^{\top} \hat{\mathbf{y}} &> \mathbf{y}^{\top}\mathbf{y}
\\
(\mathbf{y} - \hat{\mathbf{y}})^{\top} (\mathbf{y} - \hat{\mathbf{y}}) &> \mathbf{y}^{\top}\mathbf{y}
\\
\mathbf{e}^{\top}\mathbf{e} &> \mathbf{y}^{\top}\mathbf{y}
\end{aligned}
$$
So why can't $R_{uc}^2$ be negative?
Answer: Vector (and scalar) inequalities do not work like that. Just a simple counterexample:
Take $\hat{\mathbf{y}} = (-2\, -2)^\top$ and ${\mathbf{y}} = (-2\,-2)^\top$. Then elementwise you can write that ${\mathbf{y}} = (-2\, -2)^\top > 2 {\mathbf{y}} = (-4 \, -4)^\top$, but $\hat{\mathbf{y}}^\top \hat{\mathbf{y}} = 8 < 2 {\mathbf{y}}^\top \hat{\mathbf{y}} = 16$.
The reason why the uncentered $R^2$ can not be negative is written just before this equation in the Hayashi book: ${\mathbf{y}}^\top {\mathbf{y}} = \hat{\mathbf{y}}^\top \hat{\mathbf{y}} + {\mathbf{e}}^\top {\mathbf{e}}$, hence, $$R^2_{uc} =\frac{\mathbf{y}^\top \mathbf{y}- {\mathbf{e}}^\top {\mathbf{e}}}{{\mathbf{y}}^\top{\mathbf{y}}}= \frac{\hat{\mathbf{y}}^\top \hat{\mathbf{y}}}{{\mathbf{y}}^\top{\mathbf{y}}},$$
where both the numerator and the denominator are non-negative.
Comment: Note that the inequalities don't work even if the response is scalar. Inequalities are tricky when accounting for negative numbers, vector or not.
Comment: @AccidentalStatistician You are correct.
Comment: For others, note that $\frac{\hat{\mathbf{y}}^{\top} \hat{\mathbf{y}}}{\mathbf{y}^{\top} \mathbf{y}} = \frac{\hat{\mathbf{y}}^{\top} \hat{\mathbf{y}}}{\hat{\mathbf{y}}^{\top} \hat{\mathbf{y}} + \mathbf{e}^{\top} \mathbf{e}}$ since $2 \hat{\mathbf{y}}^{\top} \mathbf{e} = 0$ by the normal equation. This is why Hayashi mentions that $\hat{\mathbf{y}}^{\top} \hat{\mathbf{y}}$ and $\mathbf{e}^{\top} \mathbf{e}$ being nonnegative implies that $0 \leq R^2_{uc} \leq 1$.


Token Value to insert URL of page into field

Question: I am trying to create a webform to appear at the end of all my site pages that asks if there is anything about the page that should be improved.  This is dumped straight into the page.  In order for this to make sense I need to be able to record the url the form was shown on.
I tried to dump these tokens into the default value for a field
%nid
%title
but they output the nid of the webform not the page it is dispayed as a block on.
If the user is logged in I can use
%server[SCRIPTNAME]
which works but almost all my users won't be logged in.
Is there a way I can get this information into a field on my form?   Otherwise my feedback for is useless.
Answer: you can use form alter .get the values from url put the values using form alter to default fields .
Comment: Could you explain *how* he could do this?
Comment: he just need to add another textfield or an integer field say node id in hidden format or so then alter the form get the node values from the url(i.e node id) . prefilled that field node id by the the value from url.