How to get ready a C++ project with OpenGL, Glut and Visual Studio 2008 in Windows 7

Question: As I had many problems setting Visual Studio 2008 for using OpenGL I will ask this question that can be useful to some people:

Which are the steps to follow in order to use OpenGL with C++ in Visual Studio 2008?
Comment: mmm, not really, there's no GLUT or Winodws 7 in the question and tags, and there's no good answer
Comment: duplicate of http://stackoverflow.com/questions/822750/setting-up-opengl-with-c-and-visual-studio-2008
Comment: You don't need GLUT, it's not a vital part of OpenGL. Of course if you want to compile some tutorial that uses GLUT you'll have to install it.
Comment: And what do you suggest instead of GLUT, just to give a try and see if I like it more?
Answer: First of all you need to have a video card and check that it works with OpenGL and the drivers are updated. I used the test in this link to check it.
It is also important to check that Visual Studio 2008 is correctly installed and that the following path is created in your computer:

C:\Program Files\Microsoft SDKs\Windows\v6.0A

Now we can follow the installation steps:
1.- Download GLUT from https://www.opengl.org/resources/libraries/glut/glut_downloads.php, unzip and copy the files as instructed below:

glut.h to the folder C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include\gl\
glut32.lib to the folder C:\Program Files\Microsoft SDKs\Windows\v6.0A\Lib\
glut32.dll to the folder  C:\Windows\System32\

2.- Create an empty C++ Win32 application:

From File menu select New → Project (Ctrl+Shift+N).
Select Win32 Project, enter a Name, and click OK.
In the Wizard click Next, then check the box next to Empty Project,
and click Finish.

3.- Add a new C++ source file:

Under the Project menu select Add New Item (Ctrl+Shift+A).
Select C++ File (.cpp), enter a Name, and click OK.

4.- Link to the OpenGL libraries (important step):

Under the Project menu select Project Properties (Alt+F7) at the bottom.
Select Configuration Properties → Linker → Input from the navigation panel on the left.
Select All Configurations from the Configuration drop-down box at the top of the dialog. This ensures you are changing the settings for both the Debug and Release configurations.
Type "opengl32.lib glu32.lib glut32.lib" in Additional Dependencies and click OK (the opengl32.lib and glu32.lib are already in the system, and glut32.lib will be after downloading GLUT).

5.- Download this sample code.
6.- It is also necessary to set the paths in Visual Studio:

In Tools -> Options -> VC++ Directories -> Include Files:

C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include

In Configuration Properties → Linker → Additional Library
Directories:

C:\Program Files\Microsoft SDKs\Windows\v6.0A\Lib
Comment: Wow, it's hard to get a good answer. I had problems because i didn't install the GForce drivers, and then the includes... You are clever man
Comment: I know, but the question is how to set GLUT, openGL and Visual Studio 2008 specifically.
Comment: You don't need GLUT. It's not a vital part required for developing with OpenGL. In fact I (personally) strongly disregard its use.
Answer: MSDN has a section on OpenGL that should help out, including sample code.


Applescript: play two sounds simultaneously

Question: I am using Applescript to test melodies for carillon with the real sounds of bells.
Now, I wish I could play a chord of 2 or 3 notes simultaneously.
So far, this is my best:
 do shell script "afplay -t 0.000001 " & (quoted form of (bell1.mp3))
 do shell script "afplay -t 0.2 " & (quoted form of (bell2.mp3))

Any idea?
Thank you in advance.
Answer: do shell script work synchronously. You need to tell the first call not to wait:
do shell script "afplay " & (quoted form of bell1.mp3) & "> /dev/null 2>&1 &"
do shell script "afplay " & (quoted form of bell2.mp3)

Comment: I cannot tell how long I need to bless you for your help... Thank you!


Better practice to throw custom PHP errors using procedural way

Question: I know this question may be asked previously but I want to show my code and I would like to know that whether am doing a simple thing or complicating the code? Moreover answers say use try and catch but am going with procedural method so I would like to know that am I going right?
What I do it, for example a contact form
<?php
if(isset($_POST['contact'])) {
    $throw_error = array();

    //First Block Is Validation
    if($_POST['first_name'] == '' || $_POST['last_name'] == '') {
        $throw_error['field_blank'] = 'Fields Cannot Be Blank';
    } elseif(strlen($_POST['first_name']) < 3) {
         $throw_error['char_len'] = 'First Name Cannot Be Less Than 3 Characters';
    }

    //Second Block Is Process If No Errors Are Found
    if(empty($throw_error)) {
        $first_name = $_POST['first_name'];
       //Don't worry about the sanitizing part, am doing it
       //Process the form ahead and then redirect using header()
       }
    } elseif(!empty($throw_error)) { //Third Block To Throw Error If Any Errors Found
        if(isset($throw_error['field_blank'])) {
            echo  $throw_error['field_blank'];
        } elseif(isset($throw_error['char_len'])) {
            echo  $throw_error['char_len'];
        }
    }
?>

<form>
   <input type="text" name="first_name" />
   <input type="text" name="last_name" />
   <input type="submit" value="Submit" name="contact" />
</form>

Answer: A try/catch you be great here. It eliminates all necessary for a throw_error array, as well as cuts down dramatically on the code.
try{
    $first_name = '';
    if(isset($_POST['contact'])) {
        if($_POST['first_name'] == '' || $_POST['last_name'] == '') {
            throw new Exception('Fields Cannot Be Blank');
        } elseif(strlen($_POST['first_name']) < 3) {
             throw new Exception('First Name Cannot Be Less Than 3 Characters');
        }
        $first_name = $_POST['first_name'];
    }
}catch(Exception $e){
    echo $e->getMessage();
}

If you were looking to pass an array to this catch statement, the easist way that I have found, is to serialize the array, then unserialize once complete. This will allow you to print all errors at once:
try{
    $first_name = '';
    if(isset($_POST['contact'])) {
        if($_POST['first_name'] == '' || $_POST['last_name'] == '') {
            $throw_error[] = 'Fields Cannot Be Blank';
        }
        if(strlen($_POST['first_name']) < 3) {
             $throw_error[] = 'First Name Cannot Be Less Than 3 Characters';
        }
        if(isset($throw_error)){
            throw new Exception(serialize($throw_error));
        }
        $first_name = $_POST['first_name'];
    }
}catch(Exception $e){
    $errors = unserialize($e->getMessage());
    foreach($errors as $error){
        echo $error.'
';
    }
}

Comment: Thanks for the answer but as I already stated that I need a procedural way
Comment: Moreover if I use try and catch are you sure it wont assign `$_POST['first_name']` value to `$first_name`
Comment: `$first_name` according to your code is only set if there are no errors. Is that correct?
Answer: I would also recommend using Try/Catch. You can still use it in procedural blocks.
If you are dead set against it, this code looks like it will do what you want it to do, but it's over-engineered. Since the user can either have a field_blank or char_len error, you only need a single string error variable.
$error = NULL;
if($_POST['first_name'] == '' || $_POST['last_name'] == '') {
    $error = 'Fields Cannot Be Blank';
} elseif(strlen($_POST['first_name']) < 3) {
     $error = 'First Name Cannot Be Less Than 3 Characters';
}

...
if(!empty($error)) {
   echo $error;
}

If you need to catch and display multiple non-exclusive errors, you can use the array you cited in your sample code and just iterate over the values rather than making a giant if/elseif block.
} elseif(!empty($throw_error)) { //Third Block To Throw Error If Any Errors Found
    foreach($throw_error as $key => $message) {
        echo $message.'
';
    }
}

Comment: ya ofcourse I don't need the array stuff as am using `elseif`, that makes sense ;)


Custom Div slider is going too fast, but only when returning from another browser tab

Question: When I am viewing the code in action, there are no problems. But as soon as I spend some time at another browser tab, then return to the code in action, the timing/speed is too fast.
Here's the jQuery:
<code>var divId = 1;
var lp = 0;

$(document).ready(function (){

    setInterval(function()
        {
        //<![CDATA[

            if(divId < 6)
            {
                $('.main-banner').animate({ left: lp },400);

                $(".first-icon-inner").removeClass("active-icon");
                $("#banner-"+divId+" div:first").addClass('active-icon');

                    divId++;
                    lp-=550;

            }
            else
            {
                lp = 0;
                divId=1;

                $('.main-banner').animate({ left: lp },400);

                $(".first-icon-inner").removeClass("active-icon");
                $("#banner-"+divId+" div:first").addClass('active-icon');

            }
            //]]>

    }, 3400);

});
</code>
Comment: @ankit5607san because I usually only see them at start of the `
Comment: What version of jQuery are you using ?
Comment: Why do you have `//<![CDATA[` in the middle of your script? interesting...
Comment: @Alvin Wong, I used it for XHTML validator.
Answer: There is a bug with jQuery < 1.6.3 ... extract from jQuery 1.6.3 release notes :

We had high hopes for the browser's requestAnimationFrame API when we added support into version 1.6. However, one of the highest-volume complaints we've received since then relates to the way requestAnimationFrame acts when a tab is not visible. All the animations initiated when the tab is invisible "stack" and are not executed until the tab is brought back into focus. Then they all animate at warp speed! We've removed support for this API (which has no impact on the way you call jQuery's animation features) and plan to incorporate it into a future version of jQuery.

I suggest that you update to a more recent version ... ie jQuery => 1.6.3
Comment: let me try to upgrade my jquery versin to 1.7.x .


What is the probability that a playoff series last 9 games, if the series terminate when a team got 5 wins?

Question: Original question from AOPS:

A playoff series between two teams proceeds one game at a time until one team has won 5 games. What is the probability that the series lasts 9 games if each team is equally likely to win each game?

I researched and found some solutions on the internet (which also gives the same answer as with the official solution) giving 35/128, taking 2^9 as the total number of possibilities.
The official solution seems to be counting 000000000,000000001,000000010,…,111111110,111111111 total of 512
My question is shouldn't it count only
00000, 11111, 000010, 000100, 001000, 010000, 100000, …
and NOT including sequences like 000000000 because such game is not possibly?
In other words 000000000,000000001,000000010,…000001111 should all be just counted as 00000.
My Calculation shows that the answer should be
$$
\frac{\binom{8}{4}}{ 1+\binom{5}{1} +\binom{6}{2} +\binom{7}{3} +\binom{8}{4}  }
$$
Comment: 00000 and 010101010 are not equally likely.
Comment: Even if the winner has been determined because someone has won $5$ times, let the two teams keep playing until they have played $9$ times.
Comment: Thanks very much aTree! That 2^9 is deceptively simple
Answer: In addition to the comments that show why outcomes you are counting are not equally probable, in the way you are thinking, it is easier to see how play doesn't last $9$ games.
That is either of the team wins in $5, 6, 7$ or $8$ games.
$P(W \leq 8) =  \displaystyle \frac {2}{2^5} + \frac {2 \cdot{5 \choose 4} } {2^6} + \frac{2 \cdot{6 \choose 4}}{2^7} + \frac {2 \cdot{7 \choose 4}}{2^8} = \frac{93}{128}$
So the probability that the play lasts $9$ games is $\displaystyle \frac{35}{128}$
But it is of course unnecessary when you can simply use $~\displaystyle \frac{2 \cdot {8 \choose 4}}{2^9}$.
Answer: Since it is given that the match lasts for $9$ games, both teams must have won $4$ games each in $8$ games out of $2^8$ possible outcomes, and the last game won by someone
Thus ans = $\frac{\binom84}{2^8}= \frac{35}{128}$
Answer: Putting an answer from the comments into an answer post where it belongs.
00000 and 010101010 aren't equality likely. To get outcomes that are equally likely, they change the rules of the playoff so that the teams always play nine games even if it's already been decided.
This change doesn't affect the probability that the series will be decided before the ninth game, but it will get them 512 equally likely possible outcomes.


Como Formatar Cada Tag HTML Com Seus Atributos Em Cores Sortidas?

Question: Uma "imagem" diz mais que muitas palavras não é verdade!? Então convido a ver o:
Exemplo

Nesta image vemos algumas "tags" formatado nas cores "vermelho(red),  marrom(maroon) e azul(skyblue)"

O que pretendo com isso é fazer o que um programa/software editor HTML ja faz. Isto é, todo o processo que destaca as tags.
Veja um código de exemplo logo abaixo feito manualmente:
Código

function Tag()
{
// Faz alguma coisa para setar as cores

...

// Fim de rotina cores sortidas
}
Tag();
div.code
{
border: thin solid silver;
width:720px;
height:390px;
}

01 - <!DOCTYPE html>
02 -
03 - <html lang="en">
04 - <head>
05 -  <meta charset="utf-8"/>
06 -  <title>Centralizar DIV</title>
07 -  <link href="centralizar.css" rel="stylesheet" type="text/css"/>
08 - </head>
09 - <body>
10 -
11 -  <div id="site">
12 -
13 -   <h1>Edu??o superior na regi??o de camplinas</h1>
14 -
15 -   <p>Resultado do Censo 2010 mostra o percentual da popula??o
16 -     das cidades da regi?o de Camplinas com forma??o superior.
17 -     Compara??o com a m?dia do estado de SP e nacional</p>
18 -
19 -   <img src="grafico.jpg" alt="Gr?fico"/>
20 -
21 -  </div>
22 -
23 - </body>
24 -
25 - </html>

Sabemos que isso é útil para escrevermos artigos e mostrarmos um trecho do código de maneira destacada e bem apresentada no Site/Blog.

Lembrete
Não estou buscando modificar cores de texto, mas sim, a cor das tag HTML, é totalmente o inverso ao contrário do conceito de estilizar um elemento com CSS.
Dúvida
Como farei este efeito, da "image" no "código"?
Comment: @EmanuelF Isso mesmo, gosto de criar tudo a mão e não faço uso de editores HTML. Então, seria interessante e funcional criar uma rotina externa para pré formatar pequenos trecho dentro de uma DIV.
Comment: Onde quer aplicar essa sua idéia?
Comment: @EmanuelF Como assim!? Note o que diz "[...] é útil para escrevermos artigos e mostrarmos um trecho do código de maneira destacada e bem apresentada no Site/Blog.", compreendeu?
Comment: Agora ficou mais claro, então quer criar um campo em que as tags fiquem destacadas com cores diferentes? Algo que você usou aqui pra exemplificar sua ideia?
Answer: O nome deste tipo de pós-processamento é code mark-up, ou marcação de código.
Existem várias bibliotecas disponíveis para realizar este tipo de marcação para você.
Uma das mais utilizadas chama-se hljs (highlight.js).
Clique em Executar trecho de código para ver o exemplo em javascript a seguir:

$(document).ready(function() {
  $('pre code').each(function(i, block) {
    hljs.highlightBlock(block);
  });
});

<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.5.0/styles/default.min.css">

app.factory("callbackFactory", function ($log) {

        function registerCallBack(factoryInstance, collection, callback) {
            collection.push(callback);

            //$log.log(factoryInstance.moduleName + " observers: " + collection.length);

            if (factoryInstance.onSubscriberRegistrationCallback)
                factoryInstance.onSubscriberRegistrationCallback(callback);
        };
    };


Is there a convincing case to be made against using last years data as a holdout set when building a predictive model?

Question: Building a model on a large subset of your data and testing it on a holdout set is a common practice. I am interested to what extent this is a justifiable approach in various data laden settings.
Consider the case where you have a large data set in which the generating process of the data may change in some ways with time. Suppose we wish to build a GLM to model this data. I have been told by some practitioners in this setting that it is advisable to, for example, build your GLM on all data excluding the last 12 months worth of observations, and testing the performance on the holdout. It seems crazy to me, but this model is then put into production.
While I see the value of trying to get an accurate handle on the generalization error, our overall aim is to make good predictions in the coming years. It is not that hard to imagine that last year's data might be quite important to capturing any recent trends that will be relevant in the coming years. Is there a nice example to illustrate the potential downsides to this approach? It seems that predictions can suffer quite a bit.
I have been advocating building the model on the full data and estimating overfitting via a bootstrap. Is there a case I can make?
Comment: If the holdout test accuracy is good and you're going to production you should train on every piece of data you have.
Answer: You use cross-validation generally for two purposes

Model selection and model structure selection
To determine the generalization capability of the model

Once you have completed above step; train you model on all of the data.
Like @photox commented, you are advised to use full (all samples) data to train the final model to be deployed in production.
However, if you are planning to determine the generalization capability of the model, and if your data is time-series data; you are advised to use last 12 months data for validation. This technique often called roll-over cross-validation or forward chaining is popular in time-series domain. For details see here.


Null velocity and piecewise smooth path

Question: On texts of multivariable calculus and real analysis I have always seen the work made by $\mathbf{F}$ along the path $\gamma$ defined as the integral$$\int_\gamma\mathbf{F}\cdot\text{d}s:=\int_a^b\mathbf{F}(t)\cdot\mathbf{r}'(t)\text{d}t$$where $\mathbf{r}:[a,b]\to\mathbb{R}^3$ is a piecewise smooth curve whose support is $\mathbf{r}([a,b])=\gamma$. By piecewise smooth it is intended in the text I have read that $\mathbf{r}$ is the juxtaposition of a finite number of smooth curves $\mathbf{r}_i:[a_i,b_i]\to\mathbb{R}^3$, where smooth means that $$\mathbf{r}_i\in C^1[a_i,b_i]\quad\text{  and  }\quad\forall t\in[a_i,b_i]\quad\|\mathbf{r}_i'(t)\|\ne 0.$$This implies that $\forall t\in[a,b]\quad\|\mathbf{r}'(t)\|\ne 0$ and that $\mathbf{r}$ has finite left and right derivative for any $t\in[a,b]$.
All the proofs of the work-energy theorem that I have found in books of physics use the velocity $\mathbf{v}$ of a point, upon which the force $\mathbf{F}$ acts, to parametrise its path $\gamma$ and get, by taking into account Newton's second law $\mathbf{F}=m\frac{\text{d}\mathbf{v}}{\text{d}t}$, $$\int_\gamma\mathbf{F}\cdot\text{d}s=\int_a^b m\frac{\text{d}\mathbf{v}(t)}{\text{d}t}\cdot\mathbf{v}(t)\text{d}t=m\int_a^b\frac{1}{2}\frac{\text{d}\|\mathbf{v}(t)\|^2}{\text{d}t}\text{d}t=\frac{1}{2}m\|\mathbf{v}(b)\|^2-\frac{1}{2}m\|\mathbf{v}(a)\|^2.$$Anyhow, when examples and exercise are presented in texts of physics, $\|\mathbf{v}(a)\|$ or $\|\mathbf{v}(b)\|$ may well be zero, which is, to my eyes, a contradiction of the fact that the parametrisation of $\gamma$ must have a non-null derivative  $\|\mathbf{r}'(t)\|=\|\mathbf{v}(t)\|\ne 0$ for all $t\in[a,b]$. What am I missing or misunderstanding? I $\infty$-ly thank you for any answer!
Answer: Why would you need to have $||{\bf r}' (t)|| \neq 0$? this constraint is not necessary at all. You have pointed out yourself that you are using Newton's second law, which states ${\bf F} = m \frac{d {\bf v}}{dt}$, if ${\bf F}$ was to be directed in oppoiste direction to ${\bf v}$ and you started with a given value of ${\bf v} = {\bf v}_0$ then certainly $||{\bf r}' (t)||=0$ at some point. There is no contradiction. An example of this is throwing an object vertically in the earth's gravitational field.
Comment: The condition $\|\mathbf{r}'(t)\|\ne 0$ is needed for example to reparametrise the smooth curve by using the variable $s(t)=\int_a^t\|\mathbf{r}'(t)\|dt$ and the parametrisation $\tilde{\mathbf{r}}$ where $\forall s\in[0,L]\quad\|\tilde{\mathbf{r}}'(s)\|=1$ ($L=$ length of $\gamma$): I though that such a reparametrisation and the presence of a tangent unit vector $\mathbf{t}:=\|\mathbf{r}'\|^{-1}\mathbf{r}'$ at any point of the curve were essential properties of a smooth curve...
Comment: ...The possibility to define $\mathbf{t}=\|\mathbf{r}'\|^{-1}\mathbf{r}'$ is necessary -af far as I understand- to write the acceleration as the sum of tangential and normal components $\mathbf{a}=\frac{d\|\mathbf{v}\|}{dt}\mathbf{t}+\|\mathbf{v}\|\frac{d\mathbf{t}}{dt}$, which is used in mechanics as ubiquitously as the identity work = $=\frac{1}{2}m(\|\mathbf{v}(b)\|^2-\|\mathbf{v}(a)\|^2)$... Then, I understand that this decomposition of acceleration cannot be always used. Thank you so much!

Null velocity and piecewise smooth path


How to pass a named function with parameter in jquery instead of anon function?

Question: Is it possible to pass a named function with parameters to a jquery function as an argument instead of an anonymous function. This is what I'm trying to do:
$('body').bind("click", saySomething);

function saySomething(word)
{
    console.log(word);
}

Now I think I'm right in saying that I can't add the parentheses to the saySomething parameter in my jQuery call, so how can I pass in the parameter?
Note: This may be a duplicate of another question, but to the the difficut nature in trying to explain this question to SO and Google I've posted this.
Comment: Why don't you want to just do this:  $('body').bind("click", function(e){ saySomething(arg); });  ?, as in what is the reasoning?
Comment: The reasoning behind it, is if I wanted to bind a number of elements to the same behaviour, I figure I could encapsulate it in one function and just refer to it. That doesn't appear to be working as expected:  http://jsbin.com/dufew/15/edit
Comment: All three answers solved my question in different ways. How do I accept an answer?
Comment: @JasonMortonNZ: You choose the answer that helper you the most (e.g. you learned most from it, it's the solution you are settling with, etc).
Answer: $('body').bind("click", function(){saySomething(par);});

Something like this?
Answer: What you are doing is perfectly fine, since the click event passes an event object as the first parameter, the variable word in your saySomething function will be that event object.
If you want to define yourself what word will be, there is no way around wrapping it in some other function and call it with the value you want.
Comment: So looking at a quick JSbin example I've put together. Why isn't this working as expected: http://jsbin.com/dufew/15/edit
Comment: @JasonMortonNZ Because you had an error in it, i fixed it see: http://jsbin.com/dufew/16/ You forgot the single quote closing the string inside the console.log(); JSBin shows you the error if your code throws them. Just look at the very bottom of the javascript sourcecode.
Comment: As I learnt that there's no way around wrapping my function call in a function, which is something I didn't know, and hence was the source of my issue. I'm accepting this as my answer. But a big thanks to everyone to answered and helped out :)
Answer: Yes, you can use $.proxy, or the native .bind method,  but this wouldn't be set to the correct element anymore:
$('body').bind("click", $.proxy(saySomething, null, 'hello'));

Answer:
The reasoning behind it, is if I wanted to bind a number of elements
  to the same behaviour, I figure I could encapsulate it in one function
  and just refer to it

You can still refer to the same function call, it is just a little more verbose.  There's no way around that.
$('.item1').bind("click", function(e){ saySomething('one'); });
$('.item2').bind("click", function(e){ saySomething('two'); });
$('.item3').bind("click", function(e){ saySomething('three'); });

Also, your example in the comment seemed to work okay for me.


Mount samba volume in docker container

Question: Using the latest Docker engine, I want to create a container that mounts a volume over the network. But when I try to execute the mount command, I got the error Unable to apply new capability set.. Found out, that Docker restricts permission, like on mounting here. Different sources say, that its necessary to add SYS_ADMIN permission.
I did this, but still not working with the following command:
docker run --cap-add=SYS_ADMIN --cap-add=DAC_READ_SEARCH --privileged --memory=2g -d --name $containerName $imageName

Comment: http://backdrift.org/docker-cifs-howto-mount-cifs-volume-docker-container
Answer: This seems to work
docker run ... \
  --cap-add SYS_ADMIN \
  --cap-add DAC_READ_SEARCH \
  my_container

Currently you will probably need to be sure to unmount your volume before you stop the container. Otherwise the host will now allow restarting any containers due to an untidy work queue or something.  I created a script to stop my container by first unmounting, then killing the CMD process.  I run this inside the container when I need to kill it.
umount /mnt/efbo_share -t cifs -l
sleep 1
pkill npm
pkill node

You can read about the unmount issues at these links:
https://github.com/moby/moby/issues/22197
https://github.com/moby/moby/issues/5618

Mount samba volume in docker container


Mocking stored procedure's output parameter

Question: I have following method
<code>public bool IsUserAllowedToDoThings(string userName, string thingToDo)
    {
        var outputParameter = new ObjectParameter("IsAllowed", typeof(bool?));
        _context.SP_IsUserAllowedToDoThings(userName, thingToDo, outputParameter);
        return (bool)outputParameter.Value;
    }
</code>
The method just calls SP using EF and return SP's output result. But I'm having problems to mock SP's output for unit testing.
P.S. I'm using MOQ framework for mocking.
Comment: What problems are you having?
Comment: I just don't know how to to setup mocked output parameter.
Comment: I was suggesting you add more info to the question, but if you think it's perfect just the way it is leave it that way ;) I won't be able to help I don't know C# or Moq
Answer: After reading the MOQ's manual 3rd time I finally was able to find the way to do this. That was surprisingly simple:
<code> mockObjectContext.Setup(m => m.SP_IsUserAllowedToDoThings(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ObjectParameter>())).Callback<string, string, ObjectParameter>((a, b, c) =>
        {
            c.Value = true;
        });
</code>


Counting number of non-singular matrices

Question: How many non-singular matrices of order 3x3 we can form in which 4 entries are 1 and other entries are zero..
Any shorttrick??
Comment: Did you try anything?
Comment: 100 010 001 fixing this and adding one 1 at any one of the zero's place det remains non zero E.g 101 010 001 and so on.. also matrices of the form 110 100 001 , 100 011 010... So Atleast 8 such we can have..
Comment: Please use [MathJax](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference). Specifically,
[Matrices](https://math.meta.stackexchange.com/a/5023/290196).
Comment: Think about determinants. You know that there can't be any zero row or column, so you can restrict your options for the first 3 ones you place. The fourth one can then go anywhere you want.
Comment: Since permuting rows doesn't change being singular vs. non-singular, I would start by breaking down cases in which the rows are ordered by the number of ones in each.  With only four entries $1$, there are not  a huge number of possibilities.
Answer: Hints.

If the matrix is nonsingular, it must possess a circulant diagonal/anti-diagonal $\{a_{i\sigma(i)}:i=1,2,3,\ \sigma\in S_3\}$ of ones. How many such diagonals/anti-diagonals are there?
Having fixed the diagonal of ones, how many ways are there to put the remaining one?
Answer: We need at least one triple of $1$s appearing in ${\rm det}(A)$. If such a  triple has been chosen, e.g., the diagonal of $A$, then the fourth $1$ cannot create a second such triple. Since there are six such triples in all, and for each of them there are six spots to place the last $1$  there are $36$ regular matrices of this kind.


Problemas em String e Case

Question: Sou iniciante em programação há pouco tempo e tenho uma tarefa da faculdade na qual devo criar um sistema de cadastros que receba as entradas os dados dos clientes e em seguida numa outra opção que imprima na tela( case 2) essas informações.
Mas estou com problemas na hora de imprimir estas strings, onde acredito eu aparecem os locais de memória delas e diversos caracteres aleatórios.
Gostaria de saber o que posso fazer para que as Strings sejam lidas corretamente e se a return main() ou se o & antes da variável, tem algo em relação a esse problema. Desculpem pelo código bagunçado e meio estranho
int main(void) {

    int opcao;
    cliente cadastro[100];
    int i;
    char sair;

    printf("\n1- Clientes");
    printf("\n2- Automoveis");
    printf("\n3- Tabela de precos e classificacao");
    printf("\n4- Locacao");
    printf("\n\n\n\tDigite a opcao desejada:  ");
    scanf("%d", &opcao);

    switch (opcao)
    {
    case 1:
        system("cls");
        printf("\n1- Cadastro de Clientes");
        printf("\n2- Detalhes do Clientes");
        printf("\n3- Alterar/Excluir Clientes");
        printf("\n\n\n\tDigite a opcao desejada:  ");
        scanf("%d", &opcao);

        switch (opcao)
        {
        case 1:
            do
            {
                system("cls");
                printf("\nCadastro de Clientes\n");
                printf("\nDigite o Codigo do Cliente:  ");
                scanf("  %d", &i);
                cadastro[i].codigo = i;
                system("cls");
                printf("\n Codigo do Cliente:  %d\n", cadastro[i].codigo);
                printf("\n Nome:  ");
                scanf("  %[^\n]s", &cadastro[i].nome);
                printf("\n RG:  ");
                scanf(" %s", &cadastro[i].rg);
                printf("\n CPF:  ");
                scanf(" %s", &cadastro[i].cpf);
                printf("\n Endereco:  ");
                scanf("  %[^\n]s", &cadastro[i].endereco);
                printf("\n Carteira de Habilitacao:  ");
                scanf(" %[^\n]s", &cadastro[i].carteira_hab);
                system("cls");
                printf("\nCadastro Realizado com sucesso!");
                printf("\n\n\t\t\tDeseja Realizar outro cadastro? S / N:  ");
                scanf(" %c", &sair);

            } while (sair != 'n');
            system("cls");
            return main();

            break;

        case 2:
            printf("\nDetalhes do Clientes");
            printf("Digite o código do cliente:  ");
            scanf("%d", &i);
            printf("\nNome:  %s", &cadastro[i].nome);

        default:
            break;
        }

    default:
        break;
    }
}

Comment: Coloque também a estrutura `cliente` para se saber como foram definidas as strings. Mas uma string definida como `char[]` ou `char*` não leva o `&` no `scanf`, pois já é um ponteiro. Mas se for `char*` precisa de ser alocada antes de ser utilizada
Answer: Fiz algumas sugestões no teu código:
int main() {
    int opcao, opcao2; //nao use a mesma variavel para os dois switchs
    cliente cadastro[100];
    int i;
    char sair;

    //precisa envolver todo este código em um do-while ao inves de chamar recursivamente a funcao main
    printf("\n1- Clientes");
    printf("\n2- Automoveis");
    printf("\n3- Tabela de precos e classificacao");
    printf("\n4- Locacao");
    printf("\n\n\n\tDigite a opcao desejada:  ");
    scanf("%d", &opcao);

    switch (opcao) {
        case 1: {//faltava uma chave aqui
            system("cls");
            printf("\n1- Cadastro de Clientes");
            printf("\n2- Detalhes do Clientes");
            printf("\n3- Alterar/Excluir Clientes");
            printf("\n\n\n\tDigite a opcao desejada:  ");
            scanf("%d", &opcao2);
            switch (opcao2) {
                case 1:
                    do {
                        system("cls");
                        printf("\nCadastro de Clientes\n");
                        printf("\nDigite o Codigo do Cliente:  ");
                        scanf("  %d", &i);
                        cadastro[i].codigo = i;
                        system("cls");
                        printf("\n Codigo do Cliente:  %d\n", cadastro[i].codigo);
                        printf("\n Nome:  ");
                        scanf("%[^\n]s", cadastro[i].nome);//sem & quando for string
                        printf("\n RG:  ");
                        scanf("%s", cadastro[i].rg);//sem & quando for string
                        printf("\n CPF:  ");
                        scanf(" %s", cadastro[i].cpf);//sem & quando for string
                        printf("\n Endereco:  ");
                        scanf("%[^\n]s", cadastro[i].endereco);//sem & quando for string
                        printf("\n Carteira de Habilitacao:  ");
                        scanf("%[^\n]s", cadastro[i].carteira_hab);//sem & quando for string
                        system("cls");
                        printf("\nCadastro Realizado com sucesso!");
                        printf("\n\n\t\t\tDeseja Realizar outro cadastro? S / N:  ");
                        scanf("%c", &sair);
                    } while (sair != 'n');
                    system("cls");
                    break;
                case 2: { //faltava uma chave aqui
                    printf("\nDetalhes do Clientes");
                    printf("Digite o código do cliente:  ");
                    scanf("%d", &i);
                    printf("\nNome:  %s", &cadastro[i].nome);
                }
        }
    }
}

Problemas em String e Case


What may cause Column not found (nid) in on clause?

Question: I'm using Drupal 7.14 and Entity API and Reference 1.0-rc3.
And I'm also using i18n, entityreference (not References) and field_sql_storage.
I get this error when saving a node that has some custom fields using references.

PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column
  'field_data_body0.nid' in 'on clause': SELECT
  field_data_body0.entity_type AS entity_type,
  field_data_body0.entity_id AS entity_id, field_data_body0.revision_id
  AS revision_id, field_data_body0.bundle AS bundle FROM
  {field_data_body} field_data_body0 INNER JOIN {node} node ON
  field_data_body0.nid = node.nid WHERE (field_data_body0.deleted =
  :db_condition_placeholder_0) AND (field_data_body0.entity_type =
  :db_condition_placeholder_1) AND (field_data_body0.bundle IN
  (:db_condition_placeholder_2, :db_condition_placeholder_3)) AND
  (field_data_body0.entity_id IN (:db_condition_placeholder_4)) AND
  (node.language IN (:db_condition_placeholder_5,
  :db_condition_placeholder_6)) ORDER BY field_data_body0.body_value
  ASC; Array ( [:db_condition_placeholder_0] => 0
  [:db_condition_placeholder_1] => node [:db_condition_placeholder_2] =>
  news [:db_condition_placeholder_3] => page
  [:db_condition_placeholder_4] => 25 [:db_condition_placeholder_5] =>
  it [:db_condition_placeholder_6] => und ) in
  field_sql_storage_field_storage_query() (linea 577 di
  /home/morpheu5/web/xdatanet/modules/field/modules/field_sql_storage/field_sql_storage.module).

What bothers me is that, first of all there's a zero appended to the name of the table, and second, if I add that nid column to that table, Drupal is happy and everything seems to work.
I suspect there must have been some update gone horribly wrong, since maintenance is not under my control, and I had to implement some new features working on my local copy which at that time was already completely out of sync with the client's staging and production servers.
I tried a number of patches, and I've gone through the code myself but I'm not this familiar with Drupal.
EDIT
It seems the nid column is getting added at some point in function preExecute in includes/database/select.inc specifically at row 1236
drupal_alter($hooks, $query);

the hooks acting here are

query
query_entity_field_access
query_node_access
query_entityreference

but after a hour long investigation I only came up with a huge headache, and I'm still not sure if I actually found and debugged all of those hooks. As far as I could see, the nid column is not present before the drupal_alter call while it is after, but it's there at the beginning of each hook_query_TAG_alter I was able to find.
I must be missing something.
EDIT 2
The culprit seems to be i18n, specifically i18n_select, more specifically at row 137 of i18n_select.module where it adds the nid column.
EDIT 3
There, I opened a bug: https://drupal.org/node/1679646
Comment: I had a similar problem some time ago and I think the problem was with the `references` module. You should have a look at this http://drupal.org/node/1275096. There is a patch called `column_not_found_1054_unkonw_column-1275096-8.patch` which solved my problem.
Comment: Unfortunately I'm not using the `references` module but the `entityreference` one. I tried looking at that patch but it didn't seem like it could be translated.
Answer: The body field should definitively NOT have a nid column in the table. The field_data_body table provided by core will contain an entity_id column which is the reference to the node entity.
2 things I can think of that might be causing this:

You have custom code that's making an erroneous database query in a hook_node_load() function or similar (either directly or using an EntityFieldQuery)
(more likely I think) Core/contributed modules or files have been edited and the changes are only now causing problems.

The best advice I can give is to install the Hacked! module and determine whether or not core/contributed modules have indeed been hacked. If that comes back all clear then you're just looking at an error in some custom code somewhere which will be easy to track down.
If it doesn't come back clear, at least you know what the problem is and you can then decide how best to proceed with getting Drupal back into a proper un-hacked state.
Incidentally, don't worry about the table being referred to as field_data_body0...if you look further down in the query that's just an alias that's being used for field_data_body:
FROM {field_data_body} field_data_body0

Comment: Thanks, I'll let you know. That Hacked! module is completely new to me :)
Comment: Apparently neither the core nor contributed modules have been modified significantly: just a couple of completely unrelated lines but I managed to get them back in place and the error is still there. I also have a couple of custom modules made using Features and, as far as I know but I can't be 100% sure, this problem started after they installed these two modules I made. Neither of these appear to reference anything related to nid, though.
Comment: I updated the question.


Prove that matrix is Hermitian iff it's equal to its adjoint with general hermitian inner products

Question: The Wikipedia article for Hermitian matrices gives an alternative characterization for Hermitian matrices link. The statement I want to prove is:
$$ A^* = A \iff \langle w,Av \rangle_H = \langle Aw,v \rangle_H $$
This was proven for the standard inner product by a similar question.
I want to prove it for the general case with an arbitrary hermitian inner product on complex vector spaces.
I tried it using
$$ \langle w,Av \rangle_H = w^*HAv $$
with $H$ being a hermitian matrix and $ * $ marks the hermitian conjugate of a vector/matrix.
I don't really know how to show it without using that H and A commute.
I am thankful for any help!
Edit:
Note that I am using a positive definite hermitian form as the definition for the inner product. A hermitian form is defined as a sesquilinear form with $\langle w,v \rangle = \overline{\langle v,w \rangle}$.
Then there exists a hermitian matrix H being the transformation matrix of the hermitian form with
$$ \langle w,v \rangle_H = w^*Hv $$
Comment: Just to be clear: your definition of the inner product is $\langle x, y\rangle_H=x^* H y$?
Comment: @DavidRaveh yes exactly, I added it to the question.
Comment: Your definition of the inner product isn't valid, since it doesn't generally satisfy $\langle x,x \rangle_H\geq 0$
Comment: @DavidRaveh you're right. I clarified it a bit. please see the edit in the question.
Answer: The difference between this proof and the one you linked is mostly symbolic. We define the adjoint of $A$ denoted by $A^\dagger$ by $\langle A^\dagger i|j\rangle=\langle i|Aj\rangle$.
For any inner product, if $A=A^\dagger$
then $$A_{ij}=\langle i|Aj\rangle=\langle Ai|j\rangle=\langle j|Ai\rangle^*=A_{ji}^*$$
so $A$ is Hermitian. The converse follows by going in the opposite direction as well.
Comment: I think I don't quite get it then. Isn't $\langle Ax, y\rangle_H = (Ax)^*y$ (copied from the other question) Implying that $ H = I $ with $ I $ being the identity matrix. Or is it that the basis can be chosen to fulfil $ H=I $?
Comment: @exploitingDev I didn't realize that they didn't use general notation, so I edited to redo it. If you have any questions about how I defined the adjoint, we can go to a chatroom
Comment: Thanks for your help. It makes sense now.


Show that there is $E \in M$ such that $\mu(E)=\alpha$ for any $0 \lt \alpha \lt \mu(X)$

Question: Let $(X,M,\mu)$ be a finite measure space with no atoms. A set $A \in M$ is called an atom if $\mu(A) \gt 0$ and for any measurable subset $B \subset A$ ,either $\mu(B)=0$ or $\mu(A-B)=0$ .Show that there is $E \in M$ such that $\mu(E)=\alpha$ for any $0 \lt \alpha \lt \mu(X)$.
My attempt:
For any $F \in M$, there exists a $B \in F$ such that $\mu(B) \ne 0$ and $\mu(F-B) \ne0$ (Measure Space has no atoms).Since $\mu$ is finite, there exists a $k_0 \in \mathbb{N}$ such that $\mu(F) \lt k_0$. Then  since $\mu(F)=\mu(B)+\mu(F-B)$. Atleast one of $B$ or $F-B$ has measure less than  $\dfrac{\mu(F)}{2}$. Call it $B_1$. Similarly we can find $B_2 \subset B_1$ such that $\mu(B_2) \lt \dfrac{\mu(F)}{2^2}$. By induction we can find $B_n$ such that $B_n \subset B_{n-1}\subset....\subset B_2 \subset B_1$ such that $\mu(B_n)\lt \dfrac{\mu(F)}{2^n}$. This just means that given $\epsilon \gt 0$ , there is a set $S \in M$ such that $\mu(S) \lt \epsilon$.
Now I try to define a set $$T=\{E \in M| \mu(E) \le \alpha\}$$. This set is nonempty by the above observation. I define the order relation $"\le"$ by inclusion. Then $T$ is a partially ordered set. Any linearly ordered set $L$ in $T$ has sets which are nested. The upper bound is the union of all these, which is unfortunately not in $M$, for the union can be be over any index, countable and uncountable.
This makes me to change the set to $$T'=\{E_{\alpha} \in M|  \mu(E_{\alpha}) \le \alpha,\mu(E_{\alpha}\cap E_{\beta})=\phi, \text{for} ,\alpha, \beta \in I, \alpha \ne \beta\}$$
Then since $\mu(X)\lt \infty$, there are atmost countably many of these sets as defined in $T'$. But I am unable to find an order relation for this set. Another way could be to define an order relation such that any linearly ordered set has of the form $T'$.
I tried another possible approach:
Define ~ on $ M $ by $ E $~ $F$ iff $\mu ((E\cap F^{c}) \cup (E^{c}\cap F^{c}))=0$. Then this is an equivalence relation on $ M $ and defining $ d ([E], [F])= \mu ((E\cap F^{c}) \cup (E^{c}\cap F^{c})$ turns $M $ into a metric space. Now the problem just boils down to showing that the space $( M$,~$) $ is connected with the above metric.
Thanks for the help!!
Comment: There is a bunch of different methods to do this [here](http://math.stackexchange.com/q/254728/258909).
Comment: Can it be solved by contunuity argument? ? It seems more elegant. I am not able to show connectedness though
Answer: I came up with this, using the nuts and bolts of sigma-algebras instead:
Lemma. With $(X,M,\mu)$ as in the problem statement, assume $A\in M$, $\mu(A)>0$.
Then there exists $A'\in M$ with $A'\subset A$ and $\frac14\mu(A)<\mu(A')<\frac34\mu(A)$.
Proof.
Let $S=\{\,B\in M\mid B\subset A, \mu(B)\ge\frac 12\mu(A)\,\}$. As $A$ is not an atom, $S\ne \emptyset$ and we can consider $s:=\inf\{\,\mu(B)\mid B\in S\,\}$. Clearly, $\frac 12\mu(A)\le s<\mu(A)$.
Assume  $s\ge\frac34\mu(A)$.
For $B,B'\in S$, we have
$$ \mu(B\cap B')\ge\mu(B)+\mu(B')-\mu(A)\ge 2s-\mu(A)\ge\frac12\mu(A),$$
i.e., $S$ is closed under finite intersections.
For $n\in\Bbb N$, pick $B_n\in S$ with $\mu(B_n)<s+\frac1n$.
Let $C=\bigcap B_n$. As $\bigcup_{n=1}^NB_n\in S$ and $s\le \mu(\bigcup_{n=1}^NB_n)<s+\frac 1N$, we infer
$$\mu(C)=\lim_{N\to\infty}\mu\biggl(\bigcup_{n=1}^NB_n\biggr)=s.$$
As $C$ is not an atom, there is $D\in M$ with $D\subset C$ and $0<\mu(D)<\mu(C)$. From $\mu(D)<s$, we conclude $\mu(D)<\frac 12\mu(A)$, $\mu(A-D)>\frac12\mu(A)$, $\mu(A-D)\ge s$, $\mu(D)\le\mu(A)-s$, $\mu(C-D)\ge 2s-\mu(A)\ge \frac12\mu(A)$, $\mu(C-D)\ge s$, contradiction.
We conclude that $s<\frac34\mu(A)$.
Hence we can pick $A'\in S$ with $\mu(A')<\frac34\mu(A)$. $\square$
Let $\alpha$ be given with $0<\alpha<\mu(X)$.
We construct sequence $A_0,A_1,\ldots$ and $B_0,B_1,\ldots$ as follows, where we ensure $A_n\subseteq A_{n+1}\subsetneq B_{n+1}\subseteq B_n$ at each step:
Let $A_0=\emptyset$, $B_0=X$.
Given $A_n\subsetneq B_n$, use the lemma to pick $A'\subset B_n-A_n$ with $\frac 14\mu(B_n-A_n)<\mu(A')<\frac 34\mu(B_n-A_n)$.
If $\mu(A_n\cup A')<\alpha$, let $A_{n+1}=A\cup A'$, $B_{n+1}=B_n$; otherwise let $A_{n+1}=A_n$, $B_{n+1}=A_n\cup A'$.
Observe that $\mu(A_n)\le\alpha\le \mu(B_n)$ for all $n$.
We also have $\mu(B_{n+1}-A_{n+1})<\frac34\mu(B_{n}-A_{n})$.
Therefore with $A=\bigcup A_n$ and $B=\bigcap B_n$, we have $\mu(A)\le\alpha\le \mu(B)$ and $\mu(B-A)=0$.
In other words, $$\mu(A)=\alpha. $$
Comment: I came up with the same solution :) In fact one may construct $A'$ such that $0<\alpha<\mu(A')<\beta<\mu(A)$. But I think there should be a more elegant way to prove the original statement.
Comment: Can this been shown by continuity argument?? I am unable to show connectedness. I just added that to the question


How to plot an interaction term, using a model's coefficients, of three-factorial GEE model with full-order interactions (geepack package)?

Question: Using function geeglm from package geepack (Generalized Estimating Equation), I have modeled counts as being dependent on two nominal (factor) variables, one continuous variable with 3rd-order interactions and one grouping variable.
This is the model:
m1<-geeglm(formula = dependent.var  ~  cat.var1 *  cat.var2 * contin.var,
           family = poisson, id = group, corstr = "exchangeable")

Factor variable cat.var1 has two levels (CD and WL), factor variable cat.var2 has two levels (SAH and SKA). Group is a grouping variable to account for autocorrelation among somehow related subjects. Using anova function, I found that the only significant model's interaction terms are cat.var1 : contin.var   and cat.var2 : contin.var.
I would like to plot these two interactions:
I have used the codes below, but I am not happy with the fitted lines. Line for CD-level of cat.var1 in the first figure is the same as line for SAH-level of cat.var2 in the second figure (see figs) – therefore I think that they are not correct and I do not know how to solve this. Which model's coefficients I have to use to construct that lines? The model's coefficients used for producing of the figures are thereinafter.

Codes:
# 1st plot: cat.var1 : contin.var
par(mfrow=c(1,1))
plot(contin.var, dependent.var, type="n")
points(contin.var[cat.var1=="WL"], jitter(dependent.var[cat.var1=="WL"]))
points(contin.var[cat.var1=="CD"], jitter(dependent.var[cat.var1=="CD"]),
       pch=16)
x <- seq(3,7,0.1)
y1 <-exp(-0.1584 + 0.3474*x)
lines(x,y1, lty=2)                                 # CD
y2 <-exp(-0.1584 + 3.7293 +(-0.6685 + 0.3474)*x)
lines(x,y2, lty=1)                                 # WL

# 2nd plot: cat.var2 : contin.var
par(mfrow=c(1,1))
plot(contin.var, dependent.var, type="n")
points(contin.var[cat.var2=="SKA"], jitter(dependent.var[cat.var2=="SKA"]))
points(contin.var[cat.var2=="SAH"], jitter(dependent.var[cat.var2=="SAH"]),
       pch=16)
x <- seq(3,7,0.1)
y1 <-exp(-0.1584 + 0.3474*x)
lines(x,y1, lty=2)                                 # SAH
y2 <-exp(-0.1584 + -6.9490 + (1.2249 + 0.3474)*x)
lines(x,y2)                                        # SKA

Here are my model's coefficients, used for producing of figures, outputs from summary(m1) (statistically significant terms - outputs from anova(m1) - are denoted with asteriks **):
Coefficients:
                                         Estimate

(Intercept)                                  -0.1584
cat.var1WL                                    3.7293
cat.var2SKA                                  -6.9490
contin.var                                    0.3474   *
cat.var1WL: cat.var2SKA                       3.9970
cat.var1WL: contin.var                       -0.6685   *
cat.var2SKA: contin.var                       1.2249   **
cat.var1WL: cat.var2SKA: contin.var          -0.6860

Factor variable *cat.var1* has two levels (CD and WL),
factor variable *cat.var2* has two levels (SAH and SKA).

Here are the data: https://docs.google.com/file/d/0Bz8ojhHeiNclVi1oT0ZwTEtEN2s/edit
Answer: First of all, it's great to see the data included with your question!
It sounds like the heart of the question is whether you correctly created curve formulas based on the coefficients from the geeglm package. I don't know the correct way for that model, but using only intercept and contin.var coefficients for those cases can't be correct. Though you only see a coefficient for cat.var1WL in the package output, there is an implied complementary coefficient for cat.var1CD.
In any case, you should be able examine m1.formula to get the full formula.
Given that your model includes categorical interaction, you should show the interaction in the graphs by plotting different curves for each combination (CD&SAH, CD&SKA, WL&SAH, WL&SKA), whether overlaid or in a grid (example below with a smoother).
An alternative is to remove that interaction from the model if you've determined if to be insignificant. Then your provided graphs are more appropriate, once you fix the y formulas.
Comment: Examine the formula by "formula(model) gives Error: object 'mgeep.formula' not found. (it probably works only with classical models). Is there any other way how to extract formula?
Comment: @xan, thank you for your response. Yes, I know that using only intercept and contin.var coefficient was not correct - therefore I have asked this question. Finally I managed it myself, see my answer bellow.
Answer: As the main effects of cat.var1 and cat.var2 were not statistically significant and I was interested about plotting only significant interaction terms (see my question above), I made two separate models to obtain coefficients for construction of plots to show those interaction between explanatory variables, i.e. one model for each significant interaction from the m1. Both models contain two relevant variables and their interaction term. Second factor variable was thus something like "pooled".
# 1st plot for interaction cat.var1:contin.var:

m2<-geeglm(dependent.var ~ cat.var1 * contin.var, family = poisson, id
  = group, corstr = "exchangeable")

Coefficients:
                                         Estimate

Intercept                                  -3.464
cat.var1WL                                  5.264
contin.var                                  0.912
cat.var1WL: contin.var                     -0.917

Plot code:
par(mfrow=c(1,1))
plot(contin.var, dependent.var, type="n")
points(contin.var[cat.var1=="WL"], jitter(dependent.var[cat.var1=="WL"]), pch=16)
points(contin.var[cat.var1=="CD"], jitter(dependent.var[cat.var1=="CD"]))
x <- seq(3,7,0.1)
y1 <-exp (-3.464 + 0.912*x)
lines(x,y1, lty=2)                                 # CD
y2 <-exp ((-3.464 + 5.264) + (-0.917 + 0.912)*x)
lines(x,y2, lty=1)                                 # WL
legend(4.82, 15, c("CD", "WL"), pch=c(16, 1), lty=c(2, 1))

Plot:

# 2nd plot for interaction cat.var2:contin.var:

m3<-geeglm(dependent.var ~ cat.var2 * contin.var, family = poisson, id
  = group, corstr = "exchangeable")

Coefficients:
                                         Estimate

Intercept                                  1.1384
cat.var2SKA                               -4.1958
contin.var                                 0.1182
cat.var2SKA: contin.var                    0.7532

Plot code:
par(mfrow=c(1,1))
plot(contin.var, dependent.var, type="n")
points(contin.var[cat.var2=="SKA"], jitter(dependent.var[cat.var2=="SKA"]))
points(contin.var[cat.var2=="SAH"], jitter(dependent.var[cat.var2=="SAH"]),
       pch=16)
x <- seq(3,7,0.1)
y1 <-exp (1.1384 + 0.1182*x)
lines(x,y1, lty=2)                                 # SAH
y2 <-exp ((1.1384 + -4.1958) + (0.7532 + 0.1182)*x)
lines(x,y2, lty=1)                                 # SKA
legend(4.82, 15, c("SAH", "SKA"), pch=c(1, 16), lty=c(2, 1))

Plot:


deriving the sum of $x^n/(n+2)^2$

Question: I am writing a research paper and I have stumbled upon an issue.
I have to evaluate
$$\sum_{n=1}^{\infty} \frac{x^n}{(n+2)^2}$$
Here is what I did:
$$ \sum_{n=1}^{\infty} x^{n-1} = \frac{1}{1-x}$$
$$\sum_{n=1}^{\infty} x^{n+1} = \frac{x^2}{1-x}$$
Integrate once with respect to $x$.
$$\sum_{n=1}^{\infty} \frac{x^{n+2}}{n+2} = \frac{3}{2} - \frac{x^2}{2} - x - \log(1-x)$$
Divide by $x$
$$\sum_{n=1}^{\infty} \frac{x^{n+1}}{n+2} = \frac{3}{2x} - \frac{x}{2} - 1 - \frac{\log(1-x)}{x}$$
Integrate the expression again;
$$\sum_{n=1}^{\infty} \frac{x^{n+2}}{(n+2)^2} =  \frac{3\log(x)}{2} - x - \frac{x^2}{4} + Li_2(x)$$
All we have to do is divide by $x^2$
$$\sum_{n=1}^{\infty} \frac{x^n}{(n+2)^2} = \frac{3\log(x)}{2x^2} - \frac{1}{x} - \frac{1}{4} + \frac{Li_2(x)}{x^2}  = \frac{4Li_2(x) - x^2 - 4x + 6\log(x)}{4x^2}$$
The issue is WolframAlpha returns it as:
$$\sum_{n=1}^{\infty} \frac{x^n}{(n+2)^2} =  \frac{4Li_2(x) - x^2 - 4x}{4x^2}$$
Why is the way I did, wrong? I have an extraneous, extra log term.?
Help is appreciated.
Comment: Just after "Integrate once with respect to x.": put $x=0$.
Comment: @Kelenner, then it is 0 = 3/2?
Comment: This show that there is a computational error in deriving this formula
Comment: So the constant $C$ has to $=-3/2$ so that the sides cancel out?
Comment: @Kelenner, but why must this be satisfied? In regular integration, do we always satisfy that $LHS = RHS$ for every $x$?
Comment: You have $\sum_{n\geq 1}x^{n+1}=-1-x+\frac{1}{1-x}$. When you integrate $\sum_{n\geq 1}x^{n+1}$ as $\sum_{n\geq 1}\frac{x^{n+2}}{(n+2)}$ you have put the integration constant equal to $0$. So the RHS is $-x-\frac{x^2}{2}-\log(1-x)$ (integration constant = $0$ also)
Comment: The integration constants **cant** be $0$. If it is then:

$$\sum_{n=1}^{\infty} \frac{x^{n+2}}{n+2} = \frac{3}{2} - \frac{x^2}{2} - x - \log(1-x) + C$$,

Then if $C$ is 0. You will end with:

$$\sum_{n=1}^{\infty} \frac{x^{n+2}}{n+2} = \frac{3}{2} - \frac{x^2}{2} - x - \log(1-x)$$

So $C = -3/2$ is the requirement, so that there is no constant on the RHS>
Comment: This is a particular case of the Lerch Transcendent: http://mathworld.wolfram.com/LerchTranscendent.html
Answer: Not sure what you did, but all that work seems kinda silly to arrive at your result.
$$\sum_{n=1}^\infty\frac{x^n}{(n+2)^2}=\frac{1}{x^2}\sum_{n=1}^\infty\frac{x^{n+2}}{(n+2)^2}=\frac{1}{x^2}(-x-\frac{x^2}{4}+\sum_{n=1}^\infty\frac{x^n}{n^2})=\frac{1}{x^2}(-x-\frac{x^2}{4}+\text{Li}_2(x))$$
Comment: How is $\frac{1}{x^2}\sum_{n=1}^\infty\frac{x^{n+2}}{(n+2)^2}=\frac{1}{x^2}(-x-\frac{x^2}{4}+\sum_{n=1}^\infty\frac{x^n}{n^2}$?
Answer: Somewhere in your question, you write "Integrate once with respect to $x.$". In the equation following that phrase, you have a $\frac{3}{2}$ on the r.h.s. That's superfluous. The derivatives of the l.h.s. and the r.h.s are equal, and setting $x=0,$ we find that the constant of integration is $0.$
Comment: The $3/2$ is not the constant of integration.
Comment: The constant of int. is not 0, it is -3/2
Comment: I explained in my answer how I found that the 3/2 is unnecessary (namely, by setting x = 0). What's wrong with that?

deriving the sum of $x^n/(n+2)^2$


Resize Logical Volume Group

Question: Hi ServerFault Community.
To this volume group:
  --- Volume group ---
  VG Name               virtual-machines
  System ID
  Format                lvm2
  Metadata Areas        1
  Metadata Sequence No  2
  VG Access             read/write
  VG Status             resizable
  MAX LV                0
  Cur LV                1
  Open LV               0
  Max PV                0
  Cur PV                1
  Act PV                1
  VG Size               117,18 GiB
  PE Size               4,00 MiB
  Total PE              29999
  Alloc PE / Size       25600 / 100,00 GiB
  Free  PE / Size       4399 / 17,18 GiB
  VG UUID               iXdHIW-f7eR-aAb2-DHxR-ybAv-dQCy-oBA1Um

containing this logical volume
  --- Logical volume ---
  LV Name                /dev/virtual-machines/win7x64
  VG Name                virtual-machines
  LV UUID                2CXriq-v3M2-dVkG-j8JI-dGUD-yyph-r9waRs
  LV Write Access        read/write
  LV Status              available
  # open                 0
  LV Size                100,00 GiB
  Current LE             25600
  Segments               1
  Allocation             inherit
  Read ahead sectors     auto
  - currently set to     256
  Block device           252:0

I'd like to add another logical volume via
lvcreate -L 100G -n win7x64-gaming virtual-machines

but it says
Insufficient free extents (4399) in volume group virtual-machines: 25600 required

So i thought of resizing the vg but I did not find anything like vgresize. How could I manage to add this new lv?
EDIT:
I took an empty HDD and just called lvcreate so I assume the following is interesting for you.
  --- Physical volume ---
  PV Name               /dev/sdb1
  VG Name               virtual-machines
  PV Size               117,19 GiB / not usable 4,00 MiB
  Allocatable           yes
  PE Size               4,00 MiB
  Total PE              29999
  Free PE               4399
  Allocated PE          25600
  PV UUID               iXZ9sf-UMnI-azYF-2h0v-dCt3-44GB-NwT7v9

Answer: "but I did not find anything like vgresize" -> It does exists and it's named vgextend
Edit : If I guess correctly, You already have one disk /dev/sdb1, one vg called virtual-machines and one LV win7x64. Now you want to create another 100G LV but there is not enouch space, so you want to add another disk.

Step 1 : Identify the new disk. You can for example try dmesg.
Step 2 : Create a PV on the new disk (or on a partition of the new disk). Use pvcreate for this.
Step 3 : Add new PV to existing VG using vgextend
Step 4 : Create the new LV with your command above.
Comment: Yes. Best is to use entire disk at the beginning. pvresize qnd fdisk can be used as a workaround afterward (as always, make sure you have backups before).
Comment: Doesn't this only work for physical volumes?
Comment: What is your question? Vgextend lets you add physical volumes in existing vg.
Comment: added information to my question, maybe useful?!
Comment: NO :( : "I took an empty HDD" -> what's its name? /dev/sdb1? Doesn't seem as it's not empty. I'll update the answer with what I guess.
Comment: /dev/sdb is the harddrive
I want to add a new partition to the harddrive and then to the vg.
Comment: /dev/sdb is not empty. Two options : A) Find/create unused partition on /dev/sdb B) Add an empty disk
Comment: take A ;)
already created sdb2
Comment: couldn't i just enlarge the pv sdb1 so adding a new lv is no problem?
Comment: then you finished step 1 and have to go to step 2 :)
Comment: thank you, that worked but now I just added another partition to my VG, right? couldn't I just extend the existing physical volume so that I don't have to add a new partition every time a add a new lv?

Resize Logical Volume Group


Como usar o appendChild

Question: Queria saber como faço para que ao em vez de aparecer aquela frase apareca o ul ao clicar no botão, o que eu devo usar no createTextNode para isso acontecer.

function mais() {
  var x = document.createElement("li");
  var t = document.createTextNode("This is a paragraph.");
  x.appendChild(t);
  document.body.appendChild(x);
}

Tarefas

    <button type="button" onclick="mais()" class="btn-mais" >Adicionar</button>

          <input type="text" class="titulo" placeholder="Título">
          <button type="button" onclick="enable()" class="btn-escrever">✒</button>
          <button type="button" class="btn-apagar">✂</button>

        <textarea name="" placeholder="Texto da tarefa" class='texto'></textarea>

Answer: falta criar o ul
O appendChild acrescenta ao elemento selecionado o que for declarado na sequência entre parênteses. No caso você havia criado um elemento li e colocou no corpo do html. No entanto, geralmente o li vem dentro de um elemento ul. Então era preciso criar o elemento ul e inserir o li dentro dele como pode ver abaixo.

function mais() {
  var x = document.createElement("ul");
  var y = document.createElement("li");
  var t = document.createTextNode("This is a paragraph.");
  x.appendChild(y);
  y.appendChild(t);
  document.body.appendChild(x);
}

Tarefas

    <button type="button" onclick="mais()" class="btn-mais" >Adicionar</button>

          <input type="text" class="titulo" placeholder="Título">
          <button type="button" onclick="enable()" class="btn-escrever">✒</button>
          <button type="button" class="btn-apagar">✂</button>

        <textarea name="" placeholder="Texto da tarefa" class='texto'></textarea>

caso queira acrescentar na ul já existente você deve selecionar o ul e acrescentar seu li dentro dele assim:

function mais() {
  var x = document.createElement("li");
  var t = document.createTextNode("This is a paragraph.");
  x.appendChild(t);
  document.getElementById('tarefas').appendChild(x);
}

Tarefas

    <button type="button" onclick="mais()" class="btn-mais" >Adicionar</button>

          <input type="text" class="titulo" placeholder="Título">
          <button type="button" onclick="enable()" class="btn-escrever">✒</button>
          <button type="button" class="btn-apagar">✂</button>

        <textarea name="" placeholder="Texto da tarefa" class='texto'></textarea>

Answer: Uma das formas existentes de fazer isso:
você atribui a uma variável um código html, tome cuidado com os parênteses, isso pode dar problema. E não esqueça de fechar as chaves HTML também.
Foi utilizado JQuery, o atributo append.

<!DOCTYPE html>

  <input type="text" class="titulo" placeholder="Título">
  <button type="button" onclick="enable()" class="btn-escrever">✒</button>
  <button type="button" class="btn-apagar">✂</button>

<button id="btn1">Criar</button>

Como usar o appendChild


How can I add a source control folder to an existing team project in TFS 2010?

Question: I have a team project named "ABC web" without a corresponding source control folder. If I double-click on the source control element in Team Explorer it says:

No Source Control Folder
Cannot open $/ABC web. Source control has not been configured for this team project, you do not have permission to access it, or the team project has been moved or deleted.

If i try to add a file to "$/ABC web/test.txt" using tf.exe it says:

TF10175: The team project folder $/ABC web does not exist. Contact your Team Foundation Server administrator and ask that it be created.

How can I create the team project folder?
Comment: I just encountered exactly the same issue the other day and immediately sought help from experts. They just posted the workaround yesterday. see https://msmvps.com/blogs/vstsblog/archive/2010/11/03/how-to-add-a-source-control-folder-to-an-existing-team-project.aspx Sorry, the link to command line utility in msmvps web page was expired :-(. Can someone post an equivalent solution?
Thanks.
Answer: I just encountered exactly the same issue the other day and immediately sought help from experts. They just posted the workaround yesterday. see https://msmvps.com/blogs/vstsblog/archive/2010/11/03/how-to-add-a-source-control-folder-to-an-existing-team-project.aspx
Answer: In TFS2008, New Team Project Creation wizard contained an option called do not create a source control folder at this time which creates Team Project without configuring corresponding source control folder.TFS2010 doesn't contain this option anymore.
I think in TFS2008, this project may have been created with above configuration.
Comment: I think its not possible to configure the Source Control to your existing to Team Project. The other option is to create a New Team Project with Source Control configuration and move your existing artifacts to new Team Project using TFS Integration Platform(http://tfsintegration.codeplex.com/)
Comment: That is the most likely cause, but is there a way to fix it, i.e., create a source control folder for it?
Answer: To which TFS usergroup do you belong?
Your account may not have the Read Permissions for Source Control folders.
Comment: I'm in the Team Foundation Administrators group so it shouldn't be a security issue. TFSSecurity shows that I have read permissions on the $/ folder, so it's quite certain that this project has no source control folder.
Comment: Are you using TFS2008 or TFS2010?

If you are using TFS2010, Is it a fresh Install or upgrade from TFS2008?
Comment: It's an upgrade from TFS2008.


Categorical encoding after discretization

Question: When a variable is discretized it is converted to a categorical variable. This new variable should be encoded back to numeric using label encoding or one hot encoding. I mean, sklearn by default (https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.KBinsDiscretizer.html) uses one hot encoding but maybe it makes more sense to use label encoding. However, if I convert it back to numeric using Label Encode I don't really see the point of discretization. What's the best default: one hot encoding or label encoding?
As you can see it's not a specific question but general question about best defaults.
Answer: Depends on the algorithm!
Linear/additive models and NNs work quite well with OHE.
Tree based methods don't, so you are better off using binary or numerical (label) encodings.
Finally, you can also use frequency encoding or some type of target encoding (mean, for example), which often offer good results independently from the model.

However, I don't really see why you would discretize the variable in the first place if it's continuous, except in some particular cases for performance...
EDIT:
To be more precise on my statement about trees, I reference the original CART paper by Breiman [1984]. Finding the optimal split for a categorical variable with L categories would mean to evaluating $2^L-1$ different splits. Breiman proves that the optimal split can be found by ordering categories by mean response (or class1 probability in binary classification problems) and only evaluating the L splits of the ordered categories.
This is all and all equivalent to a target encoding, and it is proven to be the best approach for regression and binary classification. For multiclass classification the problem is more complicated.
Comment: You say that OHE is not recomended for trees but I have seen most people use it for XGBoost.
Comment: Here's a very nice post on the subject: https://medium.com/data-design/visiting-categorical-features-and-encoding-in-decision-trees-53400fa65931 -- OHE is just not recommended. The implementations that allow for categorical variables for regression and binary classificaiton usually implement a sort of target encoding, assigning a number to the categories based on their average regression value/probability of being in the positive class (I don't remember which paper this was in, I'll post it if I find it)
Comment: And this: https://roamanalytics.com/2016/10/28/are-categorical-variables-getting-lost-in-your-random-forests/ -- in general - OHE is easy to use and not too bad as long as cardinality is small :)


Can we prove this inequality holds for some region?

Question: Can we prove this inequality holds form some region
, if $(x-a)^2+(y-b)^2>R^2$ then
$$
\begin{align}
\ -x\arctan(x)+0.5x-y\arctan(y)+0.4y<0\\
\end{align}
$$
As I can see from the WolframAlpha picture there is some region that is similar to $(x-a)^2+(y-b)^2>R^2$ but I have no idea how we can prove that and find $R$
Answer: The picture suggests to take $a=0.5/2$, $b=0.4/2$ and $R\simeq 1/3$. We can bound $R$ more precisely
looking for a big disk $D$ with this center $(a,b)$, which is contained in the white region.  Thus we have to show that if $(x,y)\in D$ then
$$-x\arctan(x)+0.5x-y\arctan(y)+0.4y\ge 0.$$
We use a fact that for each non-negative $t$ we have $\operatorname{arctan} t\le t$. Therefore we have $-t\operatorname{arctan} t\ge –t^2$ for each real $t$. Then
$$-x\arctan(x)+0.5x-y\arctan(y)+0.4y\ge$$ $$–x^2+0.5x-y^2+0.4y=$$ $$-(x-a)^2+a^2-(y-b)^2+b^2\ge a^2+b^2-R^2.$$
So $R=\sqrt{a^2+b^2}=\sqrt{0.1025}=0.3201\dots.$ fits.
I thank to user8053696 for providing the picture:

But to find a small disk which contains the white region, we have to look for other, I think, not so simple arguments.
Comment: Could you, please, clarify why if $-x^2+0.5x-y^2+0.4y<0$ then $-x\arctan(x)+0.5x-y\arctan(y)+0.4y<0$? Because this circle will be inside closed region of function with arctan not outside. https://i.imgur.com/n9Xy2z1.png
Comment: For example, from 5>-5 doesn't follow that 5 is negative.
Comment: @user8053696 Thanks for the picture, I clarified my answer.


How do I start with an empty attributedString whenever the UITextView changes?

Question: I am using attributed string to format a single character string for UITextView that will update whenever a button is clicked or a picker is moved. However, because I use attributedStringLine.append(attributedCharString) the attributedString continues to grow rather than start a new attributed string whenever UITextViewis updated.
The code below demonstrates a simplified version of the problem.
NSMutableAttributedString() operates on the string in myArray. New strings are processed whenever UITextView changes. These are in array1, array2 and array3.
import UIKit

var str = "Hello, playground"

let array1                      = ["7.0", "55.55", "1.0", "9.27"]
let array2                      = ["0", "10", "20", "30", "40"]
let array3                      = ["A", "B", "C", "D", "E", "F"]

var myArray                     = [""]
let attributedStringLine        = NSMutableAttributedString()
let numberOfRawStringCharacters = myArray.count

func appendTextString(i: Int){
    let rangeOfCharString       = (myArray[i] as NSString).range(of: myArray[i])
    let attributedCharString    = NSMutableAttributedString.init(string: myArray[i], attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 18.0, weight: UIFontWeightLight)])
    attributedCharString.addAttributes([NSForegroundColorAttributeName : UIColor.blue], range: rangeOfCharString)
    attributedStringLine.append(attributedCharString)
}

func makeText() {
    for i in 0..<myArray.count {
        appendTextString(i: i)
    }
}

var line = attributedStringLine.length

myArray.removeAll()
myArray                         = array1
myArray.count
makeText()
print(attributedStringLine)
line = attributedStringLine.length

myArray.removeAll()
myArray                         = array2
myArray.count
makeText()
attributedStringLine
line = attributedStringLine.length

myArray.removeAll()
myArray                         = array3
myArray.count
makeText()
attributedStringLine
line = attributedStringLine.length

How do I start with an empty attributedString whenever the UITextView changes ?
For NSMutableString, replacing or deleting characters from the range of an existing attributed string seems to be the only alternative available. And I'm pretty sure this is not a duplicate of Value of type 'NSMutableAttributedString' has no member 'removeAll'
Answer: Since you declared attributedStringLine with let, you can remove all character from it at the start of makeText.
func makeText() {
    attributedStringLine.deleteCharacters(in: NSMakeRange(0, attributedStringLine.length))
    for i in 0..<myArray.count {
        appendTextString(i: i)
    }
}

Or you change its declaration from let to var and then use attributedStringLine = NSMutableAttributedString() at the start of makeText.
Comment: Your first solution worked fine in my Xcode project so from my point of view it will be the accepted answer. It's worth noting that in Playground attributed strings appear correctly formatted for `array2` and `array3`, but for `array1` the unformatted string appears followed by the attributed formatting script enclosed in curly brackets. On the Simulator these numeric floating point characters display correctly. Thanks.


Deriving ${\rm var}(\overline{X})$ from expected value definition

Question: I want to show ${\rm var}(\overline{X})$ is $\sigma^2/ n$ for $n$ independent random variables each with mean $\mu$ and standard deviation $\sigma$.  I would like to show this using:
$$ E(\overline{X} - \mu) ^ 2 $$
I'm doing something wrong in my own calculations because it's not reducing to $\sigma ^ 2/ n$.
Any thoughts/comments?  Thanks!  Diane
Comment: Maybe if you could post some of your own work, someone could point out where you are going astray?  Else the calculation is a fairly standard one found in most textbooks, and people might not want to bother typing it all in here (unless they have a canned answer in their files that they can paste in here easily).  Looks a lot like homework too, and if so, please add the homework tag.
Comment: $$E[(Y-\mu_Y)^2] = E[Y^2] - 2\mu_YE[Y] + \mu_Y^2 = E[Y^2]-mu_Y^2$$ since $E[Y] = \mu_Y$.  So you have an incorrect sign in the expansion.  Also, try writing $$\bar{X}-\mu = \frac{1}{n}\sum_{i=1}^n (X_i-\mu)$$ and $$E[(\bar{X}-\mu)^2] = \frac{1}{n^2}E\left[\sum_i (X_i-\mu)^2 + \sum_i\sum_{j\ne i}(X_i-\mu)(X_j-\mu)\right].$$ Can you figure out which expectations are $\sigma^2$ and which are $0$, and why?
Comment: E((Xbar - mu) ^ 2) = E(Xbar ^ 2 - 2 * Xbar * mu - mu ^ 2) =   E(Xbar ^ 2) - 2 * mu * E(Xbar) + E(mu ^ 2) = E(Xbar ^ 2) - 2 * mu ^ 2 + mu ^ 2 = E(Xbar ^ 2) - mu ^ 2.  So, I'm stuck with what to do with E(Xbar ^ 2).  That's why I was thinking there is some "trick" or something I'm missing.
Comment: OK, ignore the first two sentences of my previous comment: your expression is correct now.  The first two sentences of my previous comment were based on a draft version of your write-up, and you have corrected it in the final version.  Unfortunately, it is too late to edit my own previous comment.
Comment: Yes!  I think the biggest help was writing out Xbar - mu as the summation you have above.  Then everything is quite clear.  Thank you very much.
Answer: If each observation $X_i$ has standard deviation $\sigma$ then they each have $Var(X_i)=\sigma^2$. As they are independent, we get $Var(\sum_i X_i)= n\sigma^2$. This implies that $Var(n^{-1}\sum_i X_i)= n^{-2}n\sigma^2$, and after cancellation is states that $Var(\bar X)=\sigma^2/n$. If you want to use $E((\bar X - \mu)^2)$, then replace $X_i$ by $X_i-\mu$ everywhere in this argument... but it doesn't make any difference.


Deviation of Monte Carlo Markov Chain pi estimation

Question: I have this graph here:
https://i.stack.imgur.com/2Zxjx.jpg
https://github.com/martin-varbanov96/fmi-fall-2016/blob/master/monte_python/hw_1/b1.py
It is representing Markov-chain sampling algorithm for estimating PI with 500 trials.
My question is:
-Why very small value of delta and very big values for delta yield a less precise result compared to the medicore values?
Comment: Can you show the algorithm? Difficult to imagine what 'delta' is, etc.
Comment: yes I have put a link to the code
Comment: That said, I'm not so sure why you would do this with MCMC in the first place, rather than simply sampling from the square uniformly in the first place. Is this an assigned exercise, perhaps?
Comment: Also relevant: the last paragraph of http://math.stackexchange.com/questions/1864363/confused-about-proposal-distribution-in-mcmc/1864376
Comment: the course is called "Statistical Mechanics, Algorithms and Computations" Werner Krauth is * excellent *
Answer: This method is a Metropolis-Hastings algorithm for sampling from the uniform distribution on the square with side length 2. This assigns a density of $1/4$ to each point inside the square and $0$ to each point outside the square. To build a MH algorithm to sample from this distribution, first you need a chain which can eventually reach any point in the square. Your underlying chain (drawing points uniformly from a square of side length $2 \delta$ centered at the current point) is such a chain. Then you choose a corresponding acceptance probability, so that the resulting chain is reversible with respect to the desired equilibrium distribution. In this case, this reversibility is attained if you simply always accept a candidate inside the square and reject a candidate outside the square.
Now, the convergence rate of a MCMC algorithm, including Metropolis-Hastings, largely hinges on the decorrelation time of the chain being sufficiently short. This requires the proposal chain to be both "ambitious", so that there is some chance for a significant distance to be covered by the proposal chain in a short time, and "conservative", so that a reasonable fraction of the proposed transitions are accepted. The larger $\delta$ is, the more ambitious (and hence less conservative) the proposal chain is. Thus the convergence rate is best for intermediate values of $\delta$.
Making this rigorous is not so simple, because this problem is in continuous space. It requires you to estimate the largest nontrivial eigenvalue of the transition probability kernel, which in this case is the integral operator $(Pf)(x)=\frac{4\delta^2-A(x)}{4\delta^2} f(x)+\frac{1}{4\delta^2} \int_{\| x-y \|_\infty \leq \delta,\| y \|_\infty \leq 1} f(y) dy$, where $A(x)=\int_{\| x-y \|_\infty \leq \delta,\| y \|_\infty \leq 1} 1 dy$.
In this case of estimating $\pi$ you can get a limited idea of what's going on by imagining starting your chain at the center of the square and measuring how long it will take to get out of the circle. With small enough steps, most steps will get accepted, so it will take like $O \left ( \frac{1}{\delta^2} \right )$ time to get out of the circle (the square is because steps tend to cancel each other out, since the mean velocity is zero on most of the square). With large steps, the first step will tend to get us out of the circle, but a step will only be accepted with probability $1/\delta^2$, so it will take $O(\delta^2)$ steps for us to get out of the circle. If we assume the "constants" in these $O()$ expressions are comparable, then these will balance out when $\delta=1$, so that the best $\delta$ should be in the general vicinity of $1$. Of course this assumption might be completely wrong, but it is actually quite often reasonable, as you see from your data.


hook_node_insert PDOException exception issue

Question: I am attempting to programmatically insert some field data when a new node is being created using the following code:
function mymodule_node_insert($node) {

    $dialects = array('en-AU', 'en-NZ', 'en-US');

    node_object_prepare($node);
    foreach ($dialects as $dialect) {
        $node->translations->data[$dialect]['entity_id'] = $node->nid;
        $node->translations->data[$dialect]['entity_type'] = 'node';
        $node->translations->data[$dialect]['revision_id'] = 3;
        $node->translations->data[$dialect]['language'] = $dialect;
        $node->translations->data[$dialect]['source'] = 'en';
        $node->translations->data[$dialect]['uid'] = 1;
        $node->translations->data[$dialect]['status'] = 1;
        $node->translations->data[$dialect]['translate'] = 0;
        $node->translations->data[$dialect]['created'] = time();
        $node->translations->data[$dialect]['changed'] = time();

        $node->field_page_body[$dialect] = $node->field_page_body['en'];
    }
    node_save($node);
}

However, I recieve the following error:

I understand it's complaining about the same node ID being saved twice but I'm not sure how to avoid this exception and update my new node with the programmatically set data?
It's important I execute my code at hook_node_insert because there are hundreds of nodes to be imported later and they all need the same treatment.
The same code works when tested in mymodule_init().
Answer: You cannot call node_save($node) during hook_node_insert($node).
According to the documentation, that hook is invoked during the middle of the database transaction, so the node isn't committed to the database yet. So when you invoke node_save, the old node you're attempting to update doesn't exist yet, and it will attempt to create a new node (with the same ID). Thus, the collision.
Comment: Thanks for your response and I apologise if my question was not clear but I had already deduced that issue. My question is realy more about how I can get around this issue. I still need to insert data into the node as it is being created. I'm sure my code is implemented in the right hook but the code itself is "faulty" - what do I do to fix that?
Comment: Oh. In that case, won't hook_node_presave work for your purposes? Do you absolutely need the nid to exist for the data you're adding?
Comment: I did try hook_node_presave but the result was essentially a crash
Comment: Could you clarify? What error did you receive?

Or does it not really matter per your answer below?
Comment: I appreciate your dilligence and persistence but the problem is solved.
The error was a white screen with raw text. It was one of those that when beyond php and apache issues and shows something has absolutely gone wrong with the system.
Answer: I found the work around to this issue here.
Use field_attach_update('node', $node);
instead of:
node_save($node);


Android Flurry events are not reported on the dashboard

Question: I have integrated Flurry in a test project. I am trying to send events to Flurry but they are not reported at all on the Flurry dashboard. I have followed carefully how to integrate it in my app:
@Override
protected void onStart()
{
    super.onStart();
    FlurryAgent.onStartSession(this, "XXXXXXXXXXXXX");
}

@Override
protected void onStop()
{
    super.onStop();
    FlurryAgent.onEndSession(this);
}

public void sendEvent(View view){
    FlurryAgent.logEvent("Page_Viewed");
}

The log of the device is:
12-06 10:46:53.692: W/FlurryAgent(2058): Start session
12-06 10:46:54.232: W/FlurryAgent(2058): FlurryDataSender: report eb66f44c-1a59-4b5d-82df-04a9bf5a086a sent. HTTP response: 200 : OK
12-06 10:47:00.972: W/FlurryAgent(2058): Event count started: Article_Read

I stop the app and I restart it:
12-06 10:47:18.302: W/FlurryAgent(2058): Trying to end session
12-06 10:47:28.313: W/FlurryAgent(2058): Ending session
12-06 10:47:33.193: W/FlurryAgent(2058): Start session
12-06 10:47:33.522: W/FlurryAgent(2058): FlurryDataSender: report 017075e6-91a6-44b6-a4a7-70cffec21f00 sent. HTTP response: 200 : OK

I have waited more than 48 hours and I still do not see anything on the dashboard. I am using the Flurry SDK version 3.3.1.
Comment: Please post the code that you used.
Comment: @TharakaNirmana I have just posted the code.
Comment: @poiuytrez Did you get this issue fixed?
Comment: see this how to use logEvent() http://stackoverflow.com/a/21136813/1765530
Answer: Based on your code it looks like you are doing everything correctly. The only problem might be that you are not calling the sendEvent() method which calls logEvent()... Or there might be something on the network that is blocking the communication with Flurry servers.


When does $x^3 - x^2 - 2 x + 1$ split mod $p$?

Question: Conjecture: the primes for which the polynomial $x^3 - x^2 - 2 x + 1$ splits mod $p$ are the primes $\equiv 1$ or $6$ mod $7$ (OEIS sequence A045472).  Is this correct?
Comment: You may need to include $p=7$ because $x^3 - x^2 - 2 x + 1 = (x+2)^3 \bmod 7$.
Comment: see final example in https://www.impan.pl/en/publishing-house/journals-and-series/acta-arithmetica/all/28/3/75096/representability-by-certain-norm-forms-over-algebraic-number-fields
Comment: also see page 6 in Reuschle, https://books.google.com/books?id=wt7lgfeYqMQC&pg=PR1&lpg=PR1&dq=reuschle++tafeln+complexer+primzahlen&source=bl&ots=VGZFPrfUBn&sig=MlQ667PqXaQ9rAvLWkG3_F1rwsk&hl=en&sa=X&ved=0ahUKEwiIwtSvm9TQAhUJ-2MKHXJIA_kQ6AEIODAE#v=onepage&q=reuschle%20%20tafeln%20complexer%20primzahlen&f=false
Comment: [Related](https://math.stackexchange.com/q/2385221/11619).
Answer: If $\alpha$ is a root of $x^3-x^2-2x+1$ (in any field) then the latter splits as $$(x-\alpha)(x-\alpha^2+\alpha+1)(x+\alpha^2-2).$$ Also if $\alpha \neq -2$ and $\beta$ is a root of $$x^2+\alpha x + 1$$ then $\beta$ is a primitive seventh root of unity. Combining all this for the field $\mathbb{F}_p$ where $p\neq 7$: If $x^3-x^2-2x+1$ has a root in $\mathbb{F}_p$ then $\mathbb{F}_{p^2}$ contains a primitive seventh root of unity and so $p^2 \equiv 1 \pmod 7$. The other way around: If $p^2\equiv 1 \pmod 7$ then $\mathbb{F}_{p^2}$ contains a primitive seventh root of unity $\beta$ and $\alpha = -\beta-\beta^{-1}$ is a root of $x^3-x^2-2x+1$. Moreover $\beta^p = \beta$ (if $p\equiv 1 \bmod 7$) or $\beta^p = \beta^{-1}$ (if $p \equiv -1 \bmod 7)$. Either way $\alpha^p = \alpha$ so $\alpha \in \mathbb{F}_p$. For $p=7$ $$x^3-x^2-2x+1\equiv (x+2)^3 \pmod 7$$ as pointed out by @lhf in a comment.
Comment: Do you mind explaining why if $x^3 - x^2 - 2x + 1$ has a root in $\Bbb{F}_p$, then $\Bbb{F}_{p^2}$ contains a primitive seventh root of unity?
Comment: @ClementYung If $\alpha_1$, $\alpha_2$, $\alpha_3$ are the roots in $\mathbb{F}_p$ (as provided in the answer) then $$x^6+x^5+x^4+x^3+x^2+x+1 = \prod_{k=1}^3(x^2 + \alpha_k x + 1)$$
Comment: Sorry, but I still don't understand. The polynomial you gave contains all the primitive roots. What's next? And where does $\Bbb{F}_{p^2}$ comes in?
Comment: @ClementYung The right hand side is a product of quadratics over $\mathbb{F}_p$ so any root has degree $\leq 2$ over $\mathbb{F}_p$.
Comment: Why does the degree of the root matter here? Apologies but I'm afraid I'm completely lost. Do you mind explaining in more detail? I'm still relatively new to number theory.
Comment: In particular, I'm not sure how we can assure they the polynomial you mentioned has a root.
Comment: I have made a question on my queries [here](https://math.stackexchange.com/questions/3736057/why-does-the-polynomial-splitting-implies-existence-primitive-root-of-unity-in). If you are available, feel free to take a look.
Answer: Yes, this is because the zeros of the polynomial is $-(\zeta^j+\zeta^{-j})$
for $\zeta=\exp(2\pi i/7)$ and $j\in\{1,2,3\}$. So it splits iff $\zeta+\zeta^{-1}\in\Bbb F_p$ for $\zeta$ now a primitive seventh root of unity
in an extension of $\Bbb F_p$. This is the case iff $(\zeta+\zeta^{-1})^p
=\zeta+\zeta^{-1}$ in characteristic $p$, and that is the case iff
$p\equiv\pm1\pmod7$.
Comment: @LordSharktheUnknown , feel free to give actual criticism, or perhaps use the name Lord Snark. What is wrong with my comment?
Comment: @ThomasAndrews There are more careful ways of writing comments too!
Comment: @ThomasAndrews Its typesetting is somewhat suboptimal!
Comment: There is no way that #\zeta+\zeta^{-1}\in\mathbb F_p$, because the $\zeta$ you define is a complex number. There are more careful ways to write this answer...


Struct from C++ to C#

Question: I have a project which uses a library which was mostly build on and around C++.
The delivered DLL with this library, i have imported into my C# project.
After importing the following method in Unity:
    [DllImport("pst")]
private static extern int pst_get_sensor(PSTSensor sensor);

I require this PSTSensor struct, so actually use the method.
In the C++ .h file, the struct is defines as :
struct PSTSensor
{
        char    name[80];       /**< Device name */
        int     id;             /**< Device identifier (for other tracking interfaces */
        float   pose[16];       /**< Device pose estimate as row-major matrix */
        double  timestamp;      /**< Time the data was recorded */
};

I have tried to replicate it in C#, and i ended up with this following:
    struct PSTSensor{
    PSTSensor(char[] name, int id, float[] pose, double timestamp){
        this.name = name;
        this.id = id;
        this.pose = pose;
        this.timestamp = timestamp;
    }
    public char[] name;
    public int id;
    public float[] pose;
    public double timestamp;
}

In the example C++ code that came with this project was stated to call pst_get_sensor(&sensor) this '&' sign, i do not recognize? How would i call this method in C#, and make it work?
I think i ruined the struct, seeing how i never worked with them before. At least it doesn't throw errors on compilation anymore, but i think it is still wrong. Any ideas on that?
Many thanks in advance,
Smiley
Answer: I'm not sure if I'm answering your question entirely, but in c++ the & is used to pass an argument by reference which means that the argument you're passing in can be manipulated inside the function. To me it looks like the original function is used to fill out a sensor struct.
int C# you can pass by reference with the ref or out keyword:
private static extern int pst_get_sensor(PSTSensor ref sensor);

Why did you add a constructor in your C# implementation?
Comment: This is a great help already, i added a constructor because i was not sure how to define the arrays in a fixed size without it. I tried different ways which mostly just threw errors at me.
Comment: 'private static extern int pst_get_sensor(PSTSensor ref sensor);' This gives the error: Identifier expected, 'ref' is a keyword.
Comment: I'm sorry, I think the ref keyword is actually supposed to come first: (ref PSTSensor sensor). Check out the C# reference, maybe it will help you to gain more understanding of passing by reference in C#: http://msdn.microsoft.com/en-us/library/vstudio/0f66670z.aspx
Comment: Yep, that seems to fix it just right! Do you have any idea on the proper use of the structs? I can't find a lot of good examples on it yet.
Comment: what do you mean by "the proper use of structs?"
Comment: Well, i now use a struct with a constructor, the C++ example is what it should be like. I have a feeling that mine is over complicated (also, using a struct crashes my software, calling pst_get_sensor(PSTSensor ref sensor);
Comment: Structs are usually used when you need to have a set of related values encapsulated in one place, for example a Point with X and Y values or a struct with contact information (name, email, phone number, address) and so on. When you need methods, events and such types members there's nothing wrong using a struct, but when these types of members are required it's more common to make the type a **class** instead because as far as I can remember, the Struct cannot inherit from other Structs.
Comment: The problem is that i need the struct, because the library requires it as input. This is what happens if i remove the constructor btw: http://puu.sh/5pQlj.png
Comment: As I understand you're supposed to create a PSTsensor, pass it in the pst_get_sensor as reference, and the values will be assigned to in the pst_get_sensor function. Have you tried doing this without the constructor?
Comment: Without the struct constructor? Yes i just did. it still crashes the whole developer software (Visual studio / Unity)
Comment: I'm sorry if I'm causing you frustration with all this ;) Have you tried somethig like this to initialize your fields:   struct PSTSensor
    {
        PSTSensor()
        {
            this.name = new char[80];
            this.id = 0;
            this.pose = new float[16];
            this.timestamp = 0;
        }
        public char[] name;
        public int id;
        public float[] pose;
        public double timestamp;
    }
Comment: I have tried it like that, the problem is that it crashes as well. I think however after questioning my teacher, that my problem lies with the C++ Arrays and C# arrays. these are causing mayor issues, since they are nothing alike.
Comment: You are probably right since the c++ function can directly alter your PSTsensor struct. To me it sounded like a problem with uninitialized fields. Take a look at this, looks related to your problem: http://stackoverflow.com/questions/17654892/passing-c-sharp-structure-with-string-array-to-c-function-which-accepts-void
Comment: Thanks, i will take a look at it, i will most likely make a new topic about this problem.
Comment: Actually in an expression, as is the case here in the context of an actual parameter, `&` is used to take the address of an object. You've got to be careful of the term reference in C++ because it has a precise and specific meaning.
Answer: You did not show the C++ declaration of your function, but give that you call it like this:
pst_get_sensor(&sensor);

it is presumably declared like so:
int pst_get_sensor(PSTSensor *sensor);

The function receives a pointer to the struct. That is clear since the call uses the & operator which takes the address of an object.
On the C# side you translate this parameter as a ref parameter. Like this:
[DllImport(...)]
static extern int pst_get_sensor(ref PSTSensor sensor);

Now, your other problem is that your struct is declared incorrectly. It contains inline arrays and you must communicate the lengths of those arrays to the marshaller. Like this:
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
struct PSTSensor
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
    public string name;
    public int id;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
    public float[] pose;
    public double timestamp;
}

Answer: It seams that all you need to do is declare the parameter as ref
private static extern int pst_get_sensor(ref PSTSensor sensor);

If you want to have a look at an example, there is one here

Struct from C++ to C#


how prove the following statment for this matrix.

Question: Let $A:=[a_{ij}]_{n×n}$ , $a_{ij}=0$  or $a_{ij}=1$ and  $\exists m \in\mathbb N$ such that $A^m=J-I$, where $I$ is the identity matrix and $J=[1]_{n×n}$ (each entry is $1$). How to prove:

$\exists a \in\mathbb N$  such that $n=a^m+1$, and
$m$ is odd.

Thanks in advance.
Comment: Let's collaborate :) I am thinking; $\det(A^m) = \det(J-I)$. Luckily, $\det(J-I) = n-1$, when $n$ is odd and $\det(J-I) = -(n-1)$ when $n$ is even. Then, since $\det(A^m) = [\det(A)]^m$, the equation holds with $a = \det(A)$ (not sure yet as to why $m$ should be odd).
Comment: @Anon, your comment is practically an answer.
Comment: Theorem 1 in C. W. H. Lam, J. H. van Lint, *Directed Graphs with Unique Paths of Fixed Length*, Journal of Combinatorial Theory B, vol. 24, No. 3, 1978, http://alexandria.tue.nl/repository/freearticles/593457.pdf .
Comment: @darijgrinberg aww, I just myself took the square-root $J-I$ and saw that it was imaginary :)
Comment: its better to write $detA^m=(-1)^n(n-1)$ then $n=\frac{{detA}^m}{(-1)^n}+1$
Comment: I love what Anon wrote, but that's full no answer yet: if I'm not missing something, $m$, so far, only need be odd if $n$ is even; and second, we need to also show that this is the only way to find such an $a$...which I'm sure you're aware of, just saying...
Comment: @DonAntonio :) Seems to be at the right track, but I still cannot see the oddness of $m$ :( Shall we look at the original A itself somehow?
Comment: @gnometorule Yeah, if $n$ is even, we are done, now to handle the odd $n$. Also, the existence of $a$ appears to be enough here.
Comment: @Anon: you should post the full write-up as an answer so it can be accepted, which would be nice?
Comment: @gnometorule Well, I couldn't solve it completely anyway :) I guess the OP will find what he/she is looking for with complete details in the referenced paper.
Comment: this paper find solution for $A^k=-I+J $ but this paper refer  to another paper that may i find my answer in referd paper
Comment: @MaisamHedyelloo Apparently, the referenced paper has a restriction on the original $A$, its diagonal elements are all-zero. I will check if it is easy to extend that result and try to write a full answer here.
Comment: I wonder: can't $\det(J-I)$ be calculated explicitly? I tested some cases in wolframalpha, and it seems that the value is $(-1)^{n-1}(n-1)$.
Comment: @MatemáticosChibchas Note $J$ has rank $1$. The eigenvalues of $J$ are obviously $n$ (eigenvector $(1,\dots,1)^T$) and $0$ with mult. $n-1$ (the dimension of the null space). Thus $\det(xI-J)=x^{n-1}(x-n)$, and $\det(I-J)=1^{n-1}(1-n)=-(n-1)$, so $\det(J-I)=(-1)^n\det(I-J)=(-1)^{n-1}(n-1)$.
Answer: (The problem statement is false when $n=1$, but we will ignore this degenerate case.) We have at least three proofs.
Proof 1 (adapted from the proof by Anon; see his/her comment). We have
$$\det (A)^m=\det (A^m)=\det(J-I)=(-1)^{n-1}(n-1)$$
and therefore $n=|\det(A)|^m+1$.
Proof 2 (adapted from Theorem 1 of C. W. H. Lam, J. H. van Lint, Directed Graphs with Unique Paths of Fixed Length, Journal of Combinatorial Theory B, vol. 24, No. 3, 1978; thanks to @darij_grinberg for the information): $A^m=J−I$ implies that $AJ−A=A^{m+1}=JA−A$. Hence $AJ=JA$, i.e. all row sums and column sums of $A$ are equal to some natural integer $c$. Thus $AJ=JA=cJ$ and in turn $A^mJ=c^mJ$. But by property of $A$, we also have $A^mJ=(J−I)J=(n−1)J$. Therefore $c^m=n−1$.
Proof 3: As $2 = 1^m+1$, we may assume that $n\ge3$. Since $A$ is an entrywise nonnegative, by Perron-Frobenius theorem, the spectral radius $\rho(A)$ of $A$ is a maximal eigenvalue of $A$. Hence $\rho(A)^m$ a maximal eigenvalue of $A^m$. But when $n\ge3$, the maximal eigenvalue of $A^m=J-I$ is unique, namely $n-1$. Hence $\rho(A)^m=n-1$, or $n=\rho(A)^m+1$. Finally, as the eigenvalues of $A^m=J-I$ are $n-1$ (simple eigenvalue) and $-1$ (with multiplicity $n-1$), the eigenvalues of $A$ are $\rho(A)=(n-1)^{1/m}$ and a number of $m$-th roots of $-1$. Hence $\rho(A)=|\det(A)|$ and in turn $\rho(A)$ is an integer.