Can bass chord notes be different octaves after playing the root?

Question: The reason for my question is because it seems like everything I read, the bass note is normally the root of the chord, but I am outlining an Am chord where E is the bass note. I thought I found an answer to my question when I read about slash chords by signifying my Am chord as Am/E to specify that the lowest note is E.
However, confusion set in when I noticed almost everything was specifically related to guitar and piano playing the chord with all notes at once. I also read that the slash chord is supposed to tell the bass player what note he/she is supposed to play (which triggered me to finally post this).
Basically, I am unsure whether or not I am breaking an unwritten rule when I outline an Am chord starting at the root, but having the E be an octave lower than normal. If it is fine, then what is proper way of notating it on actual sheet music when notating the chord?
For reference here is what I am referring to: I am going from Em (top) -> Am (bottom)
EDIT: I guess messed up the chord name. I should have said this was an Am9 instead of Am. I did intend the B note as it sounded good on an actual bass guitar (at least to my tonedef ear).
Comment: Does it sound good? If so, screw rules, unwritten or otherwise.
Comment: Hey @TyCobb, do you mean that you have an Am and Em at the same time, or do you mean that the last Es in your bass line have an Am chord above them?
Comment: @BobBroadley I am outlining an `Em` chord (1st 2 bars in the image) and then progressing and outlining an `Am` chord (next 2 bars). The `E` is lower than my root's `A` in the last bar. I hope that answers your question. I'm not playing notes together.
Comment: Do you really hear an Am chord in the last bar of the bottom line?
Comment: @MattL. No, but as I wrote this, I was imagining following a guitar that was playing variations or notes of `Am`. I didn't think the bar mattered and that as long as I didn't deviate from `Am`, any note I played was still part of the `Am` chord.
Comment: You could use that fifth creatively and link it in with a dominant chord.
Answer: You're not breaking any unwritten rules here. It is in fact pretty common to use the 5th of the chord leading up to the root a fourth higher in the bass. However, in your bassline the question is if you really mean an A minor chord in the last bar. If you hear an A minor chord over both bars in the bottom line then - by definition - that's the way it is because you're the composer. But you might want to try other chords to see if it is really an A minor chord that you mean. Just two suggestions for the last bar for you to compare to your original A minor sound:
Em Bm7 (=D/B) or Em A/B
Comment: Thanks a lot for the info. I will try this out tomorrow after work. Question though, is it the octave difference that made you ask that question? I am curious because wouldn't my first two bars suffer from the issue? Maybe I don't understand the issue.
Comment: @TyCobb: Well, in general you can have any bass note under any chord (you know about slash chords), but this bass line doesn't sound to me as if you intended very complex chords. So it's just a matter of perception and style. As for the first two bars, I hear the following chords: | Em D | D/F# Em/G |
Answer: How you describe the harmony (chords) at a point such as the beginning of bar 4, depends upon what any chord symbols are going to be used for. There are in fact several ways to notate the passage you're describing. (For this answer I'm assuming that you do indeed want an Am chord sounding with all the bass notes in bars 3-4). Here are some options:

if you simply want all instrumentalists to know that an Am chord sounds throughout bars 3-4, just give them an Am symbol at the beginning of bar 3. Even though the bass line is changing through these bars, the other instruments will keep playing Am. Even putting a single Am marking in the bass part is a useful thing to do here, as the bass player will be aware that the harmony remains the same, even though their bass line changes notes. This is probably the best way to notate this passage if you feel that the bass line is an independent line, which is not integral to how the harmony functions. (Consider this example: the bass plays an A Minor scale, while the other instruments continue to play Am chords - in this case, it would be a nonsense to describe the chords as Am, Am/B, Am/C, Am/D, Am/E, Am/F, Am/G, even though this would technically describe the relationship between the continuous chord and changing bass line!)
if, on the other hand, you feel that the notes in the bass line are integral to defining the harmony, and so it would be useful for the other instrumentalists to reflect this this in their own choice of chord voicings/types, then yes, you could give the following chords to everyone: Am, Am/C, Am/E, Am/B. This would also be useful in a score, as it shows the overall harmony, created by all parts together. This could certainly be valid for your example; the bass line doesn't feel like an independent "melodic" line, and it's use of repeated notes and regular changes every two beats (ish) certainly make it feel like it has a harmonic function.
you could choose some kind of half-way point between these two sets of chord symbols. The first six beats of line two all outline an Am chord, as the bass notes are all chord tones of Am, even though the bass is changing the inversion of these chords through arpeggiation, however, the B under the last chord is not part of an Am chord. So, you could use the following: Am / / / | / / Am/B / | Again, I must stress, this only makes sense if you "hear" the Bs in the bass line here as part of the harmony (i.e. you may want them reflected in the chords played with these bass notes) rather than simply non-chord-tones independent of the accompanying chords.

TL;DR: The short answer to the very specific question about the E under an Am chord is that, yes, this is an Am/E (it is an inversion). But, bass players commonly move between chord-tones when creating a bass line to fit with a particular chord, and use non-chord-tones too. So, you could simply use an Am marking here, and consider the bass line to have a certain amount of independence from the accompanying chord.
Personally, I would favour simply using an Am marking, because I simply hear the bass line as an (reasonably) independent line, which is essentially outlining an Am arpeggio under an Am chord before ending on a non-chord-tone which approaches the root of Em strongly by a fourth. If your bass line more strongly emphasised notes which would not be expected under an Am chord, I think this would make it far more important to use slash chord notation. For instance, if the bass line were primarily using non-chord-tones, say a B throughout bars 3-4, rather than just in the last two beats, this would greatly affect the effect of the harmony, and an Am/B would be a good idea in all parts. Or, for instance, if the whole of the line used an E under the Am chord, this would merit using an Am/E symbol, for the same reason.
Lastly, with a nod to @Matt L, are you sure you want a B under Am harmony at the end of the line? I kind of like the "clash" effect you get here, but other notes might work better. If it is what you want, the distinctive sound of this chord in particular, might justify using the notation in the third bullet-point above.
Comment: That idea reminds me of the intro to Midnight At the Oasis - 1st chord called F#11 - Emaj 2nd inv. with F# bass.Another way to name the chord?
Comment: It is what I intended because I did like the sound (at least coming out of my bass guitar). Playing it on my piano last night just to see what it sounded like yielded a "meh it's okay" result. I know I can *use* it because it can be whatever I want, but I thought I was okay because `B` was listed in `Am9`. And now I realize I probably should have said `Am9`... D'OH!
Comment: @TyCobb - Am9 is far more often played with the B note on the top of the chord - something like A-C-E-G-B, but of course it could be anywhere. It's your tune, after all !
Answer: Not entirely sure what question you're asking, but any octave for a bass note will work. When you're on, say, Am, then frequently the bassist will be playing any of the notes which constitute that chord :A,C and/or E. Certainly at the 1st and 3rd beats of a 4/4 bar - the strongest, usually. The last beat or half beat may stray so that it points to the first note of the next bar, and that particular note may or may not be in the chord, or even in the scale of the Am.For instance, going from Am to a bar of Dm, I may put an Eb as the last bit of the Am bar, going straight to the D root.
Slash chords, of which you're familiar, are the best way to show what to play, the bit after the slash being the bass part, but in my example, you probably wouldn't mark the last bit of the bar with another chord change, as in Am / / Am/Eb. It gets too messy.If the tab and dots are there, there's no need, anyway.
Comment: Thanks a lot for the description. I think I understand better now on what I should/can be doing in terms of following along. I think part of my problem is that I am just creating a bass part because that's all I have ever known, but never played with anyone and after many years of playing, never actually took the time to learn actual chords or theory. It was all jukebox style and random beats.
Comment: I guess what I trying to get at in my last comment is that I am attempting to build a bass line first as I learn and add other tracks on top of it afterwards.


Print five star ratings and reviews

Question: I am using Fivestar rating in custom print. See image:

I'm trying to print a fivestar as follows:
$your_average = $variables['result']['node']->field_rating['und'][0]['average'];
$your_maximum = "100";
print theme('fivestar_static', $your_average, $your_maximum);

But, I'm getting the following error:

Fatal error: Unsupported operand types in /var/www/html/book1/includes/theme.inc on line 1088

Any suggestions?
Answer: Looking at the definition of fivestar_static theme-function in fivestar.module file under fivestar_theme(), you need to provide the theme function with an array including the following keys: rating, stars, tag. A working example should look like:
$fivestar_variables = array('rating' => $your_average, 'stars' => $your_maximum);
print theme('fivestar_static', $fivestar_variables);

Answer: Try this:-
$your_maximum="100";
$your_average  = "21";
print render(theme('fivestar_static', $your_average, $your_maximum ));

Comment: I have tried this, but not working. I am getting the same error.

Print five star ratings and reviews


How to display a star rating widget in an ExtJS list itemTpl?

Question: I'm working on a Sencha Touch 2 application and using the star rating widget from http://podlipensky.com/post/2012/03/20/Sencha-Touch-2-ExtuxtouchRating.aspx
I would like to show the rating for each item within a list that is configured like this:
Ext.define('Schneehoehen.view.LoipenUebersicht', {
extend: 'Ext.navigation.View',
xtype: 'loipenuebersicht',

config: {
    items: [{
        xtype: 'list',
        title: 'Loipen Übersicht',
        itemTpl: '{label}', // I would like to show the widget next to the label
        onItemDisclosure: true,

        store: Ext.create('Schneehoehen.store.LoipenUebersichtStore')
    }]
}
})

Now I'm wondering how to include my star rating widget within the itemTpl.
The widget is displayed within a form of another view using the following code:
new Ext.ux.touch.Rating({
   itemsCount: 5,
   label: 'Image less',
   cls: 'x-imageless-rating',
   itemCls: 'x-imageless-star',
   itemHoverCls: 'x-imageless-hover'
})

Thanks in advance!
Johannes
Answer: What you need here is how to get XTypes or other components inside a list's itemTpl template. I don't know of a direct method but even if you do manage to write your own using the template methods its very tough to have them inside the list items. Besides why have so many components hog up dom.
If you can slightly modify your approach here, there is this beautiful plugin on swarm online that could probably help you with this issue. http://www.swarmonline.com/2011/03/ext-ux-touch-listoptions-demo/
This plugin adds twitter app style menu on swipe of a list row. You can add a star rating in this area. I remember I had used it in a POC and had added Sencha buttons to the menu that shows up.
I am not sure if they have updated their code to be compatible with Sencha Touch 2 but if you look at the source closely there's not much in there.
Answer: If you are keen to use sencha components there then the most simple way is to use component dataview. See http://www.sencha.com/blog/dive-into-dataview-with-sencha-touch-2-beta-2/ for more details.


Equivalence of $\operatorname{nullity}= 0$ and injectivity

Question: I am unsure on how to prove one way of the following equivalence:
If we have $T : U \to V$ where $\dim(U)=\dim(V)=n$, then

$\operatorname{nullity}(T)=0$
$T$ is injective

I know that 1. implies 2. as if $\ker(T)=\{0\}$ and we suppose there exists $T(u_1), T(u_2)$ s.t $T(u_1)=T(u_2)$, then by definition of linear maps we know that $T(u_1 - u_2)=0 \implies u_1 - u_2 \in \ker(T)$ which is equal to $0$, and so $u_1$ must be equal to $u_2$. So $T$ is injective.
I am having difficulty proving the other way though.
Any help or guidance is appreciated.
Answer: If we have linear $T\colon U\to V$ where $U$, $V$ are vector spaces (of arbitrary, possibly infinite, possibly different dimension), then
$$ \dim\ker T=0\iff T\text{ is injective}$$
You showed $\implies$. The other direction is even simpler: If $T$ is injective and $Tu=0$, then from $T0=0$ and injectivity $u=0$, so $\ker T=\{0\}$.


NeutralinoJS: error: missing required argument 'name'

Question: I tried to create my first NeutralinoJS app using neu-cli. I typed neu create --template hello-world command in Windows Command Prompt as in the doucmentation. But it gives me this error.

error: missing required argument 'name'

So I typed it again in git bash. But it gives the same error again. How to fix this ? Any idea ?
Answer: I found the solution. Command syntax is like this :
neu create <App_Name> --template <Template_Type>

Supported template types are :

js
ts
kotlin
react

Example :- neu create MyApp --template js


TableView swipe-to-delete doesn't work

Question: I have an editable, grouped tableView, but swipe to delete doesn't work. It looks like swipe-to-delete is supposed to come along with UITableViewCellEditingStyleDelete, but it doesn't seem to for me. This is my editing style method:
<code>- (UITableViewCellEditingStyle)tableView:(UITableView *)table editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1)
    {
        if (indexPath.row < [[device_coordinator getChannelList] count]) return UITableViewCellEditingStyleDelete;
        else if (indexPath.row < [[device_coordinator getChannelList] count]+2) return UITableViewCellEditingStyleInsert;
    }
    return UITableViewCellEditingStyleNone;
}
</code>
This makes the table look right. Some cells have insert icons to the left, some have delete icons, as they should. Pressing a delete icon makes the delete confirmation button appear. But a swipe doesn't!
Even if I just return blank, newly allocated cells from my cellForRowAtIndexPath method, it still doesn't work, so it appears that nothing in my cell is causing the problem. The same problem happens on the 4.3 simulator and on my iPod touch 2g.
Answer: I think your code is correct but if I understand you right there is a logical error. You want swipe to delete in editing mode which is not possible. Swipe to delete only works when the user is NOT in editing mode.
So you just need to hide/show the editing icons by calling this method.
<code> -(IBAction)edit:(id)sender//action connected to edit button
{
    if(yourTableView.editing) [yourTableView setEditing:NO animated:YES];
    else [yourTableView setEditing:YES animated:YES];
}
</code>
Then swipe to delete will work when there are no icons next to the cells. Hope this helps.
Comment: You're right! I was hoping to be able to do both at the same time. But at least I know the reason why it won't work now. I thought my app was haunted.

TableView swipe-to-delete doesn't work


Probability question for economics

Question: There are 4 districts in the land of Oz. At home, the inhabitants of
each region wear ties of a special colour, Munchkins (M) wear blue, Scarecrows
(S) wear purple, Tin Men (T) wear red and Wizards (W) wear yellow. When visiting the Emerald city however, some inhabitants wear green ties, 25% of Munchkins, 35% of Scarecrows, 45% of Tin Men and 55% of Wizards. As a visitor approaches, the gatekeeper of the Emerald city who knows the tourism rate for the last few years assigns the probabilities as follows:
$P(M)=1/3, P(S)=1/4; P(T)=1/6; P(W)=1/4$

What is the probability that the visitor will wear a green tie?
Given that a visitor is wearing a green tie, calculate the
probability that the visitor is a Munchkin.
Comment: Hi and welcome to the site! Since this is a site that encourages and helps with learning, it is best if you show your own ideas and efforts in solving the question. Can you edit your question to add your thoughts and ideas about it?
Comment: The thing is I don't even know where to start. So if any does know how to solve it, could you explain it to me please, thank you
Answer: i) Let G denote green ties. So $$P(G) =  P(M \cap G) + P(S\cap G) + P(T\cap G) + P(W\cap G) \\ = (1/3) (.25) + (1/4) (.35) + (1/6)(.45)+ (1/4)(.55) \\= 23/60 $$.
ii) This is an application of Bayes' Theorem. $$P(M|G) = \dfrac{P(M\cap G)}{P(G)} = \dfrac{(1/3)(.25)}{(23/60) } = 5/23. $$
Comment: ANumosh thank you so much, I really appreciate your help

Probability question for economics


Batch File and Wait - MAXL

Question: Have this batch that isn't running the MAXL until the end of the batch for some reason. I'm trying to have a log file output for the start of the procedure, run the MAXL, and then tell me when the file is finished.
REM Variables 1-9 assigned SET $1=variable1
CALL    :SUB_A
CALL    :SUB_B
CALL    :SUB_C

GOTO    :EOF

:SUB_A
    ECHO STARTING Rebuild_TEST - Started at %time% on %date% > D:\Logs\Rebuild_TEST_Start.log
EXIT /B
:SUB_C
    ECHO ENDING Rebuild_TEST - Started at %time% on %date% > D:\Logs\Rebuild_TEST_END.log
EXIT /B

:SUB_B
    ECHO STARTING REBUILD
    START "REBUILD" /W /B D:\Oracle\Middleware\user_projects\epmsystem1\EssbaseServer\essbaseserver1\bin\startMaxl.bat Rebuild_TEST.msh %$1% %$2% %$3% %$4% %$5% %$6% %$7% %$8% %$9%
    ECHO ENDING REBUILD
EXIT /B

:EOF

What I'm seeing is the script goes through Subs A-C and then executes the MAXL. I was expecting Sub A to execute, Sub B to execute - Kicking off MAXL, then run SUB_C.
What am I doing wrong?
I included /W to wait, /B to run the file in the current window so I don't have to intervene
If I run it with START "REBUILD" /W CMD /c maybe that'll work better?
Comment: use keyword `call` for the call to "startMaxl.bat", not `start`.  If you want to set the title bar to "REBUILD" while it is running, use the `title` command.. then set it back to whatever you like (usually either %COMSPEC% or "Command Prompt").
Comment: If I use `call` the startMAXL.bat won't run. The variable $9 has a % symbol which gets dropped if I use call @Señor CMasMas.
Comment: I can't believe that i missed that!  Scroll bar is your friend I guess.  $x is linux/bash syntax.  cmd.exe doesn't understand it.  For cmd.exe, your params are referenced with a single "%"..  Like this %1 %2 %3, not %$1%..
Answer: Figured this one out. There were two issues, 1) MAXL.bat terminates the current process when the batch finishes - This requires a new terminal window to open 2) My password had a reserved character that drove me crazy. Echoing it helps but sometimes you'll need to encase the variable in "" when passed to maxl
StartMAXL.bat is used for Oracle Essbase data loads/rebuilds/etc. The .bat is usually 7 folders down.
To run MAXL, you list the full path to StartMAXL.bat and then pass a list of commands in a .msh file followed by the variables/parameters.
Save this as Essbase_Rebuild.cmd file
This is the basic MAXL Cmd line call
SET $1=[Essbase Username]
SET $2=[Essbase Password]
SET $3=localhost REM /*This is performed on the essbase server*/
SET $4=[Target Application Name]
SET $5=[Target App Cube Name]
SET $6=[source app]
SET $7=[source cube]
SET $8=[SQL Username]
SET "$9=[SQL password]" REM if you have special characters they might error in MAXL

D:\Oracle\Middleware\user_projects\epmsystem1\EssbaseServer\essbaseserver1\bin\startMaxl.bat Essbase_Code_File.msh %$1% %$2% %$3% %$4% %$5% %$6% %$7% %$8% %$9%

Now for your Essbase_Code_File.msh file/or list of Essbase things you're doing
login $1 identified by $2 on $3;
spool on to 'D:\\Logs\\Essbase_Code_File.log';
/* do your MAXL commands */
spool off;
logout;
exit;

The above method works for simple methods - Sometimes you might need to encase the %9% variables in "%9%" for MAXL to interpret the variable properly. Echo your variable in the .msh to view it in the command prompt by adding shell echo "$1"; to your .msh before login.
The more elegant version that took 3 months to figure out
Name it Essbase_Code_File.cmd
REM Parameters
SET $1=[Essbase Username]
-- repeat for your variables

CALL :SUB_A
CALL :SUB_B
CALL :SUB_C

GOTO :EOF

:SUB_A
ECHO Starting the Rebuild - Started @ %time% on %date% >D:\Logs\Rebuild_Start.log
EXIT /B

:SUB_B
ECHO STARTING REBUILD
START "ESSBASE_EXAMPLE" /W CMD /C D:\Oracle\Middleware\user_projects\epmsystem1\EssbaseServer\essbaseserver1\bin\startMaxl.bat Essbase_Code_File.msh %$1% %$2% %$3% %$4% %$5% %$6% %$7% %$8% %$9%
EXIT /B

:SUB_C
ECHO Ending the Rebuild - Ending @ %time% on %date% >D:\Logs\Rebuild_End.log
EXIT /B

:EOF

I like this method because the command prompt doesn't get renamed - There's logging for start/end time, the rebuild occurs in a new window and then closes when finished,

Batch File and Wait - MAXL


Fix for fatal error C1083

Question: We have a set of nightly builds that build of full suite of software using Embedded Visual C++ batch files.  There is probably a total of 30 builds that are done.  Every night at least one or two builds fail with something like the following error:

c:\lc\trunk\server\can\svcangettracedrivelength.cpp(11) : fatal error C1083: Cannot open precompiled header file: 'SH4Rel/CANWce.pch': Permission denied

It is never the same file or precompile header that fails and it is rarely the same executable.  As far as I know nothing else is happening on this build machine.
Does anyone have a fix to make our nightly builds run more reliably?
Answer: Try running it all in the visual IDE; it will be easier to catch this way.
You sure you don't have multiple compiler instances working on several builds at once? One building a project/lib/whatever while another trying to access it?
Answer: Does EVC 4.0 support macros? Maybe as a last resort you can have a macro that triggers the builds:)
I don't understand your last statement. Clearly the trouble is at compile time, not at run time.
Have you tried compiling without precompiled headers? What's the error then?
Answer: Encountered apparently same issue - was seemingly caused by Microsoft Security Essentials.  I tried disabling it, and it immediately fixed the issue and it has not returned since.
Answer: Generally speaking we do not see this error when running inside of the IDE (EVC++ 4.0).  We cannot run our nightly builds using the GUI, however.
As far as we know the build machine is idle while the nightly builds are running.

Fix for fatal error C1083


Socket não manda mensagem para os clientes corretos

Question: Quando for digitado /msg nome mensagem deveria mandar essa mensagem para o nome, porem ele manda para quem digitou
Gerenciador.java
private Socket cliente;
public static String nomeCliente;
private static BufferedReader leitor;
private static PrintWriter escritor;
private static final HashMap<String, Gerenciador> clientes = new HashMap<String, Gerenciador>();

public Gerenciador(Socket cliente)
{
    this.cliente = cliente;
    start();
}

public void run()
{
    try
    {
        leitor = new BufferedReader(new InputStreamReader(cliente.getInputStream()));
        escritor = new PrintWriter(cliente.getOutputStream(), true);
        escritor.println("Qual seu nome ??");
        String mensagem = leitor.readLine();
        nomeCliente = mensagem;
        clientes.put(this.nomeCliente, this);

        clientes.get(nomeCliente).getEscritor().println("Bem vindo ao ChatP2P " + nomeCliente);
        while(true)
        {
            mensagem = leitor.readLine();
            mensagem.replaceAll("\\s+"," ");

            if(mensagem.startsWith("/"))
            {
                String[] args = getComandos(mensagem.replace("/", ""));

                if(args.length == 3)
                {
                    String arg1 = args[0];
                    String arg2 = args[1];
                    String arg3 = args[2];

                    if(arg1.equalsIgnoreCase("msg"))
                    {
                        if(clientes.get(arg2) != null)
                        {
                            clientes.get(arg2).getEscritor().println(nomeCliente + ": " + arg3);

                            /*chatAtual.put(arg2, clientes.get(nomeCliente));
                            chatAtual.put(nomeCliente, clientes.get(arg2));
                            clientes.get(nomeCliente).getEscritor().println("Você iniciou um CHAT com " + arg2);
                            clientes.get(arg2).getEscritor().println(nomeCliente + " iniciou um CHAT com você");*/
                        }
                        else
                        {
                            clientes.get(nomeCliente).getEscritor().println(arg2 + " não existe");
                        }
                    }
                }
            }
        }
    }
    catch(IOException e)
    {
        System.err.println("O cliente fechou a conexão terminada");
        e.printStackTrace();
    }
}
private static String[] getComandos(String mensagem)
{
    mensagem.replace("/", "");
    return mensagem.split(" ");
}

public PrintWriter getEscritor()
{
    return escritor;
}
public String getNomeCliente() {
    return nomeCliente;
}
public BufferedReader getLeitor()
{
    return leitor;
}

Servidor.java
    public static void main(String[] args)
{
    ServerSocket servidor = null;

    try
    {
        servidor = new ServerSocket(9999);
        System.out.println("Servidor iniciou");

        while(true)
        {
            Socket cliente = servidor.accept();
            System.out.println("Um novo CLIENTE se conectou ao servidor");
            new Gerenciador(cliente);
        }
    }
    catch (IOException e)
    {
        System.err.println("A porta não esta disponivel");
        try
        {
            if(servidor != null)
            {
                servidor.close();
            }
        }
        catch (IOException e1)
        {
            e1.printStackTrace();
        }
        e.printStackTrace();
    }
}

Cliente.java
    public static void main(String[] args)
{
    try
    {
        @SuppressWarnings("resource")
        final Socket cliente = new Socket("127.0.0.1", 9999);

        new Thread()
        {
            public void run()
            {
                try
                {
                    BufferedReader leitor = new BufferedReader(new InputStreamReader(cliente.getInputStream()));

                    while(true)
                    {
                        String mensagem = leitor.readLine();
                        System.out.println(mensagem);
                    }
                }
                catch (IOException e)
                {
                    System.err.println("Impossivel ler a mensagem do servidor");
                    e.printStackTrace();
                    System.exit(0);
                }
            }
        }.start();

        PrintWriter escritor = new PrintWriter(cliente.getOutputStream(), true);
        BufferedReader leitorTerminal = new BufferedReader(new InputStreamReader(System.in));
        String mensagemTerminal = "";
        while((mensagemTerminal = leitorTerminal.readLine()) != null)
        {
            escritor.println(mensagemTerminal);

            if(mensagemTerminal.equalsIgnoreCase("/sair"))
            {

                System.exit(0);
            }
        }
    }
    catch (UnknownHostException e)
    {
        System.err.println("O endereço é invalido");
        e.printStackTrace();
    }
    catch (IOException e)
    {
        System.err.println("O servidor esta fora do ar");
        e.printStackTrace();
    }
}

Comment: Como usar a aplicação. Iniciei o servidor e 2 clientes, mas não aconteceu nada.
Comment: você já tentou usar o pacote **nio** para trabalhar com socket?
Answer: Depurei o código e percebi que na classe Gerenciador tem alguns atributos estáticos.
public static String nomeCliente;
private static BufferedReader leitor;
private static PrintWriter escritor;

Nenhum desse deve ser estático, pois sempre será substituído pelo último a se registrar no servidor.
Comment: Tirar o `static` resolveu meu problema, obrigado.


Probability of no two objects having same number

Question: Say I have collection of distinct objects and I assign a number to each object from the range 1 to $n^3$ (inclusive).
Here's what I have done:
\begin{array}{l}
\text { Choices }=k=n^{3}\\
\text { objects }=n\\
P(\text { No collisicn })=\frac{k}{k}+\frac{k-1}{k}+\frac{k-2}{k} \cdots \cdots \cdot \frac{k-n+2}{k}+\frac{k-n+1}{k} \\
=\frac{k !}{k^n(k-n) !}=\frac{n^{3 !}}{n^{3n}\left(n^{3}-n\right)}
\end{array}
How do I proceed after this ?
Comment: Look up the birthday paradox.
Comment: Perhaps, with respect to the article that I cited re mathSE protocols, you may consider editing your question to show your work, on both of these problems.  This way, if you make an analytical mistake, a mathSE reviewer may correct your mistake without violating mathSE protocol.  Further, explanations or ambiguity resolutions belong in the (edited) question rather than the comments.
Comment: Clarification requested: are the numbers assigned with or without replacement?  In other words, in the 1st assignment, can you have two objects both assigned the number $(n^3)$?
Comment: While I don't agree with the downvote that your question has attracted, I can at least explain it.  See [this article](https://math.meta.stackexchange.com/questions/33190/how-to-avoid-downvotes-for-beginners-questions/33236#33236) for an explanation.
Comment: @user2661923 objects can get two same numbers so this implies that it is with replacement. if it was without replacement then the porb that two objects gets same number would zero
Comment: Good catch, which I overlooked.  However, I am confused.  What is the relevance of the first assignment of numbers (from $1$ to $n^3$)?  Isn't the question asking the student to ignore the 1st number assigned, and simply consider whether the 2nd number assigned (from $1$ to $n^2$) is distinct for all distinct objects?  If so, do you perceive any difference between this problem and the birthday problem?
Comment: Also, I am assuming that the number of distinct objects is some fixed positive integer $m$, so that the final computation of the probability must be a function of both $m$ and $n$.
Comment: @user2661923. let me phrase it better. the first problem and the second is completely different. In the first case, the number of choices available are n^3. you solve probability first for this case. second problem is the same but the choices has been reduced to n^2. in both case the number of objects (distinct) are n
Comment: @user2661923 I realise you can get the equation for probability using the birthday paradox framework
Comment: @user2661923 Fair enough. will make the changes. Thanks
Comment: @user2661923 I simplified the question and updated my working
Answer:
\begin{array}{l}
\text { Choices }=k=n^{3}\\
\text { objects }=n\\
P(\text { No collisicn })=\frac{k}{k}+\frac{k-1}{k}+\frac{k-2}{k} \cdots \cdots \cdot \frac{k-n+2}{k}+\frac{k-n+1}{k} \\
=\frac{k !}{k^n(k-n) !}=\frac{n^{3 !}}{n^{3n}\left(n^{3}-n\right)}
\end{array}

How do I proceed after this ?

Should be
$$P(\text{no collision}) = \frac{k}{k} \times \frac{k-1}{k} \times \frac{k-2}{k} \times \cdots \times \frac{k-n+2}{k} \times \frac{k-n+1}{k}
$$
$$=\frac{k !}{k^n[(k-n)!]}=\frac{[n^{3}]!}{n^{3n}[\left(n^{3}-n\right)!]}
.\tag1$$
At this point, it depends on your goal.  If all you want is a closed form expression, (1) above fulfills this, so you are done.  If instead, you want to facilitate calculating this numerically, for a specific value of $n$, either through a calculator or a pc program, then you have two choices:

If the numbers aren't too bad, you can calculate the exact value in a pc program, perhaps using a big integer facility, as is provided by Java.

If a numeric estimate, accurate to 4 or 5 decimal places is sufficient, I strongly recommend using logarithms (i.e. the logarithm of a product equals the sum of the individual logarithms).  PC languages (e.g. Java, C, python, ...) should have canned logarithm routines.

Addendum
Given $m$ objects and $k$ numbers to select from (i.e. choices) without replacement ($m < k$), the standard expression for the probability of no collision is
$$\frac{k !}{k^m[(k-m)!]}.$$
In the standard birthday problem, $k = 365$,
so $\displaystyle p(m) = \frac{365 !}{365^{m}[(365 - m)!]}.$
Then, the classic problem is to compute the minimum value of $m$ such that $p(m) < (1/2).$  As discussed in the answer, this may routinely be computed via logarithms.


Check if a given time-stamp lies between two time-stamp in android

Question: I want to check if a given time-stamp lies between two time-stamp

Below is my code:
<code>public static boolean isTimeBetweenTwoTime(String initialTime, String finalTime, String currentTime) throws ParseException {
        String reg = "^([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$";
        if (initialTime.matches(reg) && finalTime.matches(reg) && currentTime.matches(reg)) {
            boolean valid = false;

            //Start Time
            java.util.Date inTime = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(initialTime);
            Calendar calendar1 = Calendar.getInstance();
            calendar1.setTime(inTime);

            //Current Time
            java.util.Date checkTime = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(currentTime);
            Calendar calendar3 = Calendar.getInstance();
            calendar3.setTime(checkTime);

            //End Time
            java.util.Date finTime = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(finalTime);
            Calendar calendar2 = Calendar.getInstance();
            calendar2.setTime(finTime);

            if (finalTime.compareTo(initialTime) < 0) {
                calendar2.add(Calendar.DATE, 1);
                calendar3.add(Calendar.DATE, 1);
            }

            java.util.Date actualTime = calendar3.getTime();
            if ((actualTime.after(calendar1.getTime()) || actualTime.compareTo(calendar1.getTime()) == 0)&& actualTime.before(calendar2.getTime())) {
                valid = true;
            }
            return valid;
        } else {
            throw new IllegalArgumentException("Not a valid time, expecting MM/dd/yyyy HH:mm:ss format");
        }

}
</code>
But Its not working for me, Please Help
Comment: There's much easier ways to do this if you would just convert to Unix timestamps...
Comment: @maňish Who says I voted?
Answer: Solved it by myself with this simple logic:
<code>    long mills = System.currentTimeMillis();
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
    Date resultdate = new Date(mills);
    String currentTime = sdf.format(resultdate);
    System.out.println(sdf.format(resultdate));

    try{
        java.util.Date inTime1 = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(initialTime);
        java.util.Date inTime2 = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(finalTime);
        java.util.Date inTime3 = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(currentTime);

        if (inTime3.getTime() > inTime1.getTime() && inTime3.getTime() < inTime2.getTime()){
            Log.e("TimeDifference","inTime3 is between inTime1 and inTime2");
            return true;
        }else{
            Log.e("TimeDifference","in Else Condition");
            return false;
        }

    }catch (Exception e){
        e.printStackTrace();
        return false;
    }
</code>


Does the payoff matrix have 1 or 4 Nash Equilibria?

Question: I'm confused. Does every grid in the following payoff matrix constitute a Nash Equilibrium? ie. Are there 4 Nash Equilibria in this game?
\begin{array}{c|c|c|}
  & {1} & {2} \\
  \hline
  1 & (10,10) & (-1,10) \\
  2 & (10,-1) & (-1,-1) \\
\end{array}
Answer: Let's begin with the definition of Nash equilibrium. A Nash equilibrium is a set of strategies for each player such that each player's strategy is a best response to the other players' strategies. This includes mixed strategies, where we assign a probability distribution over the options.
Let's say Player 1 (the row player) has a strategy to randomize between picking Option 1 with probability $p_{1 1}$ and Option 2 with probability $1 - p_{1 1}$. Similarly, let's say Player 2 (the column player) has a strategy to pick Option 1 with probability $p_{2 1}$ and Option 2 with probability $1 - p_{2 1}$.
Note that the payoff for Player 1 is $10 p_{2 1} + (-1)  (1 - p_{2 1}) = 11 p_{2 1} - 1$. This is notably not a function of $p_{1 1}$, which is to say, all strategies are best responses for Player 1. If you perform the same analysis for Player 2's payoff, which is $11 p_{1 1} - 1 \ne f (p_{2 1})$, you will find that all strategies are best responses for Player 2 as well.
You are correct that all four pure strategy sets $\{(1, 1), (1, 2), (2, 1), (2, 2)\}$ are Nash equilibria for this game. But there are an infinite number of mixed equilibria as well, as we have demonstrated.
Comment: Exactly. Neither player's actions affects her own payoff.
Comment: As you suggested, the "payoff for Player 1 is not a function of p11, so all strategies are best responses for Player 1". Can I interpret this as Player 1's payoff is independent of Player 1's own actions, and the same applies to Player 2. As a result, since neither player's actions can affect their own payoff, every strategy combination (infinitely many) in this mixed game is a mixed Nash Equilibrium?


Agregar valores no R

Question: Ao tentar agregar valores por pessoa, recebo o erro abaixo dizendo que a função sumnão funciona para fatores, no entanto, meu vetor é numérico e mesmo usando uma função para garantir isso, continuo a receber o erro!
url <- "https://raw.githack.com/fsbmat/StackOverflow/master/DiariasT.csv"
Diaria2 <- data.table::fread(url, dec = ",",colClasses = c("factor", "factor",  "numeric","numeric", "numeric"))
Diaria2$VALOR_DIA <- as.numeric(as.character(Diaria2$VALOR_DIA))
agg = aggregate(Diaria2,
                  by = list(Diaria2$VALOR_DIA),
                  FUN = sum)

Error in Summary.factor(18L, na.rm = FALSE) :
  'sum' not meaningful for factors

Comment: Quer agregar por `NOME_ORG_SOL`, por `NOME` ou por ambos?
Comment: Quero agregar por NOME.
Answer: O código da pergunta tem a variável a agregar, VALOR_DIA,  onde deveria estar a variável de agregação. E falta a variável de agregação, que não pode ser a base inteira, um objeto de classe "data.frame".
Uma maneira de agregar.
Esta maneira usa uma formula para agregar o lado esquerdo pelas variáveis do lado direito (só uma).
agg <- aggregate(VALOR_DIA ~ NOME, data = Diaria2, FUN = sum)

Outra maneira.
Esta maneira é a maneira usada na pergunta mas de forma correta.
agg2 <- aggregate(Diaria2$VALOR_DIA,
                 by = list(Diaria2$NOME),
                 FUN = sum)

Comparando os resultados vê-se que a única diferença é nos nomes das colunas dos dois resultados, os valores das somas são iguais.
Pesoalmente, prefiro o interface de fórmula por ser intuitivo e também por produzir resultados com nomes iguais aos das variáveis usadas.
all.equal(agg, agg2)
#[1] "Names: 2 string mismatches"
names(agg)
#[1] "NOME"      "VALOR_DIA"
names(agg2)
#[1] "Group.1" "x"

Comment: Muito obrigado! Tentei de várias formas e não percebi o erro simples que estava cometendo!

Agregar valores no R


Exporting from cinema-4d to unity5

Question: I am having a huge challenge in converting a particular model from c4d to unity. I do not have cinema 4d r11 or r18 and I have tried all other alternatives possible but no luck. I would appreciate if someone who has cinema 4d r16 or r18 to assist me in exporting the model to unity from c4d.
Comment: I haven't used C4D not Unity in a long time, but I remember years ago it was a matter of simply dragging the .c4d file straight into the unity project
Answer: if you have animated model(from maximo) when you export it as FBX from cinema 4d it changes all the ":" in the name to "_"! "myrig:Bone" became "myrig_Bone". Unity will fail to match it to mode!

Import the T-Pose model from Mixamo as "FBX for Unity"
Import it in Cinema4D and export it as FBX again to change all the bone names with a "_"

For .c4d files just drag and drop it to unity asset folder(project).

Exporting from cinema-4d to unity5


Does this measure make sense?

Question:
It says 2/4 but the sum of the notes is 5/8. Why is that?
Comment: Is this the very start of the piece? Because if so, Brian's answer may be incorrect.
Comment: No. This is in the middle.
Answer: The first half of the bar is a free run, and these are often written with a series of notes (slightly smaller than standard), which do not add up to the "correct" value; just play them rapidly, to fit in with the tempo of the piece. In principle there could be a "12-tuplet" marking, but there often isn't.
Comment: But as Killian points out, there's no reason *not* to mark it as a 12, to make it clear that it's not a grace-note run.
Comment: If you are teaching music writing it might be appropriate to insist on having tuplet numbers, but if you are asking about reading music that is already written, complaining about it is not very productive. I don't know who wrote this, but I immediately found an exactly comparable bar in Chopin (Nocturne op 32-1 3 lines from end), so I think it is rather useful to be able to read this.
Answer: This bar has mutiple problems. It's true that tuplet groups are counted differently from normal notes - but you're not supposed to omit the count indicator on them unless you have a long string of them and write, e.g. "simile" (similarly). And tuplets should still be printed in normal type.
Notes in small type like this are grace notes, and they're not supposed to be counted against the bar length at all, but without them you have only one quarter note, not two. So no matter whether these are grace notes or tuplets, this bar is printed in a confusing way that breaks the rules of proper notation.
Comment: Tell that to Chopin, Scriabin, and doubtless countless others....

Does this measure make sense?


Gestures in Android

Question: There are more than 30 pictures in my android app.. I'm planning to show one image at a time when the user swipes left or right.
What is the best way to do this? Can you please point some working examples?
Answer: Try using Gallery . Here is the link - http://developer.android.com/reference/android/widget/Gallery.html
And
http://www.mobisoftinfotech.com/blog/android/android-gallery-widget-example-and-tutorial/
Comment: @ Naveen : Yes . I am sorry i missed out on the deprecation part. You  can probably try using an Horizontal scroll view -http://developer.android.com/reference/android/widget/HorizontalScrollView.html
Answer: <code>    see this ...
    http://developer.android.com/reference/android/view/GestureDetector.html
You can use Gesture Detector class so detect left,rigth,up down swipes
</code>

Gestures in Android


Let ∼ be an equivalence relation on a set $A$, and let $a, b ∈ A$. Prove that $a ∈ [b]$ iff $b ∈ [a]$.

Question: I have the following proof outline, but I am not sure how to get started proving this. Can anyone point me in the right directon?
Proof.
Suppose that $\sim$ is an equivalence relation on a set $A$, and that $a,b \in A$.
[$\Rightarrow$] Suppose $a ∈ [b]$.
Then $a\sim b$.
Since $\sim$ is symmetric, $b\sim a$.
Therefore $b \in [a]$.
[$\Leftarrow$] On the other hand, suppose $b ∈ [a]$.
Then $b\sim a$.
Since $\sim$ is symmetric, then $a\sim b$.
Therefore $a \in [b]$.
Comment: But... Doesn't it follow immediately from the definition $x\in[y]\iff x\sim y$ ?
Comment: Look at the definition of equivalence class to see exactly what it takes for an element of $A$ to qualify for membership in the class.  Then write down what it means for $a$ to fit this qualification criterion and be in the equivalence class of $b$.  Do the same the other way:  write down exactly what it takes for $b$ to qualify for membership in the equivalence class of $a$.  Then see if you can see why both of the statements you wrote down are equivalent.
Comment: [b] is the set of all elements in A that are related to be related to b. So if a is an element of this set, a is related to b. Since ~ is reflexive, b is related to a. [a] is the set of all elements in in A that are related to a. Since we just found b is related to a reflexively, therefore b ∈ [a]?

Is that correct?
Comment: @dewick49 No not because $\sim$ is "reflexive"; because $\sim$ is **symmetric**. You said it correctly in your proof/question, but not in your comment above. ¶ By the way, all you need to prove is $\Rightarrow$, since obviously $a,b$ are arbitrary and $\Rightarrow$ implies $\Leftarrow$ and thus $\iff$.
Comment: @BrianO Of course, my mistake. That makes perfect sense! Thanks for clarification!
Answer: Is it not as simple as
$$x\in[y]\iff x\sim y\iff y\sim x\iff y\in[x]$$
?
It'd help if we knew precisely what definition you are using for $x\in[y]$. There are a lot of equivalent ways to phrase it but you need to use the definition you were provided with for the proof
Comment: The proof is NOT correct because reflexivity is not the right property to use here.
Comment: The title question being asked is the only information I was given to solve this problem. I have updated my original question with my current proof - is it correct?
Comment: @dewick49 yes that proof is correct.
Comment: and on a side note, is my explanation in the above comments also a correct way of analyzing the problem, or am I misunderstanding the definition of an equivalence class?
Comment: @dewick49 note it's the exact same as my proof except I used a biconditional at every step instead of doing both directions.
Comment: @dewick49 yes that is correct as well. Note again that your explanation is the exact same as your proof, except you're using the phrase "$a$ is related to $b$" in place of the symbol $a\sim b$ every time. No difference.
Comment: @FriedrichPhilipp why is that?
Comment: Well, I thought my comment was clear. Reflexivity means that for each $x$ we have $x\sim x$. But here we have $x$ and $y$, where possibly $x\neq y$.
Comment: @FriedrichPhilipp oh my bad, I didn't even notice he had mixed up the names. Yeah it should be symmetric instead


How do I run perfmon against a remote machine?

Question: For starters I'm trying to do this from a Windows 7 box to a Windows 7 box.
I know the simple answer should be to enter \\computername where it says "Select Counters From Computer". Trouble is, every time I do that I get an error message that says "Unable to connect to machine"
I know the machine is out there and accessible, because I can bring up windows explorer and enter \\computername\c$ in the explorer bar and then can browse their c drive. So the machine is out there.
Are there special permissions for perfmon? Is here a service which needs to be running on the remote machine?
Answer: You need RPC between the machines. The endpoint mapper is TCP 135, which then negotiates high-numbered ephemeral ports on which to send subsequent traffic.
Check your firewalls, both hardware and Windows Firewall.
<code>\\computername\c$</code> works because it does not require RPC, only TCP 445. (AKA Direct-hosted SMB.) And since you can access an admin share, it's safe to assume that you already have administrative permissions on the target machine.
Also I suppose you need to check the RPC and RPC Endpoint Mapper services on the machines, but I assumed those services are running since you'd be having bigger problems if they weren't.
Comment: PortQRY UI is a good way to test RPC connectivity if needed.

http://www.microsoft.com/en-us/download/details.aspx?id=24009
Answer: Not if you can get to C$ - this is a admin only share.  I notice you only put one slash at the beginning of your NetBIOS name.  Have you tried \\computername\c$, or even just computername.domain.com (or whatever your domain is)?  The later will remove any name/address issues.
Comment: Sorry about that, that was a mistake on my part. Corrected.


Can least squares be used to fit curves?

Question: Can the method of least squares be used to fit growth curves like modified exponential or Gompertz curves?
Comment: OLS can be used to fit anything. The answer depends on what you are going to do with the results.
Comment: Yes, it can but not recommended.
Answer: I assume by modified exponential curve you mean something that could be written in the form $\lambda + A\exp(\beta x)$ (sometimes called a Makeham curve when looking at mortality, where it may refer to the hazard function)
Such nonlinear functions (specifically, nonlinear in parameters) can be fitted via nonlinear least squares, yes. (But see the caveat at the end)
Whether that's the right thing to do depends on your model for the observations; if you expect there to be constant-variance additive independent errors then nonlinear least squares makes sense.
(Gompertz curves are a special case of the above. If the standard deviation of the noise is approximately proportional to the mean, it would make some sense to take logs and use least squares on that scale.)
But such curves may also be fitted using other means than least squares (especially when related to mortality; then the response would involve counts or scaled counts or logs of scaled counts and specific distributional models for the counts may be used -- see the discussion in the latter part of this answer for example).
Here's a plot of some example data:

Here's the command to fit a nonlinear least squares model of the above form in R:
<code> makehamfit = nls(y ~ lambda + a * exp(b*x),start=list(lambda=1,a=.1,b=.5))
</code>
(other packages have similar commands)
Here's the estimates:
<code>Nonlinear regression model
  model: y ~ lambda + a * exp(b * x)
   data: parent.frame()
lambda      a      b
5.0169 0.0139 0.1599
 residual sum-of-squares: 0.1917

Number of iterations to convergence: 39
Achieved convergence tolerance: 1.836e-06
</code>
Here's what the fitted model looks like:

However, while your title only mentions "curves", you mention growth curves in the body of your post; if by "growth curve" you mean to refer to longitudinal data -- taking successive observations on single individuals over time -- then just fitting by least squares will not usually be suitable (because of the dependence between successive observations that this kind of data will lead to - your size now is definitely not independent of your size last time). In that situation, see the discussion of generalized logistic growth toward the end of the Wikipedia article on latent growth modelling.


How to Install SQL Server 2008 R2 Configuration Manager

Question: I'm trying to install SQL Server 2008 R2 Express with SP2 from a command line.
Everything works fine, but the Configuration Manager is not being installed.
The file I'm using is SQLEXPRWT_x64_ENU.exe
the command line is
sqlexprwt_x64_ENU /q /hideconsole /action=Install /features=SQL
      /instancename=SQLEXPRESS /enableranu=1
      /sqlsvcaccount=NT Authority\System /AddCurrentUserAsSqlAdmin
      /skiprules=RebootRequiredCheck /IAcceptSQLServerLicenseTerms
      /securitymode=SQL /sapwd=XXXXXXX /tcpenabled=1
      /sqlsvcstartuptype=Automatic /browsersvcstartuptype=Automatic

I've also tried /features=SQL,TOOLS without success.
A manual install installs Config Manager and SSMS etc etc. so it can be done; but not from a command line apparently.
What am I doing wrong?
EDIT to expand on dvdd's answer: the SSMS parameter to Features was the missing ingredient. Given its name, I had assumed (yes, I know) that it installed SSMS; but in fact it has the effect of installing Config Manager even when not installing using the 'wt' version of the exe.
Answer: My production deployments include the install parameter /features=SQLENGINE,SSMS to accomplish this task.
Comment: To clarify, you're saying this installs Configuration Manager, not just SSMS?
Comment: Yes sir. After including this parameter, I have the following available in the start menu: SQL Server Management Studio and SQL Server Configuration Manager.

I should clarify that my installation command is `"full\path\sqlexprwt_x64_enu.exe" /Q /IACCEPTSQLSERVERLICENSETERMS /CONFIGURATIONFILE=FULL\PATH\AnswerFile.ini`.
AnswerFile.ini contains the line `/features=SQLENGINE,SSMS`. I run this command on Windows Server 2008 R2 machines. Check here for more information on answer file contents: [link](http://msdn.microsoft.com/en-us/library/ms144259(v=sql.105).aspx).


Plots of residuals in linear regression

Question: I wanted to know the intuition behind the plots of residuals vs time, residuals vs fitted values and residuals vs explanatory variables.
Could anyone intuitively explain to me what they are supposed to indicate in case they are not random (which I am told, is the way we want these plots to be)
Also, are there any other residual plots used in the diagnostics of linear regression that I am missing here?
Answer: So, which ways can we helpfully plot residuals in linear regression? There are many, so let us go through them.

QQplots of residuals, that is, quantile-quantile plots. This is usually used to compare the distribution of residuals to the normal distribution, although it could be used also to compare to some other theoretical distribution.  There are many answered Qs on this site, some: How to interpret this QQ plot? How to interpret qq plot "not on the line"? How to interpret a QQ plot    One can also make confidence bands on the QQ plot, see Confidence bands for QQ line
One assumption in linear regression is homoskedasticity, that is, constant variance.  That can be checked graphically by plotting residuals against fitted values. Examples and discussion in What does having "constant variance" in a linear regression model mean?    (the plot residuals versus fitted could also show some kinds of unmodeled nonlinearity)
Some standard plots produced (in R) by plot(some.lm.object) is discussed in  Interpreting plot.lm()
It can be useful to plot residuals against individual predictors.  Let us look at some examples.  I will use the minitab tree data contained in R:
data(trees)
colnames(trees)
[1] "Girth"  "Height" "Volume"

We will build a linear model for Volume with predictors Girth and Height.  We know that doesn't make sense, as volume should be the product and not the sum! That way, the example is good to see if we can detect this model error from residual plots.
mod1  <-  lm(Volume ~ Girth + Height, data=trees)

The plot of residuals versus Girth:

We added a horizontal reference line at zero.  If the model is adequate, the residuals should spread randomly around this line.  Here we can clearly see a "U" form, indicating unmodeled nonlinearity, that is, the effect of Girth on Volume is not linear as modeled. The similar plot for Height is less clear (not shown).
Now, if we use some knowledge of the geometry of trees, and model a tree as a cylinder or a cone, the formula for colume will have the form
$$
  \text{Volume} = C\cdot \text{Girth}\cdot \text{Height}
$$
(where the constant $C$ will have different values for "cylinder", "cone" or
"truncated cone"). Taking logarithms we get
$$
\log(\text{Volume}) = \log(C) + \log(\text{Girth}) +  \log(\text{Height})
$$
which can be estimated as linear model:
mod2  <-  lm( log(Volume) ~ log(Girth) + log(Height),  data=trees)
> summary(mod2)

Call:
lm(formula = log(Volume) ~ log(Girth) + log(Height), data = trees)

Residuals:
      Min        1Q    Median        3Q       Max
-0.168561 -0.048488  0.002431  0.063637  0.129223

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) -6.63162    0.79979  -8.292 5.06e-09 ***
log(Girth)   1.98265    0.07501  26.432  < 2e-16 ***
log(Height)  1.11712    0.20444   5.464 7.81e-06 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.08139 on 28 degrees of freedom
Multiple R-squared:  0.9777,    Adjusted R-squared:  0.9761
F-statistic: 613.2 on 2 and 28 DF,  p-value: < 2.2e-16

and note that now actually the coefficient estimates makes geometrical sense!  Is the residual plot any better?

Plots of residuals in linear regression


I need to remove the highlight off of the radtreeview in WPF

Question: Here is my code. I just need to take the highlight off of the radtreeview. I would just use IsHitTestVisible like I did in the others, but then it does not allow me to click on triggers to extend the nodes.
Any help would be appreciated.
<code> <telerik:RadTreeView x:Name="radTreeView" Margin="8" ItemsSource="{Binding Errors}" Background="Salmon" IsHitTestVisible="True" IsDropPreviewLineEnabled="False" IsDragTooltipEnabled="False" Focusable="False">
            <telerik:RadTreeView.ItemTemplate>
                 <HierarchicalDataTemplate ItemsSource="{Binding SubItems}" >
                    <Grid Background="Salmon">
                        <Grid.RowDefinitions>
                            <RowDefinition/>
                            <RowDefinition/>

                        </Grid.RowDefinitions>
                        <TextBlock Text="{Binding Description}" IsHitTestVisible="False" />

                        <ListBox Grid.Row="1" ItemsSource="{Binding Messages}" Margin="20,0,0,0" BorderBrush="#00000000" BorderThickness="0" Background="Salmon" IsHitTestVisible="False" >
                            <ListBox.ItemTemplate>
                                <DataTemplate>
                                    <TextBlock Text="{Binding Message}"/>
                                </DataTemplate>
                            </ListBox.ItemTemplate>
                        </ListBox>
                    </Grid>

                </HierarchicalDataTemplate>

            </telerik:RadTreeView.ItemTemplate>
        </telerik:RadTreeView>
</code>
Answer: Approach it from a different angle. You should try changing the following on the TreeViewItem:

SystemColors.HighlightBrushKey
SystemColors.HighlightTextBrushKey

Example:
<code><Style TargetType="TreeViewItem">
      <Style.Resources>
          <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="#FFF"/>
          <SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="#000"/>
     </Style.Resources>
</Style>
</code>
This will also work on Rad controls. You just need to adjust for a RadTreeViewItem.
Comment: Where exactly should I put this in my code?? When I added it the Exception "Items Collection must be empty before using ItemsSource."
Comment: I think I have implemented it correctly, but it still did not take the highlight off
Comment: Did you make sure to change the TargetType?


Loops com base em um fluxograma

Question: Como faço para escrever o código para um loop com base nesse fluxograma? Tem um do...while. Peeciso de uma resposta simples e direta com nested loops.
Comment: Java ou Processing ? A sua dúvida é em relação ao fluxograma ou ao `do...while` ? Independentemente disso aconselho a rever toda a matéria dada pelo professor
Comment: Processing ou java. O importante é eu entender como interpretar o fluxograma. Na matéria não ficou claro. Queria chegar nos 5 loops, mas não estou conseguindo sair nem do primeiro.
Comment: Isso eu faria com um loop infinito e um `break` em `B`
Comment: @JeffersonQuesado pode me dar um exemplo?
Comment: Estou providenciando na resposta ;-)
Comment: São 5 possíveis formar de escrever esse loop. Essa seria uma? `int i=0;
do {
  println("A");
} while (i<5);

while(i<5){
  println ("C");
}`
Comment: @Jsi83 A resposta dada responde, sim, a sua pergunta. Se não entendeu alguma coisa, sinta-se livre para questionar o autor nos comentários. A edição recente que você fez na pergunta altera, mesmo que levemente, o sentido da pergunta. Você inicialmente pediu exemplos de laços de repetição que seguem o fluxograma - cinco, para ser exato. O Jefferson mostrou muito mais que isso. Se realmente a resposta não é a desejada, você precisa rever seu texto, pois o que você pediu ele respondeu.
Comment: Eu mudei a pergunta, pois a resposta não usa do...while, e isso faz com que "A" não seja executado nenhuma vez se a condição é falsa . Assim, não corresponde ao fluxograma.
Answer: Esse fluxo, me diz o seguinte:

Execute tarefa A
Faça a comparação B; se der verdadeiro, saia do laço
Execute a tarefa C
Volte para o passo 1

Note que o fluxo no passo 4 é um desvio incondicional retornando para o passo 1. Esse desvio acaba por criar um laço infinito (enquanto B não for satisfeito). De modo geral, eu faria assim:
while (true) {
  // passo 1
  // passo 2
  // passo 3
}

O passo 4 está representado pelo controle de fluxo fornecido pelo while. Preenchendo algumas lacunas a mais, obtemos:
while (true) {
  A();
  // passo 2
  C();
}

Assumindo que A() e C() são os métodos chamados nos passos 1 e 3. Pode ser qualquer coisa, mas representei por métodos.
Sobre o passo 2, ele envolve uma condicional em B. Não tem caso senão. Então, de modo geral:
while (true) {
  A();
  if (B()) {
    // ação caso B seja verdadeiro
  }
  C();
}

A ação para sair do laço é com o break. Então:
while (true) {
  A();
  if (B()) {
    break;
  }
  C();
}

Usando a linguagem dot para descrever seu diagrama, obtive o seguinte:

Estou só republicando-a aqui pois vou usar essa linguagem para fazer algumas manipulações na estrutura do laço e gerar outras equivalentes, então a ideia é diminuir o estranhamento.

A estrutura do laço é equivalente à expressão:
AB(CAB)*

Por que falo isso? Simples, porque inicialmente A e B são executados e, dependendo desse resultado, executo C, depois A (voltando no laço) e então B novamente, para tomar a decisão para onde partir.
A seguinte descrição é a tradução da expressão. Note que esse passo-a-passo é equivalente ao primeiro.

Execute tarefa A
Enquanto não B, faça:

Execute C
Execute A

Comparando com o esquema anterior, não precisei mais de um passo de desvio incondicional, usei um "enquanto". Copiei o comando que estava anterior à condicional para o final do laço, de modo que seja executado na hora certa a mesma quantidade de vezes.
O fluxograma agora é desenhado assim:

Em código, o enquanto vira um while. O resto se mantém:
A();
while (!B()) { // perceba que eu só repito enquanto `B()` for falso, já que `B()` é a condição de saída
  C();
  A();
}

Ainda usando o fluxograma 2, podemos fazer usando o for. Não gosto dessa alternativa, mas ela funciona.
A();
for (; !B(); A()) {
  C();
}

Alterando um pouco o for, obtemos o seguinte:
A();
for (; !B(); C(), A());

Podemos fazer o for como laço infinito também:
for (;;C()) {
  A();
  if (B()) {
    break;
  }
}

Se fizer muita insistência em fazer a verificação depois das operações, essa operação precisa ficar necessariamente depois de todas as operações. Para isso, podemos definir que o rodável inicial seja apenas A, atribuir para o rodável a executação de C e em seguida A e, então, fazer a verificação condicional:
Runnable rodavel = () -> { A(); };
do {
  rodavel.run();
  rodavel = () -> { C(); A(); };
} while (!B());

Podemos também controlar de outra maneira o jeito como se roda a operação C. Podemos controlar através de uma flag mnemonicamente denominada deveExecutarC, que começa como falsa mas, no final do laço, é atribuído o valor verdadeiro nela:
boolean deveExecutarC = false;
do {
  if (deveExecutarC) {
    C();
  }
  A();
  deveExecutarC = true;
} while (!B());

Podemos tentar atribuir diversas vezes o valor da flag ao colocar essa atribuição dentro do bloco else:
boolean deveExecutarC = false;
do {
  if (deveExecutarC) {
    C();
  } else {
    deveExecutarC = true;
  }
  A();
} while (!B());

Esse problema poderia ser resolvido recursivamente também:
private void executaRecursivo() {
  C();
  A();
  if (!B()) {
    executaRecursivo();
  }
}

private void fluxograma() {
  A();
  if (!B()) {
    executaResursivo();
  }
}

Basta chamar o método fluxograma e você obterá a mesma execução.

Podemos pôr a recursão de modo distinto, passando um parâmetro para ela. A ideia é a mesmo do do-while com a flag deveExecutarC:
private void fluxograma(boolean deveExecutarC) {
  if (deveExecutarC) {
    C();
  }
  A();
  if (!B()) {
    fluxograma(true);
  }
}

private void fluxograma() {
  fluxograma(false);
}

Para obter o resultado desejado, basta chamar fluxograma(), sem argumentos.

Mais variação com recursão:
private void recursao() {
  if (!B()) {
    C();
    A();
    recursao();
  }
}

private void fluxograma() {
  A();
  recursao();
}

Como de costume, basta chamar fluxograma().

Uma variação mais amigável da recursão anterior:
private void recursao() {
  if (B()) {
    return;
  }
  C();
  A();
  recursao();
}

private void fluxograma() {
  A();
  recursao();
}

Como de costume, basta chamar fluxograma().

Outra variação:
private void fluxograma() {
  A();
  if (B()) {
    return;
  }
  C();
  fluxograma();
}

Como de costume, basta chamar fluxograma().

Mais uma recursão, inspirada nesta resposta, desdobramento Recursão indireta da função, ponteiro de função:
private void fluxograma() {
  A();
  Runnable funcaoSaida = B()? () -> {}: () -> { C(); fluxograma(); };
  funcaoSaida.run();
}

Como de costume, basta chamar fluxograma().

Se não desejar a variável:
private void fluxograma() {
  A();
  (B()? (Runnable) () -> {}: (Runnable) () -> { C(); fluxograma(); }).run();
}

Como de costume, basta chamar fluxograma().
Comment: Entendi o que tu fez e acho que é a melehor solução. Mas, e os outros 4 loops? Tenho que usar um loop dentro de outro?
Comment: Estou trabalhando para mostrar como manipular a ordem das operações, de modo a obter fluxos equivalentes e, portanto, um outro modo de ordenar. Só por curiosidade, de onde tirou esse número 5?
Comment: O número 5 é qualquer número. Estou tentando gerar o mesmo resultado para esses loops. Poderia ser qualquer número. Somente criei uma condição.
Comment: Então não são "5 formas possíveis de escrever". Você está a descrever um laço que se repita 5 vezes
Comment: Não, o 5 era um teste e poderia ser qualquer coisa. Fiz um código sem sentido. São 5 diferentes respostas para o fluxograma. Um loop é com break (resposta 1), o outro acredito que seja loops alinhados (resposta 2), o outro um loop fora do outro (resposta 3), mas e os outros 2?
Comment: Vendo as respostas [dessa questão](https://pt.stackoverflow.com/q/241665/64969) eu consegui contar pelo menos 7 maneiras para o seu caso
Comment: Tu poderias me ajudar a escrever o loop sem o break? no fluxograma tem um do...while com certeza, pois A vem antes da condicão. Até aí tudo bem, mas como dou continuidade ao loop com o C? é metade e metade: A precisa ser executado ando da condicão e C, não.
Comment: 15 alternativas: 2 com `while`, 3 com `for`, 3 com `do-while`, e o restante com recursões esotéricas. Cansei de variar, poderia ir longe ainda. Bons estudos
Comment: A resposta dada parece muito complexa. Eu só preciso de um do..while que represente o fluxograma.
Comment: Eu te dei 3 opções com `do-while` de maneira que você pode se servir delas a vontade. Inclusive mostrei fluxos de equivalência e também o comportamento regular esperado desse esquema algorítmico.
Comment: Eu estou começando a entender loops. Ficou ainda mais complicado. "A' deve ser executado pelo menos uma vez. Se uso while sem o do, isso não ocorre.
Comment: Eu dei duas opções com `while` que trivialmente você verifica que `A()` é executado sempre
Comment: O que não ficou claro: o losango é uma condição representada no fluxograma, ele é  um IF ou um WHILE no código?
Comment: @Jsi83 `while`, `if` e `for` tem condicionais dentro deles. Esse losango e esses quadrados tem uma visão mais parecida com montagem do que com estruturada ou orientada a objetos. Entenda que isso é uma máquina de estados, em que, dado um estado, é necessário ir para outro. Não tente pegar um dicionário e traduzir literalmente isso que está escrito. Para traduzir literalmente, você necessitaria de `goto`, mas Java não tem isso
Comment: `do{ A if (true) break; C } while(true);` Esse codigo faz sentido pra ti?
Comment: Não tem `B`, portanto não atende à pergunta. Sem falar que do jeito que está escrito, a versão correta é a mesma coisa da primeira opção que eu fiz, com `while`
Comment: `do {
  A();
  if (B()) {
    break;
  }
  C();
}while (true)` Posso inverter o while e usar do?
Comment: Note que isso é idêntico à primeira forma que eu escrevi.
Comment: Então agora acho entendi. Essa é uma forma de escrever o loop. Agora falta eu entender as outras 4 formas.
Comment: Eu lhe fornece 15

Loops com base em um fluxograma


Analyzing Ryuichi Sakamoto's "Ballet Mécanique" 3

Question:

(listen from 2:31)
I don't get how from the [D] part's last bar BbM7 (IV)
you could go to the [E] part (Ab/C).
And if you see the [E] part, you could see that I analyzed it as a modulation to Ab Major key.
Because if you see the [F] part, you could see that the chords and the melodies are the same as the [E] part.
So my interpretation is, from the [D] part ( F Major key ), It suddenly modulated to Ab Major key.
But How?..
How did he just went from the [D] part's BbM7 (IV) and just suddenly modulate to the Ab key ?
Comment: This is your third or fourth post regarding the same collection of pieces.  Please try to ask one question, learn from it, and apply that knowledge to subsequent analyses
Comment: @CarlWitthoft But I thought you have to write about one question at a time. Thats why I divided all the question from the same piece..and they're all different type of harmonic movement so how am i supposed to learn from just one question?
Comment: @HyunYooPark I think maybe Carl is right on this one. Usually pieces that need multiple clarifications get combined into one question.
Comment: But I got told that you should ask question individually on https://music.stackexchange.com/questions/66524/analyzing-hisaishi-joes-song-reprise
Answer: You may be interested in the concept of direct modulation. Also sometimes called "phrase modulation," it's a modulation that's created with no harmonies to connect the first key with the second. Instead, the music just abruptly switches and is magically in a new key without any harmonic transition.
It sounds to me like that's all that's happening here: we end a phrase and we suddenly move to A♭ major.
This is really common in popular music, where these phrase modulations often move up by half step.
Comment: But how do you see at as a "end a phrase" if it ends with BbM7 ( IVM7, SubDominant ) instead of a Tonic ?


using e.g. ssh over openvpn, is the traffic actually addressed to 22?

Question: Given that Client A and Client B are using OpenVPN and they are on the same virtual network.
A connects to B via e.g. SSH.
In front of B there is an external Firewall or whatever.
Is the traffic which is monitored by the firewall actually addressed to port 22 then?
So is it port 22 B should enable or is it more like the VPN port?
To take it short: am I right that all traffic from and to the VPN is "tunneled" via a single Port and therefore only this single ports needs to be open?
Answer: Your question is confusing to me.
VPN is VPN and Services running on a specific port is a service running on a specific port.
Now, if you target services are fronted by another firewall after the VPN endpoint, you also need to play with that firewall to allow traffic to the destination endpoint you want to get to.


Why are Class E IPs in use?

Question: According to all documentation, class E IPs - those in the range 240.0.0.0 to 255.255.255.255 - are for research purposes only and should never be assigned or used.  And yet, according to a review of access logs in a site I run, upwards of 70% of visits are coming from IPs in this "forbidden" range.  Some tools break when applied to IPs in this range, so I am a bit concerned.
I was able to send private messages to a few users.  Of those who responded, they disclaimed any knowledge of what could be going on.  Both American and European users were affected, and they claimed both hardwired connections and mobile connections.
So, this is a situation where the behavior defined in the formal document and the behavior exhibited in the real world differ.  What does it mean to be seeing a lot of traffic from these 'forbidden' IPs?
Comment: fit your question, so it can be answered. currently it's like you hang on documentation that is now 40 years old.
Comment: Where exactly are you seeing these addresses? Can it be that your local hosting company is doing something weird, because these addresses indeed aren't used on the internet.
Answer: To probably explain the down votes :
Class E IP  ranges do not exist any more.
Classfull network addressing is an obsolete network addressing architecture that was used in the Internet from 1981 until the introduction of Classless Inter-Domain Routing (CIDR) in 1993.
Those IP ranges are currently classified as Reserved for future use (formerly "Class E") : source https://www.iana.org/assignments/ipv4-address-space/ipv4-address-space.xhtml
No explanation as to why you see them in the wild.
Comment: Please reread the question.  Thank you.
Answer: They might be IPv6 users and I guess you are using Cloudflare proxy to serve your website. According to the Cloudflare documentation, Cloudflare uses Class E IP space to generate Pseudo IPv4 addresses when somebody access to the origin by using IPv6.
https://blog.cloudflare.com/eliminating-the-last-reasons-to-not-enable-ipv6/
Comment: Unfortunately, not using a proxy, but thank you for your insight.

Why are Class E IPs in use?


The operator != is undefined for the argument type(s)

Question: Estou tentando criar um método para salva usuários no banco de dados, fazendo a seguinte verificação caso o id do usuário passado seja diferente de null ele altera se não ele cadastra.
Código
    public void salvar(Usuario usuario){
    if(usuario.getIdUsuario() != null){ //erro aqui
        aleterar(usuario);
    }else {
        cadastrar(usuario);
    }
}

Erro

The operator != is undefined for the argument type(s) type int, null
Comment: The operator != is undefined for the argument type(s) type int, null
Answer: Tipos primitivos não podem assumir o valor null, só objetos
if(usuario.getIdUsuario() != 0){
    aleterar(usuario);
}else {
    cadastrar(usuario);
}

Comment: Tinha esquecido desse detalhe , obirgado.
Answer: Se precisa verificar se o objeto é nulo, verifique só ele, se precisa verificar o resultado, então a verificação deve ser outra, depende do retorno do método usado:
public void salvar(Usuario usuario) {
    if (usuario != null) alterar(usuario);
    else cadastrar(usuario);
}

Coloquei no GitHub para referência futura.
Comment: È isso mesmo, no caso vou cadastra o usuario no banco, caso ele seja nulo, eu cadastro se nao entende-se que o usuario quer aleterar.


Hilbert space and its dual

Question: I have an elliptic equation in the form $$-\Delta u + u =F(u).$$ For any $\phi \in C^{\infty}_{0}$ we rewrite the elliptic equation in weak form $$\int \limits_{\mathbb{R}^n}\left(-\Delta u + u\right)\phi dx=\int \limits_{\mathbb{R}^n} F \phi dx.$$ Then, thanks to the definitions of $L^{2}$ and $H^{1}$ norms we obtain $$\left\|u\right\|_{H^{1}}\left\|\phi\right\|_{L^{2}}\leq \left\|F\right\|_{L^{2}}\left\|\phi\right\|_{L^{2}} \\ \left\|u\right\|_{H^{1}}\leq \left\|F\right\|_{L^{2}}.$$
Here, I want to understand the relationship between $H^1$ and its dual space $H^*$. Is it possible to see $\left\|u\right\|_{H^{1}}\leq \left\|u\right\|_{H^{*}}$ and/or $\left\|F\right\|_{L^{2}}\leq \left\|u\right\|_{H^{*}}$?
P.S.:I saw a similiar question in: Hilbert dual space (inequality and reflexivity), but I couldn't understand well.
Comment: The dual of a Hilbert space may be isometrically identified with the initial Hilbert space via [Riesz representation](http://en.wikipedia.org/wiki/Riesz_representation_theorem).
Answer: The situation you have to keep in mind while approaching these problems is: let $V$ be a Banach space, countinuosly embedded in the Hilbert space $H$ ($V \hookrightarrow H$), then we have: $V \hookrightarrow H \cong H^* \hookrightarrow V^*$.
This is the prototype of your situation, in which $V = H^1$, $H = L^2$ and $V^* = H^{-1}$.

Hilbert space and its dual


Replicate data from Azure-Active-Directory to sql database

Question: maybe I can find the solution deep inside the developer documetation found here. But not on the surface, so I hope someone can ask the following question.
We do replicate data from on-premise active-directory to our database to store users, groups, units and configure features- and role-permissions to our applications. As we can't (at least not to start from scratch) authorize all features calling the azure-active-directory API I like to know if it is possible to replicate the needed objects from azure-ad like I can do from ad?
If yes, if someone has a link to any reference you will make my day while I continue seek for this information.
Thanks.
Answer: Yes, we are able to replicate the data from Azure AD through the Azure AD Graph REST. However the Azure AD is a different with Active Directory on-premise. For example, there is no organizational units.
You can check the exposed object in Azure Active Directory via the link below:
Entity and complex type reference | Graph API reference
And to get started with Azure AD Graph REST, you can refer Azure Active Directory Graph API. Also since Microsoft is working on Microsoft Graph, if there is no such object in the Azure AD Graph REST, you may also check the Microsoft Graph REST.
Comment: Thanks for the info. Now I know it works and schedule research.


Spring Boot (1.3.5) - Default Error View

Question: I'm using Spring Boot (v1.3.5.RELEASE). And in the docs, there's this short section regarding error-handling:

Spring Boot provides an /error mapping by default that handles all errors in a sensible way, and it is registered as a 'global' error page in the servlet container. For machine clients it will produce a JSON response with details of the error, the HTTP status and the exception message. For browser clients there is a 'whitelabel' error view that renders the same data in HTML format (to customize it just add a View that resolves to 'error').

So, to set my own custom page, I'd just need a view that resolves to error. I've added Freemarker to my classpath:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

And sure enough, making a file named error.ftl in src/main/resources/templates did the job of getting me my own custom page.
However, instead of having error.ftl in the resources/templates folder, I'd like to place it inside WEB-INF/templates.
So, I moved the file (now in WEB-INF/templates/error.ftl) and made the following spring configuration-related beans:
@Bean(name = "freeMarkerViewResolver")
public FreeMarkerViewResolver getFreeMarkerViewResolver() {
    FreeMarkerViewResolver freeMarkerViewResolver = new FreeMarkerViewResolver();
    freeMarkerViewResolver.setSuffix(".ftl");
    return freeMarkerViewResolver;
}

@Bean(name = "freemarkerConfigurer")
public FreeMarkerConfigurer getFreeMarkerConfigurer() {
    FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
    freeMarkerConfigurer.setTemplateLoaderPaths(
            "classpath:/templates/",
            "/WEB-INF/templates/");
    return freeMarkerConfigurer;
}

But now, I only get the whitelabel page instead of /WEB-INF/templates/error.ftl (when, let's say for example, I access an invalid path such as localhost:8080/invalid). Is there anything I missed?
I'm pretty sure BasicErrorController handles the job:
@RequestMapping(produces = "text/html")
public ModelAndView errorHtml(HttpServletRequest request,
        HttpServletResponse response) {
    response.setStatus(getStatus(request).value());
    Map<String, Object> model = getErrorAttributes(request,
            isIncludeStackTrace(request, MediaType.TEXT_HTML));
    return new ModelAndView("error", model);
}

And here are my logs:
2016-09-12 08:46:00.241 TRACE 5888 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : Bound request context to thread: org.apache.catalina.connector.RequestFacade@11e1fd30
2016-09-12 08:46:00.241 DEBUG 5888 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/invalid]
2016-09-12 08:46:00.242 TRACE 5888 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : Testing handler map [org.springframework.web.servlet.handler.SimpleUrlHandlerMapping@75739a6e] in DispatcherServlet with name 'dispatcherServlet'
2016-09-12 08:46:00.242 TRACE 5888 --- [nio-8080-exec-4] o.s.w.s.handler.SimpleUrlHandlerMapping  : No handler mapping found for [/invalid]
2016-09-12 08:46:00.242 TRACE 5888 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : Testing handler map [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping@67eec602] in DispatcherServlet with name 'dispatcherServlet'
2016-09-12 08:46:00.242 DEBUG 5888 --- [nio-8080-exec-4] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /invalid
2016-09-12 08:46:00.243 DEBUG 5888 --- [nio-8080-exec-4] s.w.s.m.m.a.RequestMappingHandlerMapping : Did not find handler method for [/invalid]
2016-09-12 08:46:00.244 TRACE 5888 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : Testing handler map [org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping@605d8da4] in DispatcherServlet with name 'dispatcherServlet'
2016-09-12 08:46:00.244 TRACE 5888 --- [nio-8080-exec-4] o.s.w.s.h.BeanNameUrlHandlerMapping      : No handler mapping found for [/invalid]
2016-09-12 08:46:00.244 TRACE 5888 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : Testing handler map [org.springframework.web.servlet.handler.SimpleUrlHandlerMapping@3fa90efa] in DispatcherServlet with name 'dispatcherServlet'
2016-09-12 08:46:00.244 DEBUG 5888 --- [nio-8080-exec-4] o.s.w.s.handler.SimpleUrlHandlerMapping  : Matching patterns for request [/invalid] are [/**]
2016-09-12 08:46:00.244 DEBUG 5888 --- [nio-8080-exec-4] o.s.w.s.handler.SimpleUrlHandlerMapping  : URI Template variables for request [/invalid] are {}
2016-09-12 08:46:00.244 DEBUG 5888 --- [nio-8080-exec-4] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapping [/invalid] to HandlerExecutionChain with handler [ResourceHttpRequestHandler [locations=[ServletContext resource [/], class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@16545fd3]]] and 1 interceptor
2016-09-12 08:46:00.244 TRACE 5888 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : Testing handler adapter [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter@5ef1fb8a]
2016-09-12 08:46:00.244 TRACE 5888 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : Testing handler adapter [org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter@781974d0]
2016-09-12 08:46:00.244 DEBUG 5888 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : Last-Modified value for [/invalid] is: -1
2016-09-12 08:46:00.244 TRACE 5888 --- [nio-8080-exec-4] o.s.w.s.r.ResourceHttpRequestHandler     : Applying "invalid path" checks to path: invalid
2016-09-12 08:46:00.244 TRACE 5888 --- [nio-8080-exec-4] o.s.w.s.resource.PathResourceResolver    : Resolving resource for request path "invalid"
2016-09-12 08:46:00.244 TRACE 5888 --- [nio-8080-exec-4] o.s.w.s.resource.PathResourceResolver    : Checking location: ServletContext resource [/]
2016-09-12 08:46:00.244 TRACE 5888 --- [nio-8080-exec-4] o.s.w.s.resource.PathResourceResolver    : No match for location: ServletContext resource [/]
2016-09-12 08:46:00.244 TRACE 5888 --- [nio-8080-exec-4] o.s.w.s.resource.PathResourceResolver    : Checking location: class path resource [META-INF/resources/]
2016-09-12 08:46:00.245 TRACE 5888 --- [nio-8080-exec-4] o.s.w.s.resource.PathResourceResolver    : No match for location: class path resource [META-INF/resources/]
2016-09-12 08:46:00.245 TRACE 5888 --- [nio-8080-exec-4] o.s.w.s.resource.PathResourceResolver    : Checking location: class path resource [resources/]
2016-09-12 08:46:00.245 TRACE 5888 --- [nio-8080-exec-4] o.s.w.s.resource.PathResourceResolver    : No match for location: class path resource [resources/]
2016-09-12 08:46:00.245 TRACE 5888 --- [nio-8080-exec-4] o.s.w.s.resource.PathResourceResolver    : Checking location: class path resource [static/]
2016-09-12 08:46:00.245 TRACE 5888 --- [nio-8080-exec-4] o.s.w.s.resource.PathResourceResolver    : No match for location: class path resource [static/]
2016-09-12 08:46:00.245 TRACE 5888 --- [nio-8080-exec-4] o.s.w.s.resource.PathResourceResolver    : Checking location: class path resource [public/]
2016-09-12 08:46:00.245 TRACE 5888 --- [nio-8080-exec-4] o.s.w.s.resource.PathResourceResolver    : No match for location: class path resource [public/]
2016-09-12 08:46:00.245 TRACE 5888 --- [nio-8080-exec-4] o.s.w.s.r.ResourceHttpRequestHandler     : No matching resource found - returning 404
2016-09-12 08:46:00.245 DEBUG 5888 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2016-09-12 08:46:00.246 TRACE 5888 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade@11e1fd30
2016-09-12 08:46:00.246 DEBUG 5888 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : Successfully completed request
2016-09-12 08:46:00.246 TRACE 5888 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : Bound request context to thread: org.apache.catalina.core.ApplicationHttpRequest@292356a6
2016-09-12 08:46:00.246 DEBUG 5888 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/error]
2016-09-12 08:46:00.246 TRACE 5888 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : Testing handler map [org.springframework.web.servlet.handler.SimpleUrlHandlerMapping@75739a6e] in DispatcherServlet with name 'dispatcherServlet'
2016-09-12 08:46:00.246 TRACE 5888 --- [nio-8080-exec-4] o.s.w.s.handler.SimpleUrlHandlerMapping  : No handler mapping found for [/error]
2016-09-12 08:46:00.246 TRACE 5888 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : Testing handler map [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping@67eec602] in DispatcherServlet with name 'dispatcherServlet'
2016-09-12 08:46:00.246 DEBUG 5888 --- [nio-8080-exec-4] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /error
2016-09-12 08:46:00.247 TRACE 5888 --- [nio-8080-exec-4] s.w.s.m.m.a.RequestMappingHandlerMapping : Found 2 matching mapping(s) for [/error] : [{[/error],produces=[text/html]}, {[/error]}]
2016-09-12 08:46:00.248 DEBUG 5888 --- [nio-8080-exec-4] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)]
2016-09-12 08:46:00.248 TRACE 5888 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : Testing handler adapter [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter@5ef1fb8a]
2016-09-12 08:46:00.248 DEBUG 5888 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : Last-Modified value for [/error] is: -1
2016-09-12 08:46:00.248 TRACE 5888 --- [nio-8080-exec-4] .w.s.m.m.a.ServletInvocableHandlerMethod : Invoking [BasicErrorController.errorHtml] method with arguments [org.apache.catalina.core.ApplicationHttpRequest@292356a6, org.apache.catalina.connector.ResponseFacade@4fa94295]
2016-09-12 08:46:00.248 TRACE 5888 --- [nio-8080-exec-4] .w.s.m.m.a.ServletInvocableHandlerMethod : Method [errorHtml] returned [ModelAndView: reference to view with name 'error'; model is {timestamp=Mon Sep 12 08:46:00 SGT 2016, status=404, error=Not Found, message=No message available, path=/invalid}]
2016-09-12 08:46:00.249 DEBUG 5888 --- [nio-8080-exec-4] o.s.w.s.v.ContentNegotiatingViewResolver : Requested media types are [text/html, text/html;q=0.8] based on Accept header types and producible media types [text/html])
2016-09-12 08:46:00.249 DEBUG 5888 --- [nio-8080-exec-4] o.s.w.s.v.ContentNegotiatingViewResolver : Returning [org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$SpelView@58edc30] based on requested media type 'text/html'
2016-09-12 08:46:00.249 DEBUG 5888 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : Rendering view [org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$SpelView@58edc30] in DispatcherServlet with name 'dispatcherServlet'
2016-09-12 08:46:00.249 TRACE 5888 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : Cleared thread-bound request context: org.apache.catalina.core.ApplicationHttpRequest@292356a6
2016-09-12 08:46:00.249 DEBUG 5888 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : Successfully completed request

Answer: Instead of redefining the freemarker beans (which may be the cause of your error), you could use spring-boot's property spring.freemarker.template-loader-path, as described here:

If you use FreeMarker you will also have a FreeMarkerViewResolver with
  id 'freeMarkerViewResolver'. It looks for resources in a loader path
  (externalized to spring.freemarker.templateLoaderPath, default
  'classpath:/templates/') by surrounding the view name with a prefix
  and suffix (externalized to spring.freemarker.prefix and
  spring.freemarker.suffix, with empty and '.ftl' defaults
  respectively). It can be overridden by providing a bean of the same
  name.

The default is this:
spring.freemarker.template-loader-path=classpath:/templates/ # Comma-separated list of template paths.

You could add this to your application.properties:
spring.freemarker.template-loader-path=classpath:/WEB-INF/templates/

Comment: Certainly another good way of configuring Freemarker in Spring, but my problem remains unsolved. Thank you for your input, though!
Comment: I just thought it could also solve the issue, just with the fact that you didn't redefine freemarker's bean (which could the source of the issue).
Comment: Ah. Yes, yes. I see your point; it's a valid suggestion. Thank you! (Also, there may be beginners out there, so, I'd like to point out that my folder is `src/main/webapp/WEB-INF/templates` so, in @Alex's suggestion, I'd use `spring.freemarker.template-loader-path=/WEB-INF/templates/`.


How can I get my applications to use the tap0 device, rather than eth0?

Question: I am using Ubuntu and I'm trying to establish a vpn-connection to an Endian server, which seems to be based on openvpn.
I have installed openvpn and connected to the server, using the following command:
sudo openvpn --client --pull --comp-lzo --nobind --dev tap0 --ca /home/tkn/efw.pem --auth-user-pass --remote vpn.domain.tld 1194

The above was suggested in the FAQ for Endian-vpn.
It appears to be working, since I get the following output:
Mon Aug 24 20:58:00 2009 OpenVPN 2.1_rc11 i486-pc-linux-gnu [SSL] [LZO2] [EPOLL] [PKCS11] built on Mar  9 2009
Enter Auth Username:tkn
Enter Auth Password:
Mon Aug 24 20:58:05 2009 WARNING: No server certificate verification method has been enabled.  See http://openvpn.net/howto.html#mitm for more info.
Mon Aug 24 20:58:05 2009 LZO compression initialized
Mon Aug 24 20:58:05 2009 UDPv4 link local: [undef]
Mon Aug 24 20:58:05 2009 UDPv4 link remote: 22.214.171.124:1194
Mon Aug 24 20:58:05 2009 WARNING: this configuration may cache passwords in memory -- use the auth-nocache option to prevent this
Mon Aug 24 20:58:05 2009 [127.0.0.1] Peer Connection Initiated with 220.127.116.11:1194
Mon Aug 24 20:58:06 2009 TUN/TAP device tap0 opened
Mon Aug 24 20:58:06 2009 /sbin/ifconfig tap0 192.168.10.153 netmask 255.255.255.0 mtu 1500 broadcast 192.168.10.255
Mon Aug 24 20:58:06 2009 Initialization Sequence Completed

However, if I open my browser and go to http://www.whatsmyip.org/, I get my own IP - not the remote network. Also, my network manager doesn't list the tap0 device. It's there if I select "edit connections", but I can't select it from the main dropdown.
What am I missing?
Answer: try putting line
redirect-gateway

in you OpenVPN config
Comment: +1, this will add the routing needed to have all traffic going through the vpn. The issue is routes (as stated by others) but openvpn can handle the route tables for you.  You need to make sure the vpn server and its external network are setup to allow the vpn traffic out to the Internet, the best way is to make the vpn server a NAT router for the VPN clients, iptables has a rule for it (its in the openvpn FAQ).
Comment: Thanks - This makes a difference. Unfortunately I can't access anything in my browser now, but from what I can deduce from the comments here, that is probably because the server end doesn't NAT for me?
Comment: OK. The problem appears to be that my dns-server isn't available from the remote net. I fixed this by changing to opendns' nameservers, since `--redirect-gateway bypass-dns` doesn't appear to work. I guess I could also add a route explicitly for those ips, but this is less manual work. Thanks again for pointing me in the right direction.
Answer: What you want to do is nothing to do with the VPN. What you need to do is set up routing so you go through the VPN.
Moreover, if you want to masquerade your source IP address as the host's, you'll need to set up nat router on the other end as well.
So basically what you'll need to do is:

Set up the client's routing table so that the default route goes through the VPN - but be sure that you still have a route for the specific VPN host that goes through the public network (sending VPN traffic through the VPN would not be cool)
Set up the router at the other end to do source nat for your client's IP address, with appropriate rules.

The router should then NAT the source address on all the outbound packets your client routes through it, replacing its own public IP (masquerading). Then on the inbound packets, it should do the reverse and the packets should come back via the VPN.
Answer: You're missing either a default route, or a route that encompasses everything you want to use over the VPN.


reusing logging config across python modules

Question: This snippet creates a logging filter that puts ERROR level and above into the console and DEBUG and above into the log file.  What I can't seem to figure out is how to  reuse that config across my various modules so that I'm writing to the same logfile, but the name  correctly indicates the module that generated the message.
Thanks in advance!
<code>import logging

default_formatter = logging.Formatter(
    "%(asctime)s:%(name)s:%(levelname)s:%(message)s")

console_handler = logging.StreamHandler()
console_handler.setLevel(logging.ERROR)
console_handler.setFormatter(default_formatter)

file_handler = logging.FileHandler("error.log", "a")
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(default_formatter)

noralog = logging.getLogger(__name__)
noralog.setLevel(logging.DEBUG)
noralog.addHandler(console_handler)
noralog.addHandler(file_handler)

noralog.debug('PUT ME ONLY IN THE FILE')
noralog.error('STREAM AND FILE')
</code>
Answer: This seems to work, but I'm not sure it's the best solution:
    #noralog.py
    def setup_logging(localname):
        import logging
<code>    default_formatter = logging.Formatter(
            "%(asctime)s:%(name)s:%(levelname)s:%(message)s")

    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.ERROR)
    console_handler.setFormatter(default_formatter)

    file_handler = logging.FileHandler("error.log", "a")
    file_handler.setLevel(logging.DEBUG)
    file_handler.setFormatter(default_formatter)

    noralog = logging.getLogger(localname)
    noralog.setLevel(logging.DEBUG)
    noralog.addHandler(console_handler)
    noralog.addHandler(file_handler)
    return noralog

#othermod.py
import noralog

ff = noralog.setup_logging(__name__)
ff.debug('PUT THIS ONLY IN FILE LOG')
ff.error('PUT THIS IN STREAM AND FILE LOG')
</code>