Best way to perform multiclass SVM

Question: I know that the SVM is a binary classifier. I would like to extend it to multi-class SVM. Which is the best, and maybe the easiest, way to perform it?
code: in MATLAB
<code>   u=unique(TrainLabel);
    N=length(u);
    if(N>2)
        itr=1;
        classes=0;
        while((classes~=1)&&(itr<=length(u)))
            c1=(TrainLabel==u(itr));
            newClass=double(c1);
            tst = double((TestLabel == itr));
            model = svmtrain(newClass, TrainVec, '-c 1 -g 0.00154');
            [predict_label, accuracy, dec_values] = svmpredict(tst, TestVec, model);
            itr=itr+1;
        end
        itr=itr-1;
    end
</code>
How can this be improved?
Comment: What does the variable `classes` do in the code? It seems to be useless.
Comment: did you get to any conclusion? i have this problem with my work.if you have reached to a suitable rusult please share your multiclassification code here.thanks.
Answer: There are a lot of methods for multi-class classification. Two classic options, which are not SVM-specific are:

One-vs-all (OVA) classification:
Suppose you have classes A, B, C, and D. Instead of doing a four way classification, train up four binary classifiers: A vs. not-A, B vs. not-B, C vs. not-C, and D vs. not-D. Then, pick either the positive class that's "best" (e.g., furtherest from the margin across all four runs). If none of the classifications are positive (i.e., they're all not-X), pick the "opposite" of class that's worst (e.g., closest to the margin).
All-vs-All:
Train all possible pairs of classifications. Rank the classes by some factor (e.g., # of times selected), and pick the best.

Which works best has been contentious:
Duan and Keerthi have an empirical study that suggests a specific all-vs-all method, while Rifkin and Klautau argue for a one-vs-all scheme. There are even schemes where one learns error-correcting codes describing the class labels, instead of the labels themselves.
Good luck!
Edit: What you really want, particularly for OVA, is the posterior probability of each class. For some methods, like Naive Bayes, that's trivial to get out. SVMs typically don't give you probabilities, but there are ways to compute them. See John Platt's 1999 paper "Probabilistic Outputs for Support Vector Machines..."
Comment: For OVA - can you pick the class that has the largest probability (induced by Platt scaling)?
Comment: Yeah, that's basically the upshot of the Duan and Keerthi paper. They combine the Platt probabilties with Hastie's pairwise coupling trick and get good results. I should probably edit the text to include that. Good catch B_Miner!
Comment: in SVM, do u need to do voting or sum-pooling?
Comment: @lakesh, One-vs-all or All-vs-all are like voting schemes. If you're using a set of binary classifiers, you've got to do *something* to turn them into a multi-class classifier. Alternately, you can use the modified SVM described by carlosdc below...
Comment: what is that something?
Comment: @lakesh, I meant to say that you've got a lot of choices and, without trying them, it's not clear which will be best for your application. I'd try starting with the one-vs-all, as it's "classic" and not quite as computationally demanding. The Rifkin and Klautau paper has the specifics of their approach, which looks reasonably straightforward.
Comment: my point is the code above does the classification into binary classifiers but the missing part is the voting. I just need to include the voting which i don't know how to do...
Comment: I took the liberty of formatting your post using some of CV's markdown options to make it a little more readable, @MattKrause. If you don't like it, roll them back w/ my apologies.
Comment: @iakesh Voting gets done via distance to margin. I struggled with that too.
Answer: Let me add that there is work on extending SVMs to multiple classes (as opposed to the methods Matt Krause describes that are decomposition into several binary classification tasks). One important work is: On the Algorithmic Implementation of Multiclass Kernel-based Vector Machine

Best way to perform multiclass SVM


Order of growth in uniform distribution

Question: Consider an i.i.d. sample $\{X_1, \ldots , X_n\}$ from the uniform distribution on
 $[ 0,\theta]$ and the estimator
$$M_n = \max\{X_1,X_2,\ldots,X_n\} $$
What does the above statement mean?
I mean, I can think that the joint distribution is something like
$$\left(\frac1\theta\right)^n $$
But I dont get the max part? The main question in exercise is:
Prove that Mn p→ θ as n → +∞
A proxy question..I am trying to understand example 3.1 here (http://faculty.ksu.edu.sa/73125/Publications/%5B3%5D%20Convergence%20of%20Random%20Variables.pdf)
Why is $\ F_n(x) = x^n$
Answer: The max of these random variables is less than $x$ if and only if all of them are less than $x$, and since they are independent and identically distributed, the probability of that is the $n$th power of the probability that the first one is less than $x$.

Order of growth in uniform distribution


C program crashing because of invalid address

Question: I am not able to figure out why my program is crashing in the print statements. Pls help.
char *
infix_to_postfix(char *string, int str_len, int *new_len) {
*new_len = str_len;
return string;
}
fsm_t *
fsm_nfa_construction(char *string, int str_len) {
    int new_len;
    char *postfix_str = infix_to_postfix(string, str_len, &new_len);
    // return fsm_nfa_construction_internal(postfix_str, new_len);
    printf ("%s\n", postfix_str);
    return NULL;
}
int
main(int argc, char **argv) {
    char str[32];
    strncpy(str, "ab|*c.\0", strlen("ab|*c.\0"));
    fsm_t *fsm = fsm_nfa_construction(str, strlen(str));
    return 0;
}
(gdb) f 2
#2 0x0000555555556aa8 in fsm_nfa_construction (string=0x7fffffffdc20 "ab|*c.", str_len=6) at fsm.c:715
715 printf ("%s\n", postfix_str);
(gdb) p postfix_str
$3 = 0xffffffffffffdc20 <error: Cannot access memory at address 0xffffffffffffdc20>

Comment: Your use of `strncpy` is wrong. That's not what `strncpy` is for. Just use `strcpy`
Comment: In other words: `strncpy(str, "ab|*c.\0", strlen("ab|*c.\0"));` --> `strcpy(str, "ab|*c.");
Comment: Or to make it simpler: `char str[32] = "ab|*c.";
Comment: Not that it matter but... `fsm_t` ???
Comment: fsm_t is another data structure, but irrelevant here to know its definition. Also, same crash with strcpy as well.
Comment: probably there are many ways to work-around the problem, but curious to find what is wrong with this simple code.
Answer: Looks like a null terminator issue..
in this line:
strncpy(str, "ab|*c.\0", strlen("ab|*c.\0"));

due to the length returned by strlen, the null terminating character is not being copied into str.  This is because strlen detects the length of a string by scanning until it finds a null character, which in this case is embedded in your string literal. To also copy the null terminating character, just add 1 like so:
strncpy(str, "ab|*c.\0", strlen("ab|*c.\0")+1);

Since str is not initialized, there is no guarantee that the data bytes there are zero's (null terminating characters).  The printf with the %s format specifier works by detecting the null terminating charater too. since there isn't one in your buffer, the print never stops and crashes the program.
This isn't related to your question, but I don't think your support functions here are doing what you expect.  For example, the infix_to_postfix function does not do anything useful.  It just copies one integer to another and returns the same pointer passed in.
Comment: still crashes. `strncpy(str, "ab|*c.\0", strlen("ab|*c.\0") + 1);`  added +1. Alsoo, tried memset  0 the str before strncpy. same Crash.
Comment: @AbhishekSagar Can you provide more information on the crash?  'I replicated your program on my system and the +1 fixed the crash for me.  It forces the strncpy to place a null character at the end of the desired string.  So that is definitely a problem, it just might not be your only problem.
Comment: at printf it says the postfix_ptr pointer is invalid.
(gdb) p postfix_str
$1 = 0xffffffffffffdc20
Comment: I ran with GDB, set a breakpoint at the print statement line (line 12 if my case) and was able to print the string fine.  `(gdb) break test.c:12`
Breakpoint 1 at 0x400633: file test.c, line 12.
`(gdb) r`
Starting program: /home/snelso/pg/test

Breakpoint 1, fsm_nfa_construction (string=0x7fffffffde90 "ab|*c.", str_len=6)
    at test.c:12
12     printf ("%s\n", postfix_str);
`(gdb) p postfix_str`
$1 = 0x7fffffffde90 "ab|*c."


Total Turing reducibility

Question: For $x, y\in 2^\omega$, say $x$ is totally reducible to $y$ - and write "$x\le_{Tot}y$" - if there is some Turing machine $\Phi_e$ which is total on every oracle (that is, $\Phi_e^z$ is total for all $z\in 2^\omega$) such that $\Phi_e^y=x$.
It is a neat exercise* to show that $\le_{Tot}$ is not the same as standard Turing reducibility, $\le_T$. On the other hand, it does share some basic properties:

$\le_{Tot}$ is a preorder on $2^\omega$ with the countable predecessor property.
The induced degree structure $\mathcal{T}=2^\omega/\equiv_{Tot}$ is an upper semilattice (with the usual join).
$\mathcal{T}$ has the exact pair property (the usual argument still works).
And some other basic properties, too.

I'm interested in anything that is known about the poset $\mathcal{T}$, and in particular, comparing $\mathcal{T}$ with the standard poset of Turing degrees $\mathcal{D}=2^\omega/\equiv_T$. Since there's a lot of potential questions here, let me ask specifically:

Does $\mathcal{T}$ have greatest lower bounds of pairs of elements?

Of course, glbs of pairs of elements do not always exist in $\mathcal{D}$, but as far as I can tell that proof does not immediately apply to $\mathcal{T}$.

*Fix $x$ non-computable and let $\Phi_c$ be the oracle machine which, with oracle $z$ and input $n$,  halts and outputs 0 if "$01^{2n}0$" occurs before "$01^{2n+1}0$" in $z$, and halts and outputs 1 if "$01^{2n+1}0$" occurs before "$01^{2n}0$" in $z$. We can build a $y$ such that $\Phi_c^y=x$ but $x\not\le_{Tot}y$, by diagonalizing against every total-on-all-oracles index. Letting $e$ be such an index, and having built some initial segment $y_s$ of $y$, we can just "add enough 0s": there is some $k$ such that $\Phi_e^{y_s^\smallfrown 0^k}(m)\downarrow\not=x(m)$ for some $m$ (since $x$ is not computable). The reduction $\Phi_c$ ignores strings of zeroes, so we can alternate between coding $x$ into $y$ and adding long strings of zeroes to diagonalize against total-on-all-oracles reductions.
Answer: A classical theorem of Nerode shows that a set $A$ is truth-table reducible to a set $B$ if and only if there is a Turing reduction $\Phi$ of $A$ to $B$ such that $\Phi^X$ is total for every set $X$. So you have rediscovered truth-table reducibility.
There is a very large literature on truth table reducibility. It is mentioned in all the classic texts, and covered in some detail in the books by Rogers and Odifreddi, and elsewhere.
Comment: The proof of Nerode's theorem is that, because of compactness, if $\Phi^X$ is total for every $X$, then given $n$ we can find (effectively) an $M$ such that $\Phi_M^{X \upharpoonright M}(n)$ converges for every $X$. Then we can constuct a truth table of size $M$ that tells the value of $\Phi^X(n)$ from $X \upharpoonright M$. Thus total reducibility implies truth table reducibility. The converse implication is very easy.

Total Turing reducibility


Combinatoric question on preimage of a function

Question: Got stuck on the following combinatoric question. Will be glad for any suggestions.

Find the number of functions $f:\{1,2,3,4\} \rightarrow \{1,2,3,4\}$ so that for all $1\le i\le4$, $f^{-1}(\{i\})≠\{i\}$ .

(i.e. Find the number of these functions in which the pre-image of a subset with a single member is different from the set containing that member.)

Now, finding the number of injective functions that fulfill this is pretty easy (it's called the number of "derangements" of a set and is the number of injective functions with no fixed point, equal in this case to 9) but there are so many other possibilities that checking them all, seems to be too tedious.
For example a partly injective function such as $f(1)=2 ,\ f(2)=2, \ f(3)=1, \ f(4)=3$ fulfills the condition in spite of $2$ being a fixed point, since the pre-image of $2$ is $\{1,2\}$ which is different from $\{2\}$.
Answer: If the function were injective or surjective, and thus bijective, you would indeed be talking about a specific class of permutations called derangements.  There are $!4$ such derangements.
Since you are not restricting yourself to injective or surjective functions, we can consider all $4^4$ possible functions here.  Since the numbers are so small, we can proceed directly by cases.

No fixed points:  for each $i$ we have $3$ choices for $f(i)$ to be such that $f(i)\neq i$.  There are $3^4$ such functions here.

Exactly one fixed point: Pick which one value was fixed.  From there, in order to prevent the preimage of that point being exactly that point alone, it must be the case that for each of the other points we did not avoid mapping to it.  There are $3^3$ functions with only $1$ as a fixed point, $2^3$ of which did not map any other elements to $1$ as well, making the total number of functions with exactly one fixed point $4\cdot (3^3-2^3)$

Exactly two fixed points: Pick which two values were fixed.  Due to the small number of available elements, we note that it must be the case that each of the two remaining elements are mapped one each to the chosen values.  There are $\binom{4}{2}\cdot 2$ such functions.

This gives a total of $$3^4+4\cdot (3^3-2^3)+\binom{4}{2}\cdot 2$$
I do not as of yet see a convenient way to approach the general problem were we to consider $\{1,2,3,\dots,n\}$ in place of merely $\{1,2,3,4\}$ as our set in question
Comment: The idea of sorting the possibilities via fixed points looks good but I stopped at "_There are 4^3 functions with 1 as a fixed point, 3^3 of which did not map any other elements to 1 as well_".
Shouldn't this be "_**2^3** of which did not map any other elements to 1_" ,since you are assuming no other fixed points...?
Comment: @elazar good catch.  You are correct
Comment: Ok. Great. The idea is what is important and I think that yours indeed solves the problem. Thanks a lot
Answer: You can use the inclusion-exclusion principle. Let $A_i$ denote the set of functions $f:\{1,..,n\}\to \{1,...,n\}$ s.t. $f^{-1} (i) \neq \{i\}$. Then what you are interested in is $$ | \bigcap_i A_i |= n^n - | \bigcup_i A_i^c |. $$
According to the InEx principle
$$ |\bigcup_i A_i^c | = \sum_{k=1}^n (-1)^{k-1} S_k, $$
where
$$ S_k = \sum_{ i_1<\ldots < i_k} | \bigcap_{j=1}^k A_{i_j}^c| .$$
The set $ A_i^c$ consists of fcts satisfying $f^{-1} (i) = \{i \}$. Now for fixed $i_1<...<i_k$ $$ |\bigcap_j A_{i_j}^c| = (n-k)^{n-k} ,$$
hence $$|\bigcap_i A_i | = \sum_{k=0}^n (-1)^k  \binom{n}{k} (n-k)^{n-k} .$$
The last term of the sum ($k=n$) is actually just 1, since it corresponds to the identity fct.
Comment: Need some more time to follow this solution. Meanwhile, thanks a lot  for your effort
Comment: Which part is unclear? Should I elaborate on something?
Comment: Not necessary. Figured it out. Though your solution took some figuring out, it was worth the effort, as it provides a general solution to the problem. Thanks a lot
Comment: Cool, glad to hear!


Multicollinearity in case of nonstationary variables

Question: I am using dynamic OLS regression and fully modified OLS regression (in eViews) to estimate long run relationships' coefficients; my variables are all I(1).
Do I need to check for multicollinearity before running the estimation?
Comment: since you run regressions (albeit "fully modified"/"dynamic" ones), multicollinearity is going to have the same consequences in these regressions as in others
Answer: By the sounds of it I think you will have to carry out some other tests before you get worried about multicollinearity.
Firstly, regression involving I(1) variables will have an R-squared increasing to 1 as the number of observations, T, increases. i.e. correlation will either go to 1 or -1, regardless of there being any relationship between the variables.
See: http://faculty.washington.edu/ezivot/econ584/notes/cointegration.pdf
(Zivot also has other related topics, which you may find useful)
When all elements of your correlation matrix (which you need to estimate implicitly for OLS) tend to 1 you will see what could look like multicollinearity. I know you said you are using dynamic regressions (which I assume you have a rolling window for estimations i.e. you fix T), that won't change the fact that you could be falling into a spurious regression.
I think using dynamic cointegration would be a better approach here, and you would not have to do much in terms of your model i.e. you could use OLS to estimate the cointegrating vector (your slope coefficients) via Engle-Granger and then carry out a Dickey-Fuller test for stationarity on the residuals at each regression you do. If your residuals are stationary (i.e. I(0)) at some level of significance you are likely to have a legitimate relationship between the variables. Make sure though that all your variables are I(1).
What's also nice about this approach is that you could modify it to an error correction model for prediction or fit mean reverting models to the residual (Ornstein-Uhlenbeck or Autoregressions) also for prediction.


Problemas ao realizar Build com PostSharp no AppVeyor

Question: Estou com problemas para fazer build do meu projeto no AppVeyor, (localmente funciona) pois a licença fica no regedit.
Verifiquei que é necessário criar um arquivo postsharp.config e inserir informações da licença, mas mesmo assim não deu certo
Minha licença está válida.
 C:\projects\webapibase\packages\PostSharp.5.0.41\build\PostSharp.targets(314,5):
 error PS0260: License error. The license
 xxx is not allowed to be loaded from
 C:\projects\webapibase\Service\postsharp.config.
 [C:\projects\webapibase\Service\Service.csproj]
 C:\projects\webapibase\packages\PostSharp.5.0.41\build\PostSharp.targets(314,5):
 error PS0242: License error. No valid license key has been installed.
 Please visit https://www.postsharp.net/purchase to acquire a license
 of PostSharp. To register a license key, use PostSharp Essentials or
 start the evaluation period, execute the program

O arquivo postsharp.config
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.postsharp.org/1.0/configuration">
  <License Value="xxxx" />
</Project>

PS.: Tenho o mesmo projeto no TFS e o Build lá funciona normal (não necessita do arquivo), provavelmente o PostSharp detecta que é uma build machine e ignora o check da licença.
Answer: Resolvido, a solução é adicionar antes do Build a Key no Registro:
REG ADD "HKEY_CURRENT_USER\Software\SharpCrafters\PostSharp 3" /v LicenseKey /t REG_SZ /d <your_license>


The existence of a bounded linear functional

Question: Prove the existence of a bounded linear functional $\Delta:L^{\infty} (\mathbb R) \rightarrow \mathbb{R}$ such that $||\Delta||=1$ and $\Delta f=f(0)$ for every $f\in L^{\infty}(\mathbb{R}) \cap C^0(\mathbb{R})$ Show however that there exists no function $g\in L^1(\mathbb{R})$ such that $\Delta f = \int f(x)g(x)dx$.
Deduce that $(L^{\infty}(\mathbb{R}))^*$ cannot be identified with $L^1(\mathbb{R})$
Answer: Consider the linear functional on $L^\infty (\mathbb R) \cap C(\mathbb R)$ that sends $f \mapsto f(0)$. This linear functional is bounded: it has norm $1$, since $| f(0) | \leq \sup_{x \in \mathbb R} |f(x) |$ and since the inequality is saturated by $f = 1$.
By Hahn-Banach, you can extend this linear functional to a functional $\Delta$ on the whole of $L^\infty (\mathbb R)$, while preserving the property that $|| \Delta || = 1$.
The reason why you can't find a $g \in L^1 (\mathbb R)$ such that $\int fg = f(0)$ for all $f \in L^\infty (\mathbb R) \cap C(\mathbb R)$ is as follows. Consider this sequence of "triangle" functions,
$$ f_n (x) = \begin{cases} 0 & x \leq -\frac 1 n \\ nx+1 & -\frac 1 n < x \leq 0 \\ -nx + 1 & 0 < x \leq \frac 1 n \\ 0 & x > \frac 1 n \end{cases}$$
If $g$ has the claimed property, then each $f_n$, we have
$$ \int f_n g = 1.$$
This sequence of functions converges pointwise to the function,
$$ f(x) = \begin{cases} 1 & x = 0 \\ 0 & x \neq 0 \end{cases}$$
By the dominated convergence theorem,
$$ \int f g = \lim_{n \to \infty} \int f_n g = 1.$$
But $fg$ is zero almost everywhere, so $\int fg = 0$, and we have a contradiction.
This shows that you can't identify $L^1(\mathbb R)$ with $L^\infty(\mathbb R)^\star$ by identifying $g \in L^1(\mathbb R)$ with the linear functional $ f \mapsto \int fg $ on $L^\infty(\mathbb R)$. However, I don't think this kind of argument proves that $L^1(\mathbb R)$ can't be identified with $L^\infty(\mathbb R)^\star$ in any other way...
Comment: About the Hahn-Banach step : I think we can see $L^\infty$ as $S \oplus S^\perp$ where for $f \in S, \phi(f) =\lim_{n \to \infty} \int_{-1/n}^{1/n} \frac{f(x)}{2n}dx$ is well-defined, and for $h \in S^\perp$ we set $\phi(h) = 0$
Comment: Yes you're right!


Retornar dados do Cliente

Question: Bom dia Pessoal,
Gostaria de criar uma função, que retornasse o cliente solicitado, e seus dados, que estão em 3 tabelas diferentes Clientes, ClientesTelephone, ClientesEmail, consigo adicionar o cliente perfeitamente com minha função CreateClientAsync.
CreateClientAsync:
public async Task<ApplicationClient> CreateClientAsync(ApplicationClient client)
    {
        try
        {
            var result = await _context.Clientes.AddAsync(client);

            if (result.State == EntityState.Added)
            {
                _context.SaveChanges();
            }

            return result.Entity;

        }
        catch (Exception)
        {

            throw;
        }
    }

estou tentando desenvolver uma função para retornar os dados do cliente, chamada GetClientAsync, mas não sei por onde começar, poderiam me ajudar por favor ?
public async Task<ApplicationClient> GetClientAsync(ApplicationClient client)
    {
        try
        {

        }
        catch (Exception)
        {

            throw;
        }
    }

Tabela Clientes:
public class ApplicationClient
{
    [Key]
    public Guid Id { get; set; }

    [Required]
    public int TipoPessoa { get; set; }

    public String Nome { get; set; }

    public Guid UsuarioId { get; set; }

    public virtual ICollection<ApplicationClientTelephone> ClientesTelefone { get; set; }

    public virtual ICollection<ApplicationClientEmail> ClientesEmail { get; set; }

    [ForeignKey("UsuarioId")]
    public virtual ApplicationUser Usuario { get; set; }

}`

Tabelas ClientesEmail:
public class ApplicationClientEmail
{
    [Key]
    public long Id { get; set; }

    public String Email { get; set; }

    public Guid ClienteId { get; set; }

    [ForeignKey("ClienteId")]
    public virtual ApplicationClient Cliente { get; set; }
}

Tabelas ClientesTelefone:
public class ApplicationClientTelephone
{
    [Key]
    public long Id { get; set; }

    public String Telefone { get; set; }

    public Guid ClienteId { get; set; }

    [ForeignKey("ClienteId")]
    public virtual ApplicationClient Cliente { get; set; }
}

Answer: Você deve usar o Include (Join do EF) caso a opção LazyLoading estiver definido como falso, senão ele fará automaticamente os Joins.
Segue o exemplo abaixo:
var result = await _context.Clientes.Include("ClientEmail").Include("ClientTelephone").FirstOrDefaultAsync(m => m.ID == id);

Recomendo usar FirstOrDefault para não gerar exceção se o elemento não existir, apenas retornará nulo, mais sobre: https://stackoverflow.com/questions/1024559/when-to-use-first-and-when-to-use-firstordefault-with-linq
Comment: Estou recebendo o erro que 'ApplicationClient' não contém uma definição para 'GetAwaiter'
Comment: Desculpe, troque o _FirstOrDefault_ por *FirstOrDefaultAsync*
Comment: Estou usando essa função para verificar se o `CNPJ `ou `CPF `, já está inserido na tabela, então pelo oque entendi, caso ele não encontre ele retornará `null`, e a partir desse `null` consigo fazer um `if` e fazer essa verificação, correto ?
Comment: Isso! exatamente, você ira testar se o objeto Cliente é diferente de nulo e tratar, if(cliente != null) { // Achou!  } else { //Não achou }
Comment: No caso eu não consigo retornar a `var` `result`, pois recebo o seguinte erro:  `Não é possível converter implicitamente tipo "EasySistema.Models.ApplicationClient em Microsoft.Asp.NetCore.Mvc.ActionResult`

Retornar dados do Cliente


how to fill a cell on clicking the grid on canvas in html5

Question: I want to fill a grid cell on clicking on the particular cell.Here is my code:
 function drawBox()
    {
        for (var row = 0; row < 14; row ++)
        {
            for (var column = 0; column < 13; column ++)
            {
                var x = column * 40;
                var y = row * 40;
                context.beginPath();
                context.rect(x, y, 40, 40);
                context.fillStyle = "white";
                context.fill();
                context.lineWidth = 3;
                context.strokeStyle = 'black';
                context.stroke();
            }
        }

    }

Answer: I've got a working sample here. Code:

var canvas = document.getElementById("canvas"),
    c = canvas.getContext("2d"),
    boxSize = 40,
    boxes = Math.floor(600 / boxSize);
canvas.addEventListener('click', handleClick);
canvas.addEventListener('mousemove', handleClick);

function drawBox() {
  c.beginPath();
  c.fillStyle = "white";
  c.lineWidth = 3;
  c.strokeStyle = 'black';
  for (var row = 0; row < boxes; row++) {
    for (var column = 0; column < boxes; column++) {
      var x = column * boxSize;
      var y = row * boxSize;
      c.rect(x, y, boxSize, boxSize);
      c.fill();
      c.stroke();
    }
  }
  c.closePath();
}

function handleClick(e) {
  c.fillStyle = "black";

  c.fillRect(Math.floor(e.offsetX / boxSize) * boxSize,
    Math.floor(e.offsetY / boxSize) * boxSize,
    boxSize, boxSize);
}

drawBox();
<canvas id="canvas" width="600px" height="600px"></canvas>

I edited the drawBox() function a bit to increase efficiency, also.
e.offsetX is the mouse coordinate, devide by 40, then Math.floor() this to get the cell number, then multiply by 40 to get the starting coordinate of the cell.
Comment: offsetX and offsetY should be changed to clientX and clientY respectively. client definitely works in Firefox 37 and Chromium, but offset only works in Chromium.


Error when performing OrderBy on a Sub-Property of an object

Question: I am having problem in performing OrderBy on a sub-property of an Object.
I have two separate Models as  listed below:
PersonModel:
public class PersonModel
{
   public string Name { get; set;}
   public DeptModel Dept { get; set; }
}

DeptModel
public class DeptModel
{
   public int DeptId { get; set;}
   public string DeptName { get; set;}
}

I had used automapper to map the relation between those two class and I am able to retrieve data properly.
After the data had been retrieved, I am trying to implement order by using linq on the DeptName object. Then it is showing an error "Object reference not set to an instance of an object."
The result is retrieving data as IList < PersonModel >. If Debug over here it is showing the correct data at this point.
Then I am performing the OrderBy on the retrieved data and it is crashing over here.
var tmp = result.OrderBy(x => x.Dept.DeptName).ToList();
I am not sure why I getting this error. Any suggestions on resolving the issue is greatly appreciated.
Comment: Most likely `x` or `Dept` is null. When you try to access it's properties, you get the exception. Put a breakpoint inside the lambda to see it's values at runtime.
Comment: possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it)
Comment: Hey thanks.. There are some empty values and it is only causing the issue. Thanks a lot for your help
Answer: You need to make sure you are not using null in a default comparison. This is a simple example:
var tmp = result.OrderBy(x => ((x.Dept == null) || (x.Dept.Deptname == null)) ? "" : x.Dept.DeptName).ToList();

If you want a really nice solution though, you should implement your own Comparator See more here:
Use own IComparer<T> with Linq OrderBy
Comment: You are welcome. The solution I gave is a quick solution. A much more elegant and beautiful solution is to have your own comparator, possibly applicable for more entity types and search types. It is longer to implement, but it will surely pay off on the long run. On the other hand, everyone needs the quick solution first to solve the urgent tasks.
Comment: Thanks!! Your solution had fixed my issue. I will also try to implement my own Comparator and will see how that goes. Thanks


Same Galois group for two polynomials

Question: Let $f$ and $g$ be two polynomials such that $f|g$ over some finite field $\mathbb{F}_p$ for some prime $p$. If $K_f, K_g$ are the number fields defined by these polynomials, i.e., $K = \mathbb{Q}[\theta]$ for some algebraic integer $\theta$ and minimal polynomial $f,g \in \mathbb{Z}[X]$, then is it true that $Aut(K_f) = Aut(K_g)$, i.e., they have the same Galois group ?
Thanks
Comment: The minimal poynomial of an algebraic number is irreducible. If $f$ an $g$ are minimal polynomials of numbers and $f$ divides $g$, then $f$ and $g$ are in factt equal.
Answer: No, this is false with trivial counterexamples. Let $f(x)=1$ and $g(x)=x^2+1$. Then clearly your conditions are satisfied but $K_f=\mathbb{Q}$ and $K_g=\mathbb{Q}(i)$ which have different automorphism groups ($\{e\}$ and $C_2$ respectively).
If you add the extra requirement that $deg(f),deg(g)>1$ then the theorem becomes true, but vacuously so because you require $g$ be irreducible (since it's the minimal polynomial of a number field) but also that $f|g$ which means that $f$ must be of degree $1$. Thus nothing satisfies the hypotheses so the statement is vacuously true.

Same Galois group for two polynomials


Why the name 'FACTORIAL'?

Question: Factorial is defined as
$n! = n(n-1)(n-2)\cdots 1$
But why mathematicians named this thing as FACTORIAL?
Has it got something to do with factors?
Comment: this ought to be cw.
Comment: I've heard of "shriek" as a name for the exclamation point symbol "!" in general, not just for its meaning of "factorial"; an emphatic word for an emphatic symbol.   This seems to come from the computer science world, where it's now been superseded by "bang".  See http://catb.org/jargon/html/B/bang.html, where the hard-to-pronounce "excl" is also cited.
Comment: Interesting... Cajori discusses the various notations adopted over the years, but never a mention of why it was called the "factorial". Maybe this article: http://dx.doi.org/10.1007/BF00389433 has the answers.
Comment: I was once told that an alternative name for the factorial `!` was "shriek" which makes EVEN LESS SENSE!
Comment: Seamus: It would probably interest you to know that it had been suggested at some point that n! be read as "n-admiration" (per Cajori).
Comment: I like saying $n!$ like "enn!!!!!!!!" in a really high, excited voice :)
Answer: Below is the etymology, from Jeff Miller's Earliest Known Uses of Some of the Words of Mathematics (F). Perhaps a native French speaker can lend further insight.

FACTORIAL. The earlier term faculty was introduced around 1798 by Christian Kramp (1760-1826).
Factorial was coined (in French as factorielle) by Louis François Antoine Arbogast (1759-1803).
Kramp withdrew his term in favor of Arbogast's term. In the Preface, pp. xi-xii, of his "Éléments d'arithmétique universelle," Hansen, Cologne (1808), Kramp remarks:
...je leur avais donné le nom de facultés. Arbogast lui avait substitué la nomination plus nette et plus française de factorielles; j'ai reconnu l'avantage de cette nouvelle dénomination; et en adoptant son idée, je me suis félicité de pouvoir rendre hommage à la mémoire de mon ami. [...I've named them facultes. Arbogast has proposed the denomination factorial, clearer and more French. I've recognised the advantage of this new term, and adopting its philosophy I congratulate myself of paying homage to the memory of my friend.]
Comment: Interesting! "faculty" is still used in German (as "Fakultät").
Comment: In Norway we call it "fakultet".
Comment: @Jens: I think that it only used by people who do not know the correct English word for it and use it because it sounds English and is close to the German word.
Comment: Apparently, in Swedish too!
Answer: Well, all positive integers smaller or equal to n are factors of n!
Comment: But that's true of other numbers (both smaller and larger) that aren't the factorial.

Why the name 'FACTORIAL'?


Conversão de struct com struct aninhado para record

Question: Estou com um pequeno "entrave" em um projeto que estou trabalhando. Nós recebemos uma DLL escrita em C, para podermos nos comunicar com leitores dessa empresa.
 Em anexo, veio um exemplo escrito em Borland C++ 6, que funciona corretamente. O problema consiste em usar essa DLL com o Delhpi XE5. Uma das rotinas devolve como resultado de sua operação um struct que tem outro aninhado. Segue abaixo os structs como definidos no Borland C.
struct stChannelInfo
{
  char ReaderTag[16];
  char ReaderEnabled;
 }

 struct stChannel
 {
   int ReaderNumber;
   struct stChannelInfo *ChannelInfo;
 }

A rotina que recebe esse struct é essa:
stChannels = this->deviceInterface->LookForAvailableChannels(EdDirectorySource->Text.c_str(), iSn, dateTimeStart, dateTimeEnd);
for(int i = 0; i < stChannels.ReaderNumber; i++)
 {
   CLbChannels->Items->Add(stChannels.ChannelInfo[i].ReaderTag);
 }

Eu escrevi este record que seria o equivalente em Delphi:
type stChannelInfo = record
 ReaderTag : string[16];
 readerEnabled : char ;
end;

type stChannel = record
 ReaderNumber:integer;
 ChannelInfo : ^stChannelInfo ;
end;

E a rotina que recebe o record em Delphi ficou assim :
DadosCanais := LookForAvailableChannels (Pchar(dirroot) , sn , datepickerinicial.DateTime,datepickerfinal.DateTime);
for i := 0 to (DadosCanais.ReaderNumber-1) do
 begin
  Showmessage(DadosCanais.ChannelInfo^.ReaderTag);
  inc(DadosCanais.ChannelInfo);
 end;

Pelo pouco que eu entendi do Borland C, o loop le da rotina lê os vários valores de stChannel.ChannelInfo.readerTag, mas em Delphi a string que eu recebo perde sempre o primeiro caracter e vem preenchida com espaços.
A definição de uso da rotina segundo o manual é esta:
/*
 Efetua a busca na base de dados de todos os canais do aparelho
 indicado que possuem dados disponíveis no intervalo selecionado.
 Version:
 1.00
 Parameters:
 *dataBaseFolder caminho da base de dados
 serialNumber numero de serie do aparelho
 firstLogTime timestamp inicial
 lastLogTime timestamp final
 Returns:
 stChannel Retorna uma estrutura com o numero de readers disponíveis e
 seus tags. Em caso de problemas, a estrutura terá o parâmetro
 "ReaderNumber" zerado.
*/
struct stChannel LookForAvailableChannels (const char * dataBaseFolder,
     int serialNumber, double firstLogTime, double lastLogTime)

Como eu poderia acessar os dados das tags dos readers? Não consigo imaginar uma forma para ler esses valores.
Comment: Achou alguma solução? Poste como resposta para ajudar outras pessoas.
Answer: Eu recebi de Remy , uma ajuda que estou postando aqui. Adaptei ligeiramente para o meu caso mas funcionou perfeitamente para este caso.
{$POINTERMATH ON}

 Type
  PstChannelInfo = ^stChannelInfo;
  stChannelInfo = record
  ChannelTag: array[0..CHANNEL_TAG_LENGTH-1] of AnsiChar;  // Tag (máx 16 caracteres)
  ChannelEnabled: AnsiChar;  // Habilitado se diferente de "0"
 end;

// Structure with information about channels
 stChannel = record
  ChannelNumber: Integer;  // Número de canais no buffer
  ChannelInfo: PstChannelInfo;  // Buffer com informações dos canais
 end;

 stChannels := Self.deviceInterface.LookForAvailableChannels(PChar(EdDirectorySource.Text), iSn, dateTimeStart, dateTimeEnd);
 for i := 0 to stChannels.ChannelNumber-1 do
  begin
   CLbChannels.Items.Add(stChannels.ChannelInfo[i].ChannelTag);  // Add to list the values found
  end;

Alternatively:
 Type
  PstChannelInfo = ^stChannelInfo;
  stChannelInfo = record
  ChannelTag: array[0..CHANNEL_TAG_LENGTH-1] of AnsiChar;  // Tag (máx 16 caracteres)
  ChannelEnabled: AnsiChar;  // Habilitado se diferente de "0"
 end;

 // Structure with information about channels
  stChannel = record
  ChannelNumber: Integer;  // Número de canais no buffer
  ChannelInfo: PstChannelInfo;  // Buffer com informações dos canais
 end;

 PstChannelInfoList = ^TstChannelInfoList;
 TstChannelInfoList = array[0..MaxInt-1] of stChannelInfo;
 stChannels := Self.deviceInterface.LookForAvailableChannels(PChar(EdDirectorySource.Text), iSn, dateTimeStart, dateTimeEnd);
  for i := 0 to stChannels.ChannelNumber-1 do
   begin
    CLbChannels.Items.Add(PstChannelInfoList(stChannels.ChannelInfo)^[i].ChannelTag);  // Add to list the values found
   end;

Comment: Você pode aceitar sua resposta.


Python regex extract IPs separated with colon

Question: Here is an example: '192.168.1.1;192.168.1.2'
My code:
import re
regex = '^((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)[;]?)+$'
r = re.match(regex, '192.168.1.1;192.168.1.2')
r.groups() # => ('192.168.1.2',)
# My expected result => ('192.168.1.1', '192.168.1.2',)

# re.findall(regex, '192.168.1.1;192.168.1.2') => ['192.168.1.2'] is not what I want......

I use () to capture each IP, but the result only shows one IP.
Is my usage wrong?
Thanks for your help.
Comment: [How can I find all matches to a regular expression in Python?](http://stackoverflow.com/questions/4697882/how-can-i-find-all-matches-to-a-regular-expression-in-python) and [Python - Using regex to find multiple matches and print them out](http://stackoverflow.com/questions/7724993/python-using-regex-to-find-multiple-matches-and-print-them-out) and [Get all possible matches for regex (in python)?](http://stackoverflow.com/questions/7383818/get-all-possible-matches-for-regex-in-python)
Comment: do u want both IPs on different lines?
Comment: @stribizhev I think the issue is with the regex, `findall` will not solve the problem.
Comment: Use [`findall`](http://docs.python.org/library/re.html#re.findall)
Comment: @Tushar `findall` doesn't show the two IPs in a list. I think maybe my regex is wrong...
Answer: Just use re.finditer()
import re
regex = '^((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)[;]?)+$'
for r in re.finditer(regex, '192.168.1.1;192.168.1.2'):
  print r.group()

You can use this regex also if u want:
regex = r'(\d{3}\.\d{3}\.\d\.\d)'
Comment: This only shows `192.168.11.1;192.168.12.1`, but I want to extract the two ip to a list.
Comment: use the regex provided by me and then append it to a list.
Comment: Oh..., you mean `regex = r'(\d{3}\.\d{3}\.\d\.\d)'` ? I think this format is not what I want.


Expected value of smaller broken piece

Question:
A stick having a length of $1$ is broken randomly at a point. Expectation of length of smaller part.

Source: brainstellar.com
My approach: Consider the stick is broken at $x$, then expectation of length of smaller part = $x*P(x<1/2) + (1-x)*P(x>1/2)$ = $x/2$ + $(1-x)/2$ = $1/2$. However, answer given is $1/4$.
Comment: @lulu this is not a duplicate question.  See my answer.
Comment: The length of the larger part will be randomly distributed among $~[1/2,1]~$ and the length of the smaller part will be randomly distributed among $~[0,1/2].$
Comment: Does this answer your question? [What is the expected length of the smaller piece?](https://math.stackexchange.com/questions/3260457/what-is-the-expected-length-of-the-smaller-piece)
Comment: I agree, but when solving expectation, we take that if x is less than 1/2, then length of smaller part is x and if it is greater than 1/2 then length of smaller part is (1-x) so that is what i have done here, can you point out where exactly it is wrong?
Answer: Actually, this is not a duplicate question, because the OP is asking where he went wrong.

My approach: Consider the stick is broken at $x$, then expectation of length of smaller part = $x*P(x<1/2) + (1-x)*P(x>1/2)$ = $x/2$ + $(1-x)/2$ = $1/2$. However, answer given is $1/4$.

In the 1/2 the time that $~x < (1/2),~$ you will need to take the average value of $~x~$ in this interval.  The average value of $~x~$ will be $~(1/4),~$ as indicated by the formula
$$\frac{\int_0^{1/2} x ~dx}{1/2 - 0} = \frac{x^2/2 ~|_{x=0}^{x=1/2}}{1/2} = 2 \times \frac{1/4}{2} = 1/4.$$
That is, the average value of an integrable  function $~f(x),~$ from $~a~$ to $~b,~$ where $~a < b~$ is
$$\frac{\int_a^b f(x) ~dx}{b-a}.$$

Expected value of smaller broken piece


Creating a dummy rails app with bundler for gem development?

Question: I'm using bundler for gem development, now I need a dummy rails app (usually in the test folder) for testing, there is a way to create a dummy rails app with bundler?
Answer: Just create it with the usual rails new command.


Displaying factors of a number

Question: I want to display every factor of a number typed in a textfield to achieve this I tried using an array. But I am always getting the error 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]' . Any suggestions to eliminate this error?
       NSMutableArray *array;
        array = [NSMutableArray arrayWithCapacity:100];

        for (factorsNumber=1; factorsNumber<=number; factorsNumber++) {
            if (number%factorsNumber == 0) {
                [array addObject:[NSString stringWithFormat:@"%d", factorsNumber]];
            }

        }

        for (int i = 0; i <= [array count]; i++) {
            factors.text = [NSString stringWithFormat:@"%d", i, [[array objectAtIndex:i] intValue]];
        }

Comment: The code works. But it is only displaying the first object in my array.
Answer: for (int i = 0; i <= [array count]; i++) {

should be
for (int i = 0; i <= [array count] - 1; i++) {

or
for (int i = 0; i < [array count]; i++) {

The valid indices of an n-element array are 0 to n-1.
Comment: Except, you set `factor.text = ...`. Maybe you should append to `factors.text`? (I don't know obj-c, so the guess could be totally off.)
Comment: Thanks now it works. But instead of giving me every factor of the number it only gives me the first one.
Comment: Probably because of `factorsNumber<=prime`. Shouldn't that be `factorsNumber<=number`?
Comment: Ah, sorry, hadn't refreshed. I think more code is needed to diagnose it, then.
Comment: In the snippet you have posted, I see no reason why it would only add one factor to the array. Perhaps the surrounding code would give a hint.
Answer: In your for loop, remove the = so that it reads:
for (int i = 0; i < [array count]; i++)

Answer: you problem is here:
for (int i = 0; i < [array count]; i++) { // < instead of <=
    factors.text = [NSString stringWithFormat:@"%d", i, [[array objectAtIndex:i] intValue]];
}

Displaying factors of a number


How Do I Figure Out How To Cable My Dell Powervault 220S?

Question: I have been handed an old Dell and RAID box that needs to be resurrected, however I can't figure out the magical combination of switches and cables needed to get the thing to go properly.
I have:

a Dell Poweredge 2850
a PERC 42/DI onboard
a PERC 4/DC expansion card
a PowerVault 220S with two Ultra-320 SCSI controllers
14 disks
two SCSI cables.

I don't know if the PowerVault is supposed to be in split-bus mode or not. The locals were playing with it (with everything, actually) before I got here.
The most promising configuration so far has been:

put the PowerVault into split-bus mode
connect the 4/DC channel-0 to the controller on the left - the one behind disks 0 - 8
connect the 4/DC channel-1 to the controller on the right

When I did this, each of the disks identified themselves as being a member of a 13-disk RAID-5 array. I then imported the configuration into the controller. However on reboot it is telling me that SCSI IDs 0, 2, 3, 4, 5, and 8 are not responding (ID 1 is flashing as bad so I presume that's a failed disk).
Is there something obvious I am doing wrong? Is there a way to read the disk configuration so that I can understand what the controller is expecting?
Answer: Are you actually trying to resurrect the RAID array, or start over fresh? Was this known to be working properly before you got it? Where did it come from?
If you don't know anything about it, and nor does anyone else (got it as surplus or from eBay?), then it is quite possible for there to be hidden lurking damage from the previous owner, such as a lightning strike or a hard fall off the back of a truck that broke one or more components.
The cleanest approach would be to simply try to format everything and start over fresh.
If you can determine at least one good drive in the collection that formats and reports no errors in its drive information, then you can then test progressively moving it from one slot to the next to see if you can still detect and read its drive information. If at any point you can't read these good drives, then you've found a bad/damaged slot connector or damaged controller.
Though there is some risk of peril here. If there is a problem with one or more slots, that problem can potentially damage good drives when they're plugged into bad slots (such as a damaged/deformed slot connector).
Once you know which drives and slots are bad, then you can move forward to create a new array from what remains, or seek out better undamaged replacement components.
I believe split-bus mode will increase data throughput, since the RAID controller can use both channels simultaneously to access any two drives across the two channels in parallel.
Comment: Unfortunately they are interested in the data on the array. The computer might have crashed; it definitely has one drive lost. There was a backup taken, but of course it is missing.
Comment: Have you looked through the Dell manuals for the 220S?  http://www.dell.com/support/home/us/en/19/product-support/product/powervault-220s/manuals   System install and troubleshooting guide: http://downloads.dell.com/manuals/common/powervault-220s_user%27s%20guide4_en-us.pdf


What is the technique that the 'top' program uses to redisplay data on the screen?

Question: As you probably know, when you run the "top" command in a terminal, it will show you the busiest processes on your computer and update the values periodically without adding a single line.
What is the technique called that allows it do this — to change the printed string from a CLI program?
Comment: If you don't want to use `curses`, you can almost always use ANSI escape codes (`"\033[H\033[2J"` to clear the terminal screen and move the cursor to the origin). At worst, if the terminal does not support it, you get seven garbage bytes on it. Practically all current terminals support at least the basic ANSI escapes. In Linux, `isatty(STDIN_FILENO)` returns 1 if standard input is a terminal; if it is, then normal ANSI escape sequences almost certainly work.
Answer: One way is to get the get the width/height of the terminal window, and just clear/print whole screen every time. Another way is to use VT100 escape codes to reposition cursor and overwrite whats on that position. A third way is to use a library such as ncurses.
Comment: Note, that the third way is a subset of the second way :)
Answer: Terminal accepts some control sequences for screen positioning, etc. Look into curses/ncurses library. Also, if you want to modify just one line you can do with just using \r and printing over that line again.


Unity: Problem with resolving RIA DomainContext

Question: I am using PRISM 4 and got my head around almost all features, however as soon as I would like to inject my DomainContext class (RIA) into my view model, the hell breaks loose. :)  It would be great if an experienced Unity/Prism developer could give me an advice how to proceed.
Within my bootstrapper, I am registering the required class in Unity Container like this:
protected override void ConfigureContainer()
        {
            base.ConfigureContainer();
            Container.RegisterType<SCMDomainContext>();
        }

Within the NavigationModule, I have the following in the ctor to register the NavigationView with a particular region.
public NavigationModule(IUnityContainer container, IRegionManager regionManager)
        {
            _container = container;
            _regionManager = regionManager;

            _regionManager.RegisterViewWithRegion(Constants.NavRegion, () => _container.Resolve<NavigationView>());

        }

The View takes the View Model as dependency:
 public NavigationView(NavigationViewModel viewModel)
        {
            InitializeComponent();

            Loaded += (s, e) =>
                          {
                              DataContext = viewModel;
                          };
        }

The ViewModel has the following:
public NavigationViewModel(SCMDomainContext context)
        {
            _context = context;
            ConstructCommon();
        }

As soon as I comment this ctor out and put a en empty ctor, it is all fine, for some reason I can't resolve the SCMDomainContext class. Which is the one you add to have the Domain Context created for you provided by Ria Services.
Since I am using Silverlight, I can't see the stack trace to follow the exception, all I get is this message on a page. What am I missing please?
Microsoft JScript runtime error: Unhandled Error in Silverlight Application An exception occurred while initializing module 'NavigationModule'.
    - The exception message was: Activation error occured while trying to get instance of type NavigationModule, key ''
    Check the InnerException property of the exception for more information. If the exception occurred
    while creating an object in a DI container, you can exception.GetRootException() to help locate the
    root cause of the problem.    at Microsoft.Practices.Prism.Modularity.ModuleInitializer.HandleModuleInitializationError(ModuleInfo moduleInfo, String assemblyName, Exception exception)
   at Microsoft.Practices.Prism.Modularity.ModuleInitializer.Initialize(ModuleInfo moduleInfo)
   at Microsoft.Practices.Prism.Modularity.ModuleManager.LoadModulesThatAreReadyForLoad()
   at Microsoft.Practices.Prism.Modularity.ModuleManager.IModuleTypeLoader_LoadModuleCompleted(Object sender, LoadModuleCompletedEventArgs e)
   at Microsoft.Practices.Prism.Modularity.XapModuleTypeLoader.RaiseLoadModuleCompleted(LoadModuleCompletedEventArgs e)
   at Microsoft.Practices.Prism.Modularity.XapModuleTypeLoader.HandleModuleDownloaded(DownloadCompletedEventArgs e)
   at Microsoft.Practices.Prism.Modularity.XapModuleTypeLoader.IFileDownloader_DownloadCompleted(Object sender, DownloadCompletedEventArgs e)
   at Microsoft.Practices.Prism.Modularity.FileDownloader.WebClient_OpenReadCompleted(Object sender, OpenReadCompletedEventArgs e)
   at System.Net.WebClient.OnOpenReadCompleted(OpenReadCompletedEventArgs e)
   at System.Net.WebClient.OpenReadOperationCompleted(Object arg)

Your help on this is highly appreciated,
Kave
Answer: I can't see much wrong here. But having said that, I'm using the Initialize method from the interface in the following way to register types and views for regions:
 #region properties
 [Dependency]
 public IUnityContainer Container { get; set; }

 [Dependency]
 public IRegionManager RegionManager { get; set; }
 #endregion

public virtual void Initialize()
{
   this.Container.RegisterType<NavigationViewModel>(new ContainerControlledLifetimeManager());
   this.Container.RegisterType<NavigationView>(new ContainerControlledLifetimeManager());

   this.RegionManager.RegisterViewWithRegion(Constants.NavRegion, () => this.Container.Resolve<NavigationView>());
}

Not sure whether it makes a difference if you don't explicitly register the ViewModel and the View type. Personally I prefer to have control over the way how a type gets resolved by the container.
Answer: In fact its best to create a layer for the DomainContext like this. Then its easily resolvable by an IoC:
public class ContactModuleService : IContactModuleService
    {
        readonly SCMDomainContext _context = new SCMDomainContext();

        #region Implementation of IContactModuleService

        public EntitySet<Contact> Contacts
        {
            get { return _context.Contacts; }
        }

        public EntityQuery<Contact> GetContactsQuery()
        {
            return _context.GetContactsQuery();
        }

        public SubmitOperation SubmitChanges(Action<SubmitOperation> callback, object userState)
        {
            return _context.SubmitChanges(callback, userState);
        }

        public SubmitOperation SubmitChanges()
        {
            return _context.SubmitChanges();
        }

        public LoadOperation<TEntity> Load<TEntity>(EntityQuery<TEntity> query, Action<LoadOperation<TEntity>> callback, object userState) where TEntity : Entity
        {
            return _context.Load(query, callback, userState);
        }

        public LoadOperation<TEntity> Load<TEntity>(EntityQuery<TEntity> query) where TEntity : Entity
        {
            return _context.Load(query);
        }

        #endregion
    }


Directing multiple domains to one server

Question: I would like to host 5 word-press blogs on my unlimited server space i bought from a web-hosting company similar to hostgator.
Now the companies say it is technically not possible to direct more than one domain to the hosting package and i would need to buy multiple hosting packages .
I read about vhost (apache),domain alias,ip forwarding
But not sure how ask my webhost about it when they say it is not possible
here is what i want to do
xhost.com/folder1  << www.x.com
xhost.com/folder2  << www.y.com
xhost.com/folder3  << www.z.com
xhost.com/folder4  << www.aa.com
the web host has a cpanel so dont know if they give/have access to vhosts if they are a reseller
thank you for your help
Answer: While Technically possible this may be an arbitrary limitation of your provider to increase revenue.
This is really a question for the host, if you want the technical information to actually set up your own server then you are in the right place. Unfortunately we can't usually help too much with provider specific issues. Without full access to the server and Apache config I doubt you would have much luck implementing this.
As to asking the host, you are correct, vhosts is the tech you want.
Answer: You can point as many domain names as you like to a single IP address. HTTP 1.0+ adds a Host header to the request so that the server can distinguish which of the domain names is being requested.
What you cannot do is have other services such as FTP, SSH, etc. use different domain names on the same IP address since they do not send something that the server can use to determine which domain name is being requested.


Sprite doesn't regenerate in Sprite Kit

Question: I am trying to get the sprite to regenerate itself once it moves off of the screen, but no luck.
<code>      #import "MyScene.h"

    @implementation MyScene

    -(id)initWithSize:(CGSize)size {
      if (self = [super initWithSize:size]) {
      /* Setup your scene here */

    self.backgroundColor = [SKColor colorWithRed:0.05 green:0.15 blue:0.2 alpha:1.0];

    SKSpriteNode *pole = [SKSpriteNode spriteNodeWithImageNamed:(@"pole")];
    bamboo.position = CGPointMake (30, 0);
    bamboo.size = CGSizeMake(15, 1136);

    [self addChild: pole];

    SKSpriteNode *pole2 = [SKSpriteNode spriteNodeWithImageNamed:(@"pole")];
    pole2.position = CGPointMake (290, 0);
    pole2.size = CGSizeMake(15, 1136);

    [self addChild: pole2];

    SKSpriteNode *spike = [SKSpriteNode spriteNodeWithImageNamed:(@"spike")];
    spike.position = CGPointMake (45, 600);
    spike.size = CGSizeMake(15, 75);

    SKAction *moveDown = [SKAction moveByX:(0) y:(-10) duration:(.05)];

    [spike runAction:[SKAction repeatActionForever:moveDown]];

    [self addChild: spike];

  }
  return self;
 }

 -(void)update:(CFTimeInterval)currentTime {
/* Called before each frame is rendered */
if (_spike.position.y < 250) {

    _spike.position = CGPointMake(45, 600);
 }

}

@end
</code>
What could be the problem? Xcode does not give me an error, the "spike" node simply moves off the screen and does not reset itself. I have changed the values in the conditional, but the same thing happens. It's like the conditional is being ignored.
Comment: Your conditional checking the location of the spike, will ONLY happen during this block of code when you create the spike, and not every frame. You understand that right ?
Comment: @prototypical That makes sense. Where would I place the conditional if I wanted it to update every frame? I put it in the currentTime update method to no avail.
Comment: Yes, you would put it the update method, and it does work. You likely have implemented it incorrectly. Check out the current answer, that should work. I also suggest that you learn about the debugger early on in your learning, as it will save you tons of time.
Answer: What you should do is to check Sprite's position in the update method, you can try this;
<code>-(id)initWithSize:(CGSize)size {
    if (self = [super initWithSize:size]) {
        /* Setup your scene here */

    _spike = [SKSpriteNode spriteNodeWithImageNamed:(@"spike")];
    _spike.position = CGPointMake (45, 600);
    _spike.size = CGSizeMake(15, 75);

    SKAction *moveDown = [SKAction moveByX:(0) y:(-10) duration:(.05)];

    [_spike runAction:[SKAction repeatActionForever:moveDown]];

    [self addChild:_spike];

    }
    return self;
}

-(void)update:(CFTimeInterval)currentTime {
    /* Called before each frame is rendered */

    if (_spike.position.y < 250) {

        _spike.position = CGPointMake(45, 600);
    }

}
</code>
Comment: As much as I would think this works, it does not. Any idea why?
Comment: ohh, did you write your code inside of "if (self = [super initWithSize:size])", other than that this code is working for me, can you tell what kind of error you are getting from xcode
Comment: Sorry, i should've been more clear. It isn't giving me an error, but the sprite node simply moves off of the screen, removes itself, and does not reappear.
Comment: can you edit your post by putting all of your code inside, so I can help you better
Comment: got it :), you have to use same _spikes everywhere, I edited my solution
Comment: Thank you so much! You just solved multiple problems of mine! Thanks again!

Sprite doesn't regenerate in Sprite Kit


Setup Galera Cluster with two servers

Question: Can I Create Gallera Cluster with two servers ??
Actually I have 6 servers:
2 Server for Load Balancer
2 Server for Apache
Or anyone here can suggest me how to create High Availability Web Server with 6 servers?
Thanks
Comment: Please try to do your home work and read the [vendor documentation](http://galeracluster.com/documentation-webpages/gettingstarted.html#system-requirements) - Second please to try to confine your questions a single question or at least to a single topic, because that makes answering them easier.
Answer: Yes you can. This is called a 2 + 1 set-up. 2 Galera nodes + 1 Galera arbitrator sitting on one of the app-server nodes.
But it is NOT a recommended set-up.
An alternative would be to put the Load Balancer on the app-servers. Then you have 3 db nodes and 3 app servers. But from the maintenance point of view this is more work than 2 central load balancers.
Regards,
Oli

Setup Galera Cluster with two servers


Python writing a csv to a list of dictionaries with headers as keys and rows as values

Question: I have a csv file, test.csv, as shown:
1,2,3
a,b,c
d,e,f

I want the above to look like a dictionary as shown:
{"1":"a", "2":"b", "3":"c"}
{"1":"d", "2":"e", "3":"f"}

where the header 1,2,3 are the keys and the rows are values.
I don't quite understand how to get this done using csv.DictReader. The above sample is just that, a sample. The actual data that I'm working with has many columns, and hence, I cannot access each row by using its index and manually putting them into a dictionary.
Comment: Have a look at this: http://stackoverflow.com/questions/19697846/python-csv-to-json
Comment: Thank you! This link is also a great help for my question.
Answer: Answering my own question. After trying for sometime I just now played around with it a bit more and added the for loop.
with open("test.csv") as f:
    records = csv.DictReader(f)
    for row in records:
         print row

This gives my desired output of
{'1': 'a', '3': 'c', '2': 'b'}
{'1': 'd', '3': 'f', '2': 'e'}

Comment: anyone curious, add `dialect='excel-tab'` to your DictReader call and it works with tabs.
Answer: By default first line will take as filedname in csv.DictReader
you can try
>>> a = open('/tmp/test.csv')
>>> a = csv.DictReader(open('/tmp/test.csv'), delimiter=',')
>>> [x for x in a]
[{'1': 'a', '3': 'c', '2': 'b'}, {'1': 'd', '3': 'f', '2': 'e'}]

This might be what your want


How to pass an array or an object from a module to a theme

Question: I have used hook_menu() with a page callback as follows:
function profilecb_menu() {
  $items['profilecb'] = array(
    'title' => 'Profile CB',
    'page callback' => 'pcb_exe',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

The callback code is the following:
function pcb_exe($id) {
  $ar = array('arg1'=> 'value1', 'arg2'=> $id);

  return $ar;
}

I have been able to make the callback function return a single string; when I try to return an array, I get an error.
All I need to do is to make the callback function do some tasks, like connecting to the database, and return to a template a complex array of useful information.
How can I do that?
Answer: In Drupal 6, a menu callback needs to return a string that contains the HTML to output together the output of other modules; alternatively, it can print the output and call exit().
If you need to pass an array to a theme function, then the output returned from the menu callback should be output from a theme function to which the menu callback passes an array.
function pcb_exe($id) {
  $ar = array('arg1'=> 'value1', 'arg2'=> $id);
  return theme('pcb_exe_output', $ar);
}

In Drupal 7 (and higher versions), the output of a menu callback is normally an array that has the format used by drupal_render().
It still possible to pass an array to a theme function, but the parameters passed to a theme function changed.
function pcb_exe($id) {
  $ar = array('arg1'=> 'value1', 'arg2'=> $id);
  return theme('pcb_exe_output', $ar);
}

In this case, there is no noticeable difference, as the parameter passed to the theme function was already an array.
The parameter passed to a theme function since Drupal 7 is an array containing all the values required from the theme function. See the code of theme_vertical_tabs() as example:
function theme_vertical_tabs($variables) {
  $element = $variables['element'];
  // Add required JavaScript and Stylesheet.
  drupal_add_library('system', 'drupal.vertical-tabs');

  $output = '
' . t('Vertical Tabs') . '
';
  $output .= '
' . $element['#children'] . '
';
  return $output;
}

Comment: I tried using your code above for the function pcb_exe($id) but it does not work. the page returned is blank. what could I be doing wrong?
Comment: I have drupal 7 BTW
Comment: @Charlie You need to define the theme function `theme_pcb_exe_output()` too, as Drupal doesn't define it.
Comment: And declare it in hook_theme(). I suggest you read http://api.drupal.org/api/drupal/includes--theme.inc/function/theme/7, that contains a lot of information about the theming API
Comment: @Charlie I am glad I could help you.


for loop chcek previous ID and skip iteration if needed

Question: I have this code,
<?php foreach($information as $info) : ?>
        <option selected="no" value="<?php echo $info['grade_id'];?>" id="<?php echo $info['grade_id'];?>">
            <?php echo $info['grade_desc'];?>
        </option>
<?php endforeach; ?>

Basically what this does is spit of some options for a select menu, however sometimes the select options get duplicated, is there a way so I only ever spit out 1 instance of each value? Using what I already have in the for loop? Some like check the $info['grade_id'] does not match the previous one and if it does skip that iteration?
This is what the information array looks like,
    array(4) {
  [0]=>
  array(20) {
    ["career_id"]=>
    string(2) "22"
    ["career_name"]=>
    string(7) "Builder"
    ["career_desc"]=>
    string(293) "Depending on the area of building that you would like to go into will depend on the aspects you will cover. Building covers- Civil Engineering, Electricians, Plunbers, Ground Workers, Brick Layers, Site Supervisors to name but a few. A career in construction can take you into many directions."
    ["degree_needed"]=>
    string(2) "No"
    ["useful_info"]=>
    NULL
    ["useful_links"]=>
    string(45) "http://www.bbcl.co.uk,
http://www.abe.org.uk"
    ["salary_id"]=>
    string(2) "20"
    ["basic_salary"]=>
    NULL
    ["trained_salary"]=>
    NULL
    ["progressed_salary"]=>
    NULL
    ["average_salary"]=>
    string(19) "Based on experience"
    ["careers_career_id"]=>
    string(2) "22"
    ["grade_id"]=>
    string(2) "53"
    ["grade_desc"]=>
    string(103) "GCSE grade D in Maths, English and the successful completion of Diploma Level 1 Brickwork or equivalent"
    ["course_id"]=>
    string(2) "52"
    ["course_type"]=>
    string(24) "Classroom based learning"
    ["course_names"]=>
    string(27) "Any combination of A Levels"
    ["extra_needed"]=>
    NULL
    ["course_link"]=>
    string(55) "http://www.blackburn.ac.uk/sixth_form_as_a2_levels.html"
    ["grades_grade_id"]=>
    string(2) "53"
  }
  [1]=>
  array(20) {
    ["career_id"]=>
    string(2) "22"
    ["career_name"]=>
    string(7) "Builder"
    ["career_desc"]=>
    string(293) "Depending on the area of building that you would like to go into will depend on the aspects you will cover. Building covers- Civil Engineering, Electricians, Plunbers, Ground Workers, Brick Layers, Site Supervisors to name but a few. A career in construction can take you into many directions."
    ["degree_needed"]=>
    string(2) "No"
    ["useful_info"]=>
    NULL
    ["useful_links"]=>
    string(45) "http://www.bbcl.co.uk,
http://www.abe.org.uk"
    ["salary_id"]=>
    string(2) "20"
    ["basic_salary"]=>
    NULL
    ["trained_salary"]=>
    NULL
    ["progressed_salary"]=>
    NULL
    ["average_salary"]=>
    string(19) "Based on experience"
    ["careers_career_id"]=>
    string(2) "22"
    ["grade_id"]=>
    string(2) "53"
    ["grade_desc"]=>
    string(103) "GCSE grade D in Maths, English and the successful completion of Diploma Level 1 Brickwork or equivalent"
    ["course_id"]=>
    string(2) "53"
    ["course_type"]=>
    string(24) "Practical based learning"
    ["course_names"]=>
    string(19) "Bricklaying Level 2"
    ["extra_needed"]=>
    string(3) "Yes"
    ["course_link"]=>
    string(45) "http://www.blackburn.ac.uk/bricklaying_2.html"
    ["grades_grade_id"]=>
    string(2) "53"
  }
  [2]=>
  array(20) {
    ["career_id"]=>
    string(2) "22"
    ["career_name"]=>
    string(7) "Builder"
    ["career_desc"]=>
    string(293) "Depending on the area of building that you would like to go into will depend on the aspects you will cover. Building covers- Civil Engineering, Electricians, Plunbers, Ground Workers, Brick Layers, Site Supervisors to name but a few. A career in construction can take you into many directions."
    ["degree_needed"]=>
    string(2) "No"
    ["useful_info"]=>
    NULL
    ["useful_links"]=>
    string(45) "http://www.bbcl.co.uk,
http://www.abe.org.uk"
    ["salary_id"]=>
    string(2) "20"
    ["basic_salary"]=>
    NULL
    ["trained_salary"]=>
    NULL
    ["progressed_salary"]=>
    NULL
    ["average_salary"]=>
    string(19) "Based on experience"
    ["careers_career_id"]=>
    string(2) "22"
    ["grade_id"]=>
    string(2) "54"
    ["grade_desc"]=>
    string(96) "3 GCSE passes at grade D and above preferably in English, Maths, Science or a Technology subject"
    ["course_id"]=>
    string(2) "54"
    ["course_type"]=>
    string(16) "learn on the job"
    ["course_names"]=>
    string(24) "Apprenticeship Brickwork"
    ["extra_needed"]=>
    NULL
    ["course_link"]=>
    string(56) "http://www.blackburn.ac.uk/apprentices_construction.html"
    ["grades_grade_id"]=>
    string(2) "54"
  }
  [3]=>
  array(20) {
    ["career_id"]=>
    string(2) "22"
    ["career_name"]=>
    string(7) "Builder"
    ["career_desc"]=>
    string(293) "Depending on the area of building that you would like to go into will depend on the aspects you will cover. Building covers- Civil Engineering, Electricians, Plunbers, Ground Workers, Brick Layers, Site Supervisors to name but a few. A career in construction can take you into many directions."
    ["degree_needed"]=>
    string(2) "No"
    ["useful_info"]=>
    NULL
    ["useful_links"]=>
    string(45) "http://www.bbcl.co.uk,
http://www.abe.org.uk"
    ["salary_id"]=>
    string(2) "20"
    ["basic_salary"]=>
    NULL
    ["trained_salary"]=>
    NULL
    ["progressed_salary"]=>
    NULL
    ["average_salary"]=>
    string(19) "Based on experience"
    ["careers_career_id"]=>
    string(2) "22"
    ["grade_id"]=>
    string(2) "55"
    ["grade_desc"]=>
    string(164) "Ascentis Entry Level 3 Certificate in Preparation for Employment in Construction Industries
A Functional Skills Certificate at Entry Level 3
A PSHE Certificate "
    ["course_id"]=>
    string(2) "55"
    ["course_type"]=>
    string(24) "Practical based learning"
    ["course_names"]=>
    string(78) "Construction - Preparation for Employment in Construction Industries - Level 3"
    ["extra_needed"]=>
    NULL
    ["course_link"]=>
    string(74) "http://www.blackburn.ac.uk/preparation_for_employment_in_construction.html"
    ["grades_grade_id"]=>
    string(2) "55"
  }
}

You can see in the output there are 2 [grade_desc] the same GCSE grade D in Maths, English and the successful completion of Diploma Level 1 Brickwork or equivalent. However there is only one record in the database, can I just strip any repeated data of the array?
Comment: Do a `var_dump($information);` and see if the duplicates are in there. How are you gathering this data — from a database, a text file, hardcoded, etc?
Comment: imo would be easier to do this ~before~ passing the data to foreach() - perhaps at query stage if the data comes from a database. If you don't want duplicate data here, that suggests you don't want duplicate data elsewhere - maybe a rethink of the structure is needed.
Answer: try
  foreach(array_unique($information) as $info)

plus, pay attention to Ross's comment: it might be better to optimize your db query in the first place
plus, variable names "$information" and "$info" just suck. I hope it's only an example!
Answer: use array_unique on $information variable before using it in foreach.
example:
<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>

Check above code
Answer: Use an additional variable where you store the last grade ID:
$lastGradeID = null;
foreach ($information as $info) :
    if ($lastGradeID !== $info['grade_id']) :
?>
…
<?php
    endif;
    $lastGradeID = $info['grade_id'];
endforeach;


How can I calculate sum and average in while loop (python?)

Question: Serendipity Booksellers has a book club that awards points to its customers
based on the number of books purchased each month. The points are awarded as
follows:
• If a customer purchases 0 books, he or she earns 0 points.
• If a customer purchases 2 books, he or she earns 5 points.
• If a customer purchases 4 books, he or she earns 15 points.
• If a customer purchases 6 books, he or she earns 30 points.
• If a customer purchases 8 or more books, he or she earns 60 points.
Write a python program that asks the user to enter the number of books that he or she
has purchased this month, then displays the number of points awarded.
However, my professor asks me to add:

Use a while loop for allowing the program to run repeatedly.
Prompt user to enter the number of books.  Also, prompt that to stop the program, the user must enter a negative number.
Each time user enters the number of books.  Numbers can be any positive number,  0 or more. The program should calculate points correctly.
After the program stops, it prints the number of users, the total points offered to users, and the average points given to each user.
Make sure the output print is descriptive and meaningful
Include minimum but meaningful comments to understand what your program does.

Here is what I did
# Prompt: To stop the programming, you just enter the negative number
print("To stop the programming, you just need to enter the negative number.")

# Prompt user to enter the number of books
while True:
    books = float(input("\nEnter your number of book purchased this month: "))
    if books < 0:
        break
    elif books<2:
            print("Your number of book purchased this month is ",books)
            point=0
            print("Your total point is",point)
    elif books<4:
            print("Your number of book purchased this month is ",books)
            point=5
            print("Your total point is",point)
    elif books<6:
            print("Your number of book purchased this month is ",books)
            point=15
            print("Your total point is",point)
    elif books<8:
            print("Your number of book purchased this month is ",books)
            point=30
            print("Your total point is",point)
    else:
            print("Your number of book purchased this month is ",books)
            point=60
            print("Your total point is",point)

I do not know how to prints the number of users, the total points offered to users, and the average points are given to each user after the user stop the program
Comment: What is your question?
Comment: It's easy to get caught up in all the context, but the issue you're facing is probably fundamental across all problems - try to focus on that. I'm not going to read your assignment
Comment: @HarveyHardy, the users can be saved into an array where each index will represent the customer/user and the value will represent the points collected. At the end, you can get the average easily
Comment: See how to create a [mcve]. We're volunteers here and most of what you've posted is completely irrelevant. Do the work of reducing your problem to as minimal a case as possible.
Comment: I do not know how to it prints the number of users, the total points offered to users and the average points given to each user after the user stop the program
Comment: Yes, start by forgetting about all the details except how to work out how many users have entered a number of books.
Answer:
I do not know how to it prints the number of users, the total points offered to users and the average points given to each user after the user stop the program

For total users, make a variable user_count which is the count of users recorded.
For the total points, make a variable point_total which is the cumulative points of users recorded.
For the average points, divide point_total by user_count.
I also note you have a lot of repeated code. You can reduce this easily:
user_count = 0
point_total = 0

print("To stop the program, just enter a negative number.")

while True:
    books = int(input("\nEnter your number of books purchased this month: "))
    if books < 0:
        break
    elif books < 2:
        point = 0
    elif books < 4:
        point = 5
    elif books < 6:
        point = 15
    elif books < 8:
        point = 30
    else:
        point = 60

    print("Your number of books purchased this month is", books)
    print("Your total points are", point)

    user_count += 1
    point_total += point

if user_count > 0:
    point_average = point_total / user_count
else:
    point_average = 0

print("Total number of users recorded", user_count)
print("Total number of points recorded", point_total)
print("Average number of points recorded", point_average)

Bonus
If you want to get really fancy, you could use a dictionary to store the points versus their thresholds, and use the next method plus a generator expression to map books to a points value.
# Map points to the maximum books required.
thresholds = {
    0: 2,
    5: 4,
    15: 6,
    30: 8,
    60: float('inf'),
}
...
while True:
    books = int(input("\nEnter your number of books purchased this month: "))
    if books < 0:
        break
    # Find the first value for points which is less than
    # its maximum number of required books.
    points = next(
        points
        for points, threshold in thresholds.items()
        if books < threshold
    )


How to manage large projects without Visual Studio?

Question: How does one go about keeping track of source files, resources, references, assemblies, etc.. if they didn't want to use Visual Studio. I know you can compile code with csc, and use csc to add all of the references, etc.. but it becomes quite painful to add these references as the project grows.
How do you manage it when splitting the project up into separate folders (different modules, etc..) and how do you manage dependencies, build order, etc..
Are there any open source (free) projects for managing this? Even so, is it fairly simple for one to do this without having to download any 3rd party programs?
Comment: You just want to skip on buying Visual Studio? If the price is the problem, you can download a free version that has less features.

If you're a professional then you should buy a license, it's a great IDE.
Comment: Also if you have a business that's less than 3 years old and meet a few other easy conditions, you can get MSDN (including the full Visual Studio) for free, with a $100 "exit" fee once the free period is up. http://www.microsoftstartupzone.com/pages/home.aspx
Comment: No, I don't want to avoid paying for Visual Studio. I actually own a copy. I am just an avid ViM user, and really do not like any of the plugins for vim+visual studio. I wanted to see if I can manage the project I am working on with just vim. I have intellisense setup, I compile and it lists the errors in the same window. I am working on highlighting specific lines. Would like to NOT use .sln and .csproj files.
Comment: I still think you want MSBuild.  Its output is regular/parseable, should be easy to wire up e.g. for compiling, listing errors, etc.  An even .proj files, while not beautiful, are often straightforward to edit/manage 'by hand' with an editor.  And if you get to know MSBuild well, it is quite powerful.  I would not dismiss it too lightly; I would think it would be compatible with your ultimate goals for a Vim-heavy 'IDE'.
Answer: You can still use MSBuild as well as project and solution files provided you know their format.
Comment: Indeed - MSBuild is "the" solution.  Even if you are using VS, MSBuild is doing all the heavy lifting here.  And MSBuild is part of the .Net Framework, msbuild.exe lives right next to csc.exe.
Answer: You can use many of the Open Source Build Systems for C#.
Of these, NAnt is quite popular, especially for people transitioning from Java.
Answer: As long as your projects arent complex (referencing lots of assemblies, resource files, etc). You can manage with just an editor and "autogenerated" csproj files. The basic structure of the csproj file is very straightforward, and the same in 80% of the projects, setup a pre-build task to construct the csproj from template and then execute csc.
NAnt I believe has a generic task for "build directory" that would let you do it, but you will have to have some automation to setup the nant scripts initially.
Answer: You can actually use makefiles if you're really keen. Some of our early .NET integration into our build system uses makefiles rather than csproj. However it is something of a black art which I have personally never fully understood, i.e. sorry I can't give you any prescriptive advice/samples. Nowadays we just msbuild which is considerably easier.


Regression predicting 2 dependent variables

Question: Imagine I have a big dataset $\textbf{X}$ that constitutes my independent variables and I want to predict a vector of 2 components, $\mathbf{Y} = (y_1, y_2)$. A regression will be something like $\mathbf{Y} = f(\textbf{X}, \textbf{W})$, with $\textbf{W}$ the weights or coefficients and $f$ a function that can be linear or highly non-linear.
I know how to do the regression for each $y_i$ (with $f_i$ and in general $f_1 \neq f_2$), but does it exist a way to do the regression simultaneously, that is, predicting a vector of 2 components instead of predicting a scalar value?
Comment: Try the [`multivariate-regression`](https://stats.stackexchange.com/questions/tagged/multivariate-regression?sort=votes) tag. We have many questions relating to it.
Comment: In econometrics this is called "seemingly unrelated regression". Try googling that.
Comment: Sometimes simultaneous estimation is not required. See my other answer. https://stats.stackexchange.com/questions/328797/why-do-we-use-vector-autoregressive-models/328933#328933. Other times simultaneous estimation is performed by stacking the data into a special matrix form and solving it (Seemingly Unrelated Regression).
Answer: PLS2 and multivariate multiple linear regression allow modelling of a set of dependent variables. The advantage of a single model for multiple predictors is that the model can use relationships between the dependent variables. For example PLS2 reduces the variance in both X and Y then the covariance between these two blocks.


What is the least number of concerts needed to be scheduled in order that each musician may listen, as part of the audience, to every other musician?

Question:
Six musicians gathered at a music festival. At each concert
some musicians played in the concerts while the others listened, as part
of the audience. What is the least number of concerts needed to be scheduled in order that each musician may listen, as part of the audience, to
every other musician?

I have managed to find that $4$ concerts works if we let the players be $A,B,C,D,E$ and $F$, then $A,B,C$ playing first, $B,E,F$ second, $C,D,E$ thirdly and $A,D,F$ last is a working construction.
Now the issue I'm having is that I cannot prove that the cases with $3,2$ and $1$ concerts are not possible.
Well the first one is easy since no two players are able to hear each other out ever, but how can I argue for the cases $3$ and $2$?
Comment: Well, every possible division for the first concert has one group (audience or performers) with at least three members, call them $A,B,C$.  Then, in the next concert two of those (at least) must be in the same group.
Comment: @MJD See my answer for an explanation of how the OEIS page applies to the case of $n$ musicians.
Comment: This problem appears in Terence Tao's book _Solving Mathematical Problems: A Personal Perspective_
Comment: @MJD Enjoyed your blog post - I think I remember reading it before! About different numbers of musicians: you wrote "I have a method that I'll describe in a future article". Did you ever get around to the sequel?
Comment: No, and I also forgot what the method was!
Comment: This appears to be sequence [A305233](https://oeis.org/A305233) in the OEIS.
Comment: The description of A305233 says "Minimal size of a set with n subsets such that no one contains another". I don't understand how that is isomorphic to this problem.
Comment: As this is Math.SE, I say we define the audience to be every person in the room who can hear the concert.  Then, trivially, the case of 1 concert is proven.
Comment: Those four acts would be part of one concert, so the obvious answer is 1.
Comment: Anything about bipartite graphs in this?
Answer: There are a total of $6\cdot5=30$ (listener, performer)-pairs.
If at a concert we have $n$ performers, then in that concert there are $(6-n)n$ such (listener, performer)-pairs. The maximum value of $(6-n)n$ is $9$, achieved when $n=3$.
As $30/9>3$ there is no way three concerts would suffice. Congratulations on finding a set of four concerts that works!
Answer: Given a schedule with $n$ concerts, define $S_1,\dots,S_6$ to be subsets of $\{1,\dots,n\}$, where $S_i$ is corresponds to the set of concerts that musician number $i$ played in. For example, if $n=6$, and the third musician played in concerts numbered $2,4,$ and $5$, then $S_3=\{2,4,5\}$.
If $S_i\subseteq S_j$, then every concert $i$ played in would have $j$ playing also, meaning $j$ would never sit in the audience for $i$. Since we need to avoid this, it must be the case that $S_i\not\subseteq S_j$ for all $i,j\in \{1,\dots,6\}$, $i\neq j$. This means that the list $S_1,\dots,S_6$ is an anitchain in the Boolean poset of $2^{\{1,\dots,n\}}$. (For any set, $S$, $2^S$ is the set of subsets of $S$).
Sperner's theorem says that the largest antichain in $2^{\{1,\dots,n\}}$ has a size of $\binom n{\lfloor n/2\rfloor }$. Therefore, in the case where $n=3$, the largest antichain has size $\binom 31=3$. Since no antichain of size $6$ exists, you cannot succeed with only three concerts. On the other hand, you showed that you can suceed with four concerts, so you have found the optimal solution. In fact, since $\binom 42=6$, there is no "slack", and you need to use the maximal antichain of the size-two subsets of $2^{\{1,2,3,4\}}$. Every valid schedule is therefore equivalent to yours, up to permutation of people and concerts.
An example of a schedule is below. Note if you read by columns, you see every pattern of $2$ X's and $2$ blanks exactly once.
$$
\begin{array}{c|cccccc}
 & M_1&M_2&M_3&M_4&M_5&M_6
\\\hline
C_1 & \times &\times &&\times &&
\\
C_2 &\times &&\times &&\times
\\
C_3 & &\times &\times & &&\times
\\
C_4 &&&&\times&\times&\times
\end{array}
$$
In general, if there are $n$ musicians, then in order to succeed with $k$ concerts, it is necessary that
$$
\binom{k}{\lfloor k/2\rfloor} \ge n
$$
Therefore, the optimal number of concerts is the smallest such $k$ for which the above is true. This corresponds to the following OEIS sequence: https://oeis.org/A305233. You can prove that
$$
\text{# concerts needed for $n$ musicians}=\log_2 n+\frac12\log_2 \log_2 n +O(1)
$$
as $n\to\infty$. You can prove this using the fact that $\binom k{k/2}\sim (\pi k/2)^{-1/2}2^k$ as $k\to\infty$.
The optimal schedule for $n$ musicians is as follows. With $k$ defined as above, assign each musician a distinct subset of $\{1,\dots,k\}$ whose cardinality is $\lfloor k/2\rfloor$. For each $i\in \{1,\dots,n\}$, the $i^\text{th}$ musician will play in concert number $j$, for each $j$ in their assigned set.
Comment: +1 I did not know/recall Sperner's theorem. There was a (low quality) question yesterday, that would have benefitted from having it. I did suggest $\binom{2\ell}\ell$ construction in a comment, but can't find the question now. May be it was deleted?
Comment: An advantage of this approach is that you've shown three concerts would still be insufficient even if we only had four performers.
Comment: @EspeciallyLime Indeed. More generally, if there are $n$ musicians, my approach implies the optimal number $k$ of concerts is the smallest number for which $\binom k{\lfloor k/2\rfloor}\ge n$, which implies $k=\log_2 n +\frac12\log_2\log_2 n +O(1)$.


Calculating algorithm sizes

Question: I am reviewing BigO notation from this document: http://www.scs.ryerson.ca/~mth110/Handouts/PD/bigO.pdf
This document contains this information and the accompanying table:

In the following table we suppose that a linear algorithm can do a problem up to size 1000 in 1 second. We then use this to calculate how large a problem this algorithm could handle in 1 minute and 1 hour.

I can see where values such as $n^2$ come from, as it is getting the square root of 1000. However, I am at a loss as to how the author calculated $2^n$ and $n log(n)$. Could someone help determine how these values are calculated?
Answer: For $2^n$, you just take the logarithm to the base $2$.
For $n\log n$, you are looking for the largest integer $n$ such that $n\log n$ does not exceed, say, $1000$. You can do that by just trying different values of $n$, zeroing in on the right value; there are more systematic ways, such as Newton's Method --- someone just asked a question here about solving $n\log n\le1,000,000$, maybe you could dig up that question and see what's written there.
Comment: Thanks! Logs are a tricky thing for me. Now to see if I can find that other question.

Calculating algorithm sizes


How do I display multilingual logos in D7?

Question: I have read almost every tutorial on the net about how to setup multilingual logos. Yet, I cannot get anything to work.
How do I get multilingual logos to display in D7? I have added
<code>$conf['i18n_variables'] = array(
    'logo_path',
    'theme_XXX_settings',
);
</code>
I have also uploaded using the form for the theme settings while in the langauge of the logo I want to display. All languages are set to whatever file I upload last.
Do I need to use a different variable in the conf array? Do I need to print a different variable other than $logo in the theme?
Can someone who's done this give some very specific instructions or provide a link to a recent d7 tutorial?
Answer: For D7, this is very painless.
In i18n, enable 'Variable Translation' module. To do so, be sure to have at least variable 7.x.2.x, else this module is not available. Here is the text from the module page:
<code>Multilingual variables that switch language depending on page language.
Requires: Internationalization (enabled), Locale (enabled), Variable
(enabled), Variable store (7.x-2.x) (incompatible with version 7.x-1.2),
Variable realm (7.x-2.x) (incompatible with version 7.x-1.2)
</code>
After that, go to:
configuration->Multilingual settings->variables (tab)->Theme settings. check the boxes. Then go to your theme and set a logo for each language.
That's it!


How to decrease java heap size?

Question: I've got an app which is running on JBoss. The server's RAM is too low (about 2gb), so I need to decrease Java heap size. Also I've got 2 versions of Java : system version(1.4.2) and 1.7.0 for JBoss 7 only.
So, how can I decrease Java heap size properly?
Comment: Are you getting an error message about heap, or is the java process using up too much memory on the server?
Comment: No, I'm not getting an error. My production server was working well, until I've installed JBoss. So, I decided to decrease Java heap size.
Answer: There are two flags to control the heap size: -Xms128m will start your heap at 128 megs, and -Xmx1g controls the maximum size (here, it would set it to 1 gig).
Answer: You can change the heap size in jboss startup file, edit bat or sh file and search for -Xms and change it to your required size.
Answer:
Default size of Heap space  in Java is 128MB on most of 32 bit Sun's JVM and default values of heap size parameters on 64-bit systems have been increased up by approximately 30%.

You can use
java -XX:+PrintFlagsFinal -version | grep HeapSize

to check your default size.
Read more
You can change size of heap space by using JVM options -Xms and -Xmx. Xms denotes starting size of Heap while -Xmx denotes maximum size of Heap in Java.
You can use
java -Xms1024M -Xmx2048M YourApp
Or edit the /bin/run.sh|exe file by searching for "Sun JVM memory allocation pool parameters" and changing the JAVA_OPTS line:

set JAVA_OPTS=%JAVA_OPTS% -server -Xms1152m -Xmx1152m -XX:MaxPermSize=128m
  -XX:MaxNewSize=128m

How to decrease java heap size?


Correct answer for this limit?

Question: So I tutor this student, and we came to the conclusion that the delta needs to be 0.1975, but her TA thinks it should be 0.2025. This was a homework question for her, and she got it wrong because she originally had what I had. Where did I go wrong, and how can you prove it using the epsilon delta proof? Everything I have found, and every attempt at a solution I give says that we were correct...
I found this answer by finding b and c, then finding the distances from x=4. Knowing the nature of $\sqrt{x}$, the shortest distance would need to be delta to avoid being outside the range of epsilon by picking the larger distance. This comes out to the distance from b to 4, which is 0.1975.
I proved this using the standard epsilon delta proof and it worked out. If needed, I can go through my steps here
Comment: you are correct though
Comment: IMHO asking students to find the largest possible $\delta$ that still works is pedagogically harming. It reinforces the misguided thinking that proofs about limits are about solving inequalitites as opposed to making possible crudy but sufficient estimates.
Comment: We could tell where you went wrong _only_ if you show how you arrived to the answer.
Comment: @user58697 apologies! Im not sure where it went...
Comment: @JyrkiLahtonen they arent my favorite either, but they are common questions so I have to help when needed
Comment: The TA is wrong.  You are correct, and so is the reason you gave.
Comment: @JyrkiLahtonen: the question is not asking the *largest* $\delta$, just *some* $\delta$, and is fully right in doing so.
Comment: From the figure, it is obvious that $\delta\le4-b<c-4$.
Comment: @YvesDaoust Looking at the picture, and judging from the fact that they ask for $b$ and $c$ (totally irrelevant pieces of information), I'm hard pressed to think of another motivation. You're right in that it doesn't matter. But I have seen so many generations of calculus students wasting effort on such questions... Anyway, there is no single "correct" answer. Any $\delta\le\min\{4-b,c-4\}$ will do equally well.
Comment: @JyrkiLahtonen: this is exactly what they mean by "find *a* positive number". Your grumbling is unjustified, you misread the question. And $b,c$ are absolutely relevant as they are upper bounds for $\delta$, without which you would have to answer by trial and error, which would be pedagogically harming.
Answer: The TA's answer is clearly incorrect, because if $\delta = 0.2025$, you can choose $x = 3.8$, which satisfies the condition $|x - 4| < \delta$, but not $|\sqrt{x} - 2| < 0.05$.  If the TA cannot accept this simple counterexample, then they are not competent to grade this question.
Answer: Your answer is correct!
Note:
$$|x-4|<\delta \Rightarrow 4-\delta <x<4+\delta \Rightarrow \sqrt{4-\delta}<\sqrt{x}<\sqrt{4+\delta}\\
|2-\sqrt{x}|=\big{|}\frac{(2-\sqrt{x})(2+\sqrt{x})}{2+\sqrt{x}}\big{|}=|\frac{4-x}{2+\sqrt{x}}|<\frac{\delta}{2+\sqrt{4-\delta}}=\epsilon=0.05 \Rightarrow \delta=0.1975.$$
Answer: Sanity check:
$$\begin{align}|\sqrt{4-0.1975}-2|&=\color{green}{0.05}
\\|\sqrt{4+0.1975}-2|&=\color{green}{0.04878\cdots}
\\|\sqrt{4-0.2025}-2|&=\color{red}{0.06415\cdots}
\\|\sqrt{4+0.2025}-2|&=\color{green}{0.05}\end{align}$$

Correct answer for this limit?