Non-trivial semisubgroups of the unit interval?

Question: The open unit interval $(0,1)\subset \mathbb{R}$ forms a semigroup under multiplication. What are examples of subsemigroups of this semigroup, which are not intervals of the form $(0,a)$ for $a\in (0,1)$? Have they been studied? (Where) do they naturally appear? Are there some known classification results?
Comment: The subsemigroup of rationals... and for any ring $R$ with $\mathbb{Z}\leq R\leq \mathbb{R}$, $R\cap(0,1)$ if nontrivial.
Answer: Consider any subset $P$ of the positive prime integers $\{2,3,5,7,11,13,17,\ldots\}$. Next, consider the set of all numbers of the form $p_1^{-n_1} \cdots p_k^{-n_k}$, where $p_1,\ldots,p_k \in P$, and where $n_1,\ldots n_k \ge 1$ are integers. This gives uncountably many distinct examples (given that the set of positive prime integers has uncountably many distinct subsets).
Answer: Using minus the logarithm, you are looking at the subadditivesemi-group of $(0,\infty)$. The set ${\bf N}\backslash\{0\}$ is an example of such subadditivesemi-group.
Answer: To add to both the other answers, the group $\mathbb{R}$ is isomorphic to $\bigoplus_c \mathbb{Q}$, so has not just uncountably many, but $2^{2^{\aleph_0}}$ many subgroups, by taking the suspace over $\mathbb{Q}$ generated by any subset of the basis for $\mathbb{Q}$ over $\mathbb{R}$. Any intersection of this with $(0,\infty)$ is a subsemigroup of $(0,\infty)$, and they are all different. So there are $2^{2^{\aleph_0}}$ distinct subsemigroups of $(0,\infty)$, hence $2^{2^{\aleph_0}}$ distinct subsemigroups of $(0,1)^\times$.
Another thing to notice is if you take any element $a \in (0,1)$, the set $ \langle a \rangle = \{a^n|n \in \mathbb{N}-\{0\} \}$ is a subsemigroup. This actually applies to any element of any semigroup, so you can almost always find lots of subsemigroups.


How to use data analysis output (e.g. clustering) in predictive regression?

Question: I performed some data analysis and visualizations on my dataset and found there are likely $k$ clusters present. How can I use this in a predictive regression setting?
My first thought is to create a regression model within each cluster. Therefore given a testing $x$, decide what cluster it belongs to, and perform the predictive regression within that cluster. Note that the regression is completely independent of the data in other clusters.
But this seems like there is data inefficiency, especially worse if the size of the cluster is not very large.
On the other hand, the performance of a global regression model is not necessarily affected by the presence of clusters, so I can ignore the clusters. But this seems like a waste of knowledge.
TLDR: How can I use clusters in regression?
Comment: Any idea what causes the clustering?
Comment: In general, no.
Comment: What sort of data do you have, and what are the clusters based upon?
Comment: I'm more interested in a general answer, not so data specific. the question was inspired by the boston housing prices dataset fyi.
Answer: The shortest answer: it depends. Appearance of several clusters in the data is a strong hint of several data-generating processes in play. It is quite possible that they have different error term properties. Disagree with @Zach, since cluster classification adds no new information into the regression, and the differences in effects would simply be dumped into the "cluster" indicator. The first question to ask would in my opinion be: are the coefficients in the cluster-specific regressions significantly different from each other (or from the pooled regression)?
Especially if you are severely lacking degrees of freedom, pooled regression looks much more promising.
So far we have been talking about in-sample properties of your set, but as long as you want to use it for prediction, it is out-of-sample performance that should ultimately drive your decision-making.
Comment: cluster classification can add new information to the regrssion, I think. If you run, say, a random forest to classify but a linear regression to regress, then clearly the random forest could split the data in non-linear ways that are precluded to the linear regression. Am I making sense here?
Answer: I totally agree with Deer Hunter that we don't have enough information to answer your question. Moreover, an answer will usually not be possible from within the data, it will depend on the application and data-generating processes.
For predictive models, ultimately the validation with independent representative test cases will show whether what you did was a good idea or not.
The fact that you have clusters means that you have to be careful if using resampling validation schemes (cross validation or out-of-bootstrap). However, the examples below show that the apparent clusters may not coincide with the important structures in the data generating process. So knowledge of clusters only tells you that you'll probably run into trouble with "naive" resampling of the cases, but you cannot conclude about how the appropriate regression and resampling set-ups. Therefore, an inner loop of resampling validation may not be able to guide your modeling.
Some situations from chemical calibration with different clustering as "symptom" and  conclusions for the appropriate regression model differing independent of the type of observed clustering.
In all examples, the concentration of some analyte is to be modeled.
Situation 1:
A number of calibration samples is obtained. From each of these calibration samples, a number of measurements is taken.
The reference value may be pre-specified (calibration samples are mixed accordingly), or samples are taken e.g. from a production process and reference values are measured with some other method.
You expect a strong clustering because of the repeated measurements, but per-cluster-regression is utterly meaningless. However, this situation is unproblematic, as you'd immediate notice that the information for the dependent variable is between the clusters, not within.
Situation 2:
Calibration samples are often prepared by dilution of a stock solution (German Wiki on serial dilution is much better than the English. Dilution series of several independently prepared stock solutions are measured.
Per-stock-regression may lead to better prediction of measurements from the same stock.
However, this is usually not appropriate, as rarely samples from the same stock are to be predicted.
You may see clusters in the independent data like in situation 1 that come from the fact that concentration series are usually prepared at "pretty" levels.
You may see the different stocks as clusters in the residuals (if instrument noise and random error in arithmetic dilution is << random error in concentration of stock solutions -- usually a bad sign wrt. the preparation).
Situation 3: You run into matrix effects and your data comprises a number of different matrices. In this case, per-matrix-regression is a valid option an can be much more successful than an overall regression.
Like in situation 2, you may encounter systematic patterns in the residuals of an overall regression.
Actually, you'd need to state for each regression model exactly in which situation it is appropriate. Your models cannot be expected to generalize to unknown matrices.
Answer: You could add them in as a categorical variable.


Chi Square test with massive difference in sample size

Question: Let's say I have a frequency table of two independent groups, structured like so:
Control  0.0    1.0    All
----------------------------
False    3648   2205    5853
True     33480  18132  51612
All      37128  20337  57465

And I want to run an A/B test to see whether the two randomly assigned populations performed a certain action.
Are these two populations so vastly different in sample size that it will mess up the math to see if there is a statistically significant relationship?
Comment: Please give the 2-way table with row and column totals. If `33480` is for Gp A, is it total in Bp A or is it count of subjects in A with 'no action'? How was it determined whether subject is in Gp A or Gp B. Random assignment? // Just tact that Gps A and B are of different sizes is not a problem. _Why_ so different may be.
Comment: Updated the frequency table, and added the margins. The two populations were just randomly assigned.
Comment: There is assumptions to the chisq regarding relative samples size between groups.  I see no problems performing the test.
Answer: One possibility is to consider binomial proportions of False responses in the two groups. Is the difference in the observed proportions false (roughly $0.098$ and $0.108,$ respectively), significantly different between the two groups?
In R, this test (which uses a normal approximation) is done using the prop.test procedure. (I have opted not to use continuity correction on account of the large
sample sizes.) The null hypothesis that proportions are equal is strongly rejected
with P-value $0.00012 < .05 = 5\%.$
 prop.test(c(3648, 2205), c(37128, 20337), cor=F)
      2-sample test for equality of proportions
      without continuity correction

data:  c(3648, 2205) out of c(37128, 20337)
X-squared = 14.851, df = 1, p-value = 0.0001163
alternative hypothesis: two.sided
95 percent confidence interval:
  -0.01540543 -0.00493134
sample estimates:
    prop 1     prop 2
0.09825469 0.10842307

An almost-equivalent test is to consider whether a chi-squared test of homogeneity
across Groups is rejected. The appropriate $2\times 2$ table and results of the
test are shown below. Again the null hypothesis of homogeneity between the two groups is strongly rejected.
False = c(3648, 2205);  True = c(33480, 18132)
TBL  = rbind(False, True);  TBL
       [,1]  [,2]
False  3648  2205
True  33480 18132

chisq.test(TBL)

        Pearson's Chi-squared test
        with Yates' continuity correction

data:  TBL
X-squared = 14.74, df = 1, p-value = 0.0001234

Notes: You can look at some of the "Related" pages (right margin) found by our robots for more details.
Alternatively, you can look at this NIST page on tests of binomial proportions. Another recent related page.
Comment: Thanks for a detailed response. I use python and used `chi2_contingency()` to arrive at the second result.


ASP.NET C# ListView ItemCommand não está funcionando

Question: Meu ItemCommand do ListView não funciona. Alguém consegue me apontar se há alguma coisa faltando ou erros no código?

    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
     <ContentTemplate>

                Foram encontrados <%=QuantResultados%> Produtos

                <asp:ListView ID="ListProduto" runat="server" DataKeyNames="ID_PRODUTO"
                onitemcommand="ListProduto_ItemCommand" >
                    <EmptyDataTemplate>

                            Não há produtos a serem mostrados

                    </EmptyDataTemplate>
                    <ItemTemplate>

                                <img class="image" src="../../Sessions/Company/img/Produtos/<%# DataBinder.Eval(Container.DataItem, "IMAGEM") %>"  alt="">

                                            <%# DataBinder.Eval(Container.DataItem, "NOME_PRODUTO") %>

                                        <%# DataBinder.Eval(Container.DataItem, "DESCRICAO") %>

 De:R$100

 Por:<%#String.Format("{0:c}", Eval("PRECO_PRODUTO"))%>

                                <asp:Button ID="AdicionaLista" class="AddToList" runat="server" CommandName="AdicionarProduto"  Text="Adicionar à Lista.." />

Ver empresa

                                            <%# DataBinder.Eval(Container.DataItem, "NOME_FANTASIA") %>

                                            <%# DataBinder.Eval(Container.DataItem, "RAMO") %>

                    </ItemTemplate>
                    <LayoutTemplate>
                     <asp:PlaceHolder runat="server" ID="itemPlaceholder"></asp:PlaceHolder>
                    </LayoutTemplate>
                </asp:ListView>

            </ContentTemplate>
 </asp:UpdatePanel>

Comment: Consegui Resolver, era só colocar no botão para não ter AutoPost. Obrigado pela Atenção.
Comment: Veja esse link https://msdn.microsoft.com/pt-br/library/4hx47hfe(v=vs.110).aspx
Comment: Pode colocar na sua pergunta o evento `ListProduto_ItemCommand`?
Comment: Seria interessante colocar a resposta e aceitá-la para sua pergunta não ficar em aberto :-)
Answer: <asp:Button ID="AdicionaLista" class="AddToList" runat="server" CommandName="AdicionarProduto"  Text="Adicionar à Lista.." Autopostback="false" />

Solução:
Autopostback="false"


window.open não está abrindo a popup

Question: Tenho uma extensão que envia coisas pra um servidor externo por ajax post (tudo em javascript) e a resposta do send (enviada do servidor) é recebida na própria extensão. Quero colocar essa resposta em uma outra pop-up. Como posso fazer isso? Tentei com window.open(...,'_self',...) mas não deu, não abre a janela. Alguém da alguma ajuda aí? obs: não sei usar jquery
Comment: Você poderia adicionar o código que faz o POST ajax? Assim fica mais fácil visualizar o que está fazendo.
Answer: Fiz um exemplo de extensão que permite fazer o que você pediu.
No arquivo manifest.json é necessário adicionar uma permissão para ter acesso ao host,
caso contrário não será possível executar o ajax. No caso, eu vou usar uma página de eco
do jsfiddle:
"permissions": [
    "http://jsfiddle.net/"   // aqui está a permissão necessária, para acessar o host
]

O resto é igualzinho ao desenvolvimento Web normal... dá até pra usar jQuery.
Eu coloquei o arquivo do jquery junto com os arquvos da extensão.
A versão usada é a que está linkada na listagem de arquivos abaixo.
Arquivos

jquery-1.11.2.min.js
manifest.json
{
  "manifest_version": 2,

  "name": "Extensão de teste, com Ajax e Janela de Pop-up",
  "description": "Extensão de teste, com Ajax e Janela de Pop-up",
  "version": "1.0",

  "browser_action": {
    "default_popup": "popup.html"
  },

  "permissions": [
    "http://jsfiddle.net/"
  ]
}

popup.html
<!doctype html>

    <title>Abrindo resultado de ajax em outra tela</title>

    <button id="btn">Abrir conteúdo em outra janela</button>

popup.js
$(function() {
    $('#btn').click(function() {
            $.ajax({
                url: 'http://jsfiddle.net/echo/html/',
                data: {
                    html: '
Documento carregado via ajax!
',
                    delay: 1
                },
                type: 'POST',
                success: function(data){
                    var win = window.open(
                        "",
                        "Title",
                        "toolbar=no,"+
                        "location=no,"+
                        "directories=no,"+
                        "status=no,"+
                        "menubar=no,"+
                        "scrollbars=yes,"+
                        "resizable=yes,"+
                        "width=780,"+
                        "height=200,"+
                        "top="+(screen.height-400)+","+
                        "left="+(screen.width-840));
                    win.document.body.innerHTML = data;
                },
                error: function() {
                    alert("error: "+JSON.stringify(arguments));
                }
            });
            return false;
        });
});

window.open não está abrindo a popup


Tamanho da fonte no jasperreport

Question: Alguém saberia me explicar, porque não altera o tamanho da fonte ao gerar o pdf?
A fonte que está definida, é o padrão SansSerif TAMANHO 15, porém sempre aparece no pdf o tamanho 10 Porque?
Ps..: lembrando que a opção PdfEmbedded esta marcada!
Answer: O problema é que faltar .jar da fonte em questão no seu projeto, procura um .jar do seu gosto e adiciona na biblioteca do seu projeto!

Tamanho da fonte no jasperreport


(Answered: A Persian Tar) What is the name of this stringed instrument? It is stringed, skinny, and has a hour-glass-shaped-body

Question:
What is the name of this stringed instrument?
If any are curious as to where I got this image from, it is here:

Comment: It's stated in the video's description.
Answer: Looks like a Persian tar to me.
Comment: What reasoning was used for this to be construed as an unacceptable answer. Short, true, nevertheless correct.
Comment: Tim - looks like an auto flag based on length


Prediction of features given predictor

Question: I am working on a problem where my objective is to predict y given some features x1,x2,x3,...x8,x9 I solved this problem using some statistical and machine learning techniques like regression, trees, random forests & svm. Now that I have a prediction for y, at a given x1,x2,x3..x6 I would like to achieve an optimal value of y, by changing some values of xn which are in my control. Let us say that y was predicted to be 5, however I need a value of 10. Can I put three features aside say x1,x2,x3 and get like a range or values for the aforementioned aside features such that the value of y is 10?
Basically, it is sort of like an inverse problem, where assuming I know the predictor I need to manipulate the features to increase the value of the predictor.
Reproducible example:
    y<- rnorm(100)
x1<- sin(rpois(100))
x2<- cos(rnorm(100))
x3<- sin(rnorm(100))+ rnorm(100)* 3cos(rnorm(100))
x4<- rnorm(100)
y.fit<- lm(y~x1+x2+x3+x4)
library(caret)
y.rf<- train(ROP~ .,data=training,method="rf",prox=TRUE)

So now that I have y.rf and y.fit, lets say i have control over the  values of x1 & x2, hence I would like a given value of y say 0.5, and to achieve this value of y (0.5) at a fixed value of x3,x4 I would like a range for x1 and x2 or possible values for x1 & x2.
How should I proceed?
Comment: Check the following papar: The inverse classification problem
http://jcst.ict.ac.cn:8080/jcst/CN/article/downloadArticleFile.do?attachType=PDF&id=9242
Comment: Look into **Response Surface Analysis**, for example https://stats.stackexchange.com/questions/296760/design-of-experiments-for-baking
Answer: From what I understood, you would like to modify the features given the prediction label. I would say that this problem is pretty ill-posed. Why? Imagine you have three distinct data clusters where each cluster is a class. Obviously each data point belonging to its class carries a label from that class. The important point here that there are different points from one particular class carrying the same label but with different features. With no additional info you cannot go back from label to features. One straight forward way would be to map from label to class centroid. If instead of a label you had some measure (like a probability) belonging to that cluster and you had fit a Gaussian (for example) on that class, you could get the corresponding feature... But this is pretty hacky, not sure about applications.
Comment: Think about it from an engineering perspective, where you would like to get you set the speed of the wood slicer at 60 slices per minute, and one can change a few parameters like the speed of the chopper, sharpness of chipper teeth etc. , but some parameters are not changeable like the kind of wood. So after prediction of the speed of cutting the wood, I would like to achieve an optimal speed, so I would like to know what level I have to set the other parameters so that I can achieve this. Basically using the statistical model as a formula and using the inverse option!
Answer: It is rather difficult to get your exact answer, but I can see a quick improvement to help you get closer to what you'd like.
First rather than trying to find how to tweak your features to get y from 5 to 10, you can calculate the gradient, or more simple the sensitivity of y to each of your features at 5.  This way you can know 'locally only' how to move your factors to move slightly closer to 10 from 5.  If your relationships of your factors to y is simple enough, then you may be able to iterate this to convergence.
This has several issues.  For one, using your example, is it not known whether the factor values that set y=10 are unique or if they even exist.
Another issue, and implied by xeon above, is that your estimation of y is a a distribution and not a deterministic value.  Because of this, when you are fitting you need to know what you are optimizing for.   Do you want to find the factor levels where your mean estimate of y is 10, or median estimate, etc...?
Comment: That makes a lot of sense, I am not sure that my model is simple enough, but I would like to give the sensitivity thing a try. How would I go about calculating the sensitivity of my features at y=5 or at y=10?
Comment: It will be slightly different for each model used.  However on the simpler models like linear regression, the sensitivity is simply the coefficients (Betas) in the model `y = beta*x`.  For more complicated models, it might be enough for you to just calculate the derivative of y with respect to the factor you care about.

Prediction of features given predictor


Backup Exec: Seeking guidance on hands-off backup-to-disk strategy

Question: In a nutshell:

SBS03 server with Backup Exec 12
installed.
Two USB drives, each 1TB.
USB drives are swapped weekly.

A weekly full backup and 4 days of subsequent backups just about fills a drive. After swapping a drive, the next Weekly Full job will throw an alert about low space and we have to manually clean out the drive so that the backup will finish. I know there's a way to dial this in so that Backup Exec will manage that space for us, but I can't seem to hit the right settings!
The media set properties for "media set periods" are currently at:

Overwrite protection period: 13 days
Append period: 1 hour

The weekly job is set to "Append to media, overwrite if no appendable media is available"
[added later] Tools -> Options -> Media Management had "media overwrite protection" at the default "Partial" setting.
What other settings am I missing to get this working without intervention?
Comment: Under the 'Media' tab in Backup Exec, take a look at the media sets that are allocated on those backup-to-disk folders. Are any of them listed as 'Overwriteable' even though the jobs are complaining about no media available? If so, you're hitting the exact same problem I am right now, and I'm planning log a call with Symantec next week...
Comment: Yeah, they're now at 8 days overwrite protection / 1 hour append period.
Answer: Sounds to me like your Overwrite Protection Period is the culprit.
Have you tried lowering the threshold on that value?  For what it's worth, I utilize that value only to be sure that I don't mistakenly overwrite a particular backup.  In your case, that would be 8 days.  (Assuming you always do the full on the same day of the week).
I have found that the protection periods are really draconian in their calculations, so keeping it shorter is better.  With 8 days, you will still ensure that the second week doesn't overwrite the first, but you should also be safe from it forcing you not to be able to overwrite. (For what it's worth, I am fairly certain that the overwrite period begins at the time the backup job completes)
The "Append to media, overwrite if no appendable is available" setting merely tells BE to err on the side of saving the data if it's possible, but that setting will not allow you to overwrite something that is still in overwrite protection.
Hopefully this helps some, and if not, let me know and I will see what else I can come up with.
Comment: Ahh... "I am fairly certain that the overwrite period begins at the time the backup job completes." That may be the issue. I'll try your suggestion of 8 days (or anything less than 13 really (weekly takes over 12 hours).
Comment: +1. It sounds to me like the overwrite protection settings are the culprit. The overwite protection is calculated based on the modified date, not the allocated date so in this case 13 days is too long. The overwrite settings need to be calculated from the last date that a backup is performed on that particular piece of media.
Comment: I'll know tomorrow :-)
Comment: ... Nope, changing from 13 to 8 days didn't do anything for me. I've now visited Tools -> Options -> Media Management and changed it "Media Overwrite Protection level" from Partial to None.
Answer: Are the backup sets contained on second drive created more than 13 days ago when you connect it to be used?  If not then drive will appear appear as full (based on the fact that you stated the full backup and four days worth of backups fill the drive).  You may need to lower the overwrite protection period.
Comment: Yes, they weekly runs every 7 days, same as the drive rotations. So... in theory... the jobs should be 14 days old. However, if the timer starts when the weekly job *finishes* then my times are off by a day.
Comment: I would change your overwrite period to 12 days then and see if that solves it.  You don't want to set it too low and end up overwriting data sets you might need.


Lambda expression Where on navigation property

Question: Good afternoon,
I have three entities (that concern this question)
Company (ID, etc..)
CompanyAddress (AddressID, CompanyID, Rank)
AddressDetails (AddressID, Street, City, State, Zip)
The reason Rank and company id aren't in the AddressDetails is because the address details are shared with contacts via a ContactAddress entity.
Anyway, I need to build an IQueryable given an IQueryable that will check if a string is contained in the City (and eventually or state).  I'd like to use Lambda expressions not the from c in companies syntax...I tried
query = query.Select(c => c.Addresses.Where(a => a.AddressDetails.City.Contains(City)).Select(ca => ca.Company));

In this example c.Addresses is the navigation property for CompanyAddress.
Thanks for any help,
Paul
Comment: I should add that c.Addresses is a collection so doing c.Addresses.AddressDetails.City.Contains(City) will not work.
Answer: I think that this will work:
query = query.Where(c => c.Addresses.Any(a => a.AddressDetails.City.Contains(City)));

I assume that query is IQueryable<Company>.
Comment: Thanks...I need to get to know the Any extension method a bit better...It didn't even occur to me.
Comment: `Any` is something like `exists` in sql.


Filter data in a big matrix in MATLAB

Question: In MATLAB, I am dealing with a matrix URm of size [200K*150K] whose elements are between [0-5].
I would like to filter the values so I can have access the matrix enteries whose values are [4-5] and [1-2]. I am successful in the first case but I encounter error while trying to use the second one.
  Upos = sparse(URm > 3)       ;
  Uneg = sparse(URm<3 & URm>0) ;

I can obtain Upos but for Uneg, I encounter the following error:
Error using  <
Requested 30711160620x1 (228.8GB) array exceeds maximum array size   preference. Creation
of arrays greater than this limit may take a long time and cause MATLAB to become
unresponsive. See array size limit or preference panel for more information.

Error in Provide_Information_about_URm (line 14)
Uneg = sparse(URm<3 & URm>0)

The error is more probably rooted on the fact that MATLAB generates an inner matrix before & operation is applied which takes huge space. How do you think the problem can be solved? Thanks for your opinions in advance.
Answer: Your expression URm<3 is true for several values, including all zeros of URm, which is probably nearly every element. This results in a very large sparse matrix with only few nonzero elements.
Instead rewrite the logic in a way you never select the zeros
Uneg=xor(URm>=3,URm>0)

Comment: This is true, most of values in the matrix are <=3 and infact zero. To help, I am using sparse matrices. How can the problem be solved? I prefer to avoid loops!
Comment: @Yas: Updated my answer, took my some minutes to come up with a solution.
Comment: Daniel, brilliant idea! It works very well , thank you :-)

Filter data in a big matrix in MATLAB


how to initialize static array within struct

Question: I have this struct:
typedef struct {
    int start;
    int end;
    char board[10][10];
} move;

when I try initializing it this way:
char new_board[10][10]
move struct new_move = {0, 0, new_board}

I get this error:
warning C4047: 'initializing' : 'char' differs in levels of indirection from 'char (*)[10]'
any suggestions?
Answer: If you want to initialize the array by zeroes then you can write simply
move new_move = { 0 };

If you want that the structure array would contain values of array char new_board[10][10] then you have to copy its element in the structure array.
for example
char new_board[10][10] = { /* some initializers */ };

move new_move = { 0 };

memcpy( new_move.board, new_board, sizeof( new_board ) );

If board is an array of strings then you could also to copy using a loop each string in the structure array using standard C function strcpy.
Answer: First - the reason why you can't do this: if you do something like this you are saying to the compiler that you're trying to overwrite a constant pointer (a table is a constant pointer).
You can initialize the array by using two four loops like this:
int i, j
for (i = 0; i < 10; i++)
    for (j = 0; j < 10; j++)
        new_move.board[i][j] = new_board[i][j];

That should work best in my opinion.


Dominant 7 alt vs tritone sub

Question: Why do we use Dominant 7th alt term. Because the dominant 7th alt is basically the tritone sub but with a natural and flat nine and flat five with the flat 5 in bass. I mean i guess g7alt is better than reading Db7(nat.9,b9,b5)/G
Comment: Sorry, I don't understand your question. Could it be that some words got lost? Would you please reread and eventually make some corrections or precisions?
Comment: I think the question is about the terminology used to name the chord, rather than when to use the chord itself.
Answer: You are right in that a ♭II7 tritone sub chord with a ♭V in the bass sounds essentially like a V7alt chord but your analysis of "Db7(nat.9,b9,b5)/G" being a G7alt is not quite right. In the keys you referenced a G7alt contains ♭9, #9, ♭5 and ♭13. This is basically the same as a D♭13#11 Which has 9, #11, 13. They have the same notes but they have different roots.
The root largely defines the chord and the way it functions in a chord progression so it's better to spell a chord from the root when possible. That's why we use the term "alt". I'm sure I'm not alone in saying that I would rather see G7alt over a D♭13#11/G on a chart. As a musician, bass player and improviser I even approach the two differently when creating walking lines or improvising. Hope this answers your question.
Comment: Yeah most people at least myself still voice the 5th of the g7 in the g7 alt giving essentially a Db13,9,b9/G because you have to take in account the actual g7 your playing under extensions i mean i know you dont have to voice 5th but it adds more tension
Comment: It's true that the natural 5 will add even more tension to an already tension filled chord. I however think of the 7alt chord as having a b5 because the scale that is often used to play over it, the 7th mode of the melodic minor (R b9 #9 3 b5 b13 b7) has no natural 5.
Answer: We can use V7(b5b9)or its triton substitution when ever we want, just the way we like it.
There's no rule, no law or principle why we should choose the one or the other.
Sometimes it is comfortable to progress chromatically down steps walking through the circle of fifths, especially the bass line.
Comment: The question is asking: "what's the point in describing a chord as an altered dominant if we could more simply just describe it as a tritone substitution? After all, the two chords (altered dominant and tritone sub) share the same notes."

Dominant 7 alt vs tritone sub


How to change dynamically dropdown values in Angular 8?

Question: I have dropdown which is related another dropdown with ID. I would like to change dynamically when I change dropdown value it should automatically change in another one. In backend I am using aspnet core and getting data using services.
My components looks like:
   ngOnInit() {
    this.model.managementId = 1    // this should be also dynamic which I don't know how
    this.model.mfp = this.getManagementsForProject()
    this.range = this.getRange()
  }

  getRange() {
    this.mgmtSerive.getRange(this.model.managementId).subscribe(h => this.range = h)
  }

  getManagementsForProject() {
    this.ms.getManagementsForProject().subscribe(u => this.model.mfp = u);
  }

My html dropdowns:

        Network

        <mat-form-field class="example-full-width">
          <select matNativeControl required name="managementId"
         [(ngModel)]="model.managementId">
            <option value="-1" disabled>--Please select network--</option>
            <option *ngFor="let item of model.mfp" [ngValue]="item.managementId">
              {{ item.managementName }}
            </option>
          </select>
        </mat-form-field>

        IP Address

        <mat-form-field class="example-full-width">
          <select matNativeControl required name="ipAddress" [(ngModel)]="model.ipAddress">
            <option value="-1" disabled>--Available Networks--</option>
            <option *ngFor="let item of range">
              {{ item }}
            </option>
          </select>
        </mat-form-field>

My backend methods looks like:
        [HttpGet("range/{id}")]
        public IActionResult GetRange(int id)
        {
            var selectedNetworkRange = _context.NetworkRanges.FirstOrDefault(x =>
            x.ManagementId == id);
            var vmIpAddresses = _context.VirtualMachines.Select(x => x.IpAddress);
            if (selectedNetworkRange != null)
            {
                var cidr = selectedNetworkRange?.Start + "-" + selectedNetworkRange?.End;
                var cidrRange = IPAddressRange.Parse(cidr)
                    .AsEnumerable()
                    .Select(adr => adr.ToString());
                var result = cidrRange.Except(vmIpAddresses).ToList();
                return Ok(result);
            }

            return Ok("Something failed");
        }

    [HttpGet("managementforproject")]
    public IActionResult GetManagementForProject()
    {
        var model = from management in _context.Managements
            select new {ManagementName = management.Name, ManagementId = management.Id};
        return Ok(model);
    }

When I change management dropdown I would like dynamically update Range dropdown. I know I am using managemntId = 1 inside ngOnInit but how to change dynamically I don't know.
Comment: You need to detect the change in `ngModel` value of the first drop down using `(ngModelChange)`  and then pass that value to bind next drop down values.
Comment: @Mridul works like charm
Answer: You could implement change event on  tag or click on  tag.

Change

Your html:

    <mat-form-field class="example-full-width">
      <select (change)="updateID($event)" matNativeControl required name="managementId"
     [(ngModel)]="model.managementId">
        <option value="-1" disabled>--Please select network--</option>
        <option *ngFor="let item of model.mfp" [ngValue]="item.managementId">
          {{ item.managementName }}
        </option>
      </select>
    </mat-form-field>

Your ts:

ngOnInit() {
    this.model.managementId = 1    // this should be also dynamic which I don't know how
    this.model.mfp = this.getManagementsForProject()
    this.range = this.getRange()
  }

  updateID(event) {
  this.model.managmentId = event.something probably
  }

  getRange() {
    this.mgmtSerive.getRange(this.model.managementId).subscribe(h => this.range = h)
  }

  getManagementsForProject() {
    this.ms.getManagementsForProject().subscribe(u => this.model.mfp = u);
  }

Click

Your html:

    <mat-form-field class="example-full-width">
      <select matNativeControl required name="managementId"
     [(ngModel)]="model.managementId">
        <option value="-1" disabled>--Please select network--</option>
        <option (click)="updateID(item.managmentId)" *ngFor="let item of model.mfp" [ngValue]="item.managementId">
          {{ item.managementName }}
        </option>
      </select>
    </mat-form-field>

Your ts: would be the same as #1.
Comment: what should be instead of event something?
Comment: You console log data and see what is there, for example, if it is an object like this:

{ value: 15 },

 then you say:

 updateID(event) {
  this.model.managmentId = event.value
 }

But in second case, on click method you can say directly:

 updateID(id: string) {
  this.model.managmentId = id
 }


Abrir script na mesma janela

Question: Estou utilizando um script para juntar strings e abrir um link, porém, ele abre em uma nova guia. Preciso que seja aberto na mesma janela.
<form>
<input name="url" type="text" id="cpf">
<input type="button" id="btn" value="Acessar" onClick="javascript: window.open('http://site.com.br/' + document.getElementById('cpf').value + '-2/');"

Comment: Ao usar `window.open` você está explicitamente dizendo para abrir uma nova janela. Pesquise como fazer para **redirecionar** o usuário.
Answer: Para abrir na mesma janela o comando seria:
<form>
<input name="url" type="text" id="cpf">
<input type="button" id="btn" value="Acessar" onClick="javascript: window.location.href = 'http://site.com.br/' + document.getElementById('cpf').value + '-2/';"

O window.open é utilizado para criar uma nova janela, já o window.location.href vai indicar para o navegador que o novo endereço deva ser o parâmetro que está sendo informado.
Também pode ser utilizado o window.location.assign(url), conforme referências listadas abaixo.
Referências:
window.open : https://developer.mozilla.org/pt-PT/docs/Web/API/Window/open
window.location : https://developer.mozilla.org/pt-BR/docs/Web/API/Window/location

Abrir script na mesma janela


Examples of Many-one reductions.

Question: I'm trying to wrap my head around many-one reductions for an assignment in Mathematical Logic.
The assignment is to show
$A$ r.e $\Leftrightarrow$ $A\leq_m K$ where $K=\{x\in\mathbb{N}\ |\ x\in W_x\}$
($W_x$ is the domain of the (Turnip-)program having code $x$)
I don't want you to solve this explicitly but rather give examples of many-one reductions to help me reason about them. I've tried using Google for this but haven't found anything that helps me.
Can you give examples of recursively enumerable sets that easily can be reduced to K?
For reference:
$A\leq_m B$ iff there is a total recursive function $f:\mathbb{N}\rightarrow \mathbb{N}$ such that $x\in A\Leftrightarrow f(x)\in B$
Comment: Presumably, the spelling corrector changed Turing to turnip...
Comment: @ThomasAndrews Nope, it is actually the correct one. I have only seen it in my course book though http://www.oup.com/us/catalog/general/subject/Mathematics/Logic/~~/dmlldz11c2EmY2k9OTc4MDE5ODUyOTgwNA==

One defines $T^{++}$-programs on Turnip machines. It's kinda silly.
Comment: Ah, it's probably using something different enough from Turing machines to make the Johor want to avoid using that name
Comment: The way I think about $A \leq_{m} B$ is that we can determine if $a \in A$ (or not) by asking a single, effectively determinable question about $B$. So if we have knowledge of $B$ (i.e. you can always tell if $b\in B$), the we also have knowledge of $A$ (since we have access to $f$). This is a way of describing the idea that $A$ can be computed from $B$, though, as @William indicated, this is not the most general way since a single pre-specified question about $B$ is too stringent.
Answer: Well a standard r.e. set is $A=\{x:W_x\ne \emptyset\}$. For each $x$, we can define a function
$$g_x(n)=\begin{cases}
0 &\text{if } (\exists m)[\varphi_x(m)\downarrow]\\
\uparrow &\text{otherwise}
\end{cases}$$
and let $f$ be the function which takes $x$ to an index of $g_x$ (i.e. some $y$ such that $g_x=\varphi_y$).
Comment: Thank you! It's so simple as soon as you understand how it works. On question though: Why is $f$ recursive? I'm guessing that I'm missing some simple fact about it.
Comment: @Hashmush Well $f(x)$ is just the Godel number (or whatever enumeration you choose) of $g_x$, and the definition I've given can be turned into a Godel number by some standard algorithm (the algorithm being independent of $x$), after you replace $\varphi_x$ with the symbols defining $\varphi_x$.
Comment: @Hashmush He's employing the [Church-Turing thesis](http://en.wikipedia.org/wiki/Church%E2%80%93Turing_thesis) to conclude $f$ is computable (because proving it rigorously would very tedious).
Answer: Let $H = \{(e,x) : \Phi_e(x)\downarrow\} = \{(e,x) : x \in W_e\}$. $H$ is your standard Halting Problem set, which asserts that $(e,x) \in H$ if and only if the $e^\text{th}$ Turing program halts on input $x$.
A very useful fact is that $H \equiv_m K$, i.e. $H \leq_m K$ and $K \leq_m H$. It is clear that $K \leq_m H$. To show $H \leq_m K$, there exists a computable function $f$ such that $\Phi_{f(e,x)}(z)$ halts on any input $z$ if and only if $\Phi_e(x) \downarrow$. To precisely prove that $f$ is computable, you will likely need to use the s-m-n theorem. However appealing the Churing-Turing Thesis, given $e$, $x$, and $z$, make a program $\Psi$ such that $\Psi(e,x,z)$ halts if and only if $\Phi_e(x)\downarrow$ (note $z$ is not used at all). Because of the obvious uniformity (or use s-m-n theorem to be precise), there is a computable $f$ such that $\Psi(e,x,z) = \Phi_{f(e,x)}(z)$. Then $x \in H$ if and only if $\Phi_{f(e,x)}(f(e,x)) \downarrow$ if and only if $f(e,x) \in K$.
Hence this shows that $H \equiv_m K$.
Now to prove that $A$ is c.e. if and only if $A \leq_m K$. If $A$ is c.e., by definition $A = W_e = \text{dom}(\Phi_e)$ for some $e$. Hence $x \in W_e$ if and only if $(e,x) \in H$. Thus $A \leq_m H$ using the computable function $f(x) = (e,x)$. Since it was just shown that $H \leq_m K$, $A \leq_m K$ by transitivity of $\leq_m$. Suppose $A \leq_m K$. Then there is a computable function $f$ such that $x \in A$ if and only if $f(x) \in K$. Since $K$ is c.e., define
$\Psi(x) \begin{cases}
1 & \quad f(n) \in K \\
\uparrow & \quad \text{otherwise}
\end{cases}$
is a partial computable function. hence $\Psi = \Phi_i$ for some $i$. Then $x \in A$ if and only if $\Psi(x) \downarrow$ if and only $x \in \text{dom}(\Phi_i)$ if and only if $x \in W_i$. Hence $A = W_i$. Thus $A$ is c.e.

This result shows that $K$ is $m$-complete, which is means every c.e. set is reducible to it. Another example, which is also a standard exercise in $m$-reducibility, is to show that $\{e : W_e \neq \emptyset\}$ is also $m$-equivalent to $K$.
An obvious example is $\emptyset \leq_m K$, but $K \not\leq_m \emptyset$.

$A \leq_m B$ means roughtly that there is a "very computable procedure" to determine membership in $A$ if you know about membership in $B$. So to solve reduciblity questions, you should think about how use $B$ to know about $A$, as in the example of obtaining above, where I reduced $H$ to $K$ and $K$ to $H$.
I say "very computable procedure" because there is a more general notion of Turing reducibility $A \leq_T B$, which more accurately means knowing $A$ computably from $B$.
Comment: Thank you, though I explicitly stated that I didn't want you to solve it. Just provide examples.

Examples of Many-one reductions.


Calculate percentages on ranges

Question: I have the following table with data:
+----------+------------+-----------+
| country  | age        | gender    |
+----------+------------+-----------+
| China    |    15      |  male     |
+----------+------------+-----------+
| China    |     25     |   female  |
+----------+------------+-----------+
| China    |     50     |  male     |
+----------+------------+-----------+
| China    |     62     | male      |
+----------+------------+-----------+
| Burma    |     25     |   female  |
+----------+------------+-----------+
| Burma    |     50     |  male     |
+----------+------------+-----------+
| France   |    27      | male      |
+----------+------------+-----------+
| France   |    55      | female    |
+----------+------------+--------- -+

I want to query select with the following result:
+----------+-----------+---------+-----------+-----------------+----------------+
| region   | age_range |  gender | count     | gender_percent  | total_percent  |
+----------+-----------+---------+-----------+-----------------+----------------+
| Asia     |  0-49     | male    |   1       |     33          |   12.5         |
+----------+---------- +---------+-----------+-----------------+----------------+
| Asia     |  0-49     | female  |   2       |     67          |   25           |
+----------+-----------+---------+-----------+--------------- -+----------------+
| Asia     |  50+      | male    |   3       |   100           |   37.5         |
+----------+-----------+---------+-----------+-----------------+----------------+
| Europe   | 0-49      | male    |   1       |    100          |  12.5          |
+----------+-----------+---------+-----------+-----------------+----------------+
| Europe   | 50+       | female  |   1       |    100          |  12.5          |
+----------+-----------+------- -+-----------+-----------------+----------------+

Ie. I want to calculate different percentages on ranges of data. One percentage for gender to each range of countries (region) and age range, and one percentage relative to the total count.
How do I do this?
I will prefer a cross RDBMS solution, which is as less hard coded as possible. Speed and simplicity are also major dimensions. I am developing on MySQL but the solution will later be ported to Oracle as well as MS SQL.
Thanks a lot in advance.
Comment: @naruto, yes both solutions will be suitable and interesting. Thx.
Comment: Partial solution similar to
http://stackoverflow.com/questions/4645322/how-to-group-number-of-users-by-age-bands-in-mysql
Comment: Why are people down rating this question? I cannot find similar question, only small parts of it. The question is not only about ranges.
Comment: Region must be hard coded same as age ranges, i.e. that China and Burma belong to Asia and so forth. Thx.
Comment: from where you get region?
Comment: You cant do that. You need that data in some where. Sql isnt google maps
Comment: @HenrikHansen Yes ,either you have to store region data in DB and then join table and map it or use hardcoded query to tell that this country belongs to this region.
Comment: If I can case when `age`<50 then `0-49`I guess I can do same with region case when `Burma` then ´Asia`? Or why not?
Answer: Here is the full answer. Anyway, I wouldnt have been able to make it without the answer from @Juan Carlos Oropeza. Thanks again to Juan :-)
SELECT region.*,
   (`count` / region_range_total.gender_total) * 100 as gender_percent,
   (`count` / (select count(*) from country)) * 100 as total_percent
  FROM
   (
    SELECT
      CASE country
        WHEN 'China' then 'Asia'
        WHEN 'Burma' then 'Asia'
        WHEN 'France' then 'Europe'
      END region,
      CASE WHEN age < 50 then '0-49'
         ELSE '50+'
      END age_range,
      gender,
      count(country) as `count`
  FROM country
  GROUP BY
      region,
      age_range,
      gender
  ) region
JOIN
  (
  SELECT
      CASE country
        WHEN 'China' then 'Asia'
        WHEN 'Burma' then 'Asia'
        WHEN 'France' then 'Europe'
      END region,
      CASE WHEN age < 50 then '0-49'
          ELSE '50+'
      END age_range,
      count(country) as gender_total
  FROM country
  GROUP BY
      region,
      age_range
 ) region_range_total
 ON region.region = region_range_total.region
 AND region.age_range = region_range_total.age_range

Comment: You could use `WHEN country IN ('China', 'Burma') THEN 'Asia' ELSE 'Europe'`.
Comment: Yes, that's even better :-) Thx.
Comment: good, Just try to avoid use field names like `count` because those are reserved words in the sql lenguaje and can be confusing.
Comment: @Juan Carlos Oropeza, I fully agree with you. In real life, I would always prefix variables for several reasons...
Answer: I put region as a column in country. In the select I use CASE to get range label. You can do the same for region if dont want add the region field
CREATE TABLE country
    (`region` varchar(6), `country` varchar(6), `age` int, `gender` varchar(6))
;

INSERT INTO country
    (`region`, `country`, `age`, `gender`)
VALUES
    ('Asia', 'China', 15, 'male'),
    ('Asia', 'China', 25, 'female'),
    ('Asia', 'China', 50, 'male'),
    ('Asia', 'China', 62, 'male'),
    ('Asia', 'Burma', 25, 'female'),
    ('Asia', 'Burma', 50, 'male'),
    ('Europe', 'France', 27, 'male'),
    ('Europe', 'France', 55, 'female')
;

SqlFiddleDemo
SELECT region.*,
       (count_range_gender / region_range_total.gender_total) * 100 as gender_percent,
       (count_range_gender / world.world_total) * 100 as total_percent
FROM
    (
      SELECT `region`,
             CASE WHEN age < 50 then '0-49'
                  ELSE '50+'
             END age_range,
             gender,
             count(country) as count_range_gender
      FROM country
      GROUP BY `region`,
               CASE WHEN age < 50 then '0-49'
                    ELSE '50+'
               END,
               gender
      ) region
JOIN
    (
      SELECT `region`,
              CASE WHEN age < 50 then '0-49'
                  ELSE '50+'
              END age_range,
              count(country) as gender_total
      FROM country
      GROUP BY `region`,
               CASE WHEN age < 50 then '0-49'
                    ELSE '50+'
               END
     ) region_range_total
  ON region.region = region_range_total.region
 AND region.age_range = region_range_total.age_range
CROSS JOIN
    (
      SELECT count(country) as world_total
      FROM country
     ) world

OUTPUT
| region | age_range | gender | count_range_gender | gender_percent | total_percent |
|--------|-----------|--------|--------------------|----------------|---------------|
|   Asia |      0-49 | female |                  2 |        66.6667 |            25 |
|   Asia |      0-49 |   male |                  1 |        33.3333 |          12.5 |
|   Asia |       50+ |   male |                  3 |            100 |          37.5 |
| Europe |      0-49 |   male |                  1 |            100 |          12.5 |
| Europe |       50+ | female |                  1 |            100 |          12.5 |

EDIT
In MySql you can also use IF(age < 50, '0-49', '50+')
Comment: Nice solution. However, in the SQLFiddleDemo the total_percent is wrongly calculated... (I had made it wrongly for gender_percent for Europe, which I have corrected). Thanks a lot so far :-)
Comment: Also, how to do it, if the region info is not in the source table? Thanks again.
Comment: @HenrikHansen If the region info is not in the source table, you must tell us where it is in your database schema... Actually, not only the region info, but the association between the region info and the country...
Comment: The region info is supposed to be hard coded (or be in a separate region table) - same as the age ranges. Thx.

Calculate percentages on ranges


high number of bytes read from write queue

Question: If you see a high number of reads from write queue for a program, what would you guess about that programs behavior?
I have noticed for majority of programs there are very few bytes read in total from the write queue but this is not true for one case which I'm studying. I'm trying to explain that.
I'm using gem5 for my simulations btw.
Answer: You mean store-forwarding?  That probably means the program has a lot of store/reload.
e.g. from passing args on the stack, and/or by reference so the caller has to store and the callee has to reload (if the function doesn't inline).
If you're simulating x86, even call/ret can reload the return address from the store buffer.


PowerMockito 2 on Java 11 error when running test: class javax.xml.parsers.FactoryFinder cannot access class jdk.xml.internal.SecuritySupport

Question: I get an error when running my PowerMockito2 tests on Java 11.
I was able to resolve this error by putting this annotation at class level but I do not want to do this. Is there a way not to get this error without using @PowerMockIgnore?
@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*"})

Gradle Dependencies:
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.powermock:powermock-api-mockito2:2.0.9'
testImplementation "org.powermock:powermock-module-junit4:2.0.9"

Error when starting tests:
class javax.xml.parsers.FactoryFinder (in unnamed module @0x4d96fc12) cannot access class jdk.xml.internal.SecuritySupport (in module java.xml) because module java.xml does not export jdk.xml.internal to unnamed module @0x4d96fc12
java.lang.IllegalAccessError: class javax.xml.parsers.FactoryFinder (in unnamed module @0x4d96fc12) cannot access class jdk.xml.internal.SecuritySupport (in module java.xml) because module java.xml does not export jdk.xml.internal to unnamed module @0x4d96fc12
    at javax.xml.parsers.FactoryFinder.<clinit>(FactoryFinder.java:69)
    at javax.xml.parsers.SAXParserFactory.newInstance(SAXParserFactory.java:147)
    at ch.qos.logback.core.joran.event.SaxEventRecorder.buildSaxParser(SaxEventRecorder.java:79)
    at ch.qos.logback.core.joran.event.SaxEventRecorder.recordEvents(SaxEventRecorder.java:57)
    at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:151)
    at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:110)
    at ch.qos.logback.core.joran.GenericConfigurator.doConfigure(GenericConfigurator.java:53)
    at ch.qos.logback.classic.util.ContextInitializer.configureByResource(ContextInitializer.java:75)
    at ch.qos.logback.classic.util.ContextInitializer.autoConfig(ContextInitializer.java:150)
    at org.slf4j.impl.StaticLoggerBinder.init(StaticLoggerBinder.java:84)
    at org.slf4j.impl.StaticLoggerBinder.<clinit>(StaticLoggerBinder.java:55)
    at org.slf4j.LoggerFactory.bind(LoggerFactory.java:150)
    at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:124)
    at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:417)
    at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:362)
    at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:388)
    at foo.bar.fooService.<clinit>(fooService.java:22)
    at java.base/java.lang.Class.forName0(Native Method)
    at java.base/java.lang.Class.forName(Class.java:315)
    at javassist.runtime.Desc.getClassObject(Desc.java:72)
    at javassist.runtime.Desc.getClassType(Desc.java:181)
    at javassist.runtime.Desc.getType(Desc.java:151)
    at javassist.runtime.Desc.getType(Desc.java:107)
    at foo.bar.fooServiceTest.setUp(fooTest.java:72)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.junit.internal.runners.MethodRoadie.runBefores(MethodRoadie.java:133)
    at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:96)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:310)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:131)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.access$100(PowerMockJUnit47RunnerDelegateImpl.java:59)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner$TestExecutorStatement.evaluate(PowerMockJUnit47RunnerDelegateImpl.java:147)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.evaluateStatement(PowerMockJUnit47RunnerDelegateImpl.java:107)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:298)
    at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)
    at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:218)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:160)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:134)
    at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
    at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:136)
    at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:117)
    at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:57)
    at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
    at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:43)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
    at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133)
    at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
    at org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:82)
    at org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:73)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:248)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$5(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:226)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:199)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:132)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:99)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
    at com.sun.proxy.$Proxy5.stop(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.stop(TestWorker.java:133)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)
    at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:414)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
    at java.base/java.lang.Thread.run(Thread.java:834)

This is the reference with the @PowerMockIgnore work-around solution that I do not want to use.
Comment: I am also getting the same error .
Comment: @PrashantSingh I assume I never solved this or else I would have answered my own question. I think I ended up using `@PowerMockIgnore`.
Comment: @javaPlease42 is your issue resolved ? I am the facing same issue.
Answer: You'll find the answer here https://github.com/mockito/mockito/issues/1562#issuecomment-921605319
Try adding the following to the failing class
@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*"})


How to fill multidimensional array using an equation in python

Question: I am new to python and I would like to fill a Numpy multidimensional array using an equation. In Fortran I can use the index of the array to fill it up, is this possible to do in python? Say I have an equation a=i*j where i and j are the row and column position respectively. So if I have an n by n array then the array would be filled with the results from the equation, so first value would be 1 since a=1*1 and so on.
Comment: Possible, but not advisable. If you use Python loops to operate on your numpy arrays, you lose the real benefit of numpy, that is **speed**.
Answer: You could use numpy broadcasting to get this result:
i = np.arange(3)[:, np.newaxis]  # (3, 1)
# array([0, 1, 2])
j = np.arange(4)[np.newaxis, :]  # (1, 4)
# array([0, 1, 2, 3])
arr = i * j                      # (3 ,4)
# array([[0, 0, 0, 0],
#        [0, 1, 2, 3],
#        [0, 2, 4, 6]])

You can perform most calculations you could want with the index arrays i [n x 1] and j [1 x m] and the result will be always be [n x m]
arr = np.sin(i)**2 + np.cos(i)**2 + (j-i)
# array([[ 1.,  2.,  3.,  4.],
#        [ 0.,  1.,  2.,  3.],
#        [-1.,  0.,  1.,  2.]])

You could also use np.meshgrid() to explicitly repeat the indices along the other dimension to get full 2d arrays for  i and j:
i, j = np.meshgrid(np.arange(3), np.arange(4), indexing='ij')
# i
# array([[0, 1, 2, 3],
#        [0, 1, 2, 3],
#        [0, 1, 2, 3]])
# j
# array([[0, 0, 0, 0],
#        [1, 1, 1, 1],
#        [2, 2, 2, 2]])

arr = i * j
# array([[0, 0, 0, 0],
#        [0, 1, 2, 3],
#        [0, 2, 4, 6]])

This is a good visualisation of what happens during broadcasting automatically.
Note the indexing argument ij of np.meshgrid() for matrix indexing; from the docs:

Giving the string 'ij' returns a meshgrid with matrix indexing, while 'xy' returns a meshgrid with Cartesian indexing. In the 2-D case with inputs of length M and N, the outputs are of shape (N, M) for 'xy' indexing and (M, N) for 'ij' indexing.
Comment: It is worth noting that arrays are indexed from 1 in Fortran, but from 0 in Python.
Answer: To do a=i*j, or something similar, it is best to first create an array containing i values and an array containing j values, and than simply do a=i*j:
For example, if you want a 5 x 10 matrix:
import numpy as np

i, j = np.meshgrid(np.arange(5), np.arange(10))
a = i * j

The result is:
array([[ 0,  0,  0,  0,  0],
       [ 0,  1,  2,  3,  4],
       [ 0,  2,  4,  6,  8],
       [ 0,  3,  6,  9, 12],
       [ 0,  4,  8, 12, 16],
       [ 0,  5, 10, 15, 20],
       [ 0,  6, 12, 18, 24],
       [ 0,  7, 14, 21, 28],
       [ 0,  8, 16, 24, 32],
       [ 0,  9, 18, 27, 36]])


Explicação do funcionamento de declaração de variável de loop For/In

Question:

var meusDados = {
    nome: 'Bruno Coelho',
    email: 'firstname.lastname@example.com',
    idade: 23
};
var dados;
for(dados in meusDados){
    console.log(meusDados[dados]);
}

Por que declarar a variável dados antes do for/in é necessário?
Comment: Use `for(let dados...` porque é sempre melhor evitar escopo global. Mas o `let` pode não ter suporte em navegadores mais antigos.
Answer: Não precisa, pode ser dentro do laço, é até o ideal:

var meusDados = {
    nome: 'Bruno Coelho',
    email: 'firstname.lastname@example.com',
    idade: 23
};
for (var dados in meusDados) {
    console.log(meusDados[dados]);
}

Coloquei no GitHub para referência futura.
Answer: Porque se não declarar, onde irá armazenar o conteúdo durante o laço? A variável precisa existir para receber o valor. Mas não precisa ser necessariamente antes do laço; pode ser dentro dele também, o que, particularmente, acho mais legível.

var meusDados = {
    nome: 'Bruno Coelho',
    email: 'email@example.com',
    idade: 23
};

for(var dados in meusDados){
    console.log(meusDados[dados]);
}

// Perceba que dados continua existindo fora do laço
console.log(dados);

Coloquei um console.log ao final mostrando que a variável dados continua existindo mesmo fora do laço. Dependendo do seu gosto, pode achar que isso polui o escopo global, pois uma variável que é utilizada em apenas um local específico continua existindo fora dele. Se assim for e deseja evitar tal ocorrência, pode utilizar o let:

const meusDados = {
    nome: 'Bruno Coelho',
    email: 'email@example.com',
    idade: 23
};

for(let dados in meusDados){
    console.log(meusDados[dados]);
}

// Perceba que dados NÃO continua existindo fora do laço
console.log(dados);

Qual é a diferença entre declaração de variáveis usando let e var?


Possible to 'exit' racket prematurely

Question: To short-circuit a C function (for example, for testing purposes), I can put an early return in there. For example:
int main(void) {
    puts("Hello");
    return;

    ...bunch of other code...
}

Or do a sys.exit(0) in python. Is there a way to do this in DrRacket / Scheme? As often I will have a workbook with a few hundred lines of code and I only want the top few functions to run before exiting. For example:
#lang sicp

(define (filtr function sequence)
  (if (null? sequence) nil
      (let ((this (car sequence))
            (rest (cdr sequence)))
        (if (function this) (cons this (filtr function rest))
            (filtr function rest)))))

(filtr  (lambda (x) (> x 5)) '(1 2 3 4 5 6 7 8 9))

(exit)  ; ?? something like this I can drop in to terminate execution?

...200 more lines of code...

Is there a way to do that here?
Answer: #lang racket can do that with the function named... exit. Try:
#lang racket

(display 1)
(exit 0)
(display 2)

#lang sicp doesn't have exit, but you can require it from Racket:
#lang sicp

(#%require (only racket exit))

(display 1)
(exit 0)
(display 2)

Early return from a function can be done using continuation. For example, with the let/cc operator:
#lang racket

(define (fact x)
  (let/cc return
    (if (= x 0)
        1
        (begin
          (display 123)
          (return -1)
          (display 456)
          (* x (fact (- x 1)))))))

(fact 10)
;; display 123
;; and return -1

Or equivalently, with call-with-current-continuation, which exists in both #lang racket and #lang sicp:
(define (fact x)
  (call-with-current-continuation
   (lambda (return)
     (if (= x 0)
         1
         (begin
           (display 123)
           (return -1)
           (display 456)
           (* x (fact (- x 1))))))))

Possible to 'exit' racket prematurely


How can they establish the impact of sports on mortality without control groups?

Question: So, this paper in BJM "Associations of specific types of sports and exercise with all-cause and cardiovascular-disease mortality: a cohort study of 80 306 British adults" is making rounds in all the media, e.g. this article in CBC interprets the findings as

Cycling, swimming, doing aerobics and playing racquet sports offer
  life-saving benefits, a large British study suggests.

As far as I can tell the researchers did not have a control group, i.e. the didn't make a random group of people to do exercise and the other random group to not do exercise. How would they reliably address the selection bias? Maybe people who are less likely to die from a heart attack are exactly those who stick around and do tennis for 10 years? If your heart is weak, you'll keep feeling uncomfortable and quit the sport, or maybe there will be some other way through chemical released in the blood impacting your brain to quit the sport in this case.
They should take a large sample of people and force them do exercise regardless of their initial conditions. That's the only way to reliably understand the impact of sports in my opinion. The closest is probably a school, where everyone is supposed to take physical education classes. Even that is imperfect since kids can get all kinds of exemptions.
Answer: The title of the paper is "Associations of specific types of sports and exercise with all-cause and cardiovascular-disease mortality: a cohort study of 80 306 British adults"

Conclusions: These findings demonstrate that participation in specific
  sports may have significant benefits for public health. Future
  research should aim to further strengthen the sport-specific
  epidemiological evidence base and understanding of how to promote
  greater sports participation.

They don't claim causality.  They sort of imply it however.  They control for potential confounders, but probably can't achieve conditional independence.
That said, I am no epidemiologist.  But in domain areas one can typically mix theory (i.e.: "we think that exercise is good") and weak evidence to make a stronger argument than could be made with weak evidence alone.
Comment: There are strategies towards causal inference in observational data.  They typically involve quasi-experiments and natural experiments.  These methods are best-developed in the econometrics literature, because economists typically can't run large-scale policy experiments.
Comment: This study doesn't do that.  It uses control variables to try and proxy for selection.  That strategy is never perfect.  A quasi-experiment could be, for example, to use some sort of random variation in inducements to exercise as an instrumental variable for participation in exercise.  Such approaches however need large sample sizes to be statistically efficient, and valid istruments are hard to find.
Comment: Another quasi-experimental strategy would be to find instances of oversubscribed sports activity that uses a lottery for admissions, most likely in primary or secondary school. This likely solves selection bias, but you still need to worry about things always-takers. A long shot, but it might be out there in the world.
Comment: Of course, they imply causation, otherwise what's the point of the publication? There's obviously a relationship: if someone's very ill they won't do sports. So, they all after causal relationships even if they don't state it strongly. I just want to understand whether this kind of research is really reliable from the point of the view of outsiders.
Answer: This question highlights two major issues. One is the inherent limitation of epidemiological research in terms of establishing causality. The second is the distortion of research results in the popular press.
The answer from @generic_user has covered the second issue. The authors did not claim causality. The dose-response relations for participation levels in some but not other types of exercise do suggest some underlying physiological basis, other than selection bias, for the results.
In terms of the limitation of epidemiological research, the types of controlled studies that you would like to see would be impractical or unethical even though they might better address issues of causality. Small-scale controlled studies, over limited periods of time, of some types of exercise have been done and some were cited in this research paper.
Under US standards, at least, you cannot "force them do exercise regardless of their initial conditions" unless they agree to be participants in a research study. This sets up a different type of selection bias.
The "control group" needed to compare against the forced-exercisers would presumably be required to abstain from exercise. Given the evidence from many types of studies and present knowledge of the physiologic effects of exercise, it would be unethical to prohibit people from exercising.
Finally, the scale of the project would be daunting. From my own experience, it is difficult enough to oversee simple controlled observational studies of a few hundred participants over a few years. Tens of thousands of participants would be required, over the course of decades, to answer these questions in controlled prospective trials even if they were ethical.
Comment: Probably in North Korea.
Comment: The [Nuremberg Code](https://en.wikipedia.org/wiki/Nuremberg_Code) forms a critical basis for human research ethics. Informed consent to human experimentation is a cornerstone of the Code. The webpage in the link in this comment has several additional links to related principles.
Comment: The ethical standards must be different across the world. Could the controlled study be done in some other country?
Answer: It is perfectly possible to run clinical trials of exercise ethically. There must have been hundreds of them. In a typical such study a group of people would be screened for inclusion. They might be people with a pre-existing health condition, people with a risk factor for a health condition or just volunteers. They are then randomised into one of at least two arms. One arm will be treatment as usual (often called standard of care) where they receive the usual treatment for their condition. In the other arm(s) they would receive some sort of exercise.
The problem with the trials is that they are usually

Small because there is no profit to be made from exercise so major players do not want to fund it

Have short follow-up because of limited funds and also problems with loss to long term follow-up

Often are difficult to generalise to the wider environment

Studies of the epidemiology of sport and other things like going for walks, dancing, gardening, and so are valuable as a complement because they show what happens in the real world.


Ms Access VB6 update recordset instead of duplication

Question: Hi i am using vb6 ms access backend, instead of updating a record it duplicates and creates a new entry. my table does not use primary key due to the relationship with other tables. How can i make it update a record and not duplicate here is my code
Private Sub cmdSave_Click()
With Connect.rsitem
       .Open , , adOpenDynamic, adLockOptimistic
        If EditItem = False Then .AddNew
           !itemno = txtItemNo.Text
           !desc1 = txtDesc1.Text
           !desc2 = txtDesc2.Text
           !onhandqty = txtOnhandQty.Text
           !unitprice = txtUnitPrice.Text
           !Size = txtSize.Text
           !upc = txtupc.Text
           !Ordercost = txtOrderCost.Text
   .Update
   .Close
End sub

Answer: Do select query first ..
Dim rs As DAO.Recordset

rs.Open "SELECT * FROM mytable WHERE itemno = '" & txtItemNo.Text & "'"
If Not rs.BOF and Not rs.EOF then

  'save the record ......

End If
If rs.State = adStateOpen Then rs.Close
Set rs = Nothing

Comment: That's a cool way to do it with a select statement, I've never thought of that!  I always use `rs.findfirst()` and  `if .nomatch`.  I'm not sure if there is a benefit either way though.


Reference Request - Statistics Book with exercises

Question: I'm looking for an as complete as possible statistics book with exercises, including the following topics:
Probability Review
Random Variables and Samples
Descriptive Statistics
Estimation (confidence intervals for mean of population, probability, difference of means of population etc)
Hypothesis Tests
Chi Square Test
Linear Regression
Analysis of Variance
Non parametric tests (Kolmogorov-Smirnov, Friedman, Kruskal-Wallis, Sign test etc)
Comment: https://math.stackexchange.com/q/51785/321264
Answer: May I recommend "The Practice of Statistics" by Daren S. Starnes. It is a great comprehensive textbook that I used in my AP Statistics class when I was in high school, and I still use it to this day in my everyday statistics problems.
https://www.amazon.com/Practice-Statistics-Daren-S-Starnes/dp/1464108730
Answer: Here  are three rather complementary recommendations:

Introductory Mathematical Statistics: Principles and Methods by Erwin Kreyszig
This classic  is an elementary introduction which presents in the first part Descriptive statistics, followed by Probability Theory and the main part is Statistical Inference.
E. Kreyszig has the talent to make  things easily   understandable, he comes straight to the point and puts the focus on the essentials. The book covers what you need and is full of nice examples which help to make the theory behind it clear and comprehensible.

Note: Years ago I became acquainted with one of his books when I was reading Introductory Functional Analysis. This is  a great, very simple introduction into the subject without requiring measure theory. Since that time I am a fan of him.
The next two recommendations are example centered.

Schaum's Statistics by Murray R. Spiegel and Larry J. Stephens
No need to explain anything about Schaum's outline. They all contain typically good and sometimes great examples for training.
I'd like to instead cite from chapter XXII from Indiscrete Thoughts by Gian-Carlo Rota:
Anyone who is about to teach the undergraduate mathematics curriculum should come down to earth by looking through The Schaum's Outlines before burdening the class with those well printed, many-colored, highly advertised hardcover volumes that are pathetically passed off as textbooks.

and the third one:

Introductory Statistics with R by Peter Dalgaard
In order to improve understanding and get a better feeling for the material it is extraordinary helpful to play around with many, many examples. So, if a computer is available and you are willing and able to write some code snippets, I strongly recommend to heavily use it for many examples.
Since I'm somewhat experienced in R programming, I recommend the book above. But any other computer language with statistics package and some supporting literature may also do the job.
Comment: @rrjrjtlokrthjji: Thanks a lot for granting the bounty. Regards,


Is there any harm in including all predictors of interest in an lmer() model?

Question: I have a study in which ~60 participants rating a subset of 200 items. I have four potential predictors that I would like to use to predict those ratings.
I will run an lmer() model including random subject and item intercepts.
Is there any harm in simply including all four candidate predictors, and seeing which are significant using the "lmerTest" package?
I had originally thought to build the model one predictor at a time via LRTs, starting with the one I have the most reason to believe should matter. But I was told this is a bad approach.
Answer:
Is there any harm in simply including all four candidate predictors, and seeing which are significant using the "lmerTest" package?

Breaking that into two questions, the answers are respectively "no" and "yes."
Separating out the different predictors throws away shared information and can lead to problems like omitted-variable bias. Sometimes the effect on one predictor might depend directly on the value of another, or the influence of one predictor might best be seen when other predictors are also taken into account. The only harm in "including all predictors" is when you have a low ratio of cases to predictors, which is not your problem here. Even then, there are principled ways to proceed that effectively penalize predictors to avoid the overfitting that would otherwise ensue. So there's no harm in including all 4 of your predictors at once.
You should, however, reconsider the part about "seeing which are significant using the 'lmerTest' package." If your interest really is in prediction and you can expect to have values for all 4 of your predictors in future cases, there's no reason to cut back on the number of predictors. That will just tend to make predictions less reliable. In general, for prediction you want to include as many predictors in your model as is consistent with not overfitting. Finding a predictor "not significant" might just mean that your study was too small to document its effect, and if your model is used at a larger scale it might be seen as quite important. Statistical significance is not to be confused with practical importance, in either direction.
Comment: Thanks very much for the answer! I'm not so much interested in future cases, but rather to know if/which of the four predictors are related to my dependent variable. Does that change anything? So, I'm not saying I'll remove non-significant predictors, but rather will just not interpret them.
Comment: @Dave sill include all predictors in the model, at least to start. Do temper any statements you might make about the practical importance of the "not-significant" predictors. It might just be that your study wasn't big enough to find their significance. Also, make sure that omitting the "not-significant" predictors doesn't substantially affect conclusions about the others. It's possible that removing a "not-significant" predictor will affect your ability to evaluate the others adequately. I'd just report the entire model, and let the significance estimates speak for themselves.
Comment: Thanks a lot @EdM !


How to hide the breadcrumb in ssrs report manager

Question: I have created a report and uploaded it in Report manager in SSRS. I have a asp.net web page where I have a hyperlink that has the URL to open the report in the report server. Now when the report opens user can see the report path on the breadcrumb. My question is how to hide that? My hyperlink is
/ReportsDev/Pages/Report.aspx?ItemPath=%2fCFM%2fCurrentGeneralLedger%2fInterestCharges')">
I have tried &rv:Toolbar=false after the link but didn't work.
I cannot change style as suggested in a link by going
:\Program Files\Microsoft SQL Server\MSRS10_50.MSSQLSERVER\Reporting Services\ ReportManager as I don't have permission.
Any suggestion will be helpful!
Answer: what i do to hide breadcrumb is
instead of going to (default site)
http://servername/Reports/Pages/Folder.aspx

and then navigating to the report
i go to
http://servername/ReportServer

Comment: in your case it could be http://servername/ReportDevServer or http://servername/ReportsDevServer
Comment: I have tried that, but then I get HTTP not found error
Answer: I have been trying to find the same answer and realised the below.
Considering the link:
http://servername/Reports/Pages/Report.aspx
If in the above scenario "Reports" is named something else for e.g. "Reports_foobar" then the equivalent for report viewer would be "ReportServer_foobar" as below:
Report aspx:
http://servername/Reports_foobar/Pages/Report.aspx
ReportViewer aspx:
http://servername/ReportServer_foobar/Pages/ReportViewer.aspx


If $R$ is a strict partial order prove that is asymmetric

Question: Suppose $R$ is a relation on a set $A$, and $R$ is asymmetric if:
$\forall x \in A$ $\forall y \in A$ $((x, y) \in R \rightarrow (y, x)\not \in R)$
The first point of the exercise was to demonstrate that if $R$ is asymmetric then it is also antisymmetric.
What I am not understanding is a proof solution to the following question:

Show that if $R$ is a strict partial order, then it is also
  asymmetric.

A partial order is a binary relation on a set, say, $A$ that is reflexive, antisymmetric and transitive.
And the proof is the following:

Suppose that R is a strict partial order, and suppose that for some
  $x,y \in A$, $(x,y) \in R$ and $(y,x) \in R$. Then by transitivity of
  $R$, $(x, x) \in R$, which contradicts the fact that $R$ is
  irreflexive. Therefore, $R$ is asymmetric.

What exactly I am not understanding is why if $(x,y) \in R$ and $(y,x) \in R$, since $R$ is antisymmetric. At least, $x = y$. Then I also cannot understand why it follows immediately that it's asymmetric.
Comment: These notions arise naturally in different contexts. When presented in the abstract they may seem like meaningless bean counting, but they are useful tools for categorizing relations.
Answer: A strict partial order is a relation $R$ that is irreflexive (for every $x\in A$, $(x,x)\notin R$) and transitive.
Why is it asymmetric? Suppose $(x,y)\in R$ and $(y,x)\in R$; by transitivity, $(x,x)\in R$, which isn't true because the relation is irreflexive.
Therefore, if $(x,y)\in R$, it holds that $(y,x)\notin R$.

Why did mathematicians invented all that? Simple: strict partial orders and (lax) partial orders are exactly the same thing.
If $A$ is a set, write $\Delta(A)=\{(x,x):x\in A\}$.
If $S$ is a strict partial order on $A$, then $S^*=S\cup\Delta(A)$ is a partial order on $A$ (prove it).
If $R$ is a partial order on $A$, then $R_*=R\setminus\Delta(A)$ is a strict partial order on $A$ (prove it).
Note also that $(S^*)_*=S$ and $(R_*)^*=R$, so there is a very well behaved bijection between the strict and the lax partial order relations on $A$.
Think to the above as the connection between $<$ and $\le$.
Answer: I don't know if this will help, but let's try it out.
For every $x\in R$ and $y\in R$, there are only four possibilities:

$(x,y)\in R$ and $(y,x)\in R$
$(x,y)\notin R$ but $(y,x)\in R$
$(x,y)\in R$ but $(y,x)\notin R$, or
$(x,y)\notin R$ and $(y,x)\notin R$.

A reflection is asymmetric if only the last three ever occur. The proof shows that it is impossible for the first to occur in $R$, and therefore we conclude that $R$ is asymmetric.


Can we characterize those Euclidean domains $D$ for which $D/I$ is finite for any ideal $I \ne \{0\}$ of $D$?

Question: Let $I$ be any ideal of $\mathbb Z[i]$ , then as $\mathbb Z[i]$ is euclidean domain , so $I=(z)$ for some gaussian integer $z$ ; so we can write every element of $\mathbb Z[i] / I$ as $x+(z)=qz+r+(z)=r+(z)$ where either $r=0$ or $N(r)<N(z)$ ; now for $r=0$ , every element of the form $x+(z)$ is nothing but $(z)$ and otherwise $N(r)$ is bounded above by $N(z)$ , so $N(r)$ , being a non-negative integer , can take only finitely many values , and since for a given $m \in \mathbb Z$ , $N(r)=N(r'+ir'')=r'^2+r''^2=m$ implies $r',r''$ can take only finitely many values , so $r$ can take only finitely many values ; hence the number of distinct elements of $\mathbb Z[i] / I$ is finite. Now my question is , can we , in general say  that for any euclidean domain $D$ and any ideal $I$ of it , $D/I$ is finite  ? If not , then can we characterize those Euclidean domains for which $D/I$ is finite for any ideal ? As far as I can see , I cannot carry the gaussian   domain approach in general , as there I used the finiteness of solution of $a^2+b^2=k$ in integers $a,b$ for given $k$ , to conclude $N(r)=k$ for a given $k$ has only finitely many solutions in $r$ in the euclidean  domain , It is true that if $N(r)=k$ for a given $k$ has only finitely many solutions in $r$ in the euclidean  domain $D$ , then $D/I$ is finite for any ideal $I$ , but I don't know whether this condition is necessary or not . Please help . Thanks in advance .
$EDIT:$ In all of above $I \ne \{0\}$
Comment: You should add $I \neq 0$.
Comment: @MartinBrandenburg : Ah true , surely I will add that ...
Answer: Such rings are called residually finite, or rings with the finite norm property FNP). Below is an entry point into the literature.

Levitz, Kathleen B.; Mott, Joe L.  $ $ Rings with finite norm property.
Canad. J. Math. 24 (1972), 557--565.

Let  $A$  be a ring with  $A^2 \ne 0 ,$ and  $A^+$  the additive group
  of  $A$ . If each non-zero homomorphic image of  $A$  is finite, then
  $A$  is said to be a ring with finite norm property (FNP ring). K. L.
  Chew and S. Lawn studied FNP rings with identity, which they called
  residually finite rings [same J. 22 (1970), 92--101; MR0260773 (41 #5396)]. In the paper under review, the authors extend the results of Chew and Lawn to arbitrary FNP rings. They also prove the following
  results:
$(1)\ $ If $A$ is an FNP ring then $A^+$ is torsion and bounded, or
  torsion-free and reduced, or torsion-free and divisible. Henceforth,
  $A$ will be a commutative integral domain with $1$ and with quotient
  field $K$ .
$(2)\ $ Let L be a finite extension of $K$ ; if $A$ is an FNP ring,
  then so is  every intermediate ring of $L/A$ .
$(3)\ $ Let $A'$ be the integral closure of $A$ in $K$ ; then, $A$ is
  an FNP ring if and only if $A'$ is a Dedekind domain and $A_P$ is an
  FNP ring for every maximal ideal $P$ .
$(4)\ $ Let $K$ be of characteristic $0,$ then, every subring of $A$
  is an FNP ring  iff $K$ is a finite extension of the field of rational
  numbers.
$(5)\ $ Let $K \ne A$ be of prime characteristic; then, every subring
  of $A$ is an FNP ring iff $K$ is a finite extension of some $F(x),$
  where is the prime field of  $K$ and  $x$  is transcendental over $F$
  .

Review by H. Tominaga (AMS MR 45 #6872)