Can I configure LLBLGen to include generated SQL in exceptions?

Question: I'm using LLBLGen and I have some code like so:
<code>    if (onlyRecentMessages)
    {
        messageBucket.PredicateExpression.Add(MessageFields.DateEffective >= DateTime.Today.AddDays(-30));
    }

    var messageEntities = new EntityCollection<MessageEntity>();
    using (var myAdapter = PersistenceLayer.GetDataAccessAdapter())
    {
        myAdapter.FetchEntityCollection(messageEntities, messageBucket);
    }
</code>
I'm currently getting a SqlException on the FetchEntityCollection line.  The error is:
System.Data.SqlClient.SqlException: The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect. Too many parameters were provided in this RPC request. The maximum is 2100.
but that's a side note.  What I actually want to be able to do is include the generated SQL in a custom exception in my code.  So for instance something like this:
<code> using (var myAdapter = PersistenceLayer.GetDataAccessAdapter())
        {
            try
            {
               myAdapter.FetchEntityCollection(messageEntities, messageBucket);
            }
            catch (SqlException ex)
            {
               throw new CustomSqlException(ex, myAdapter.GeneratedSqlFromLastOperation);
            }
        }
</code>
Of course, there is no such property as GeneratedSqlFromLastOperation.  I'm aware that I can configure logging, but I would prefer to have the information directly in my stack track / exception so that my existing exception logging infrastructure can provide me with more information when these kinds of errors occur.
Thanks!
Steve
Answer: You should get an ORMQueryExecutionException, which contains the full query in the description. The query's execute method wraps all exceptions in an ORMQueryExecutionException and stores the query in the description.
ps: please, if possible ask llblgen pro related questions on our forums, as we don't monitor stackoverflow frequently. Thanks. :)
Comment: Thanks, I guess now my task is to try and get ELMAH to do something with that description, or else to do some custom exception handling that refers to it.
Comment: Oh, and I do end up searching llblgen.com/tinyforum but honestly to ask questions I find SO to be a nicer interface and I don't have to remember one more login.


Ao usar jQuery append exibe o texto [object Object] e não insere a elemento

Question: Criei uma div.box no html e nela quero inserir uma outra div que crio na execução do código, segue o avaixo:
HTML:

JS:
var item = $('
', {class: 'item'})
var box = $('.box')

box.on('click', function (e) {
  this.append(item)
})

Porém ao inves de aparecer a div.item dentro de div.box aparece o texto [object Object]. Percebi que isso só acontece quando executado no evento de click, fazendo da forma abaixo funciona:
var item = $('
', {class: 'item'})
var box = $('.box')
box.append(item)

Alguém tem uma explicação para isso?
Comment: Isso não responde a pergunta, mas uma outra coisa que se pode fazer no lugar de usar append é concatenar os innerHTML dos elementos com o que estava antes + o conteúdo novo - Este não é o modo mais eficiente, mas algumas vezes é o mais simples.
Comment: Quando tu usa o `this` dentro do `.on()` ocorre o erro, mas e se tu mudar para `box.apend(item);` dentro do `.on()` o erro persiste?
Answer: Ao usar o this você está usando um objeto do JavaScript Puro que não têm as implementações do JQuery, para corrigir basta dar 1 cast no this
box.on('click', function (e) {
  $(this).append(item)
})

Se você der um console.log no this e no $(this) verá que o $(this) tem várias propriedades a mais que o this nativo.
Comment: Valeu cara, era isso mesmo. Bobeada minha. Sua resposta foi escolhida pois teve a explicação do cast.
Answer: Faltou colocar o this "dentro" do jquery $(this), la no seu click.
So dei uma modificada pra voce ver funcionando.

$('document').ready(function(){
  var item = $('
NOVO TEXTO
');
  var box = $('.box');

  box.on('click', function (e) {
    $(this).append(item)
  });
});

TEXTO

Comment: Te falo q verdade que nao sei o motivo exato, mas se colocar a variavel item `var item = $('NOVO TEXTO');` dentro do click, antes do `append` funciona com certeza. La vai chute mas pode ser pra nao colocar objeto repetido, quando usa o `$('...')` acredito que o jquery cria uma nova "instancia" para esse elemento, e talvez ele saiba que ja deu append com aquela instancia. Quando esta dentro do click é sempre uma nova instancia, ou talvez não tenha absolutamente nada a ver com isso que falei.
Comment: @AntonioAlexandre Só vai uma vez pq o "novo texto" esta numa váriavel e toda vez que você clica ele pega a mesma div com o "novo texto" e coloca no mesmo lugar se mudar o código para _$(this).append(item.clone())_ ele insere várias vezes...
Comment: Neuber, gostei da sua resposta(+1). Só uma pergunta: Porque se eu clicar de novo não adiciona NOVO TEXTO mais uma vez em baixo?
Comment: Tbém percebi isso, só adiciona uma vez.
Comment: @NeuberOliveira o que vc escreveu faz sentido. Deve ser por isso mesmo. De qualquer forma se colocando dentro do bloco do onclick tb resolve, no dia que for necessário fica tranquilo tb. Ex: se fosse o caso de existir necessidade que o conteúdo seja passado fora desse bloco poderia ser até  var itemcontent = 'NOVO TEXTO'; fora do bloco do onclick e $(this).append($(itemcontent)) dentro do bloco do onclick.


Create a Graph of words who differ by 1 char

Question: I have a Map which contains a

key = length of words
value = arraylist with words of that length

an example of the map:

[1] = a, [2] = at, in, it, an, ...

1.User will input wordA
2.User will input wordB
3.Will check if both the same length
4.If yes, a graph will be made with all the words that differ from wordA by 1 letter being adjacent.
5.Then those words that differ from wordA by one letter will be adjacent to words that differ from them by 1 letter. This is done until wordB is reached.
How can I make the graph and adjacency list?
What can I use to find the path from word1 to word2.
Thank you,
Fernando Diaz
Comment: if this is homework tag it as such
Comment: This is identical, aside from the language, to the first problem from the second assignment Stanford's intro C++ course: http://www.stanford.edu/class/cs106b/handouts/13-Assignment-2-ADTs.pdf.  That should help you to break any algorithm block.
Answer: In terms of building the path from word1 to word2, this should give you something to start with:
    public static List<String> findLadder(String word1, String word2) {
        //invalid request
        if (word1 == null || word2 == null || word1.length() != word2.length()) {
            return Collections.emptyList();
        }

        List<String> result = new ArrayList<String>();
        List<String> words = dictionary.get(word1.length());
        result.add(word1);

        while (! word1.equals(word2)) {
            String nextWord = null;
            for (int index = 0; index < word1.length(); index++) {
                if (word1.charAt(index) != word2.charAt(index)) {
                    String testWord = word1.substring(0, index) + word2.charAt(index) + word1.substring(index + 1);
                    if (words.contains(testWord)) {
                        nextWord = testWord;
                        word1 = nextWord;
                        result.add(word1);
                        break;
                    }
                }
            }
            if (nextWord == null) {
                //no mapping exists
                return Collections.emptyList();
            }
        }

        return result;
    }

Note that this code will not evaluate any moves that don't move incrementally closer to the desired output, such as code -> core when mapping from "code" to "data".  Evaluation of such moves is for you to figure out.
Example here:  http://ideone.com/9JnNH


Find set of polynoms

Question: How can I find all polynoms $P$ with degree $ \ge  3$ where

$P(2) = 1$
$P'(2) = 3$
$P''(2) = 4$
$P^{(n)}(2) = 0 \quad \forall  n\geq 3$
Comment: Taylor formula ?
Comment: Hint: guess the degree first.
Comment: You understand that your condition 4 eliminates all polynomials with degree $\geq 3$?
Answer: Using the Taylor formula at $x=2$ we have that such a polynomial must be
\begin{align}P(x)&\\=&P(2)+P'(2)(x-2)+\dfrac{P''(2)}{2!}(x-2)^2+\dfrac{P'''(2)}{3!}(x-2)^3+\cdots+\dfrac{P^{(n)}(2)}{n!}(x-2)^{n}\\\underbrace{=}_{P^{(n)}(2)=0,n\ge 3}&P(2)+P'(2)(x-2)+\dfrac{P''(2)}{2!}(x-2)^2\\=&1+3(x-2)+2(x-2)^2.\end{align}
Answer: Hint: The derivative of $f(x)=c$ and $f(x)=0$ is zero, which means that the second derivative of your function is a constant function.

Find set of polynoms


Does WebDAV even work on IIS 7? I say nay

Question: AKA "When developers have to be their own sysadmins"
I've tried every configuration from the top 10 stack overflow and server fault results for WebDAV 405 on IIS (for verb PROPFIND and PUT). I'm running server 2008 SP2. Followed all the instructions here. I'm no stranger to configuring servers. This has gotten nowhere after 8 hours.
Confirmed system.webserver in applicationhost.config:
<add name="WebDAV" path="*" verb="PROPFIND,PROPPATCH,MKCOL,PUT,COPY,DELETE,MOVE,LOCK,UNLOCK" modules="WebDAVModule" resourceType="Unspecified" requireAccess="None" />

Port 443 with basic auth, same issue.
Tried port 80 with windows auth. Broken. (405)
Windows authentication. Check.
Added authoring rules for default site and application. Check.
Not the firewall. Check.
added "Desktop Experience" role feature
Tried HTTPS with Basic Authentication on port 443. Does not work.
No other services are running like Sharepoint. Check.
confirmed user has read/write NT level permissions for the folder/virtual dir
tried net use * http://localhost /user:MYDOMAIN\me myPass get error 1920, if I don't authenticate I get error 67
confirmed I'm not applying filtering to WebDAV:
  <requestFiltering>
    <fileExtensions applyToWebDAV="false" />
    <verbs applyToWebDAV="false" />
    <hiddenSegments applyToWebDAV="false" />

405 - HTTP verb used to access this page is not allowed.
The page you are looking for cannot be displayed because an invalid method (HTTP verb) was used to attempt access.

SHOULD I JUST GIVE UP?

Other questions that helped none:
405 - 'Method not Allowed' adding service hosted in IIS7
webdav on iis7.5 - simply cannot make it work
http://studentguru.gr/b/kingherc/archive/2009/11/21/webdav-for-iis-7-on-windows-server-2008-r2.aspx
Comment: +1 We're evaluating non-Windows solutions for WebDav. Our 2003R2 setup works flawless, 2008R2 not so much.
Comment: Get Head Options Trace are the default set of verbs for a non-DAV site. Sure the host header is lining up OK? (also: nice of you to blank out the URL target (aside: is a double-trailing-slash normal?) but you haven't blanked out the Host header. Which has the same information.)
Comment: @jscott yeah, it seems that MS might have gotten overzealous in trying to lock down server security.
Comment: @TristanK I think that is just how the client (cyberduck) is rendering the error information. Should I be connecting to the default site host or the application directly? I've been connecting to the application (but I think I tried the default site at some point).
Answer: I just tried using very basic settings:

Installed IIS Role with WebDAV Authoring & Windows Authentication selected (+ defaults)
Enabled Windows Authentication on the default Website
Disabled Anonymous authentication on the default website
On the default website, in "webDAV authoring rules", i put:

All Content / All users / Read/Source/Write
And I enabled WebDAV on the default website

I disabled the Firewall
then, from another machine:

net use * http://app2008r2-01.lab.domain.com /user:LAB\Administrator
The command completed successfully

Maybe that helps getting you started...
Comment: Thanks. I will try exactly as you did. Are you running IIS 7.5 or 7.0? I've heard server 2008 R2 might work better than 7.
Comment: Windows 2008 R2 comes with IIS 7.5
Comment: Yeah, i'm running SP2, not R2, so I'm on IIS 7
Comment: Cool. I think the one thing I missed was disabling anonymous auth-- not many of the installation guides mentioned this. I am now able to map the drive. I was hoping to use it with webdav API commands, but none of the clients I use can provide the correct 401 challenge authentication.
Answer: I've struggled and struggled with this. I have stopped my website running on port 80 and WebDav works fine. As long as I create a seperate site for WebDav and have it running on a different port then both my website AND WebDav work! Yay, I'm golden. I hope this helps someone else.


Question about Subrings and integraly closed

Question: The following is a proposition from abstract algebra. The book gives this as a proposition and asks the reader to do it as an exercise. It seems it should be easy. (Assuming every ring has a $1$.)

Let $R$ be a subring of $S$. If $S \setminus R$ is closed under multiplication, then $R$ is integrally closed in $S$.

I went by contradiction. Let $s$ be in $R \setminus S$. Then, we get that
$$
s^n+a_1s^{n-1} + \cdots + sa_{n-1}+a_{n}=0
$$
for some $n$ and the $a$'s are in $R$. Now I am thinking this
$$
s^n=(-1)(a_1s^{n-1} + \cdots + sa_{n-1}+a_{n})
$$
Now multiply both sides by $s$ again to get
$$
ss^n=(-s)(a_1s^{n-1} + \cdots + sa_{n-1}+a_{n})
$$
Now by closure, $ss^n$ is in $S \setminus R$ which means the rest $a_1s^{n-1} + \cdots + sa_{n-1}+a_{n}$ is in $S \setminus R$ which means the $a_i$'s are in it, which is a contradiction.
Does this look correct?

Edit (not by OP): The above is also Exercise 7 from Chapter 5 of Atiyah and Macdonald's Introduction to Commutative Algebra.
Comment: Welcome to [math.se]. Please don't edit out your question after you have received an answer/a hint, the purpose of the site is to have the questions and answers as resources for others having the same or a sufficiently similar problem in the future. Editing the question out to say thanks defeats that purpose.
Comment: Why to denote by $\;s\;$ an element in $\;R\setminus S\;$ ? To confuse? Anyway, if $\;R\subset S\;$ , then it **must** be $\;s\in S\setminus R\;$ . Finally, at the end you say "...which is a contradiction"? To **what** ? Where did you clearly state what is the assumption you make? I think I know what you meant, yet you must explicitly state this.
Answer: Hint $\ $ Choose $\,n\,$ minimal. Then $\ s f(s) = s (s^{n-1}+ r_{n-1} s^{n-2} + \cdots + r_1)\, =\, -r_0.\,$ But $\,f(s)\not\in R\,$ by minimality of $\,n\,$ so $\,s,f(s)\in S\backslash R \,\Rightarrow\, sf(s) = -r_0\in S\backslash R ,\,$ contradiction.
Comment: The base case $\,n = 1\,$ is trivial: $\ s+r_0 = 0\,\Rightarrow\, s = -r_0\in R.\,$
Comment: See also [here](https://math.stackexchange.com/a/100201/242).


Android: calculating time away from app

Question: In my app, I'd like to keep track of time away from the app, so that if the user is away for say, 2 hours, and come back, they receive 1 in game currency.
In practice I could easily do this by using a date object to get the current time in onStop, saving that date object, and comparing it to a new date object when they return.
However, I have a feeling this can easily be spoofed by change the internal date settings.
Is there a more secure way? Should I just put a cap on how many hours away you can bank up? I'd love some insight. Thanks as always.
Comment: This question is more about server vs client trustworthiness. Basically don't trust the client. Send a package to the server that the client is gone and send another one when he's back. Calculate the difference on the server and pass it back to the client.
Comment: Is it an all local application? If you have a db, you could add a timestamp to the db and compare it on every login.
Answer: you can try to make more secure code in the app, but the safest way is to request something from a server
if you are app is already using internet permissions consider making an HTTP request to get time.
look at this site for example
http://www.timeapi.org/
if you have backend to support your app that would be extra better
if you are not using internet permissions it might not be worth it to add it just for this, you might consider a different "offline" solution
Comment: This is awesome! I didn't even consider doing this. Thank you for the link above as well.

Android: calculating time away from app


Prove the equation using a combinatorial argument

Question: Prove using a combinatorial argument that both sides count the same thing:
$${{n \choose 2} + 1 \choose 2} = {n \choose 2} + 3{n \choose 4} + 3{n \choose 3}$$
Answer: Claim. Both sides represent the number of ways to choose one or two edges from a complete graph on n vertices.
Proof. The left hand side is obvious, while the three summands on the right hand side are respectively equal to the number of ways in which the chosen edges are incident to precisely 2,4,3 vertices.


Como colocar quebra de linha em um textarea?

Question: Quando eu for alterar ou incluir algum dado de uma textearea eu queria que salvasse as quebras de linhas. E também, quando for mostrar numa textarea antes os dados que já existem eu queria que mostrasse com as quebras de linhas.
Depois eu junto os dois textarea e salvo no banco. Já olhei os códigos de quebrar linha e tentei aqui e não deu certo, alguém pode me ajudar?
Observações:

    <textarea name="obs" cols="150" rows="10" style="resize:none" readonly ><?php echo $obs; ?></textarea>

Para adicionar dados usar o campo abaixo.
<textarea name="obs1" rows="10" cols="150" style="resize:none" ></textarea>

Comment: Tentou usar o `nl2br($obs)` ?
Comment: mexi aki e consegui resolver valeu!!
Comment: eu coloquei no primeiro textearea  e nao ta quebrando as linhas. no primeiro tem que mostrar as linhas em cada linha separado e no segundo eu digito o texto e se eu der enter quero que salve com as quebras. porem como eu to junto os dois text area tem que ter uma quebra de linha entre eles
Comment: Mas você está salvando o texto no banco usando o `nl2br` ?
Comment: nao pq ja tentei por e nao aceita da erro.
Comment: Dá erro ? Mas não deveria... assim, tem que salvar com `nl2br` e puxar com `nl2br`.
Comment: fiz aki e ate deu. porem ele fica mostrando o  dentro do text area é assim mesmo? texte5
texte6texte7, o texte 6 e 7 ta grudado pq no seguno texte area eu junto com o primeiro e eu queria q a linha ficasse quebrada nisso tbm.
Comment: Não, não é assim. Faz assim: `$quebras = array("","","");
    $text = str_ireplace($quebras, "\r\n", $obs);`. Depois tira o `nl2br` e faz `echo $obs` no **textarea** pra ver.
Comment: o  continua aparecendo dentro do text area
Comment: Como você fez ? Eu errei no final. É `echo $text`.
Comment: eu tinha colocado do jeito q vc falo ai mudei pro $text e deu certo. so a junção do textarea1 e do 2 que ta grudado. tipo eu junto o $obs com $obs1 e regravo no banco pq eu eu quero adicionar informação eu mostro o q ja tem e no campo de baixo escreve o que precisa adicionar e dai junto os dois no final... eu tava fazendo de outro jeito mas como eu sei que vao fazer errado to desmembrando.
Comment: estou fazendo teste aki e conforme eu vou editando as informações ele ta pondo quebra de linha a mais do que deveria. tipo em vez de pular uma conforme eu vou adicionando informação ele ta pondo mais de uma quebra de linha nos dados anrteriores
Comment: Edita sua pergunta e coloca seu código atual.
Comment: tem como me dar mais uma ajuda? preciso mostrar esse campo de $obs q eu peguei na textarea mas sem ser dentro dela e com as quebras de linhas
Comment: É só tirar o `textarea` não e usar a variável do mesmo jeito.
Comment: eu tirei o textarea e ta mostrando tudo em uma linha e nao ta quebrando.
Comment: consegui coloquei o  e foi, hj ta dificio de pensar....
Answer: você pode concatenar a sua string com

<textarea cols='60' rows='8'>Primeira Linha.
Segunda Linha</textarea>

Answer: Salve no banco de dados com as quebras de linhas do <textarea>:
str_replace("\n",'
', addslashes(htmlspecialchars($_POST['valor']
// OPCIONAL: addslashes é para conversão do caracter ' e não dá conlflito no BD
// OPCIONAL: htmlspecialchars é para não permitir caracteres especiais

Para pegar o valor do <textarea> no banco de dados faça assim:
str_replace('
', "\n", $valor);

Answer: Você pode colocar usando:
Echo nl2br($row['campo']);

Comment: com row nao funciona nao aceita


Getting negative variance

Question: I'm having a problem when calculating the variance of the following estimator:
$\hat\theta=\frac{1}{N}\sum_{n=1}^{N}D_n$ with $D_1....D_N$ independent random variables.
In order to calculate the variance of this estimator, I follow the following procedure:
$\sigma_{\hat\theta}^{2}=E[(\hat\theta - E[\hat\theta])^2]=E[\hat\theta^2]+E[E[\hat\theta]^2]-2E[\hat\theta]E[E[\hat\theta]]$
Knowing that $f(D)=\frac{1}{\theta}e^{-\frac{1}{\theta}D}$ and therefore, $E[D]= E[\hat\theta]=\theta$.
From this point, I get that $\sigma_{\hat\theta}^{2} = E[\hat\theta^2] +\theta^2-2\theta^2$
So, in order to obtain $E[\hat\theta^2] = \frac{1}{N^2}\sum_{n=1}^{N}\sum_{m=1}^{N}E[D_nD_m]$ that will be $E[D^2]$ for $n=m$ and $E[D_n]E[D_m]=\theta^2$ for $n \neq m$. At this point, when calculating  $E[D^2]$ from its pdf I get that it is equal to 0, so I would obtain:
$E[\hat\theta^2] = \frac{1}{N^2}(N^2-N)\theta^2$ taking into account that there are $(N^2-N)$ values that satisfy the condition $n \neq m$  and therefore,
$\sigma_{\hat\theta}^{2} = \frac{1}{N^2}(N^2-N)\theta^2 +\theta^2-2\theta^2=-\frac{\theta^2}{N}$, which I know it is not ok since it is negative. Why could this be happening?
Any help is appreciated!
Comment: SOLVED. The problem came from $E[D^2]$ which from my initial calculations obtained that it was 0, but it was not, being $E[D^2]=2\theta^2$. After this correction, the obtained variance is the one Deep North provided.
Comment: Warning bells should go off in your head that something is awry as soon as you calculate the expectation of $D^2$, _a nonnegative random variable_, as being $0$. -1 for wasting everybody's time.
Comment: The point is, you are asking for help in the wrong way by not even _thinking_ that your calculation of $E[D^2]$ might be incorrect and asking where you went wrong. Instead, you have a huge rigmarole about estimators etc and waste everyone's time by asking why the variance of your estimator is negative, Sheeesh! finding the variance of an exponential variance might even be an exercise in your textbook, and if not, your book probably has a table of commonly occurring with their means, variances, pdf formulas, etc neatly tabulated where you could have looked up the result.
Answer: Your $D$ just has an exponenital distribution $f(d)=\frac{1}{\theta}e^{-\frac{1}{\theta}d}$ wtih $E(D)=\theta$ and  $Var(D)=\theta^2$.
Now your $\hat{\theta}$ is just the mean, by i.i.d
$Var(\hat\theta)=Var(\frac{1}{N}\sum_{n=1}^{N}D_n)=(\frac{1}{N})^2\theta^2+(\frac{1}{N})^2\theta^2+...+(\frac{1}{N})^2\theta^2$, totally there are $N$ such terms.
Therefore,the variance is $
\frac{1}{N}\theta^2$
Comment: You can, but your equaiton $E[\hat\theta^2] = \frac{1}{N^2}\sum_{n=1}^{N}\sum_{m=1}^{N}E[D_nD_m]$ is not correct I think. You should do this way $E[\hat\theta^2]=E[(\frac{1}{N}\sum_{n=1}^{N}D_n)^2] =\frac{1}{N^2}E[(D_1+D_2+...+D_n)^2]=\frac{1}{N^2}E(D_1^2+D_2^2+...+D_n^2+2D_1D_2+...+2D_1D_n+2D_2D_3+...+D_2D_n+...+D_{n-1}D_n]$. It is a quite complicated way.
Comment: But the variance of an estimator is defined as the expected value of the squared sampling deviations, so shouldn't I have to follow the formula $ E[(\hat\theta - E[\hat\theta])^2]$ to calculate it? @deep-north
Comment: You can, but your equaiton $E[\hat\theta^2] = \frac{1}{N^2}\sum_{n=1}^{N}\sum_{m=1}^{N}E[D_nD_m]$ is not correct I think
Comment: You are totally right. I had a mistake when calculating $E[D^2]$, which I already solved, and obtained the variance you mentioned with my method, so I guess now both are correct. Thanks a lot! @deep-north

Getting negative variance


How to search fields with '-' characters in elastic search

Question: I am new to elastic search. I have got following document where one of the field "eventId" has "-" in value.
When i try to search with complete value of eventId, i don't get any results.
<code>Sample Document app/event
 {
     "tags": {}
         "eventId": "cc98d57b-c6bc-424c-b54c-df1e3df0d942",
 }
</code>
I haven't created any explicit settings for my index.
Thanks.
Comment: Which query are you using?
Answer: you should check if the tokenizer splits your value into multiple fields. Maybe your value is stored as 5 fields: "cc98d57b", "c6bc", "424c", "b54c" and "df1e3df0d942"
You can analyze that with the 'Kopf' Plugin (https://github.com/lmenezes/elasticsearch-kopf).
If that is your problem you should change your field mapping, so that the value is not analyzed ("index" : "not_analyzed").
For an example how to set that mapping see here: Elasticsearch mapping settings 'not_analyzed' and grouping by field in Java
After that, you should be able to search for your specific value.


Does counting sort range always need to be in [0,k]?

Question: Can I do a counting sort on a small range of numbers say A=[7,9,12,15] from a huge pool of numbers, which I know will consist of only the numbers in the small array? Or does the small range always have to be [0..k].
I can do counting sort on the array A by saying [0..15] but it does not make sense.
And what if A=[100,750,452]
So I guess it is feasible.
I would like some inputs please.
Answer: Your question isn't very clear, but here it goes. From your example A=[7,9,12,15] the range be [0..15] and would require addition space of size k=15 (and another result array of A[length]. Since n (A[length]) is 4, the overall runtime would be theta(k + n). Counting sort is a "space-time tradeoff" algo, but if used in your case it wouldn't make any sense. Since, there isn't any tradeoff. Counting sort should be use when you have k=Big-O(n), which means the maximum value in your A[] is less than the size of A[]. btw, I believe the algorithm would still sort your example correctly.


Do time signatures make sense?

Question: Most people have probably thought at one time or another, why isn't 4/4 time the same as say 8/8 time or 2/2 time? (Anyone who knows about reducing fractions can attest to that).
I think time signatures really are anachronistic. Really you just want to know is there 3 beats, 4 beats or even 5 beats in a bar.
Mostly the only ones used are 3/4, 4/4 and very rarely 5/4.
So is it just convention to use this method. Or is there some hidden meaning.
I mean a semibreve is always 4 crotchets no matter what the time signature is.
So is this just an anachronism we have to put up with or does anyone find this weird way of expressing the beats in a bar useful?
Comment: For the record, 2/2, 4/4, and 8/8 are very different in terms of beats and accentuated beats! Just the top number matters in this case: 2/2 means two beats, first accentuated, 4/4 means 4 beats, etc. Accent always on the first beat. The question should rather be: why 4/2 vs. 4/4 vs. 4/8, for example (with appropriate tempos, they are all equivalent).
Comment: Compare six eighth's notes in 3/4 time ( ONE and, two and, three and, …) with 6/8 time (ONE two three, Four five six).  They sound completely different.
Comment: A time signature isn't a fraction. For instance, the 3 over 4 time signature is not the same as 6 over 8
Answer: If you think the denominators are arbitrary, try notating a stately sarabande in 3/8 time - you'll drown in beams and flags. Next, try notating a lively tarantella in 3/1 time - you'll be overwhelmed by ties and similar-looking note heads and be unable to read anything.
The point of having different-length notes available rather than just clarifying everything with tempo indications is that the choice of base beat is a rough tempo indication. It's easier to assimilate this information by consuming the familiar shape of quavers, crotchets etc. than to keep remembering "oh yeah, this is supposed to be really fast, like, 192 BPM". Gestalt recognition is a thing, and it's a good idea to take advantage of it.
The standard musical notation system is actually pretty well adjusted to the quirks of human perception. It has a couple of longstanding bugs in it (for instance, the inability to distinguish half-tone and whole-tone intervals at a glance), but time signatures aren't one of them.
Comment: @Dekkadeci - Not sure if it's what you're referring to, but over the years there's been a sort of 'note inflation': the length of time represented by a given note has steadily increased.  (In some of the earliest notation, the two main note values were a 'lunga' (long) and a 'breve' (brief; ½ or ⅓ of a lunga).  The lunga hasn't really survived, but you might still see a breve occasionally: in US terminology it's two whole notes, or 2 bars of 4/4.)  It probably results from centuries of composers wanting their music to go faster than performers can manage :-)
Comment: @gidds the longa (note spelling) is still seen in some modern editions of Renaissance music.  That the breve is twice as long as a whole note explains why whole notes are known in some parts of the world as *semibreves.*
Comment: I've read that, back in Baroque times, slow music was actually associated with shorter note values and fast music with longer note values. According to that source, Telemann's Gulliver Suite was pushing that to extremes with its Lilliputian Chaconne (in 3/32 time) and Brobdingnagian Gigue (in 24/1 time), but it wasn't as extreme as you might think.
Comment: @Dekkadeci - yes, part of the thinking is that: shorter note values for slow music will take up less paper, so you can fit more on a page. Fast music uses larger values which are easier to read and will better convey the urgency required.
Comment: My point wasn't that denominators are arbitray but that in most cases you can just use 4 as int 3/4 4/4 5/4. My point was as fractions 2/4=3/6=4/8 etc.
Comment: @gidds: It's important to keep in mind that long *notes* didn't always represent long *syllables*.  Many settings of psalms and other such religious works would use four notes per line--lunga, breve, lunga breve.  E.g. from Psalm 23: lunga: " Yea, though I walk through the valley of the shadow of death, I will fear no"; breve: "evil"; lunga: "for thou art with me; thy rod and thy staff they"; breve: "comfort me".  Most syllables within breves will be longer than those within the lungas, but the total lengths of the lungas will be longer because they have more syllables.
Answer: In some pieces the beat is divided into 2, and the half-beats might in turn be halves. In that case, you might well choose to notate it with the crotchet/quarter-note as the beat, thus 2/4, 3/4 or 4/4, say.
But in other pieces, the beat is divided into 3. In these pieces it might be better, for the sake of those notes of one-third of a beat, to notate it with the dotted crotchet/quarter-note as the beat, thus 6/8, 9/8 or 12/8, say.
Answer: If you play alone you might ignore 2/2 and 4/4 - as the accents will be similar, but if you play with others in an ensemble or orchestra this differentiation will be more important: mind that in 2/2 you count to 2 while in 4/4 you count to 4, and if you have even a conductor he will conduct only 1-2 in a 2/2 time. So it's important for orientation, telling where we are, from where we start, even if the rhythm feeling might not differ so much as we think.
Yes, they make sense! Also consider the examples of the other answers.
Comment: I can see why that might be important when you have a conductor and he is marking out the beats. But, when playing alone it does seem kind of pointless. Then again when you have a conductor, he or she can communicate to the orchestra how they are marking the beats so it leaves the time signature irrelevent.
Answer: In time signatures, the top number refers to the number of beats per bar, while the bottom number refers to the note value of the beat. Unlike fractions, 3/8, 3/4 and 3/2 all have the same number of beats per bar. The values are different so as to be convenient to read or write in different tempos. All time signatures have specific meanings and uses. 6/8, for instance, is also often used and only has 2 beats per bar, divided into three quavers each.
Comment: @zooby no they're not.  Or rather, it's not just about the beats but about accent, stress, and grouping.  Consider setting the following seven-syllable phrases as a measure of six eighth notes followed by a dotted half note: "would you like to hear me sing?" is 3/4, while "wouldn't you rather go home?" is in 6/8.
Comment: @zooby but it isn't: a six-beat time signature is invariably used to specify two beats subdivided in three, while a three-beat time signature is used to specify three beats subdivided in two.
Comment: @zooby a good violinist, or actually any violinist who is at least passably mediocre, will play those two phreases differently, even if they both comprise the same notes (for example C-D-E-F-E-D-C).
Comment: My point is 3 beats in a bar is the same as 6 beats in a bar payed twice the speed.
Comment: Well the beats are all in your head anyway. Unless there is a conductor or a metronome.
Comment: In an orchestra, the accents can be marked by percussion like drums. But I guess this is a good reason if say the violins are marking the beats by stressing them. When I used to play in an orchestra I never thought to stress any notes that weren't marked in the notation. Well nobody told me to anyway.
Answer: I feel the difference is most pronounced with  6/8 vs 3/4.
Consider a measure with six 8th-notes. In 6/8 time the emphasis will be on the first and fourth note, but in 3/4 time it will be on the first, third and fifth note.
I've come up with a small example. You can listen to it here: https://musescore.com/user/16549076/scores/5852825
The original melody is in 6/8 or even 12/8 (I can't remember), and it sounds completely different with the 3/4 emphasis. Note that Musescore automatically grouped the notes just right to help the player get the emphasis right.
Which measures have which notes emphasized is a matter of tradition. Using the measure that fits what you want makes it easy for experienced musicians to play the piece the way the composer intended.
Comment: My favourite illustration of this (although not worth a separate answer) is 'America' from West Side Story. The bars of the main theme alternate 6/8 and 3/4 with very clear distinction between two beats and three beats. I believe the original score was notated as 6/8+3/4 at the start. https://youtu.be/_e2igZexpMs?t=59
Answer: Some of it is historical convention.
Before the metronome longer note values in the lower number of the time signature implied slow tempos.
While 3/4 and 3/2 as fractions kind of reduce mathematically to the same thing, it isn't important musically. 3/2 in the past meant play at a slow tempo.
Another important thing to be aware of is simple meter versus compound meter like 3/4 versus 6/8. As fractions they reduce to the same thing, but musically the metrical pulse is different. As you pointed out knowing if the rhythm is grouped by 2 or 3 (duple or triple) is essential. 3/4 is triple with three strong pulses, but 6/8 is compound and has two strong pulses. Reducing 6/8 to 3/4 is a mistaken reading of time signatures and looses the important information about where the metrical pulse is.

...Anyone who knows about reducing fractions

Time signatures are not fractions, they are time signatures.

Do time signatures make sense?


AbstractController::ActionNotFound para a destroy action

Question: Olá,
Tenho duas aplicações rodando no Heroku com o mesmo código, só que estou tendo um probleminha na versão de produção.
Ao tentar fazer uma requisição, tenho o seguinte log:
AbstractController::ActionNotFound (The action 'destroy' could not be found for Managers::RecruitmentsController)

O problema é que ele está tentando buscar no controller Managers::RecruitmentsController, mas o correto seria em Managers::ApplicantsController, como já acontece na versão dev:
Started DELETE "/managers/recruitments/1/applicants/7" for 22.214.171.124 at
Processing by Managers::ApplicantsController#destroy as HTML

Bem, essta solicitação vem do link_to abaixo:
 <%= link_to "Outra chance?", "javascript:;", id: "newChance", method: 'delete', btn: true, style: :link, 'data-toggle' => 'modal', 'data-target' => '#modalNewChance', 'data-applicant-id' => applicant.id %>

Javascript:

Meu controller:
class Managers::ApplicantsController < Managers::BaseController
...
def destroy
  @applicant = Applicant.find(params[:id])

  CandidatesMailer.new_chance(@applicant).deliver
  CompanyMailer.new_chance_company(@applicant).deliver

  @applicant.destroy

  flash[:success] = "Aplicação resetada com sucesso. Candidato tem nova chance."
  redirect_to managers_recruitment_path(params[:recruitment_id])
end

Minhas rotas:
namespace :managers do
 get "guide/index"
 resource :dashboard, only: :show
 resource :profile,   only: [:show, :edit, :update]
 resource :company,   only: [:edit, :update, :destroy] do
   resource :payment, only: [:edit, :update]
 end
 resources :plans,    only: [:new, :create], path_names: { new: 'choose' }
 resources :recruitments do
  member do
    patch 'close'
  end
  resources :applicants do
    member do
      put 'comment'
      patch 'comment'
    end
  end
 end
end

Aqui estão as Rotas relacionadas aos controllers citados.
Comment: o que aparece quando você roda uma rake routes?
Comment: @ThiagoDiniz,aparece todas as rotas, mas quanto ao controller em questão vou editar em minha resposta.
Comment: Você verificou se a rota está certa no html?
Comment: Poxa @ThiagoDiniz...Não pensei nisso! Eu refatorei o código, transferindo o `link_to` para uma view respondesse ao mesmo controller que no caso era o Applicants. Tipo, a view que eu estava fazendo a requisição era relacionada ao controller Recruitments, então eu transferir o código para a view que responde ao controller Applicants, sem perder valor para o negócio. Não sei se esse era o problema mas acabou funcionando. PS.: Sou iniciante no mundo Rails!
Answer: o end-point que é chamado no trecho de código

Leva para o controller Managers::RecruitmentsController mesmo... o Rails tá fazendo certo, como pode ser observado na linha 26 da saída das rotas que você postou
https://gist.github.com/augustoppimenta/afe3cbcb6163f2e9cf13#file-routes-L26
não há nenhum redirect ocorrendo antes do router do Rails processar sua URL?


C program to transfer pixels of a real time video image

Question: I need to know the C program used to transfer pixels of a real time video image of size 160*120 into another table of same size using array
Comment: You want to write one or want to know some existing implementation? This question in its current form makes little sense, can you edit it and be more specific?
Answer: <code>#define kBytesPerPixel 4
#define kPixelsPerRow 160
#define kRowsPerFrame 120
#define kBytesPerFrame (kRowsPerFrame*kPixelsPerRow*kBytesPerPixel)
typedef struct { unsigned char raw[kBytesPerFrame]; } VideoFrame;

*(VideoFrame *)target = *(VideoFrame *)source;
</code>


Trigger when a user clicks on a link

Question: I have a menu listing different links and on some of the links, I want to trigger a notification to the User. I'm working on drupal 7. Also please let me know what modules I would need in the process.
Thanks!
Answer: Have you looked into the Rules module? It's great for making conditional actions and can do stuff like sending out mails.
Comment: I don't see a option inside the rules interface for an action when the user clicks on a link, am i missing something ? or should i be writing custom code ?
Comment: You want to look at the 'user is going to view a page' rule
Comment: This event does not appear in drupal 7. Any idea why?
Comment: Use "Drupal is initialising" as the trigger event and then add a Data comparison condition to test the path. That should get you the same functionality as 'user is going to view a page'.
Answer: Just if someone come across it and not able to solve.
Steps:
Download the Rules module

Go to admin/config/workflow/rules
Create a rule
Event: Drupal is initializing
Condition: Data comparison:

Data to compare :[site:current-page:url]
Operator: equals
Data value: any URL you want

Action: page redirect / popup load / send email / etc...

Hope it helps.
Answer: Just to expand on the above for anyone that finds this post, I achieved this following danbohea's directions and using Text comparison as the condition
Parameter: Text: [site:current-page:url], Matching text: home
Comment: Hello, can you please post above with steps, right now it is not constructive.

Trigger when a user clicks on a link


Sharepoint 2010 : Using infopath form content type on a document set

Question: Here is the situation :
- Created a web-enabled form using InfoPath and published it to the Sharepoint site as a content type named PAF Cost , uploaded the model form as well in a library on the site.
- Created a document set named PAF, which containes the PAF Cost splitting content type.
- Created a library Forms in which i allowed the document set PAF content type
When I create a new document set say PAF1, i go inside it and i go to the ribbon document/new document command and i can create one new PAF Cost frame. I can edit this form through the web interface which is correct.
Now i want this form to be automatically created when i create a new document set PAF1,
To do this i specified a template for the default content type in the document set PAF settings, and i give the .XNS form file as a template. The form gets automatically created in the document set, but when i click on it it launches Infopath, and does not open as a web form. The icon as well is different from the manual y created form which open as a web form.
How can i make this automatically created form to open as a web form ?
Answer: I haven't found a way to make it work with a .xns as template. But if you specify the .xml (just creat an empty form in the library, it's an -xml with the .xns as reference) as the template within the documentset it works fine.
(Same goes for infopath documents created from code - I hade to use the .xml as template, to have it open in thw browser by default.)


Effect size and multiple linear regression and y values

Question: When evaluating the effect size of parameters in a multiple linear regression using standardized variables(via z-scores), is it also necessary to standardize your y-values? Would a transformation of the dependent variable (eg. logarithmic) affect the interpretation of the effect size of your beta values?
Answer: The coefficients (betas) from a multiple regression model are already measures of effect size.  In general, there are two kinds of effect sizes: unstandardized (raw) and standardized.  The betas from you model using the data as given constitute unstandardized effect size measures.  Unstandardized measures are best if you can count on your audience being familiar with the units of your data.  For instance, a cariologist will be very familiar with mmHg, but people outside of medicine may not be.
If you can't rely on your audience understanding the units used, you could use a standardized measure of effect size.  If you only standardized X (or only Y) first, I suppose you could say that was 'partially-standardized', although that's a bit of a neologism.  If I thought the consumers of my study would be familiar with only one of the variables (say, Y), I might only standardize the one I thought they wouldn't already have a handle on.  If I couldn't count on them knowing either, I would standardize both.  That's the logic here.  Note that none of these options is really 'right' or 'wrong'.

Regarding your last question, yes, a log transform would change the interpretation.  That's because the logarithm is a non-linear transformation, whereas standarization is a linear transformation.  Regarding the interpretation in that case, you should read this CV thread: Interpretation of log transformed predictor.


Custom select dropdown, unable to select user added item

Question: So I have this custom dropdown select that i'm building. It has some nested items in there and as the first option, the user can create their own item. I've got it working so they can click it, type in there, and once they hit enter it will be selected. The thing I can't figure out is after they have created it, and then they select something else, they are unable to go back to select that newly created item. Hopefully that makes sense. Here is the jsfiddle https://jsfiddle.net/johnsonjpj/18zm9kwz/2/
This is the part of the script i'm using to change that add button into an input, and then replace that data back into the list.
$(document).ready(function() {

    $('body').on('click', '.addBtn', function(){

      var $el = $(this).parent('.newInner');

      var $input = $('<input type="text" class="form-control">');
        $input.attr('placeholder', 'Enter your category name and press "Enter"');
//
      $el.replaceWith( $input );

      var save = function(){
        var $p = $('').text( $input.val() );
        $input.replaceWith( $p );
        $('.category-active').removeClass('category-active');
        $('.addNew').removeClass('addNew').addClass('list-group-item category-active');
        $('#categoryPlaceholder').attr('value', $input.val());

        var container = $(".list-group.list-group-root");
        container.hide();
        $('.category-select').removeClass('category-open');

      };

      $input.one('blur', save).focus();

        $input.keypress(function (e) {
             var key = e.which;
             if(key == 13)  // the enter key code
              {
                save();
              }
        });

    });
});

All help is very much appreciated. Thanks!
Answer: you need to use the event delegation so that the events will be bind to the dynamically added elements
you need to change
$('.catName').on('click', function() {

to this
$('body').on('click','.catName', function() {

Working fiddle : https://jsfiddle.net/x2m54gjj/
Comment: you are welcome  here is the document on event delegation https://learn.jquery.com/events/event-delegation/
Comment: Thanks so much, you rock!
Answer: When the document has loaded the first time you add the function $('.catName').on('click', function() {...} to all categories. This is the function that handles the selection and without it you can not click on any items, right?
The way you use on('click'...) is a so called direct-binding and only applies to current object.
So this function is applied to all existing items at that time. So when the user adds a new item to the list, this new item is missing this function and can therefore not be selected.
To fix this you need to add a delegated-binding instead which you do by changing
$('.catName').on('click', function() {

to
$('body').on('click','.catName', function() {

Comment: Wonderful, Thanks for the explanation as well. That makes sense now that i read up on it.


Toda vez que eu carrego arquivos obtenho uma quantidade grande de erros

Question: Preciso de ajuda.
Toda vez que carrego qualquer arquivo no Visual Studio 2015 obtenho uma quantidade imensa de erros gerais.
Estou começando a desenvolver para windows phone e logo ao importar o primeiro sample, baixado da msdn obtenho uma quantidade consideravel de erros:

Vale ressaltar que os erros que ocorrem não ocorreram em um computador da universidade em que curso, visto que foram abertos diversos samples nos computadores de lá.
Durante o periodo em que eu tive aulas sobre isso, meu professor simplesmente desmarcou ou marcou alguma opção em alguma checkbox e pronto, sumiram todos os erros.
Gostaria de saber como fazer para resolver esta dor de cabeça que me impede de importar arquivos!
Comment: Jovem, que "sample" é esse que você está tentando importar? Como você está tentando importar? Clique em [edit] e coloque o código do "sample" e como você está fazendo para importar na sua pergunta
Comment: Amigo, vou me explicar melhor:
Comment: Estou desenvolvendo aplicativos para windows 10 (windows phone, desktop e tudo mais da UWP). Quando crio um aplicativo e compilo ele, não obtenho nenhum erro na janela que indica qualquer possível erro. Como parte do meu desenvolvimento, eu procuro abrir diversos exemplos de aplicativos que são disponibilizados na MSDN. Durante o curso que fazia, o professor abria os mesmo exemplos e conseguia compilar e rodar naturalmente, porém aqui em casa é só eu carregar estes arquivos que obtenho inúmeros erros. Por exemplo: carreguei um exemplo de NFC e recebi 400 erros
Answer: Tudo indica que o "Sample" que vc está tendando abrir foi feito em ASPNET 4 MVC 5, e vc está criando um projeto ASPNET 5 MVC 6.
Crie um novo projeto, mas como ASPNET MVC 5 (e não ASPNET 5 ou vNext) e faça a importação.


JavaScript working in debugger but not when published to IIS

Question: I have a few scripts that work fine running in the debugger, but when I publish it to IIS it's like they aren't running.
Here are the lines i'm using to include the scripts inside the head tags
<code><script src="http://ajax.googleapis.com/ajax/libs/mootools/1.2.4/mootools-yui-compressed.js"></script>
<script src="<%=ResolveClientUrl("~/Scripts/")%>ScrollSpy.js"></script>
</code>
scripts are contained in Scripts folder
Answer: Correct me if I'm wrong but it sounds like you can't debug Javascript in VS? If so, have you considered using browser based debugging tools? Chrome, Firefox, and IE 11 have pretty great debugging tools that allow you to set breakpoints just like in Visual Studio.
There's a free course online that'll teach Google Chrome's DevTools at Codeschool - http://discover-devtools.codeschool.com/
Comment: If it was an issue with the scripts themselves, wouldn't they also not work when VS is running the project locally?
Comment: It could be a variety of things. I'd start with the Javascript debugger in a browser to see if it loads (you'll be shown if they don't). You can run some of the functions from the command line if they do to see if they fire appropriately. As an aside, if your second script relies on the first then it could be an issue with linking to the HTTP version vs the HTTPS (depending on your browser security rules). I'd link to it as "//ajax.googleapis.com/ajax/libs/mootools/1.2.4/mootools-yui-compressed.js" and not use the HTTP in there.
Comment: Awesome! Best practice in the future would be just link with the "//" and without the HTTP/HTTPS. Take care. :)


Updating existing XmlNode into a self closing XML tag

Question: I have this scenario where I would want to replace an existing XML element eg:
<Car xsi:nil='true'></Car>

into
<Car xsi:nil='true'/>

I want to accomplish the above by using only XmlNode. Is this possible?
Comment: Why?  The only thing it does is reduce the size of the file.
Comment: @jdweng Hi yes understood too. Its just to standardise our XML docs
Answer:     Dim xml As New XmlDocument()
    xml.LoadXml(<Car></Car>.ToString())

    For Each n As XmlElement In xml
        If String.IsNullOrEmpty(n.Value) Then n.IsEmpty = True
    Next

Comment: Hi, is there anyway to do it through XmlNode? Thanks.
Comment: I've updated it to using the System.Xml classes. I presume this is what you're meaning by XmlNode.
Comment: I think it is a different class albeit it being part of the System.Xml family. There is no IsEmpty property for XmlNode.
Comment: XmlElement derives from XmlNode. XmlNode is just an abstract concept of a node. So you are technically using XmlNode. Why do you need it to be only XmlNode?
Comment: You are right. Apologies didn't noticed the relation between them previously. It works now. Thanks!


R - Criar coluna de controle a partir de outras duas colunas

Question: Caros,
Tenho uma base de dados bem grande com a seguinte característica:
ORIENTAÇÃO   VOTO

Sim          Sim
Não          Sim
Sim          Não
Não          Não

Gostaria de criar uma terceira coluna na qual se os valores baterem, aparecerá 1. Se não bater, 0. Exemplo:
ORIENTAÇÃO   VOTO     CHECK

Sim          Sim        1
Não          Sim        0
Sim          Não        0
Não          Não        1

Podem me ajudar?
Muito obrigado desde já!
Answer: Vou fazer em duas linhas de código.
Basta ver que os valores lógicos FALSE/TRUE são codificados internamente pelo R como inteiros 0/1, respetivamente. Então, vê-se primeiro se os valores da duas colunas são iguais e depois transforma-se em inteiros.
Há ainda que ver se as colunas são de classe "character" ou "factor". As funções read.table e derivadas assumem o argumento
stringsAsFactors = TRUE

e portanto, para não ter surpresas, as colunas são comparadas como "character". Outra solução será ler os dados com o argumento acima com o valor FALSE.
dados$CHECK <- as.character(dados$ORIENTAÇÃO) == as.character(dados$VOTO)
dados$CHECK <- as.integer(dados$CHECK)

dados
#  ORIENTAÇÃO      VOTO CHECK
#1        Sim       Sim     1
#2        Não       Sim     0
#3        Sim       Não     0
#4        Não       Não     1
#5        Sim Abstenção     0

Outra opção é usar o pacote dplyr, muito popular para transformar dados.
library(dplyr)

dados %>%
  mutate(ORIENTAÇÃO = as.character(ORIENTAÇÃO),
         VOTO = as.character(VOTO),
         CHECK = as.integer(ORIENTAÇÃO == VOTO))

O resultado é o mesmo.
Edição.
Ainda outra solução.
dados$CHECK <- as.integer(Map(`==`, dados[[1]], dados[[2]]))

Dados.
Acrescentei uma linha de dados para não ter os mesmos níveis do "factor" nas duas colunas, caso a base seja lida com o valor por defeito de stringsAsFactors. É esse o primeiro caso abaixo.
1º caso: Ler como "factor".
dados <- read.table(text = "
ORIENTAÇÃO   VOTO
Sim          Sim
Não          Sim
Sim          Não
Não          Não
Sim          Abstenção
", header = TRUE)

2º caso: Ler como "character".
dados <- read.table(text = "
ORIENTAÇÃO   VOTO
Sim          Sim
Não          Sim
Sim          Não
Não          Não
Sim          Abstenção
", header = TRUE, stringsAsFactors = FALSE)

Comment: Perfeito, Rui. Muitíssimo obrigado. Funcionou bem!
Forte abraço!


Proving convergence of a sequence through a polynomial

Question: Let ($x_n$)$\rightarrow$x and let $p(x)$ be a polynomial.
(a) Show $p(x_n)$$\rightarrow$$p(x)$.
(b) Find an example of a function $f(x)$ and a convergent sequence ($x_n$)$\rightarrow$x where the sequence $f(x_n)$ converges, but not to $f(x)$.
For part (a) Is it enough to say that p($x_n$) is continuous at x because polynomials are continuous at all points, so the limit as $x_n$$\rightarrow$x of p($x_n$)=p(x) ?
For part (b) I'm having trouble seeing how this is possible.
Comment: For (b), consider $f(x)=\frac{\sin x}{x}.$ $f(0)$ is not defined, but, $1/n\to0$ and $ n\sin (1/n) \to 1$.
Comment: For (a) using continuity of polynomials is sooner.
Comment: Or let $f: x \mapsto 1/x : ]0, \infty[ \to \mathbb{R}$ and $x_{n} := 1/n$ for all $n \geq 1$.
Comment: For part a, you just need to prove that sums and products of continuous functions are continuous. That's the beauty of polynomials: they're built up only by algebraic operations.
Comment: @Chilango so if I prove that the sums and products of continuous functions are continuous, then I know that the limit of p($x_n$) exists for all $x_n$? can you explain your idea please? thank you!
Comment: Is it enough to say that p($x_n$) is continuous at x because polynomials are continuous at all points, so the limit as $x_n$$\rightarrow$x of p($x_n$)=p(x) ?
Comment: That should be enough, yes Laura.
Answer: For part b, all we need is a noncontinuous function, since continuity is what grants us that property.  Here's a simple one:
Define $f(x)=1$  if $x\ne 0$  and $f(0)=0$.  Then look at $x_n=\frac 1 n$.  Clearly $x_n\to 0$,  but $f(x_n)=1$ for all $x_n$,  hence $f(x_n)\to 1\ne f(0)$


github with Visual Studio 2013 - cannot pull because of uncommitted changes

Question: I am a single developer right now, but I do have a workplace, and I also do work at home. Github is pretty ideal for me because the goal is to track my code, but also just keep it in a good repository so I don't lose it. So here is my work process...

Do work at home (site a)
commit changes to github frequently

sometimes, this will be up to 20 commits in a day, depending on productivity. I commit
often.

go to other work site b (usually office)
clone repository at site b

this is done within visual studio, by going to Team Explorer -> Projects -> Connect to Team Projects, and then using Clone with the github repository URL.

redownload nuget packages, etc - resume work as normal at site b for the day

I perform frequent commits here, as well.

return home (site a) and open up Visual Studio 2013
open up the project I was working on
go to Team Explorer -> Unsynched Commits and click Pull

sometimes it works
sometimes, however, I receive the following error and I have no idea why

I would understand this if I had made edits to the current project before trying to pull - but I haven't. All I've done is loaded up Visual Studio. It says "See the Output window for details" but the Output window is completely blank - there are no details, and in this situation the only answer I've found is to delete the WHOLE project from my computer and clone the entire repository again.
Certainly this isn't right, I'm a complete newbie to git, and I have read the documentation over and over and this still makes no sense to me. Can anyone help shed some light on any of this?
Comment: Can you double check by execute command 'git status -s', for any changed pending to commit.
Comment: From project home directory
Comment: Yes in command prompt
Comment: I merely get the result `'git' is not recognized as an internal or extranl command, operable program or batch file.`
Comment: Where would I execute that, exactly? I've never used git through the command line as of yet, only the Visual Studio interface.
Comment: Just in a normal command line? Like `cmd.exe`?
Comment: Hey @VinitPrajapati, I just wanted to follow up on this and let you know that you helped me a lot too. I know that I cannot give you "answer" points, but if you would be so kind as to place your statements into an actual "response" to the question, I would gladly up vote it to give you appropriate credit, since I was able to accomplish other things with your suggestions and now can use `git` from my command line.
Comment: If you're interested in solving this from Visual Studio instead of passing from the command line, please upvote: https://visualstudio.uservoice.com/forums/121579-visual-studio-2015/suggestions/4576531-provide-stash-support-in-visual-studio-tools-for-g
Answer: Before pull-ing you need to stash your uncommitted changes first. Visual Studio does not support full range of Git functionality yet, including git stash, so you have to do it through command line or use something like Source Tree in addition to Visual Studio for such occasion. Run git status -u to see uncommitted changes and git stash to temporarily hide them before pulling/syncing. Once in a while Visual Studio will cache the status results and will get out of sync with reality, in this case kill Studio, delete .git\ms-persist.xml file and restart.
Comment: @Ciel if just opening a solution in Studio creates new changes you should review your `.gitignore` file, this generated cruft is user or computer specific and should not be tracked or be part of your repo, the `bin` and `obj` folders, the `.suo` files, etc.
Comment: @Ciel if you're not comfortable with command line or Chocolatey I would recommend installing Source Tree, it'll download it for you and will give you a nice interface for stashing.
Comment: @Ciel depends on what will show up as uncommitted. Remember that Git command line is the 'source of truth', when `git status` and Studio give difference results trust the `git`, Studio was built for non-DVCS TFS and even removing readonly flag qualifies as a change, because Windows. It's early days of "native" support for Git in Studio, there are plenty of bugs and missing features but props to them for doing it anyway.
Comment: So the "changes" could be as simple as me even opening up the solution in visual studio. That would actually explain a lot. I wonder if they are aware of this at Microsoft... I'm going to try and find the right place to contact to show this to them and see if this can be looked into.
Comment: @Ciel `.git` is a hidden folder in the root of your project, it what makes it a Git repo rather than a just a folder and contains all the history, hashes, branches, etc. Only delete it `ms-persist.xml` when `git stash` and Studio's explorer say difference things, it means bad things happen and it should force Studio to regenerate it.
Comment: So why is this being down voted now ..? It was a legitimate problem, and one that an answer was not readily available for, and we solved it very quickly. I've known a lot of developers with this same issue who were pleased when I directed them to this thread.
Comment: I just wanted to follow up and let you know that I have successfully done this on all of my work environments and it works __beautifully__. This has completely, and absolutely solved my problem. I am learning more about _`git`_ every single day and am finding the tool you linked me instrumental in it. I have also spoken to the appropriate people at __Microsoft__ about these issues, and have been told that many of them will be built right into the next update to _Visual Studio 2013_ or the next CTP of _Visual Studio 2014_, or both.
Comment: To be clear, is this the program you are referring to? http://www.sourcetreeapp.com/ (everything about it matches your statement, so I assume so)
Comment: Also, thank you so much for helping with this. It has driven me nuts. You showed me how to fix it, but is it possible for me to ask how this even happened? Do you have any idea why it saw "uncommitted changes" when there in fact were no changes at all?
Comment: Thanks again, that is actually a lot of very useful information. I've learned quite a bit just from this small problem alone in a very short span of time.
Comment: In my case, since I am also having the same issue in Visual studio 2015, I used the SourceTree and it works seamlessly.
Comment: In Visual Studio 2015 they made the handling worse. There are no splits to "included changes", "excluded changes" and "untracked files". I could only fix this with external tools. F.e. once having local changes in gitignore can no more ignore it via untracked files in VS, I can only undo it and create a gitignore each time, or check it in and have this faults over and over again. Wonder who is that stupid at MS to allow this change in first place - now they have this annoying bug and no way out of it without using external tools. Also the commit-view is a total mess now!
Comment: Alright... I am sorry to be ignorant, but what exactly do I need in order to do that? Trying to run these git commands in a command line isn't working, so I assume I need to install something. I did the `Install git 3rd party tools` through Visual Studio as it prompted me to, so I assumed it was downloading everything related to that.
Comment: Okay, following these instructions, I have added git to the "path"; http://blog.countableset.ch/2012/06/07/adding-git-to-windows-7-path/ - though I am on Windows 8, so I hope it works the same. Let me try what you have suggested and get back to you.
Comment: Aha! That worked! I had to go through `PowerShell`, a normal command line didn't seem to take it. Let me try this a few more times on some intentionally damaged tests in order to make sure I grasp it - then I'll accept the answer once stackoverflow's timer lets me.
Comment: I am plenty comfortable with using a command line, I just never have for git. I am very new to it. I have a lot of experience with command line tools, simply not this one. However the tools you've suggested, I'll take a look at them. I do prefer more convenient approaches when they are available.
Comment: Ok. `git stash` worked - and it allowed me to pull the repository correctly. Now you said to delete `.git\ms-persist.xml`, where should I be finding this file? I closed Visual Studio and do not see it. I am running a search on my system, but I have a REALLY old, pathetic computer (this is a temporary machine, an old Celeron CPU at that, while I wait for new parts to arrive)


Is $\min(f(x),\beta)$ a Lipschitz function?

Question: Let $\beta >0$ be some constant and $f:\mathbb{R}^n \to \mathbb{R}$. Assume that $f(x)$ is $L$-Lipschitz in the domain: $X = \{x \vert f(x) \leq \beta\}$, i.e., $\vert f(x)-f(y) \vert \leq L \vert x-y\vert$ for all $x,y \in X$. Is $\min(f(x),\beta)$ a Lipschitz function in $\mathbb{R}^n$?
Comment: My original attempt at an answer - self-deleted. It was, fundamentally, an answer to the wrong question.
Answer: Let $f(x)=x+2\times \Bbb 1_{\{x>0\}}$ and $\beta=1$. Then $f$ is Lipschitz on $(-\infty,0]$. But $\min\{f,1\}$ is not.
Comment: I have edited to make more clear the definition of $f$. If you do not like it fell free to reverse the edit.


Are there any breathing methods for Rap vocals?

Question: I am looking for handy vocal techniques for maintaining my flow during rap. This technique(s) will have to help me maintain my breath during rapping. I seem to be trying to hold my breath too long but when I think about breathing I lose track of my vocals and lines.
I am referring to high speed rapping btw so any methods for taking short snappy breaths of air and making them last will be much appreciated.
Comment: For more ideas to practice breath support, check out this question: http://music.stackexchange.com/questions/17/improving-breath-support
Answer: Making sure to breath down and supporting your breath with your diaphragm, rather than to the chest, and not to exhale all your air at the same time is extremely important for anything that requires use of breathing. This is called 'breath support' or 'full breathing'. If you're doing it right, you should feel your stomach inflating when you breath in, rather than your chest.
A few exercises to help you work on breath support include:

Hold your hand in front of your face with your palm facing you. The blow each finger after full breathing, as if they're birthday candles and they won't go out. Make sure that when you exhale, you direct all the air towards one point (finger tip) rather than just letting the air escape.
Take a full breath down to your diaphragm for 4 counts as you can (make sure not to breath into your chest!), hold your breath for 8, then make a strong 'hissing' sound for 8 counts. Over time, as you get better, increase the amount of counts for all three of these things.

If you feel like either of those exercises is too easy, then try doing it while lying down on your back.
Now when it comes to actually rapping, don't try to hold all your air in. Know your raps well, and know where to snag a quick full breath - this becomes especially important with faster raps.
As for thinking about breathing making you lose concentration - the only way to solve this, is to practice, and then practice some more. Eventually breathing properly and at the right time will become something that you can do without thinking about it.
Comment: Great! thanks :) I am already happy with the progress ive made in Rap, (I can fully cover Rap God by Eminem) but these breathing techniques are really helpful.
Comment: Shieldbug - can you add your suggestions to this question? http://music.stackexchange.com/questions/17/improving-breath-support
Comment: Just another quick question regarding this answer, What will breathing into the chest do? can it cause chest problems as I am currently experiencing tightness of the chest and cramps in my right side close to my pectoral muscle...
Comment: @ThunderToes it doesn't cause chest problems it's just when you breath into the chest you're only filling up the top of your lungs but when you breathe into your stomach you're using your full lung capacity


Binary logistic regression with only positive training examples - does that even make sense?

Question: (I have learned about polynomial linear regression, logistic regression, and neural networks.)
I have a binary logistic regression problem. I need to classify things to be true or false. What makes this hard for me to understand is that I only have y=1 training examples. Is it possible to get a decision boundary for this data set?
I simplified the problem by only thinking about 2 of my features.

I experimented a little bit by placing fake y=0 training examples everywhere.

Gradient descent with the real and fake training sets seems to fit the data ok. It is a bit underfit, taking into account that this is a degree 6 curve and regularization is turned off.
There has to be a better way to approach this problem. Heck, I could even calculate the convex hull! (Not sure how well that will work in 15+ dimensions.) Any advice?
Comment: What you're doing is called [density estimation](https://en.wikipedia.org/wiki/Density_estimation), and there are purpose-designed methods for the task. Clustering is related, and both fall under the purview of unsupervised learning.
Answer: Do you have a test set with $y = 0$ examples? If not, it will be pretty hard to evaluate your classifier!
Anyway, logistic regression isn't the greatest tool for this, but there are other neat techniques that were designed for problems like this, usually falling under the umbrella term of one-class classification. I think the most commonly used is the one-class support vector machine.


What is the difference between page callback and access callback?

Question: Can anyone please explain with example for difference between page callback and access callback in drupal?
Answer:
page_callback is a function called which will be used to generate contents of the page
access_callback is a function called which will be used determine if a user has access to view the page. This can be used where a simple permission isn't enough. An example would be that the author of the node would be allowed to edit the node or any user with a special admin permission.
Note the access_callback will by default be the user_access function which will check that the user has a specific permission.

Both of these keys have a sidekick, [page/access] arguments which should be an array of arguments that is passed to the function. arguments can either be static or you can use numbers to reference the URL. If a load function us used on a URL arg, like %user, referencing it will yield the return of the load function, like the user object instead of the user id (uid).
Page callbacks will receive any URL args that aren't used for pattern matching. So if you define an URL foo/bar and user goes to foo/bar/baz, baz will be added to the list of args passed to the page callback. This can be handy in some cases where you can provide a default argument that can be overridden in the URL.
If in doubt always check the api refference api.drupal.org
Comment: There is always a access callback function, by default it is `user_access()` and the argument passed to it is a permission. I remember that I found it initially confusing that the permission is an array but you can only specify a single permission. Maybe you could clarify that part a bit :)
Answer: Page callback: a function that is responsible to provide html for the page
e.g.
function get_html(){
    return "";
}

or
    drupal_get_form() if page is generation a form. In this case 'page arguments' are required to link form defining callback with it.
Access callback: A function that is responsible to check a user has access on the content of this page callback.
normally it is user_access()


Using SDL to make a simple game, struggling with linking everything together

Question: I would like to attempt to make a simple game in c++.
So I found really cool series about how to make a game but the creator didn't include how to install different libraries etc.
So, in the tutorials, he gives us this code:
http://gynvael.vexillium.org/ext/vc/game.cpp
As a basic framework to make the game.
From now on I will list for you what I found out and what I think is the problem:
The problem is that when you just try to compile and run it, it will throw tons of errors at you etc.
I needed to link my project to SDL first, which I did and I think it works because there is no major errors or underlined code.
But then, there was a problem with the gl.h file.
So I have figured out that I need to install OpenGL libraries and link them to my visual studio project. I found out that I need FreeGlut and GLEW to run the piece of code from the link above.
So I have linked GLEW fairly easily with my project but there is a problem with GLUT.
Apparently, for unknown for me reason you have to compile the .lib file yourself. And that brought me to a whole new level of problems. So the newest version of GLUT (3.0) doesn't have the visual studio folder in it (In the tar file) so I cannot compile the newest version.
On the other hand, all the older versions have that visual studio folder which allows me to compile the freeglut.lib file and add it to my program's dependencies.
But when I do that, it comes up with an error: LNK1104: cannot open file 'freeglut.lib'
I have no idea why's that because I did everything exactly like in tutorials, multiple times.
I think that it could be because I got the newest version of GLEW, but old (from 2013 I think) version of GLUT, because the newest one doesn't have a folder with visual studio project to compile.
All I need is to make the code (from the link) work.
@EDIT~~~~~~~~~~~~~~~~~~~~~~~~
I have found out that my dependencies folder was in the wrong place and I moved it, instead of the problem with the freeglut.lib file, which seems like has been sorted out (I think I fixed it :D) I get like 5 new errors:
Screenshoot of the error log: http://puu.sh/hD6x5/d5fc1e1be6.png
but none of this rings the bell. Nothing happens either if I doubleclick it.
Comment: If you mark my question as already answered somewhere else it would be nice to post a link so I can get the freaking answer at least...
Answer: That error means that you need to link with these three additional libraries:

Glu32.lib
SDLmain.lib
SDL_Image library

You may need to download and build SDL_Image, but the other two should already be part of Windows SDK and SDL respectively.
Oh, and you need to not define a main() function in your own code. It's either the framework code you are using, or even SDL (IIRC) that is doing that for you.
Comment: Hello. Ive been playing around and trying to figure out stuff and I have reached this:

http://puu.sh/hD7QE/31dfed84ff.png (sorry for link I can't post images because I am a new user)

Which seems much better than what I had before. Any ideas how to fix these? I feel like I am getting closer and closer to the goal.
Comment: Link with "Glu32.lib" to fix the first error, and get (and link with) "SDL_Image" to fix the second.
Comment: thank you so much!!! Thanks to you I am getting so much closer to the working program. Sorry for taking your time though.

My program compiles just fine without any errors, but: http://puu.sh/hD8fo/d993ed0cba.jpg

Any ideas??


Codes in onAnimationRepeat is not running

Question: I want to do some things  in onAnimationRepeat .
its my code:
final LinearLayout l = (LinearLayout) findViewById(R.id.parent);

//line 03

        RotateAnimation anim = new RotateAnimation(0, 0, 0, 0);
        anim.setInterpolator(new LinearInterpolator());
        anim.setRepeatCount(4);
        anim.setDuration(10);

        anim.setAnimationListener(new AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {
//line 01
                View v = LayoutInflater.from(MainActivity.this).inflate(
                        R.layout.product_layout, null);
                TextView t = (TextView) v.findViewById(R.id.test);
                t.setText(i + "");

                View root = v.findViewById(R.id.root);
                View face = v.findViewById(R.id.face);
                View back = v.findViewById(R.id.back);

                l.addView(v);
                flipCard(root, face, back);
//line 02
                i++;
            }

            @Override
            public void onAnimationEnd(Animation animation) {

            }
        });
        l.startAnimation(anim);

but it not working.
when I copy line 01 - line 02 codes into line 03 both of them (copied codes and line 01 - line 02 codes) be performed.
what is problem?
thanks
Answer: My problem is solved.
LinearLayout l was defined with
android:layout_height="wrap_content"
and it was empty.
I changed it to
android:layout_height="match_parent".
and my problem is solved.


Does the new f1 double points rule apply for all places?

Question: From formula1.com:

Double drivers' and constructors' points will be awarded at the final
  race of the Formula One season - Abu Dhabi for 2014 - in order to
  maximise focus on the championship until the end of the campaign.

Does this rule also apply for the places outside the points (11th-22nd). Does an 11th place in the last race count as two 11th places? That would be important for the small teams without any points at the end of the championship.
Answer: This new rule give duplicate points only for the last race of the season, so:

the winner takes 25*2=50 points
the second takes 18*2=36 points

so on from 3rd to 9th arrived

the 10th takes 1*2=2 points
the 11th do not takes points

The pilots award only one placement (so no double victory on the same track).
Comment: This is all correct, @Ale but it doesn't specifically answer the poster's question, i.e. when determining who finished first amongst the non-point-scorers in the championship, will the team who finished 11th in the final race be credited with the equivalent of two 11th place finishes thereby potentially beating another back-marker team who "only" finished 11th in one other race.
Comment: As written in the last line, I think (so I cannot assume it like a definitive sentence) that also in this case it will be duplicate only the points


How do I get rid of the white noise when playing guitar through pulseaudio?

Question: Instead of using an amp, I have a cheap adapter that allows me to plug my guitar cable into the 3.5mm audio input port on my laptop. I then use pactl load-module module-loopback latency_msec=1 to route the input to my speakers and play guitar that way. This method has two issues, namely, latency starts off being unnoticeable but slowly increases until there is a very minute but noticeable delay between hitting a string and hearing it through the speaker and a lot of white noise present as long as the guitar is plugged in. I have tried using pactl load-module module-echo-cancel instead of the former command to a moderate amount of success, but that module sometimes nerfs the notes played instead of the white noise. Is there any way to minimize the amount of white noise present? Would insulating the cables further help? I am using Linux.
Edit: Decreasing the gain of the microphone port helps but then I lose the compressed sound effect, which I wouldn't like to do.
Answer: Pulseaudio is not really intended for realtime operations: use jackd for that instead.  That will help with making latency more predictable.  However, the combination of "cheap adapter" and "audio input port on laptop" is good for a lot of white noise and that's not really something that software has a reasonable chance to fix.  An external audio card with a high impedance input (or "Instrument" input) in connection with jackd should allow you to set up reliable operations, though using the laptop speakers will require stuff like zita-j2a since then you are dealing with two audio cards.
Another option for getting latency under control would be to set up monitoring on your laptop audio (assuming it offers that) bypassing pulseaudio and other software solutions entirely.  But that will not help against white noise.
Comment: Thanks for the quick answer! Is there another kind of adapter that would produce a lower amount of white noise? I saw pictures of ones that use USB instead of the line in port. Would those be better for this?
Comment: +1 An external audio interface is really what you need. Any decent one should provide its own monitoring outputs, which would allow you connect to speakers without having to use your laptop's sound card in tandem.


search and replace text in all php-files in a directory and it's subdirectories

Question: I am trying to replace a string in all PHP files within a directory and it's subdirectory!
So in order to do that I created 2 text files, namely "pattern.txt"(Contains string to be replaced) and "replacement.txt" (Contains the replacement string)
I fired up my gitBash Shell on Windows 10 and typed in the following command
pattern=`cat /path/to/pattern`; replacement=`cat /path/to/replacement`
find . -name "*.php" | xargs -n 1 sed -i -e 's|$pattern|$replacement|g'

But an error arises after executing the second command, which is
sed: can't read ./admin: No such file or directory
Please help!
Answer: You could avoid using xargs and do everything within find for example:
find . -name "*.php" -exec sed -i '' 's/pattern/replacement/g' {} +

On BSD, MAC by passing an empty string to sed's -i args will create no backup sed -i ''


Mudar o tamanho do espaçamento do TAB no JTextPane

Question: Quero mudar a tabulação da tecla TAB do jTextPane pois está com muitos espaços, por exemplo:
Atualmente se encontra assim:
Uma casa azul

// após TAB

                Uma casa azul

E o que eu quero seria assim :
Uma casa azul

// após TAB

       Uma casa azul

Tem como fazer isso?
Segue um exemplo do meu código:
public class TAB extends javax.swing.JFrame {

    /**
     * Creates new form TAB
     */
    public TAB() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextPane1 = new javax.swing.JTextPane();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jScrollPane1.setViewportView(jTextPane1);

        jLabel1.setText("Como mudar o TAB ?");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
            .addGroup(layout.createSequentialGroup()
                .addGap(151, 151, 151)
                .addComponent(jLabel1)
                .addContainerGap(150, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(24, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TAB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TAB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TAB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TAB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TAB().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextPane jTextPane1;
    // End of variables declaration
}

E  a classe principal só faz isso :
 new TAB().setVisible(true);

Comment: Por favor. adicione um código  com o problema mencionado, que seja um **[mcve]** para que seja possivel avaliar possiveis soluções. Sugiro que leia também [ask]
Comment: Eu tenho um jTextPane e quero que o TAB dele não seja tão exagerado(como o valor default). É só.
Comment: Sem ver o código para testar, fica complicado ajudar. Recomendo a leitura de [ask]
Comment: Código de exemplo inserido na pegunta
Answer: Precisa alterar a forma como o método nextTabStop() da classe ParagraphView trabalha. No exemplo abaixo, a constante TAB_SIZE é que está definindo o tamanho entre esses tabs, em pixels, basta alterar de acordo com o que achar melhor para seu componente:
import javax.swing.text.*;
import javax.swing.*;

public class TabSizeEditorKit extends StyledEditorKit {

    public static final int TAB_SIZE=36;

    @Override
    public ViewFactory getViewFactory() {
        return new MyViewFactory();
    }

    public static void main(String[] args) {
        JFrame frame=new JFrame("Custom default Tab Size in EditorKit example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JEditorPane edit=new JEditorPane();
        edit.setEditorKit(new TabSizeEditorKit());
        try {
            edit.getDocument().insertString(0,"1\t2\t3\t4\t5", new SimpleAttributeSet());
        } catch (BadLocationException e) {
            e.printStackTrace();
        }
        frame.getContentPane().add(new JScrollPane(edit));

        frame.setSize(300,100);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    static class MyViewFactory implements ViewFactory {

        @Override
        public View create(Element elem) {
            String kind = elem.getName();
            if (kind != null) {
                if (kind.equals(AbstractDocument.ContentElementName)) {
                    return new LabelView(elem);
                } else if (kind.equals(AbstractDocument.ParagraphElementName)) {
                    return new CustomTabParagraphView(elem);
                } else if (kind.equals(AbstractDocument.SectionElementName)) {
                    return new BoxView(elem, View.Y_AXIS);
                } else if (kind.equals(StyleConstants.ComponentElementName)) {
                    return new ComponentView(elem);
                } else if (kind.equals(StyleConstants.IconElementName)) {
                    return new IconView(elem);
                }
            }

            return new LabelView(elem);
        }
    }

    static class CustomTabParagraphView extends ParagraphView {

        public CustomTabParagraphView(Element elem) {
            super(elem);
        }

        @Override
        public float nextTabStop(float x, int tabOffset) {
            TabSet tabs = getTabSet();
            if(tabs == null) {
                // a tab every 72 pixels.
                return (float)(getTabBase() + (((int)x / TAB_SIZE + 1) * TAB_SIZE));
            }

            return super.nextTabStop(x, tabOffset);
        }

    }
}

Que resulta em:

Referência:

Default TabStop size customization in JEditorPane
Comment: Pergunta editada
Comment: @Beto você parece ter mudado a duvida, que era como reduzir o tamanho da tab. Isso seria outra pergunta e não uma edição.


Make a scatter plot by drawing 100 items from a mixture distribution

Question: I was asked the following:
Make a scatter plot by drawing 100 items from a mixture distribution
$0.3 N\left((5, 0)^{T}, \begin{pmatrix} 1 & 0.25 \\ 0.25 & 1\\ \end{pmatrix}\right)
  +0.7 N\left((-5, 0)^{T}, \begin{pmatrix} 1 & -0.25 \\ -0.25 & 1\\ \end{pmatrix}\right)
  $.
I generate this using the built-in Python random module, specifying the variance and the sample. I got feedback from the instructor

Mixture distribution combines density functions, not observations.

I have no idea what is wrong? Can anyone explain this to me?
Comment: It would help to describe exactly how you generated the values, because it sounds like you did something wrong, such as generating exactly 30 items from the first component and 70 from the second.  Currently we don't have enough information to determine what the problem might be.
Comment: It sounds like you will need to consult with the instructor concerning what they meant.
Comment: If you show the plot it is easier to see what you did. The comment from the instructor is not directly clear.
Comment: I created to distribution with exact parameters as above, then added them with weights 0.3 and 0.7. Then I used .sample(100) from that distribution.
Comment: I guess that you might have drawn two times 100 items, one set of hundred from the first distribution and one set of hundred from the second distribution, and add/sum those two pairwise together with weights 0.3 and 0.7. If that is the case, then you did not use a mixture distribution.
Answer: Here you see an example with 400 points

What you probably did is making weighted sums from pairs of X and Y, ending up with a single cluster of points.


How to create a redirection programmatically?

Question: I try to create a redirection 301 with the redirect module. For example, I want to redirect an URL source to an internal URL through my custom module.
I want to create a redirection when I create a node. Import old content, create a new node and keep the old path.
Anyone have an idea?
Comment: You should definitely add more information to your question. What have you tried so far? What is your exact problem? Why don't you mention the migration you mentioned in a comment to one of the answers?
Comment: You can use below code snippets to create programmatically URL redirect.

// Create an object with the redirect parameters
$redirect = new stdClass();
redirect_object_prepare($redirect);
$redirect->source = 'old-url';
$redirect->source_options = array();
$redirect->redirect = 'node/5'; // New system path
$redirect->redirect_options = array();
$redirect->type = 'redirect';
$redirect->language = LANGUAGE_NONE;
redirect_save($redirect);
Comment: You can use `RedirectResponse` to achieve this. Refer the following link [https://drupal.stackexchange.com/a/138852](https://drupal.stackexchange.com/a/138852)
Comment: Thanks for your answer. But i want to create a redirection when i create a node. I import a old content in create a new node and i keep old path.
Comment: The [Redirect module](https://www.drupal.org/project/redirect) contains this functionality. Unless you have another use case but then I would need more information in order to help.
Answer: If you want to store redirects in database use the module Redirect. This module provides a user interface to add redirects. The redirects are stored in a content entity, which you can also create programmatically:
use Drupal\redirect\Entity\Redirect;

  Redirect::create([
    'redirect_source' => 'redirects/redirect1',
    'redirect_redirect' => 'internal:/node/1',
    'language' => 'und',
    'status_code' => '301',
  ])->save();

You can do this at the time you create nodes from imported data or in entity hooks when inserting, updating or deleting nodes.
Answer: You can change your .htaccess by adding this code :
#custom redirects
RewriteRule ^old/URL/path$ http://example.com/new/path [R=301,L]
#end custom redirects

Or if you want do this in Drupal :
return new RedirectResponse(Drupal\Core\Url::fromUri('route_name'));


P values of coefficients in rlm robust regression

Question: I am using rlm robust linear regression of MASS package on modified iris data set as follows:
<code>> myiris = iris
> myiris$Species = as.numeric(myiris$Species)
> head(myiris)
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2       1
2          4.9         3.0          1.4         0.2       1
3          4.7         3.2          1.3         0.2       1
4          4.6         3.1          1.5         0.2       1
5          5.0         3.6          1.4         0.2       1
6          5.4         3.9          1.7         0.4       1

> library(MASS)
> rmod = rlm(Species~., data=myiris)
> rmod
Call:
rlm(formula = Species ~ ., data = myiris)
Converged in 6 iterations

Coefficients:
 (Intercept) Sepal.Length  Sepal.Width Petal.Length  Petal.Width
  1.14943807  -0.11067690  -0.02603537   0.21581357   0.63793686

Degrees of freedom: 150 total; 145 residual
Scale estimate: 0.191
>
> sumrmod = summary(rmod)
> sumrmod

Call: rlm(formula = Species ~ ., data = myiris)
Residuals:
     Min       1Q   Median       3Q      Max
-0.59732 -0.15769  0.01089  0.10955  0.56317

Coefficients:
             Value   Std. Error t value
(Intercept)   1.1494  0.2056     5.5906
Sepal.Length -0.1107  0.0579    -1.9128
Sepal.Width  -0.0260  0.0599    -0.4346
Petal.Length  0.2158  0.0571     3.7821
Petal.Width   0.6379  0.0948     6.7287

Residual standard error: 0.1913 on 145 degrees of freedom
</code>
This does not give p.values so I calculated them as follows (using pt function of base R):
<code>> dd = data.frame(sumrmod$coefficients)                             #$
> dd$p.value =  pt(dd$t.value, sumrmod$df[2])                       #$
> dd
                   Value Std..Error    t.value    p.value
(Intercept)   1.14943807 0.20560264  5.5905804 0.99999995
Sepal.Length -0.11067690 0.05786107 -1.9128044 0.02887227
Sepal.Width  -0.02603537 0.05991073 -0.4345693 0.33226054
Petal.Length  0.21581357 0.05706173  3.7821068 0.99988663
Petal.Width   0.63793686 0.09480869  6.7286751 1.00000000
</code>
However, these are not correct since ordinary lm function and other regression functions show that Petal.Length and Petal.Width are highly significant in this regression:
<code>> summary(lm(Species~., data=myiris))

Call:
lm(formula = Species ~ ., data = myiris)

Residuals:
     Min       1Q   Median       3Q      Max
-0.59215 -0.15368  0.01268  0.11089  0.55077

Coefficients:
             Estimate Std. Error t value Pr(>|t|)
(Intercept)   1.18650    0.20484   5.792 4.15e-08 ***
Sepal.Length -0.11191    0.05765  -1.941   0.0542 .
Sepal.Width  -0.04008    0.05969  -0.671   0.5030
Petal.Length  0.22865    0.05685   4.022 9.26e-05 ***
Petal.Width   0.60925    0.09446   6.450 1.56e-09 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.2191 on 145 degrees of freedom
Multiple R-squared:  0.9304,    Adjusted R-squared:  0.9285
F-statistic: 484.5 on 4 and 145 DF,  p-value: < 2.2e-16
</code>
Where is the error? Am I not using correct method to calculate p.value here?
Edit: As suggested (further) by @Glen_b in the comments:
<code>> dd$p.value =  2*pt(abs(dd$t.value), sumrmod$df[2], lower.tail=FALSE)      #$
> dd
               Value Std..Error    t.value      p.value
(Intercept)   1.14943807 0.20560264  5.5905804 1.089792e-07
Sepal.Length -0.11067690 0.05786107 -1.9128044 5.774455e-02
Sepal.Width  -0.02603537 0.05991073 -0.4345693 6.645211e-01
Petal.Length  0.21581357 0.05706173  3.7821068 2.267410e-04
Petal.Width   0.63793686 0.09480869  6.7286751 3.691993e-10
</code>
These seem to be correct (finally).
Comment: Even if it were correct to use a t-distribution for this calculation, you don't seem to be calculating p-values correctly.
Comment: You're still not calculating correctly. Consider carefully what you're computing when the statistic is negative. Think about the use of `abs` on the statistic, and don't use `1-`, set the `lower.tail` argument the other way in the call to `pt`
Comment: I have edited the last part of my answer. Is this the correct method?
Comment: Try doing the same calculations on `lm` output and you'll see immediately if the approach works correctly.
Comment: I think I have to multiply by 2 for correct (?2-sided) P value.
Comment: That looks right. If you now look at `summary.lm` (just type that at the console), you'll find this bit of code: `ans$coefficients <- cbind(est, se, tval, 2 * pt(abs(tval),`  `rdf, lower.tail = FALSE))` ... and the last item in the arguments to `cbind` there is the p-value column in the regression table when you call `summary` on an `lm` object
Comment: I have to multiply by 2 to get 2-tailed value but when should I need to make lower.tail=FALSE ?
Comment: By using `abs` you're making the statistic positive, and you then need to look in the upper tail. So that would be "when you use `abs`"
Answer: Even if it were correct to use a t-distribution for this calculation, you don't seem to be calculating p-values correctly.
You seem to be calculating this:

when you want this:
Comment: I tried but could not figure out proper way of calculating the P value. Please see my edit in question above and advise.