Como colocar .vbs dentro do .bat

Question: Estou montando um projeto e não consegui colocar o arquivo .vbs dentro do .bat.
cadastro.bat:
    @echo off
    :Menu
    cls
    echo.ÉÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ»
    echo.º                                                                             º
    echo.º                  ESCOLHA UMA DAS OP€åES ABAIXO E TECLE ENTER                º
    echo.º                                                                             º
    echo.ÌÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ͹
    echo.º                                                                             º
    echo.º                                                                             º
    echo.º  [1] ADICIONAR                                                              º
    echo.º                                                                             º
    echo.º  [2] BUSCAR                                                                 º
    echo.º                                                                             º
    echo.º                                                                             º
    echo.º                                                                             º
    echo.º                                                                             º
    echo.º                                                                             º
    echo.º                                                                             º
    echo.º                                                                             º
    echo.º                                                                             º
    echo.º                                                                             º
    echo.ÈÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍͼ
    echo.          PC NAME ( %USERNAME% ) DATA: %date%  HORA: %time:~0,5%
    echo. ÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ
    set /p opt1= Digite a op‡ao:
    if "%opt1%"=="" goto Error
    if %opt1%==1 goto:Adicionar else goto:Error
    if %opt1%==2 goto:BusCodigo else goto:Error
    :Error
    cls
    echo.
    echo.ÉÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ»
    echo.º                               º
    echo.º    Houve um erro.             º
    echo.º Foi digitado valor incorreto  º
    echo.º Digite o numero correto.      º
    echo.ÈÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍͼ
    rem pause>nul
    echo.
    echo.
    echo.
    echo.
    echo.
    echo.
    echo.
    echo.
    echo.
    echo.
    echo  VOLTANDO A TELA ANTERIOR...
    goto:Menu

    :Adicionar
    cls
    color 0b
    title SYSTEM - Adicionar Registro
    echo.ÉÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ»
    echo.º                                                      º                      º
    echo.º                    ADICIONAR REGISTRO                º [V] VOLTAR AO MENU   º
    echo.º                                                      º                      º
    echo.ÈÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍͼ
    rem ###Nesta linha Caso nao exista o arquivo para gravacao e leitura sera criado o arquivo com codigo zero "0" .###
    if NOT exist Cont echo 0 > Cont
    if NOT exist Cont2 echo 0 > Cont2

    set /p cod=< Cont
    set /a cod=%cod%+1

    set /p codg=< Cont2
    set /a codg=%codg%+1
    echo  %date%  %time:~0,5%
    echo  Codigo: %cod%
    echo.ÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ
    rem ###Obtendo dadas para a gravacao###.
    set codigo=%cod%
    set codig=%codg%
    echo.

    :Cad1
    set /p Nome= NOME :

    FOR /F "DELIMS=0123456789" %%§ IN ("%Nome%") DO (
    GOTO :Cad2
    )
    IF "%Nome%"=="" goto Campo1Branco
    if %Nome%==v CLS&goto Redireciona
    if %Nome%==V CLS&goto Redireciona
    GOTO :ERRO

    :Campo1Branco

    echo CAMPO EM BRANCO, DIGITE UM VALOR!

    goto Cad1

    :ERRO
    echo VOCE DIGITOU (%Nome%) DIGITE SOMENTE LETRAS
    echo.
    GOTO :Cad1

    :Cad2
    echo.
    set /p telf= TELEFONE :

    if %telf%==v CLS&goto Redireciona
    if %telf%==V CLS&goto Redireciona

    FOR /F "DELIMS=abcdefghijklmnopqrstuvxwyzABCDEFGHIJKLMNOPQRSTUVXWYZ" %%§ IN ("%telf%") DO (
    GOTO :Gravar
      )
    IF "%telf%"=="" goto Campo2Branco
    GOTO :ERRO2

    :Campo2Branco

    echo CAMPO EM BRANCO, DIGITE UM VALOR!

    goto Cad2

    :ERRO2
    rem CLS
    echo VOCE DIGITOU (%telf%) DIGITE SOMENTE NUMEROS
    echo.
    GOTO :Cad2

    rem ###Fim da obtencao dos dadas.###

    echo ------------------

    rem ###Gravando os dados###
    :Gravar
    echo. %codigo% > Cont
    echo. %codig% > Cont2
    echo %codigo%__Nome:............[ %Nome% ] >>Registros
    echo %codigo%__Telefone:........[ %telf% ] >>Registros
    echo %codigo%__Data:............[ %date% ] >>Registros
    echo %codigo%__Hora:............[ %time:~0,5% ] >>Registros
    echo.                                      >> Registros
    echo PC NAME( %USERNAME% ) Login:(%login%) Adicionou o Registro nº (%codigo%) data e hora:(%date% %time:~0,5%) >> Log_Adicionar_Registros.txt
    rem ###Fim da gravacao dos dados###

    echo REGISTRO ADICIONADO COM EXITO...
    ping localhost -n 2.8 >nul
    echo VOLTANDO AO MENU PRINCIPAL...
    ping localhost -n 2.8 >nul
    cls
    Goto Menu

    :BusCodigo
    cls
    echo.ÉÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ»
    echo.º                                                      º                      º
    echo.º                      BUSCAR CODIGO                   º     [V] VOLTAR       º
    echo.º                                                      º                      º
    echo.ÈÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍͼ
    set /P "codigoPesq=- DIGITE O CODIGO PARA PESQUISAR: "
    if %codigoPesq%==v CLS&goto Menu
    if %codigoPesq%==V CLS&goto Menu
    cls
    echo.ÉÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ»
    echo.º                                                      º                      º
    echo.º                      RESULTADOS BUSCAR CODIGO        º     [V] VOLTAR       º
    echo.º                                                      º                      º
    echo.ÈÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍͼ
    echo.
    if exist Registros find  /I "%codigoPesq%__" Registros
    echo.
    echo.
    set /p opcao3= DESEJA EXPORTAR ? (S-SIM / N-NAO):
    if %opcao3%== s goto:Export else goto :Error
    if %opcao3%== S goto:Export else goto :Error
    if %opcao3%== n goto:Buscar else goto :Error
    if %opcao3%== N goto:Buscar else goto :Error
    echo.

    :Export

      For /f "delims=" %%i in ('Cscript //nologo "script_.vbs" "Selecione uma pasta"') do Set "folder=%%i\%codigoPesq%__RELATORIO.txt"
 For /f "eol=- delims=" %%i in ('find /I "%codigoPesq%__" Registros') do >>"%folder%" Echo.%%i

    START %folder%
    ECHO.
    ECHO.
    ECHO.
    ECHO.
    ECHO                      VERIFIQUE O LOCAL [%folder%]
    ECHO.
    echo.
    echo                      ENTER PARA VOLTAR AO MENU PRINCIPAL
    pause>nul

    Goto :Menu

Este é o script_.vbs
Dim objFolder, objShell
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.BrowseForFolder(0, "Selecione uma pasta.", &H4000, 0)
If Not (objFolder Is Nothing) Then
   wscript.echo objFolder.Self.path
Else
   wscript.echo 0
End If

Answer: Você pode gerar o .vbs em tempo de execução do seu batch:
echo Dim objFolder^, objShell > script_.vbs
echo Set objShell ^= CreateObject^(^"Shell.Application^"^) >> script_.vbs
echo Set objFolder ^= objShell.BrowseForFolder^(0^, ^"Selecione uma pasta.^"^, ^&H4000, 0^) >> script_.vbs
echo If Not ^(objFolder Is Nothing^) Then >> script_.vbs
echo    wscript.echo objFolder.Self.path >> script_.vbs
echo Else >> script_.vbs
echo    wscript.echo 0 >> script_.vbs
echo End If >> script_.vbs

Repare que coloquei algums ^, pois existem alguns caracteres especiais, e precisamos escapar deles:
Comment: MUITO OBRIGADO AMIGO.
Answer:

Update (agora que me caiu a ficha!) Bat + VBS num só arquivo Bat!??

O que você busca é ter um Bat/VBS num só arquivo, ou seja, um script hibrido de Bat & VBS?

É possível usando tag de comentários na parte/execução do bat e vbs, fazendo o script bat tartar comentarios na execução bat, e chamar a si mesmo para ser executado no CScritpt.exe , onde, na parte VBS, o código em bat fica entre tags de comentários, na execução do VBS:

o escopo fica assim:
    *// fecha comentário bat/vbs
<job></job>*// fim do código em VBS

Exemplo já portando para o seu Bat c/ VBS dentro/junto num só, ficaria assim:

<job></job>

Ter o bat e o vbs rodando no mesmo arquivo?

Observações para quando o bat for gerar o VBS:

Nos caracteres  especiais que serão ecoados e estão dentro de aspas, você  não precisa usar escapes, igualmente nas aspas, nas virgulas e no sinal de igual, estes caracteres não irão precisar de escapes, use o echo direto.

Abaixo um forma mais "compacta".

@echo off & >"%temp%\script_.vbs"^
    (echo/Dim objFolder, objShell & echo/ Set objShell = CreateObject^("Shell.Application"^)
     echo/ Set objFolder = objShell.BrowseForFolder^(0, "Selecione uma pasta.", ^&H4000, 0^)
     echo/ If Not ^(objFolder Is Nothing^) Then & echo/ wscript.echo objFolder.Self.path
     echo/Else & echo/ wscript.echo 0 & echo/End If)

Abaixo uma forma "expandida".

@echo off & >"%temp%\script_.vbs"^
    (
     echo/ Dim objFolder, objShell
     echo/ Set objShell = CreateObject^("Shell.Application"^)
     echo/ Set objFolder = objShell.BrowseForFolder^(0, "Selecione uma pasta.", ^&H4000, 0^)
     echo/ If Not ^(objFolder Is Nothing^) Then
     echo/  wscript.echo objFolder.Self.path
     echo/ Else
     echo/  wscript.echo 0
     echo/ End If
    )

Como colocar .vbs dentro do .bat


Dirac Delta function and normal distribution

Question: I understand the Dirac Delta is the limit of a normal distribution when the variance of the normal distribution tends to 0:
$$
\delta(x) = \lim_{v\to 0}\frac{e^{-x^2/2v}}{\sqrt{2\pi v}}
$$
Then what is the limit
$$
\lim_{v\to 0} \frac{e^{-x^2/2v}}{\sqrt{2\pi v^n}}
$$
for some integer $n$? Can we expand the normal density function, or an integral with the normal integrator, into perhaps a power series of the variance v, which is assumed to be small?
By the way, I typed the first limit into Mathematica9, but didn't really get the Dirac Delta.
Answer: The statement $$\delta(x) = \lim_{v\to 0}\frac{e^{-x^2/2v}}{\sqrt{2\pi v}}$$ means that for every $C^\infty$ smooth function $\varphi$ with compact support we have
$$\varphi(0) = \lim_{v\to 0} \int_{-\infty}^\infty \frac{e^{-x^2/2v}}{\sqrt{2\pi v}} \varphi(x)\,dx \tag{1}$$
(I would not expect computer algebra systems to correctly handle various modes of function convergence, especially convergence in the sense of distributions.)
Let's replace $v$ by $v^n$ under the square root in (1); I will consider real $n$, not just integers. The resulting limit can be written as
$$ \lim_{v\to 0} v^{(1-n)/2} \int_{-\infty}^\infty \frac{e^{-x^2/2v}}{\sqrt{2\pi v}} \varphi(x)\,dx \tag{2}$$
where the integral converges to $\varphi(0)$, as previously professed. There are two cases:

$n<1$. Then the limit is zero. So, the functions $\lim_{v\to 0} \frac{e^{-x^2/2v}}{\sqrt{2\pi v^n}}$ converge to zero in the sense of distributions.
$n>1$. The limit does not exist, which means $\lim_{v\to 0} \frac{e^{-x^2/2v}}{\sqrt{2\pi v^n}}$ does not exist, even in the sense of distributions.


Use Angular-CLI or still use webpack for newer Angular 4 projects

Question: We have reached mid 2017 and frontend space has gone through a lot of upgrades and the most recent one being webpack adoption by Angular-cli. I am about to work on a new Angular 4 project. Before I start, I want to have an opinion from the community on which between the two (Webpack or Angular-CLI) should I adopt for my project and why?.

Have Angular-cli reached to a stage where it can be put into use for big projects or is yet evolving?
If I opt to go for Angular-Cli, is there anything that could pull me off later (limitations/features)?
Is Angular-cli docs proper and useful?
Comment: Well I have news for you. Angular-CLI runs Webpack to build and bundle all JavaScript and CSS code and comes with Webpack dev-server.
Comment: in addition to this question, I want to know whether we can use both together?
Comment: Be advised though that you cannot override the `webpack.config.js` in an Angular-CLI project. See this topic on github;
https://github.com/angular/angular-cli/issues/1656 .
Answer: Update
My original answer is below but outdated. Angular CLI now supports webpack.config via ng eject.

https://github.com/angular/angular-cli/wiki/eject

Original

Angular CLI uses Webpack to build / bundle project code.
Angular CLI does not currently support webpack.config (and it doesn't look like they plan to anytime soon), which could be a problem for your project down the line.
I don't see why you couldn't start with Angular CLI and then transition the project away from it over time. Angular CLI certainly makes scaffolding a project easier.


Dependency and duplicates error, during installation of HHVM on Redhat

Question: I installed HHVM on Redhat-6.6 (Santiago) using yum install hhvm, But it returns Following errors
Error: Package: gcc-java-4.4.7-17.el6.x86_64 (rhel-6-server-rpms)
 Requires: gcc = 4.4.7-17.el6
             Removing: gcc-4.4.7-11.el6.x86_64 (@rhel-x86_64-server-6)
                            gcc = 4.4.4-15.el6
                            gcc = 4.4.7-11.el6
                        Updated By: gcc-4.8.2-8.el6.x86_64 (hop5)
                            gcc = 4.8.2-8.el6
                        Available: gcc-4.4.4-13.el6.x86_64 (rhel-6-server-rpms)
                            gcc = 4.4.4-13.el6
                        Available: gcc-4.4.5-6.el6.x86_64 (rhel-6-server-rpms)
                            gcc = 4.4.5-6.el6
                            gcc = 4.4.4-15.el6
                        Available: gcc-4.4.6-3.el6.x86_64 (rhel-6-server-rpms)
                            gcc = 4.4.6-3.el6
                            gcc = 4.4.4-15.el6
                        Available: gcc-4.4.6-4.el6.x86_64 (rhel-6-server-rpms)
                            gcc = 4.4.6-4.el6
                            gcc = 4.4.4-15.el6
                        Available: gcc-4.4.7-3.el6.x86_64 (rhel-6-server-rpms)
                            gcc = 4.4.7-3.el6
                            gcc = 4.4.4-15.el6
                        Available: gcc-4.4.7-4.el6.x86_64 (rhel-6-server-rpms)
                            gcc = 4.4.7-4.el6
                            gcc = 4.4.4-15.el6
                        Available: gcc-4.4.7-4.1.el6_5.x86_64 (rhel-6-server-rpms)
                            gcc = 4.4.7-4.1.el6_5
                            gcc = 4.4.4-15.el6_5
                        Available: gcc-4.4.7-16.el6.x86_64 (rhel-6-server-rpms)
                            gcc = 4.4.7-16.el6
                            gcc = 4.4.4-15.el6
                        Available: gcc-4.4.7-17.el6.x86_64 (rhel-6-server-rpms)
                            gcc = 4.4.7-17.el6
                            gcc = 4.4.4-15.el6
                        Available: gcc-4.6.3-2.el6.x86_64 (hop5)
                            gcc = 4.6.3-2.el6
                        Available: gcc-4.8.2-7.el6.x86_64 (hop5)
                            gcc = 4.8.2-7.el6  You could try using --skip-broken to work around the problem
             ** Found 8 pre-existing rpmdb problem(s), 'yum check' output follows: 12:dhcp-common-4.1.1-51.P1.el6.x86_64 is a duplicate with
             12:dhcp-common-4.1.1-43.P1.el6_6.1.x86_64
             glibc-common-2.12-1.192.el6.x86_64 is a duplicate with
             glibc-common-2.12-1.149.el6_6.5.x86_64
             glibc-common-2.12-1.192.el6.x86_64 has missing requires of glibc =
             ('0', '2.12', '1.192.el6') kernel-headers-2.6.32-642.3.1.el6.x86_64 is
             a duplicate with kernel-headers-2.6.32-504.12.2.el6.x86_64
             libgcc-4.4.7-17.el6.x86_64 is a duplicate with
             libgcc-4.4.7-11.el6.x86_64 ncurses-base-5.7-4.20090207.el6.x86_64 is a
             duplicate with ncurses-base-5.7-3.20090208.el6.x86_64
             nss-softokn-freebl-3.14.3-23.3.el6_8.x86_64 is a duplicate with
             nss-softokn-freebl-3.14.3-22.el6_6.x86_64 tzdata-2016f-1.el6.noarch is
             a duplicate with tzdata-2015a-1.el6.noarch

I tried The following
yum clean all
rpm --rebuilddb
yum update

Answer: Your system has multiple problems here that need to be fixed:

First, you have rpmdb problems (duplicate packages) because a previous run of yum was interrupted. You can try to clean this up with:
yum-complete-transaction   # which may fail
package-cleanup --cleandupes

Second, your system has a third party repository named hop5 which is providing packages that conflict with the packages provided by RHEL. This repository needs to be disabled or removed. If you were actually using packages from this repository, you should instead get them from official RHEL sources, or for third party packages, a more reliable source.
yum-config-manager --disable hop5

Finally, your system appears to be locked onto RHEL 6.6, and you need to update to the current release (today 6.8). You can fix this with:
subscription-manager release --unset
yum --releasever=6.8 update


Misuse of redo in a history class

Question: I am a student in Computer Science. This semester, I have to make a project (a Sudoku). One of the features of this project is the setting up of a history. So I started to implement this feature.
The "undo" seems to work but I have a little problem with the redo. I think I understand where the bug is coming from, but I do not know how to fix it.
When I change the value of a "Case", I add the old "Case" to my history. This allows me to recover them with undo. However, when I "redo", the first action does nothing, and if If I do all the "redo" possible, it is missing an action. I think it comes from the fact that I only have the old values and not the news. But if I add the news, the problem would be reversed (undo bug, redo works?).
If you have an idea or a track, I'm interested! thank you in advance !
Here is the code when i add an item to my history :
// IN MY HISTORY CLASS
public E getCurrentElement() {
        return leftQ.getLast();
}

public void add(E e) {
    leftQ.addLast(e);
    rightQ.clear();
    currentPosition = currentPosition + 1;
    endPosition = currentPosition;
}

// IN MY add actionPerformed
history.add(Case.duplicate(c)); // Add oldCase
c.addPossibleValue(++addedValues); // change old case
refresh();

Code when i "undo" (work) :
// IN MY HISTORY CLASS
public void goBackward() {
        currentPosition = currentPosition - 1;
        rightQ.add(leftQ.removeLast());
    }

// In my undo actionPerformed
c = history.getCurrentElement();
history.goBackward();
refresh();

Code when i "redo" (dont work) :
// IN MY HISTORY CLASS
public void goForward() {
        currentPosition = currentPosition + 1;
        leftQ.addLast(rightQ.poll());
    }

// In my redo actionPerformed

history.goForward();
c = history.getCurrentElement();
refresh();

Here is the execution trace when I debug:
First i add 2 element to my history. So i have " 1 2 " on my Label.
at the end of the First undo :
LEFT : [Case : Candidates :[]
] --> FIRST Element on history, empty
 RIGHT : [Case : Candidates :[1] // Second one, contains "1"
]

Second undo :
LEFT : []
 RIGHT : [Case : Candidates :[]
, Case : Candidates :[1]
]

then 2 redo :
LEFT : [Case : Candidates :[]
]
 RIGHT : [Case : Candidates :[1]
]

LEFT : [Case : Candidates :[]
, Case : Candidates :[1]
]
 RIGHT : []

My label only contains "1". I think that it comes from the fact that I always add the old value, and so that my history does not contain the state of the object before the first undo ... But I do not see how I could do.
Comment: Also, I should warn you that, if your instructor finds this, you could face accusations of plagiarism and/or allowing plagiarism.  You should instead create a [**Minimal**, Complete and Verifiable Example](http://stackoverflow.com/help/mcve) that demonstrates your problem without giving away too much of your assignment solution.
Comment: I have downvoted this question because there is far too much code here.  In order to make it clear exactly where your problem is, please remove any code that is not directly causing your problem, and if you can reduce it to ten lines or less, I will consider retracting the downvote.  See: [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) and [How to Debug Small Programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)
Comment: As I wrote above, the code is only a small application created to illustrate my problem. All the code here is necessary for this application so you can understand my approach. Case and History are classes used in my project, and each method is used. So I do not see how to make a shorter example...
Comment: Surely you're not suggesting that you need all 283 lines of that code to do a redo?
Comment: I edited. I summarized as much as I could.
Comment: Can you also [edit] to tell us what your debugging efforts have shown you about the state of your queues at each point?
Comment: Edited with my execution trace.
Answer: Using linked lists could be a great way to shorten down your undo / redo implementation. Store your turns as nodes in the list, so that whenever you take a turn, you generate a new node at the end of the list. inside of each node, save an int[3][3] of your board layout. When undo is called, step the board back by loading the board on the previous list node. when redo is called, that node is still there, and you can just step forward. By doing this, you can undo all the way back to turn 1, and then redo all the way up to turn x. Since this is just Sudoku, using a linked list will not require too much memory. This solution is not the best choice for more complex requirements.

Misuse of redo in a history class


Exponential problem in definite integral

Question:
$$\frac{1}{\sqrt{2\pi s^2}} \int_{-\infty}^{\infty} xe^{-(x-m)^2/(2s^2)} \, dx$$

I am stuck at this problem. Please give some hint as how to initiate?
Answer: Hint: Make the change of variable $t = \frac{x - m}{s}$, and use the celebrated Gaussian integral formula:
$$\int_{-\infty}^\infty e^{-\frac{t^2}{2}} dt = \sqrt{2\pi}. \tag{$*$}$$
For a proof for $(*)$, check this link. Also, the first answer to this math stack exchange post referred a paper that gives $10$ different ways to prove $(*)$, which is very fun to read.
If you have learned some probability, you may identify this expression as the mean value of normal distribution $\mathcal{N}(m, s^2)$, which is $m$.
Answer: Hint:
$$\int_{-\infty}^\infty xe^{-(x-m)^2/(2s^2)}\,dx
  =\int_{-\infty}^\infty (x-m)e^{-(x-m)^2/(2s^2)}\,dx
    +m\int_{-\infty}^\infty e^{-(x-m)^2/(2s^2)}\,dx\ .$$


Out of Memory Error when using graphics

Question: I have been making a game for my games development class but due to the limitations in college we have to create a game using Visual Basic and no plugins, so I only have GDI+ to work with.
I have run into an error where it will run out of memory and the game stops running, the error is at line 312 - "_backBufferGr.DrawImage(_backbuffer, 0, 0, _resWidth, _resHeight)"
I think it may be due to the images that are being spawned aren't being cleared but I'm not sure as I have only been coding for about 3 months. If anyone can help that would be very appreciated. I have attached the code below - the classes are in separate files in my project.
Here is an image of my error:
https://i.stack.imgur.com/TfMSi.jpg
and as text:
System.OutOfMemory: Out of memory.
  at System.Drawing.Graphics.CheckErrorStatus(Int32 Status)
  at System.Drawing.Graphics.DrawImage(Image image, Int32 x, Int32 y, Int32 Width, Int32 height)
  at SpaceInvaders.Spaceinvaders.DrawGraphics()

Imports System.Drawing.Imaging
Imports System.IO

Public Class Spaceinvaders
'Star Generation Variables
ReadOnly _random As New Random
Private ReadOnly _r As New Random
Private ReadOnly _stars As New List(Of Point)

'Sound Variabless
Public Shared Intsound As Integer = 0
Public Shared Snd As New Sounds

'Graphics varibles
Dim _backbuffer As Bitmap
Dim _backBufferGr As Graphics
Public Shared Gr As Graphics
Shared _sourceRec As Rectangle

'View Port Variables
Dim _resWidth As Int16 = 700
Dim _resHeight As Int16 = 650
Dim _paused As Boolean = False
Dim _pauseNum As Int16 = 0
Dim _pausedText As Int16 = 40
Dim _mouseX, _mouseY As Int16

'Key Detection
Public Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Int16) As Int16
Public Function GetKeyState(ByVal key1 As Int16) As Boolean

    Dim s As Int16
    s = GetAsyncKeyState(key1)
    If s = 0 Then Return False
    Return True

End Function

'Character Variables
Dim _bmpPlayer As Bitmap
Public Shared PlayerW, PlayerH As Int16
Public Shared XPos As Int16 = 0
Public Shared YPos As Int16 = 0
Dim _movementSpeed As Int16 = 8
Dim _moveDir As Int16 = 0
Dim _lastDir As Int16 = 0

'Fire Variables
Dim _fire As Boolean
Dim _bulletArray(100000) As Bullet
Dim _bulletNum As Int16 = 0
Dim _cooldown As Int16
Public Shared Points As Int32 = 0
Public Shared EnemiesKilled As Int16 = 0
Public Shared ExploArray(100000) As Explo
Public Shared ExploNum As Int16 = 0

'Enemy Variables
Dim _spawnNum As Int16
Public Shared EnemyArray(100000) As Enemies
Public Shared EnemyNum As Int16 = 0
Public Shared Lives As Int16 = 3
Dim SpawnSpd As Int16 = 30

'Other Variables
Dim _isRunning As Boolean = True
Public Shared CollitionDetc As New StreamWriter(Application.StartupPath() & "\" & "Detection" & ".Log")
Public Function FadeInImage(ByVal bmp As Bitmap, ByVal opacity As Single) As Bitmap
    Dim bmp2 As New Bitmap(bmp.Width, bmp.Height, PixelFormat.Format32bppArgb)
    opacity = Math.Max(0, Math.Min(opacity, 1.0F))
    Using ia As New ImageAttributes
        Dim cm As New ColorMatrix
        cm.Matrix33 = opacity
        ia.SetColorMatrix(cm)
        Dim destpoints() As PointF = {New Point(0, 0), New Point(bmp.Width, 0), New Point(0, bmp.Height)}
        Using g As Graphics = Graphics.FromImage(bmp2)
            g.DrawImage(bmp, destpoints, New RectangleF(Point.Empty, bmp.Size), GraphicsUnit.Pixel, ia)
        End Using
    End Using
    Return bmp2
End Function

'Form Events
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Show()
    Focus()

    'Create Stars - 300 is the Number of Stars
    CreateStarField(300)

    'Start Music
    Intsound += 1
    With Snd
        .Name = "Sound" & Intsound
        .PlaySound(1, True)
    End With

    'This creates the graphics and the backbuffer, along with drawing the player to the screen
    Gr = CreateGraphics()
    _backbuffer = New Bitmap(_resWidth, _resHeight)
    _bmpPlayer = New Bitmap(My.Resources.Ship)
    XPos = (Width / 2)
    YPos = 500
    Gr.DrawImage(_bmpPlayer, XPos, YPos, _sourceRec, GraphicsUnit.Pixel)

    StartGameLoop()

End Sub
Private Sub Spaceinvaders_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing

    Do Until Intsound = 0
        Snd.Kill("Sound" & Intsound)
        Intsound -= 1
    Loop
    Dispose()
    End
End Sub
Private Sub Spaceinvaders_MouseMove(sender As Object, e As MouseEventArgs) Handles MyBase.MouseMove

    _mouseX = e.X
    _mouseY = e.Y

End Sub
Private Sub Spaceinvaders_MouseDown(sender As Object, e As MouseEventArgs) Handles MyBase.MouseDown

    If (290 + 110 < _mouseX Or _mouseX < 290 Or 336 + 63 < _mouseY Or _mouseY < 336) Then

    Else
        _paused = False
    End If

End Sub

'Starfield Background Generation
Private Sub CreateStarField(numStars As Integer)
    _stars.Clear()
    For i = 1 To numStars
        _stars.Add(New Point(_r.Next(0, Width), _r.Next(0, Height)))
    Next
End Sub

'Runs the actual game over and over again until it is stopped
Sub StartGameLoop()

    Do While _isRunning = True

        Application.DoEvents()

        LivesCheck()
        SetMoveDir()
        MovePlayer(_moveDir)
        'Start the drawing events & FPS Counter
        DrawGraphics()

    Loop

    Do While _isRunning = False
        Application.DoEvents()

    Loop

End Sub

'Subs to do with player creation and movement
Private Sub GetPlayer(ByVal dir As Int16)
    Select Case dir
        Case 1 'Upfacing Direction
            _bmpPlayer = New Bitmap(My.Resources.Ship)
            _sourceRec = New Rectangle(0, 0, 85, 50)
            PlayerH = 50
            PlayerW = 85
        Case 2 'Downfacing Direction
            _bmpPlayer = New Bitmap(My.Resources.Ship)
            _sourceRec = New Rectangle(0, 0, 85, 50)
            PlayerH = 50
            PlayerW = 85
        Case 3 'Left Facing Direction
            _bmpPlayer = New Bitmap(My.Resources.ShipLeft)
            _sourceRec = New Rectangle(0, 0, 96, 76)
            PlayerH = 76
            PlayerW = 96
        Case 4 'Right Facing Direction
            _bmpPlayer = New Bitmap(My.Resources.ShipRight)
            _sourceRec = New Rectangle(0, 0, 96, 76)
            PlayerH = 76
            PlayerW = 96
    End Select
End Sub
Sub SetMoveDir()
    If GetKeyState(Keys.W) = True Then _moveDir = 1
    If GetKeyState(Keys.A) = True Then _moveDir = 3
    If GetKeyState(Keys.S) = True Then _moveDir = 2
    If GetKeyState(Keys.D) = True Then _moveDir = 4

    If GetKeyState(Keys.Space) = True Then _fire = True
    If GetKeyState(Keys.P) = True Then
        If _pauseNum = 0 Then
            _paused = True
            _pauseNum = 1
        ElseIf _pauseNum = 1 Then
            _paused = False
            _pauseNum = 0
        End If
    End If

    If GetKeyState(Keys.W) = False And
       GetKeyState(Keys.A) = False And
       GetKeyState(Keys.S) = False And
       GetKeyState(Keys.D) = False Then
        _moveDir = 0
    End If

    If _moveDir <> 0 Then _lastDir = _moveDir
End Sub
Private Sub MovePlayer(ByVal dir As Int16)

    Select Case dir
        Case 1
            If YPos <= 0 Then
            Else
                YPos -= _movementSpeed
            End If

        Case 2
            If YPos >= 544 Then
            Else
                YPos += _movementSpeed
            End If

        Case 3
            If XPos <= -2 Then
            Else
                XPos -= _movementSpeed
            End If

        Case 4
            If XPos >= 606 Then
            Else
                XPos += _movementSpeed
            End If

    End Select

End Sub

'Draw the stuff to the screen
Sub DrawGraphics()
    If _paused = True Then

        Gr.DrawString("Paused", New Font("Verdana", _pausedText), New SolidBrush(Color.White), New Point(235, 256))

        If (290 + 110 < _mouseX Or _mouseX < 290 Or 336 + 63 < _mouseY Or _mouseY < 336) Then
            Gr.DrawString("Play", New Font("Verdana", 25), New SolidBrush(Color.White), New Point(290, 336))
        Else
            Gr.DrawString("Play", New Font("Verdana", 25), New SolidBrush(Color.Red), New Point(290, 336))
        End If

        'Copy BackBuffer To Graphics Object
        Gr = Graphics.FromImage(_backbuffer)
        'Draw BackBuffer to the screen
        Try
            _backBufferGr = CreateGraphics()
            _backBufferGr.DrawImage(_backbuffer, 0, 0, _resWidth, _resHeight)
        Catch ex As Exception
            MsgBox(ex)
            _isRunning = False
            Exit Sub
        End Try
        Gr.Clear(Color.Black)

        'Runs when the game is unpaused
    ElseIf _paused = False Then

        Gr.Clear(Color.Black)
        'Draws Stars to the screen
        DrawStars()

        'Draws Enemies to the screen
        EnemyDraw()

        'Draws bullets to the screen
        BulletDraw()

        'Draws Explosions
        Expslostion()

        'Draw the player
        DrawPlayer()

        'Draws lives to the screen
        DrawHUD()

        'Copy BackBuffer To Graphics Object
        Gr = Graphics.FromImage(_backbuffer)
        'Draw BackBuffer to the screen
        Try
            _backBufferGr = CreateGraphics()
            _backBufferGr.DrawImage(_backbuffer, 0, 0, _resWidth, _resHeight)
        Catch ex As Exception
            MsgBox("ERROR: " & vbCrLf & ex.ToString)
            _isRunning = False
            Exit Sub
        End Try

        Gr.Clear(Color.Black)
        GC.Collect()
        _fire = False
        WriteLog()
    End If
End Sub
Sub BulletDraw()
    If _bulletNum = 0 Then
        _bulletNum = 0
    Else
        For i = 1 To _bulletNum
            _bulletArray(i).Move(i)
        Next

    End If

    If _cooldown < 2 Then
        _cooldown += 1
    Else : If _fire = True Then
            _bulletNum += 1
            _bulletArray(_bulletNum) = New Bullet
            _bulletArray(_bulletNum).Spawn(_bulletNum, 4)
            _cooldown = 0

        End If : End If
End Sub
Sub EnemyDraw()
    If EnemyNum = 0 Then
        EnemyNum = 0
    Else
        For i = 1 To EnemyNum
            EnemyArray(i).Move()
        Next
    End If

    If _spawnNum < SpawnSpd Then
        _spawnNum += 1
    Else
        Points += 5
        EnemyNum += 1
        EnemyArray(EnemyNum) = New Enemies
        EnemyArray(EnemyNum).Spawn()
        _spawnNum = 0
    End If

End Sub
Sub Expslostion()

    If ExploNum = 0 Then
        ExploNum = 0
    Else
        For i = 1 To ExploNum
            ExploArray(i).Animation()
        Next
    End If

End Sub
Sub DrawStars()
    For Each pt As Point In _stars 'Loops until all the stars are added to the form background
        Dim num = _random.Next(1, 6) 'Randomly Picks a number
        Dim numSize = _random.Next(1, 3)
        If num = 1 Then 'Picks a colour based on the number picked
            Gr.FillEllipse(Brushes.White, New Rectangle(pt, New Size(numSize, numSize)))
        ElseIf num = 2 Then
            Gr.FillEllipse(Brushes.Blue, New Rectangle(pt, New Size(numSize, numSize)))
        ElseIf num = 3 Then
            Gr.FillEllipse(Brushes.DimGray, New Rectangle(pt, New Size(numSize, numSize)))
        ElseIf num = 4 Then
            Gr.FillEllipse(Brushes.DarkOrange, New Rectangle(pt, New Size(numSize, numSize)))
        ElseIf num = 5 Then
            Gr.FillEllipse(Brushes.Red, New Rectangle(pt, New Size(numSize, numSize)))
        End If
    Next
End Sub
Sub DrawPlayer()
    If _moveDir = 0 Then
        _bmpPlayer = New Bitmap(My.Resources.Ship)
    Else
        GetPlayer(_lastDir)
    End If
    _bmpPlayer.MakeTransparent(Color.Fuchsia)
    Gr.DrawImage(_bmpPlayer, XPos, YPos, _sourceRec, GraphicsUnit.Pixel)
End Sub
Sub DrawHUD()
    Select Case Lives
        Case 3
            Gr.FillRectangle(Brushes.Red, 510, 5, 150, 10)
        Case 2
            Gr.FillRectangle(Brushes.Red, 510, 5, 100, 10)
        Case 1
            Gr.FillRectangle(Brushes.Red, 510, 5, 50, 10)
    End Select

    Gr.DrawString("Ships Destroyed: " & EnemiesKilled, New Font("Verdana", 10), New SolidBrush(Color.White), New Point(5, 5))
    Gr.DrawString("Score: " & Points, New Font("Verdana", 10), New SolidBrush(Color.White), New Point(5, 20))
End Sub

Sub WriteLog()
    Dim sw As New StreamWriter(Application.StartupPath() & "\" & "Variables" & ".Log")

    sw.WriteLine("--------Variables Log--------")
    sw.WriteLine("")
    sw.WriteLine("Sounds Playing: " & Intsound)
    sw.WriteLine("")
    sw.WriteLine("Window Resolution: " & _resWidth & " " & _resHeight)
    sw.WriteLine("Game Running: " & _isRunning)
    sw.WriteLine("")
    sw.WriteLine("Player Postion: " & XPos & " " & YPos)
    sw.WriteLine("Player Size: " & PlayerW & " " & PlayerH)
    sw.WriteLine("Player Movement Speed: " & _movementSpeed)
    sw.WriteLine("PLayer Last Direction: " & _lastDir)
    sw.WriteLine("")
    sw.WriteLine("Bullets Being Fired?: " & _fire)
    sw.WriteLine("Number Of bullets spawned: " & _bulletNum)
    sw.WriteLine("")
    sw.WriteLine("Number of enemies spawned: " & EnemyNum)
    sw.WriteLine()
    sw.WriteLine("--------Bullet Variables--------")
    sw.WriteLine("Bullet Number  X     Y")
    For i = 1 To _bulletNum

        sw.WriteLine(i & "            " & _bulletArray(i).X & "  " & _bulletArray(i).Y)

    Next

    sw.WriteLine("--------Enemy Variables--------")
    sw.WriteLine("Enemy Number  X     Y")
    For i = 1 To EnemyNum

        sw.WriteLine(i & "           " & EnemyArray(i).X & "  " & EnemyArray(i).Y)

    Next

    sw.Close()
    sw.Dispose()

End Sub
Sub LivesCheck()
    If Lives = 0 Then
        _isRunning = False
        Gameover.Show()
    End If
End Sub
End Class

Public Class Bullet
Dim _bulletX, _bulletY As Int16
Dim _bmpBullet As Bitmap = My.Resources.bullet1
Dim _bulletRec As New Rectangle
Dim _bulletSpd As Int16 = 4
Dim _enemyNum As Int16
Dim _active As Boolean = True

Function X()
    Return _bulletX
End Function
Function Y()
    Return _bulletY
End Function

Sub Spawn(ByVal i As Int16, ByVal s As Int16)

    Spaceinvaders.Intsound += 1
    With Spaceinvaders.Snd
        .Name = "Sound" & Spaceinvaders.Intsound
        .PlaySound(2, False)
    End With
    _bulletSpd = s
    _bulletX = Spaceinvaders.XPos + (Spaceinvaders.PlayerW / 2)
    _bulletY = Spaceinvaders.YPos + (Spaceinvaders.PlayerH / 2)
    _bmpBullet = My.Resources.bullet1
    _bmpBullet.MakeTransparent(Color.Fuchsia)
    Spaceinvaders.Gr.DrawImage(_bmpBullet, _bulletX, _bulletY, _bulletRec, GraphicsUnit.Pixel)

End Sub

Sub Move(ByVal bulletNum As Int16)
    If _active = False Then
        Me.Finalize()
    Else

        _enemyNum = Spaceinvaders.EnemyNum
        For i = 1 To _enemyNum
            Dim EnemyRect As Rectangle
            EnemyRect = Spaceinvaders.EnemyArray(i).Rectangle

            If (_bulletRec.IntersectsWith(EnemyRect)) Then
                If Spaceinvaders.EnemyArray(i).Invc >= 40 Then
                    Spaceinvaders.EnemyArray(i).Kill(-10, -10)
                    _active = False
                    Spaceinvaders.Points += 500
                    Spaceinvaders.CollitionDetc.WriteLine("Enemy Num: " & i & " & " & "Bullet Num: " & bulletNum & "   - HIT")
                    _bulletX = -100
                    _bulletY = -100
                    _bulletRec = New Rectangle(-100, 100, 1, 1)
                    Spaceinvaders.Intsound += 1
                    With Spaceinvaders.Snd
                        .Name = "Sound" & Spaceinvaders.Intsound
                        .PlaySound(3, False)
                    End With
                    Dim enemyX, enemyY As Int16
                    enemyX = Spaceinvaders.EnemyArray(i).X
                    enemyY = Spaceinvaders.EnemyArray(i).Y
                    Spaceinvaders.ExploNum += 1
                    Spaceinvaders.ExploArray(Spaceinvaders.ExploNum) = New Explo()
                    Spaceinvaders.ExploArray(Spaceinvaders.ExploNum).Spawn(enemyX, enemyY)
                    Me.Finalize()

                End If
            End If
        Next

        If _bulletY <= 0 Then
            _bulletX = -100
            _bulletY = -100
        Else
            _bulletY -= _bulletSpd
            _bmpBullet.MakeTransparent(Color.Fuchsia)
            Spaceinvaders.Gr.DrawImage(_bmpBullet, _bulletX, _bulletY)
            _bulletRec = New Rectangle(_bulletX, _bulletY, 16, 16)
        End If
    End If

End Sub
End Class

Public Class Enemies
Dim _enemyX, _enemyY As Int16
Dim _bmpEnemy As Bitmap = My.Resources.InvaderSkullWhite
Dim _moveNum As Int16 = 0
Dim _active As Boolean = True
Dim _tempInvc As Int16 = 0
Dim EnemyRect As Rectangle

Function X()
    Return _enemyX
End Function
Function Y()
    Return _enemyY
End Function
Function Kill(ByVal x, ByVal y)
    _enemyX = x
    _enemyY = y
    _active = False
    EnemyRect = New Rectangle(x, y, 1, 1)
    Me.Finalize()
End Function
Function Invc()
    Return _tempInvc
End Function
Function Rectangle()
    Return EnemyRect
End Function

Sub Spawn()
    Dim rand As New Random

    _enemyY = 3
    _enemyX = rand.Next(10, 600)

    Select Case rand.Next(1, 5)
        Case 1
            _bmpEnemy = My.Resources.InvaderSkullWhite
        Case 2
            _bmpEnemy = My.Resources.InvaderSkullRed
        Case 3
            _bmpEnemy = My.Resources.InvaderSkullGreen
        Case 4
            _bmpEnemy = My.Resources.InvaderSkullYellow
    End Select
    _bmpEnemy.MakeTransparent(Color.Fuchsia)
    Spaceinvaders.Gr.DrawImage(_bmpEnemy, _enemyX, _enemyY)
    Move()

End Sub

Sub Move()
    If _active = False Then
        Me.Finalize()
    Else
        If _tempInvc < 40 Then
            _tempInvc += 1
        End If

        If _moveNum < 10 Then
            _moveNum += 1
            _bmpEnemy.MakeTransparent(Color.Fuchsia)
            Spaceinvaders.Gr.DrawImage(_bmpEnemy, _enemyX, _enemyY)
        Else
            If _enemyY >= 700 Then
                Spaceinvaders.Lives -= 1
                _enemyX = -5
                _enemyY = -5
            Else
                Dim randX As New Random
                _enemyY += 5
                Select Case _enemyX
                    Case _enemyX <= 5
                        _enemyX = _enemyX + randX.Next(1, 4)
                    Case _enemyX >= 600
                        _enemyX = _enemyX + randX.Next(-4, -1)
                    Case Else
                        _enemyX = _enemyX + randX.Next(-4, 4)
                End Select

                _bmpEnemy.MakeTransparent(Color.Fuchsia)
                Spaceinvaders.Gr.DrawImage(_bmpEnemy, _enemyX, _enemyY)
                EnemyRect = New Rectangle(_enemyX, _enemyY, 64, 64)
            End If
            _moveNum = 0
        End If
    End If
End Sub
End Class

Public Class Sounds
Public Declare Function MciSendString Lib "winmm.dll" Alias "mciSendStringA" (ByVal lpstrCommand As String, ByVal lpstrReturnString As String, ByVal uReturnLength As Integer, ByVal hwndCallback As Integer) As Integer
Dim _appPath As String = Application.StartupPath()
Private _oName As String = Nothing

Public Property Name As String
    Set(value As String)
        _oName = value

    End Set
    Get
        Return _oName
    End Get
End Property

Public Sub PlaySound(ByVal id As Integer, ByVal repeat As Boolean, Optional vol As Integer = 35)

    If repeat = True Then
        MciSendString("Open " & GetFile(id) & " alias " & _oName, 0, 0, 0)
        MciSendString("Play " & _oName & " repeat", CStr(0), 0, 0)

    Else
        MciSendString("Open " & GetFile(id) & " alias " & _oName, CStr(0), 0, 0)
        MciSendString("Play " & _oName, CStr(0), 0, 0)

    End If
    'Set Vol
    MciSendString("Open " & GetFile(id) & " alias " & _oName, CStr(0), 0, 0)
    MciSendString("setaudio " & _oName & " volume to " & vol, CStr(0), 0, 0)
End Sub

Private Function GetFile(ByVal id As Integer) As String

    Dim path As String = ""

    'Here is where you put the sound paths so that your game can play sounds

    Select Case id
        Case 0 'Menu Background Music
            path = _appPath & "\Audio\Menu.mp3"
        Case 1 'Ingame Background Music
            path = _appPath & "\Audio\InGame.mp3"
        Case 2 'Fire Spund
            path = _appPath & "\Audio\Lazer.mp3"
        Case 3 'Expolsion sound
            path = _appPath & "\Audio\Expolsion.mp3"
    End Select

    path = Chr(34) & path & Chr(34)

    Return path

End Function

Public Sub Kill(ByVal song As String)
    MciSendString("close " & song, CStr(0), 0, 0)
    _oName = Nothing
End Sub
End Class

Comment: @MathieuGuindon I don't think that works for reputation 1 users.  They need at least 10 reputation.
Comment: Your code is begging for more object types. Reminds me of my experimentations with XNA Game Studio - consider looking into how XNA projects abstract away drawable content and integrate game loop concerns like `Update` and `Draw`. That said, consider `Using` blocks everywhere an `IDisposable` is involved, rather than explicit disposal. Also the `Shared` stuff worries me, should be instance variables AFAICT.
Comment: FYI There's no such thing as VBA.NET. Either you're doing VBA, or you're doing VB.NET.
Comment: Did ya upload enough code there Butch?  You should rarely store the graphic object.  Always dispose of it when done.  Dispose your images when done, too.
Comment: Also please use the standard uploader (click the 'Image' icon in the toolbar) to insert an image in your post.
Comment: @LarsTech possible... but odd, given how many times I've edited 1-rep users' posts to include the missing `!` that would make an `i.stack.imgur` url show up as an image.
Comment: @MathieuGuindon : They can still upload the image, but it will only be put as a link because they do not have the privileges to post viewable images. We do though, which is why we can edit their posts to fix it.
Comment: Thanks for the comments, I tried to post it as an image but my rep is too low.
Comment: The error message is: System.OutOfMemory: Out of memory. at System.Drawing.Graphics.CheckErrorStatus(Int32 Status)  at System.Drawing.Graphics.DrawImage(Image image, Int32 x, Int32 y, Int32 Width, Int32 height)  at SpaceInvaders.Spaceinvaders.DrawGraphics()   @Andrew Morton
Answer: Whenever you're done with an object that implements IDisposable in almost all cases you should probably call it (there are exceptions outside the scope of this answer).  For note, A "using" statement always calls Dispose when it's done (so you're Graphics calls that are using a using are good on that front).
Where I see potential problems are the places you're using a class wide variable and resetting new Bitmap's onto it (I don't think the old one's get disposed and as a result I think they're hanging out there and slowly eating up your memory).
 _bmpPlayer = New Bitmap(My.Resources.Ship)

See if something like this helps:
If _bmpPlayer IsNot Nothing Then
    _bmpPlayer.Dispose()
End If

_bmpPlayer = new Bitmap(My.Resources.Ship)

That said, if you're using these same images over and over I would probably store them and re-use them as opposed to re-writing a new Bitmap from the resource every time.
Answer: Thanks to everyone trying to help me fix the problem. I fixed the out of memory error by changing this bit of code:
If _bulletNum = 0 Then
        _bulletNum = 0
    Else
        For i = 1 To _bulletNum
            _bulletArray(i).Move(i)
        Next

    End If

To this:
If _bulletNum = 0 Then
        _bulletNum = 0
    Else
        Dim skipbullet As Int16
        skipbullet = _bulletNum - 50
        If skipbullet >= 1 Then
            For i = skipbullet To _bulletNum
                _bulletArray(i).Move(i)
            Next
            For i = 1 To skipbullet
                _bulletArray(i).Kill()
            Next
        Else
            For i = 1 To _bulletNum
                _bulletArray(i).Move(i)
            Next
        End If

    End If

Comment: `If _bulletNum = 0 Then _buttetNum = 0`???  Why not just `If _bulletNum > 0 Then` run the else code.
Comment: Honestly don't know why I wrote that :D

Out of Memory Error when using graphics


Cautions with sparse features

Question: I got some sparse data for the first time and it's quite intimidating.
After reading sklearn preprocessing docs it seems I should scale them with MaxAbsScaler (the sparseness is important). However, what are other recomendations for such kind of problems?
Is it possible to use PCA or other kind of feature selection on this kind of data?
Comment: What do you want to do with this data? How the data looks like (samples)?
Comment: What data have you got? What research questions are you asking? What hypotheses do you wan to test? What are you trying to find out?
Answer: Your question is, itself, relatively sparse so not much can be said. But generally

If you have an enormous volume of sparse data, you want to avoid any operation (such as mean-centering) that could disrupt sparsity. This is one reason MaxAbsScaler could be helpful: it can be computed without disrupting sparsity, and applying it also doesn't disrupt sparsity.
MaxAbsScaler scales by the largest absolute  value (which is cheap to estimate). Likely for numerical reasons, the scipy.sparse authors do not implement standard deviation methods for sparse data types; if you disregard numerical concerns, one  could scale by standard deviation (but you'd have to write your own sparsity-respecting code to do so).
You don't want to use PCA, since it requires centering your data (destroying sparsity). But you can still access an orthogonal basis representation of your data using sparse SVD.
PCA isn't feature selection, it just rotates the data.
MaxAbsScaler isn't feature selection, either, it just scales data.
Comment: what do you mean by "disrupting sparsity"?
Comment: @Aksakal Suppose you have a vector that's mostly 0, but 1% of elements are nonzero. A sparse representation has roughly 1% the storage costs of the dense representation. Mean-centering the vector requires storing all the values, as none are zero, and there is only slight difference between dense and sparse storage requirements (the sparse storage cost could even be higher!) Some specialized sparse arithmetic packages let you use non-zero values as the "implicit value" of zero used by `scipy.sparse`, but this is uncommon, so anything that breaks the "mostly 0" property is generally Bad News.

Cautions with sparse features


AWS SAM template with API gateway only?

Question: We're planning to use API Gateway as REST API HTTP proxy only initially - as we have existing REST service and we wish to split it into smaller parts under covers without changing client interface (possibly later replacing some of those parts with lambda functions).
Before we do that, I wish to see if we will have any support running such scenario locally, hence I've configured API gateway in AWS management console and exported OpenAPI definition.
So my template.yaml looks like
AWSTemplateFormatVersion: '2010-09-09'
Transform: 'AWS::Serverless-2016-10-31'
Description: Demo SAM API
Resources:
  MyApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: test
      DefinitionBody:
        'Fn::Transform':
          Name: AWS::Include
          Parameters:
            Location: swagger.yaml

and swagger.yaml looks following:
openapi: "3.0.1"
info:
  title: "Test.API"
  description: "Test.API"
  version: "2020-09-14T07:49:45Z"
servers:
- url: "https://dummydomain.com"
paths:
  /api/v3/Client:
    get:
      x-amazon-apigateway-integration:
        type: "http_proxy"
        uri: "https://dummydommain.com/api/v3/client"
        passthroughBehavior: "when_no_match"
        httpMethod: "GET"
        timeoutInMillis: 29000
components: {}

And running sam local start-api --debug this gives error:
Error: Template does not have any APIs connected to Lambda functions

I've added dummy lambda function just to pass through the error, but still no luck - it had message in debug output:
Lambda function integration not found in Swagger document at path='/api/v3/client' method='get'

and responded to `http://localhost:3000/api/v3/client' with:
{"message":"Missing Authentication Token"}

Does this mean, that SAM is very very coupled to lambda's and it won't run API gateway as proxy locally or I'm doing something stupid?
Comment: @petey - that's the point, I need only apigateway doing http proxying, I don't need any lambda at the moment.
Comment: @MarcellAlves - I've dropped the idea to use SAM for my purposes - too much trouble, I've faced other issues as well without clear answers.
Comment: `...does not have any APIs connected to Lambda functions` Where's your lambda function?
Comment: yea, you should hook up a lambda function. I dont think it will work without it.
Comment: @Giedrius, I have the same scenario. How did you solve this?
Answer: Answering your question:

Does this mean, that SAM is very very coupled to lambda's and it won't run API gateway as proxy locally or I'm doing something stupid?

No, you're not stupid. It won't run as a proxy, and the documentation isn't clear about that.
It turns out that the only integration type accepted by local API is aws_proxy (for Lambda Functions only) or mock (which does nothing).
It's on a comment in their source code
Your type: "http_proxy" might work on production, but not on localhost
Answer: Add Lambda integration to your template.yaml file:
YourLambdaFunction:
        Type: AWS::Serverless::Function
        Properties:
            CodeUri: path/to/your/lambda/
            Role: arn:aws:iam::<ACCOUNT_NUMBER>:role/service-role/role-for-lambda
            Events:
                YourGetEvent:
                    Type: Api
                    Properties:
                        Path: /api/v3/Client
                        Method: get
                        RestApiId:
                            Ref: MyApi

AWS SAM template with API gateway only?


Is there any way to allow multithreading on a program with a loop like this one?

Question: Is there any way to allow multithreading on a program with a loop like this one?
int a=100000,b=50,c;while(a){c=b*a+c;a--;}
Windows 7/Code::Blocks IDE with the default mingw c++ compiler/Dual-core 4 threaded i5 cpu
Answer: This isn't a programming issue per se.
Your CPU has either four cores, or two cores with hyperthreading.  The program is using 100% of 1 core, which is reported as 25% usage in the Windows task manager.
You won't be able to 'increase your CPU usage' without threading.
(As an aside, the reason you see it as 'distributed between the four threads' is because the operating system is, if you like, changing its mind about which core it wants to run your program on.  Such issues of scheduling can't be changed (and won't have a noticable impact on) individual programs.)
Comment: Threads are not considered cores, but a thread can only run on one core at a time so if you want to use more than one core you are required to use more than one thread.  Using multiple threads is fundamentally hard though; you need to be careful or else your program will have unpredictable behavior.
Comment: Thanks for the fast reply, it fully answers my question, I really didn't know that threads could be considered as cores.
Comment: @DavidGrayson - I thought Windows didn't make a distinction between real and hyperthreaded 'cores'?  I'm more of a Unix guy, though, so I could be remembering incorrectly.
Comment: Well, there is one way to 'increase CPU usage' without threading -- just run four instances of your program at the same time.
Comment: You could also use [OpenMP's parallel for-loops](http://bisqwit.iki.fi/story/howto/openmp/#LoopDirectiveFor) if it's appropriate for the given problem.
Comment: @MikaelPersson That's the point, there's no way to speed up a program like the one below? Is there any way to use parallel processing on a program like this? int a=100,b=50,c;while(a){c=c+b*a;a--;}
(consider an important number of loops, some milions or so)


What is Firebase and Legacy iOS means in GTM setup

Question: I am new to GTM .
I am making a new account for GTM and got the following screen.
I want to Implement only GTM not GA. I will track events via GTM only.
I am getting this screen is Initial Setup:

I Have two option two select. Firebase and Legacy (iOS).
I am not able to figure it Out. Please suggest me what to do.
I am not Implementing Firbase at all.
Answer: The Firebase option uses Firebase Analytics' events as input to Tag Manager. You can use these events to fire (and modify) Firebase events, Google Analytics, other Google tags, custom tags, and some third party tags. Using this SDK doesn't mean you have to use Firebase features other than Firebase Analytics.
The "Legacy iOS" container is the previous version of the SDK. It supports Google Analytics, Adwords, DoubleClick, and custom tags. The legacy SDK requires more code to setup. In the legacy SDK tags are triggered by calling Google Tag Manager's DataLayer APIs.
Comment: Hi @Eric Burley,
Can you kindly guide me how can i test GTM in my application?
Comment: If you use the "Legacy iOS" container are you able to use third party tags?


Jquery Ajax post

Question: When I post base64 string over 1.2 mb apache tomcat giving the error: "The request sent by the client was syntactically incorrect"
When it is under 1.2 mb it works fine, I receive the data at the server side.
Is there size restriction and how am I going to past this issue? Any help will be appreciated.
Thanks a lot :)
   $.ajax({ type: 'POST',
        url: 'http://localhost/testServer/image',
        data: {imageData : result} ,
        async: true,
        success: function(data) {

        },
        error: function (xhr, textStatus, errorThrown) {
           alert(xhr.responseText);
        }
    });

Answer: The HTTP specification doesn't impose a specific size limit for posts. They will usually be limited by either the web server or the programming technology used to process the submission.

In httpd.conf add this line
LimitRequestBody<filesize>
LimitRequestBody Directive specifies the number of bytes from 0 (meaning unlimited) to >2147483647 (2GB) that are allowed in a request body
For more information,please refer the URL:
http://httpd.apache.org/docs/mod/core.html#limitrequestbody

Source: here
Comment: Ok thanks :) It helped, but this is for httpd server. What I did was      adding maxPostSize="0" to the connector in server.xml file solved it. Thanks
Comment: Yes that's what I said 'tomcat gives the error: 'The request sent by the client was syntactically incorrect' thanks
Comment: See [this](http://www.enterprise-architecture.org/documentation/doc-administration/145-post-size-limit) regarding tomcat...
Comment: Glad to hear that you figured it out! :)

Jquery Ajax post


Avoiding information leakage in CV folds with scaling

Question: Chapter 6 (Algorithm Chains and Pipelines) in the book Introduction to ML with Python made me aware of a common mistake when scaling data for cross validation: leaking information into the test set by scaling the training and test set together.
I wanted to make sure my implementation now is correct:
skf = StratifiedKFold(n_splits=10, shuffle=True)
clf = SVC()

for train_index, test_index in skf.split(x_train_all, y_true):
    x_train, y_train = x_train_all[train_index], y_true[train_index]
    x_test, y_test = x_train_all[test_index], y_true[test_index]

    scaler = StandardScaler()
    x_train_scaled = scaler.fit_transform(x_train)
    clf.fit(x_train_scaled, y_train)

    x_test_scaled = scaler.transform(x_test)
    y_prediction = clf.predict(x_test_scaled)

As comparison, beforehand I scaled the whole test set, which I believe is incorrect:
skf = StratifiedKFold(n_splits=10, shuffle=True)
scaler = StandardScaler()
x_train_all = scaler.fit_transform(x_train_all)
clf = SVC()

for train_index, test_index in skf.split(x_train_all, y_true):
    x_train, y_train = x_train_all[train_index], y_true[train_index]
    x_test, y_test = x_train_all[test_index], y_true[test_index]

    clf.fit(x_train, y_train)
    y_prediction = clf.predict(x_test)

Hopefully somebody can comment on whether my cross validation is now sound or not.
Answer: Your solution is correct in the sense that it does not suffer from data leakage.
However, it will not yield proper predicive abilities, so in that sense your computation is bad.
You can see that undesired behaviour when you try to predict a single test case: the scaling of the test data is not going to work then. In other situations, the problem is more subtle: your prediction will work only for representative data sets to be predicted together.
The solution is to consider the scaling parameters (center and scaling fractor) as parts of the model. That would make your prediction start by centering with the center estimated on the training data and scaling with the scaling factors estimated on the training data. Note that this is as stable as your training data is good, and doesn't have any problems with predicting single cases.
Comment: I am not 100% sure I understood your answer correctly.

I use this method as internal validation for my model and I'll never ever going to have just one single case for my prediction here. And as this data is selected by me, all data should be representative. But maybe I got it all wrong. Especially the last paragraph was not clear to me.


Counting nodes in binary search tree

Question: I need to create a recursive method that takes as a parameter the root node of a binary search tree. This recursive method will then return the int value of the total number of nodes that have one left descendant.
int Tree::leftPtrCount(int count) {
    return leftPtrCountHelper(rootPtr, count);
}
int Tree::leftPtrCountHelper(TreeNode *node, int count){
    if (node == NULL)
        return 0;
    if (node->leftPtr != NULL && node->rightPtr == NULL)
        count++;
    else
        return leftPtrCountHelper(node->leftPtr, count) + leftPtrCountHelper(node->rightPtr, count);
}

Comment: And what is the question?
Comment: Welcome on StackOverflow! This site has some etiquette that should be respected. Please read http://stackoverflow.com/questions/how-to-ask to help improving your question.
Comment: You don't return the counter in all cases, which leads to [*undefined behavior*](http://en.wikipedia.org/wiki/Undefined_behavior) (and I guess that this is one of the problems you might be having). In fact, the counter is not needed at all.
Answer: If I understand correctly the assignment then the function will look as
size_t Tree::leftPtrCountHelper( const TreeNode *node )
{
    if ( node == NULL ) return 0;
    return ( node->leftPtr != NULL && node->rightPtr == NULL ) +
             leftPtrCountHelper( node->leftPtr ) +
             leftPtrCountHelper( node->rightPtr );
}

Counting nodes in binary search tree


"argument of type "int(*)()" is incompatible with parameter of type int" error?

Question: So I'm trying to write this code which is supposed to generate a sum of two different numbers and identify whether the player has won or lost or neither according to said sum. And then proceed to calculating the budget of the player according to their status. I keep getting the ""argument of type "int(*)()" is incompatible with parameter of type int" error and I'm not sure why.
#include "stdafx.h"
#include <iostream>
#include <cmath>
#include <string>

using namespace std;

//prototyping functions
int sum();
int bla(int, int, int, int);
void main()
{
    //declaring variables
    int budget, bet, new_budget;
    string yes_no;

    //inputting budget
    cout << "Please enter your budget: ";
    cin >> budget;

   //inputting bet
cout << "Please enter your bet: ";
cin >> bet;

//validating bet and budget
if (bet > budget)
{
    cout << "Error, bet cannot be larger than budget. Please reenter your budget and bet, respectively: ";
    cin >> budget;
    cin >> bet;
}
else //calling functions
{
    double m = sum();
    double n = bla(sum, budget, bet, new_budget);
}

//asks player if they would like play again
cout << "Would you like to play again? Enter Y for Yes or N for No";
cin >> yes_no;

//repeats program
if (yes_no == "Y" && (new_budget > 0))
{
    cout << "Please enter your budget: ";
    cin >> budget;

    cout << "Please enter your bet: ";
    cin >> bet;

    if (bet > budget)
    {
        cout << "Error, bet cannot be larger than budget. Please reenter your budget and bet, respectively: ";
        cin >> budget;
        cin >> bet;
    }
    else
    {
        int sum();
        bool win_or_loss(int sum, double budget, double bet);
    }
}

system("pause");
}

int sum() //calculates the sum of the dice
{
int x;
int y;
int sum;

x = rand() % 7;
y = rand() % 7;

sum = x + y;

cout << "The sum of the two dice is " << sum << endl;

return sum;
}

int bla(int sum, int budget, int bet, int new_budget) //calculates the new budget according to whether the player won or lost or neither
{
bool flag = false;

if ((sum == 7) || (sum == 11))
{
    cout << "You have won" << endl;
    new_budget = budget + bet;
    flag = true;
}
else if ((sum == 2) || (sum == 3) || (sum == 12))
{
    cout << "You have lost" << endl;
    new_budget = budget - bet;
    flag = false;
}
else
{
    cout << "Neither win or loss, please generate new numbers" << endl;
    int sum();
    flag = false;
}

return new_budget;
}

Comment: `int sum() { int sum; /**/ }`, Avoid to use same name for variable and function...
Comment: `bool win_or_loss(int sum, double budget, double bet);` That's not how you call a function... and `int sum();` right before it declares another function called sum taking no parameters and returning it, this is not a variable of type int.
Comment: `int sum(); bool win_or_loss(int sum, double budget, double bet);` -- Maybe you should explain what your intentions are with this code.
Comment: Please [edit] your question to provide a [mcve].
Comment: When you call `bla`: `bla(sum, budget, bet, new_budget);` you're trying to pass the `sum` function as an argument. That's what is producing the error: the compiler expects an `int` and you're giving it a pointer to a function.
Answer: int bla(int, int, int, int);

bla function expects int arguments but
double n = bla(sum, budget, bet, new_budget);

you are passing sum as a parameter which is a function. As your sum function returns an int, you can pass it as sum()
double n = bla(sum(), budget, bet, new_budget);

Side Note: Inside sum function you have declared a variable named sum. Avoid using same name for a function and a variable. It causes ambiguity.

"argument of type ”int(*)()“ is incompatible with parameter of type int" error?


Finding example of a compact metric space a non hausdorff Topological space and a continuous function that maps X onto Y

Question: This question is from my topology assignment and I am struck on it.

Give an example of a compact metric space $(X,d)$ , a topological space $(Y,\mathcal{U})$ that is not Hausdorff and a continuous function $f$ that maps $X$ onto $Y$.

Topological space can be taken $Y=\mathbb{N}$ under usual topology. But I am not able to decide $(X,d)$ as compact so that a continuous function exists.
If I take Euclidean metric $d$ then I have to take a closed and bounded subset but I am not able to then find a continuous function then.
Kindly guide!
Comment: $\Bbb N$ with the usual topology **is** Hausdorff.
Comment: Please edit your Question to clean up the wording of the title and notation, spelling, punctuation, etc. in the body.  You've asked a couple of hundred Questions here, so it's not unrealistic to expect attention to details.
Comment: Why not take any compact metric space $(X,d)$ (with more than one point) and let $Y=X$ with the trivial topology $\mathcal U=\{\emptyset,Y\}$? So $(Y,\mathcal U)$ is a non-Hausdorff topological space, and it shouldn't be hard to find a continuous function that maps $X$ onto $Y$.
Answer: HINT: You know that the continuous image of a compact space is compact, so $Y$ must be a non-Hausdorff compact space. An easy way to make sure that $Y$ is compact is to make it finite. We need at least two points in $Y$ if it is to be non-Hausdorff, so let's let $Y=\{0,1\}$ and $U=\{\varnothing,\{0\},Y\}$. $[0,1]$ is a nice compact metric space; we can try to find a continuous function $f$ mapping $[0,1]$ onto $Y$. What has to happen in order for $f$ to be continuous? We need $f^{-1}[\varnothing]$, $f^{-1}[\{0\}]$, and $f^{-1}[Y]$ to be open in $[0,1]$. Two of those are automatically true; which two? Now find a way to define $f$ so that the third is true as well and $f$ is surjective (onto), and you'll be done.
Comment: $Y$ is [Sierpinski space](https://en.wikipedia.org/wiki/Sierpi%C5%84ski_space)
Comment: @J.W.Tanner: Yep. Very useful little fellow, that space is.
Comment: I used it to answer [this question](https://math.stackexchange.com/questions/3956825/compact-subset-of-a-compact-topological-space)
Comment: @BrianM.Scott I think f(x) $\equiv 0 $ will do? Am I right
Comment: @No-One:  that's not surjective
Comment: @J.W.Tanner  Can you tell how to construct 1 such function?
Comment: @No-One: Here's a further hint: when defining $f$, consider the subsets $\left[0,\frac12\right)$ and $\left[\frac12,1\right]$ of $[0,1]$.


Question about point mass prior and continuous distribution

Question: Suppose we have a point mass prior,
$$\theta \sim \begin{cases}  I(\theta=1)  ,& prob=\frac{1}{2} \\
Gamma(c,c), & prob=\frac{1}{2} \end{cases}$$
Then if we are asked
$\lim_{c \to \infty} P(\theta=1)$
Now here is the issue, since Gamma is a continuous distribution, it seems that in the case of gamma,we will never have $\theta=1$.
To me it thus seems that regardless of the value of c, the $p(\theta=1)=\frac{1}{2}$
However, we also have that since expected value of a $gamma(a,b)=\frac{a}{b}$ so that the expected value of the gamma is 1 when we have $a=b=c$
But, by Markov, for $X \sim Gamma(c,c)$
$\lim_{c \to \infty} Pr(|X-\mu| \lt \epsilon) \to 1$ for any $\epsilon \gt 0$
So is $\lim_{c \to \infty}P(\theta=1) =1$ , or is  $\lim_{c \to \infty}P(\theta=1)=\frac{1}{2}$
As even though the markov inequality holds, it is a continous distirbution, so we will never have it exactly equal to 1.
Thanks all
Answer: Your specified prior distribution is a mixture of a continuous and discrete part.  Let $I \sim \text{Bern}(1/2)$ be the indicator that the parameter is taken from the gamma distribution.  Then using the law of total probability you have:
$$\begin{equation} \begin{aligned}
\mathbb{P}(\theta = 1|c)
&= \mathbb{P}(\theta = 1|c, I=0) \cdot \mathbb{P}(I=0) + \mathbb{P}(\theta = 1|c, I=1) \cdot \mathbb{P}(I=1) \\[6pt]
&= \frac{1}{2} \cdot \mathbb{P}(\theta = 1|c, I=0) + \frac{1}{2} \cdot \mathbb{P}(\theta = 1|c, I=1) \\[6pt]
&= \frac{1}{2} + \frac{1}{2} \cdot \mathbb{P}(\theta = 1| \theta \sim \text{Ga}(c,c)) \\[6pt]
&= \frac{1}{2}. \\[6pt]
\end{aligned} \end{equation}$$
(Note that the last step comes from recognising that the gamma is a continuous distribution, so the probability of a specific point is zero under this distribution.)  This result holds for all values of $c$, so you are correct that it also holds in the limit:
$$\lim_{c \rightarrow \infty} \mathbb{P}(\theta = 1|c) = \lim_{c \rightarrow \infty} \frac{1}{2} = \frac{1}{2}.$$
Your later use of Chebychev's inequality shows that as $c \rightarrow \infty$ you get $\theta \rightarrow 1$ (convergence in probability), but this does not change the fact that $\mathbb{P}(\theta = 1|c) = 1/2$ for all $c > 0$.  (To understand the reason for this more fully, have a read about the distinction between convergence in probability and almost-sure convergence.  Presumably the example is selected precisely to illustrate this distinction.)
Answer:
Disclaimer The above answer is completely fine if the question
is about the prior probability that $θ=1$. While there is no
indication whatsoever in the text of the question to the alternative, namely
that the question is about the posterior probability that $θ=1$, a recent
exchange with students about a very similar question in my book, The
Bayesian Choice (Exercise 5.9), leads me to propose the extension
to the posterior setting.

In this posterior case, when $X\sim \mathcal{E}(\theta)$ [for instance] the probability that $θ=1$ is
\begin{align*}
\mathbb{P}(\theta=1|x)&= \frac{e^{-x}}{e^{-x}+\int_0^\infty \theta e^{-\theta x} \pi_c(\theta)\text{d}\theta}\\
&=\frac{e^{-x}}{e^{-x}+ \int_0^\infty \theta e^{-\theta x} c^c \theta^{c-1}e^{-c \theta} \Gamma(c)^{-1}\text{d}\theta}\\
&=\frac{e^{-x}}{e^{-x}+c^c (c+x)^{-c-1} \Gamma(c+1)\Gamma(c)^{-1}}\\
&=\frac{e^{-x}}{e^{-x}+c^{c+1} (c+x)^{-c-1}}\\
&=\frac{e^{-x}}{e^{-x}+ (1+x/c)^{-c-1}}\\
\end{align*}
which converges to
$$\frac{e^{-x}}{e^{-x}+e^{-x}}=\frac{1}{2}$$
when $c$ goes to infinity.


Messing with several versions of drush

Question: When I run
drush --version

I get next output:
count(): Parameter must be an array or an object that implements     [warning]
Countable Table.php:789
 Drush Version   :  7.4.0

For getting rid of the warning, I have been told I to install drush version 8.
So I issued:
composer require drush/drush:8

giving next result:
./composer.json has been updated
Running composer update drush/drush
Loading composer repositories with package information
Updating dependencies
Nothing to modify in lock file
Installing dependencies from lock file (including require-dev)
Nothing to install, update or remove
Generating autoload files
9 packages you are using are looking for funding.
Use the `composer fund` command to find out more!

So I suppose drush was already at version 8, but issuing the command above, I still have the same result: version 7.4.0. I am probably messing with several versions of drush.
I would like to understand better how to get rid of the old version, and being sure I am using the last one.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/123460/discussion-between-pierre-francois-and-leymannx).
Answer: You are mixing up the globally installed Drush with a locally installed Drush. To run the local Drush from your project, run vendor/drush/drush/drush --version from inside your project. This will give you 8.0.0 which is a bit old. Better get the latest Drush 8 release with composer require drush/drush:^8. Currently this is Drush 8.4.8.
Next, you can consider to either update the globally installed Drush (not recommended) composer global require drush/drush:^8 or alternatively (recommended) install the Drush Launcher instead. The Drush Launcher is just a wrapper command to always pick up the project-local Drush. So you can easily run Composer-based D7 and D8/D8+ projects on the same machine in parallel and calling drush --version in a project will adjust accordingly.
If your project is D8 or D9 install Drush 10 instead composer require drush/drush.
Answer: This is how I solved my problem after trying a lot of things to upgrade composer and drush and finally crashing completely:
cd $HOME                                           # the current directory must be $HOME
rm -rf .composer                                   # remove all composer packages
curl -s https://getcomposer.org/installer | php    # install composer in $HOME
sudo mv composer.phar /usr/bin/composer            # move composer from local to global
composer -W global require drush/drush:^8.4        # install the version of drush I need

Voilà.
After this, the executable composer.phar is renamed to composer. So do not longer look at $HOME/composer.phar if you ever want to uninstall it. You will just have to delete /usr/bin/composer.
Check your $PATH: $HOME/.config/composer/vendor/bin must be included. Caution: some configurations have $HOME/.composer/vendor/bin in the $PATH variable, which is also possible, but you need to keep it coherent with the place where the packages are installed.
Comment: `~/.composer/vendor/drush/drush/drush` and I think a symlink at `~/.composer/vendor/bin/drush`. Most people add `~/.composer/vendor/bin` to their $PATH.
Comment: Where is the (global) executable of drush?
Comment: I found it in `~/.config/composer/vendor/bin` with a symlink to `../drush/drush/drush`, i.e. `~/.config/composer/vendor/drush/drush/drush`

Messing with several versions of drush


What is the volume of the largest truncated octahedron that can be inscribed in the unit sphere?

Question: If you were to maximize the volume of a truncated octahedron while keeping it in completely inside a given sphere, what percentage of the sphere's volume would it take up?
This question is an extension of a larger one I've been wondering. What is the largest space-filling polyhedron of any kind that can be inscribed in a sphere? Space-filling meaning, can perfectly tile the 3D plane in Euclidean space. Would, for example, a rhombic dodecahedron maximized in a sphere take up more space than the maximized truncated octahedron?
More concretely, imagine you have spheres of a valuable material you need to pack. You can pack them more densely by cutting them in a more packable shape, thus saving more of the material, but you lose whatever you cut off. Is there a space-filling polyhedron you could cut each sphere into that contains more than ~74.048% (maximum sphere packing density) of the original sphere?
Comment: @StinkingBishop This makes the much harder, more general problem the main focus, which was not my intention, since I think it is much less likely to be answered.
Comment: Not a problem, I just know that we have this in the policy, and I would not want you to fall afoul of it: https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question#33671
Comment: Please use the body of your Question to give a self-contained problem statement.  The title is fine as a brief notice of what the Question is about, but it should not serve as the first sentence of the body of the Question.  You know what you are asking, but the choppy jump to a new problem without stating fully the initial problem is quite confusing to Readers.  The final paragraph suggests an entirely different problem than maximizing area, namely a *volume* objective.  Multiple problems in one post are strongly discouraged; quality over quantity should be your goal.
Comment: Sorry. Rolled it back now.
Comment: @StinkingBishop Thanks! Sorry for the trouble.
Comment: @hardmath Sorry, and thank you for telling me. I hope the new revision I made is adequate.
Answer: I think the thing that you're interested in here is the covering density of the sphere, rather than its packing density - this is the lowest-density arrangement of overlapping unit spheres needed to cover every point in $\mathbb{R}^3$.
In the plane, the hexagonal lattice is optimal for both packing and covering. In three dimensions, though, they differ - the FCC lattice is best for packing, but the BCC lattice (a cubic lattice along with the centers of each cube) is the lattice offering the thinnest covering density of $\frac{5\sqrt{5}\pi}{24}\approx1.4635$. (Whether a non-lattice packing could do better is an open problem, I believe - see here.)
If you take the Voronoi cells of the BCC lattice with side length $1$, you get truncated octahedra with edge length $\sqrt{2}/4$, volume $1/2$, and circumradius $\sqrt{5}/4$, thus taking up $\frac{24}{5\sqrt5\pi} \approx 0.6833$ of the sphere, which of course ends up being the reciprocal of the covering density.
This correspondence between covering density of a sphere arrangement and relative volume of the voronoi cell means that the truncated octahedron is optimal, at least among space-filling bodies which tile by translation, and that any improvement would lead to a previously-unknown thinnest sphere covering. (The converse is not necessarily true, since the Voronoi cells of a non-lattice packing don't have to be congruent.)
For reference, though, a rhombic dodecahedron with coordinates $(\pm1,\pm1,\pm1)$ and all permutations of $(\pm2,0,0)$ has volume $16$ within a sphere of radius $2$, so occupies only $\frac{3}{2\pi}\approx0.4775$ of the circumsphere.
Comment: If I'm understanding this right, does this mean the truncated octahedron is optimal among plesiohedra, but not necessarily provenly among all space-filling polyhedra (although no better polyhedron has yet been shown to exist)?
Comment: I think it's not quite plesiohedra, which would correspond to isohedral sphere coverings (which is a superset of lattice coverings). But it is the case that no better space-filling polyhedron has been shown to exist, or it would correspond to a better (potentially non-lattice) sphere covering.
Answer: The regular truncated octahedron is an Archimedean solid; eight faces are regular hexagons and six faces are squares with common edge length $a$.  For example:

All permutations of $(0, ±1, ±2)$ are Cartesian coordinates of the vertices of a truncated octahedron of edge length $a = \sqrt 2$ centered at the origin.

The volume of this truncated octahedron of edge length $a$ is $V=8\sqrt 2 a^3 = 32$. Its circumscribing sphere has radius $\sqrt 5$, so volume $(4/3)\pi \cdot(5\sqrt 5)$.  Consequently the sphere is filled in the ratio:
$$ \frac{32}{(4/3)\pi \cdot(5\sqrt 5)} = 0.68329204... $$
For comparison the regular octahedron inscribed in the unit sphere has a volume of $4/3$, giving a filled ratio of $1/\pi \approx 0.31831$, so truncation makes quite an improvement.  Indeed the best filled ratio of a Platonic solid inscribed in a sphere is for the dodecahedron, at about $0.6649$.  See the blog post: Which Platonic Solid is Most-Spherical? which references an 1841 "Penny Cyclopaedia" printed by the Society for the Diffusion of Useful Knowledge.


Prove limit doesn't exist using epsilon-delta definition

Question: Prove $\lim_{x \to 0}\frac{x}{x-\lfloor \sin x \rfloor}$ doesn't exist.
I can prove the same claim using Heine's definition by showing that sequences $\{x_n\}=\frac{\pi}{2n}$ and $\{x_m\} = -\frac{\pi}{2m}$ converge to 0, but the values of function at these sequences diverges.
In the proof from definition I can get about this far:
Suppose the limit exists at $x_0 = 0$, then choose $\epsilon = \frac{1}{2}$ (I know this should fail because as $x$ approaches zero from left, it tends to zero and as $x$ approaches zero from right it tends to 1).  Since $x \in (-\sigma, \sigma)$ this should hold:
$$
-\frac{1}{2} < \frac{\sigma}{\sigma - \lfloor \sin \sigma \rfloor} - L < \frac{1}{2} \\
-\frac{1}{2} < \frac{-\sigma}{\lfloor -\sin \sigma \rfloor -\sigma} -L < \frac{1}{2}
$$
Here my problem starts.  I believe that from the first equation I'd need to derive that $L \geq 1$ and from the second: $L \leq 0$.  But there's no way I can get at these values.

More importantly, I'm trying to discover a general procedure for solving such questions, here's what I "discovered" so far:

Guess $\epsilon$ (by calculating several values of the function near $x_0$).
Assume $x \in (-\sigma, \sigma)$.
Write two inequalities: $-\epsilon < f(\sigma) - L < \epsilon$ and $-\epsilon < f(-\sigma) - L < \epsilon$.
Apply series of algebraic transformation to both inequalities until contradiction is apparent.
The proof is complete at this point.

Does this sound like a reasonable approach?
Comment: If you really mean $\lfloor \sin x \rfloor$, then this is fairly easy: the floor of $\sin x$ is $-1$ for $x$ close to and less than $0$ and is $0$ for $x$ close to and greater than $0$. So the left and right limits at $0$ are clearly different.
Comment: @RobArthan yes, I do mean floor. I typoed the first time I wrote it. And yes, I have all reasons to believe it should be simple, and yet I'm asking this question.
Answer: Hint: when $0 < x < \pi$, $\lfloor \sin x \rfloor = 0$, so that $\frac{x}{x - \lfloor \sin x \rfloor} = 1$. When $-\pi < x < 0$, $\lfloor \sin x \rfloor = -1$, so that $\frac{x}{x - \lfloor \sin x \rfloor} = \frac{x}{x + 1}$. Take $\epsilon = \frac{1}{2}$ (say) and see if you can find a $\delta >0$ such that when $-\delta < x < 0$, then $\left|\frac{x}{x+1}\right| < \epsilon$.
See the comments below for more on the methodological question about general procedures for solving this kind of problem.
Comment: I probably need to explain more. Since I'm just learning this, I'm struggling with finding a general procedure for solving such problems, so I would really like to either solve it using the way I stared, or to find out that the way I attempted to solve was wrong. Alternative answers, which use some unique property of this formula are great, but I would appreciate it, if the answer was dealing with the specific way of solving the problem.
Comment: The point is that the limit as you approach $0$ from the right and the limit as you approach it from the left must agree. Do you see why? So in your attempt, you can argue that $L$ must be $1$ because it must agree with the limit from the right. This will get you to the $\epsilon/\delta$ argument from "first principles" that you are after. (It will also help if you don't omit the floor function.)
Comment: I just need the very superficial, algorithmic, if you like, way to approach solving this kind of problems. I don't have a problem seeing why this limit doesn't exist. I plotted it, and made sure I completely understand how the function behaves etc. My problem is with the specific way of solving the problem, not with solving it in general (if I just wanted to solve it, I'd simply typed it into Maxima or Maple and be happy with the result).
Comment: Sorry for extensive commenting, maybe this'll explain it better. Compare these: say, you could multiply matrices by recognizing that one of the matrices is diagonalizable and so you could simply use the eignevalues for multiplication (which would be quicker), or you could ignore that fact and just do the slow-but-sure row-by-column multiplication. I'm certain there's a slow-but-sure way to solve any limit problem, and that's what I'm trying to find. (Unfortunately, my teacher and the textbooks are worthless at that).
Comment: There is no slow but sure way to solve any limit problem. That isn't just a brash claim: the first order theory of the trigonometric functions (say), (or even the theory of the real field together with the floor function, which is more relevant to your problem) can be proved to be undecidable. Going back to your question, have you tried to do what I suggested in my hint, i.e., to find a $\delta > 0$ such that when $-\delta < x < 0$, $\left|\frac{x}{x+1}\right| < 1/2$?
Comment: Yes, but that doesn't help. I need to know what and if did I do wrong.
Comment: Well, edit your question to explain what you did and why it didn't help.
Comment: To be more concrete: here you use the "trick" which allows you to avoid slow-but-sure calculation when you substitute value for $\lfloor sin x \rfloor$ because you know how the function behaves at the entire range $(-\sigma, \sigma)$, but a computer wouldn't know that and isn't allowed to assume this based on few values it can compute, thus it wouldn't be a permissible slow-but-sure approach.
Comment: As I said, the general problem is not decidable, i.e., the slow-but-sure effectively computable approach **does not exist**. Your approach may be a useful heuristic and you would get it to work in this case by doing the algebraic simplifications correctly.
Comment: Not arguing, but how do systems like Maple, Mathematica or Maxima solve limits? I'm sure they use heuristics too. But maybe there are some restrictions for the problem which make some subset of it decidable? After all, there are lots of everyday things in computer science, which are undecidable, yet they are used on a regular basis in mission-critical systems.
Comment: Sure there are lots of decidable subclasses of this kind of problem and computer algebra systems have lots of very good heuristics for calculating limits. Computer algebra systems don't produce $\epsilon/\delta$ proofs though and that is what you have been asking for. I think you might do well to ask a "soft" general question about automating $\epsilon/\delta$ proofs if that is what you are really interested in - to avoid getting bogged down in the details of this particular example.
Comment: Well, Turing's universal computation thesis implies that if someone as mathematically challenged as myself can (and is expected to) apply a procedure to solve this problem (I'm supposed to learn, i.e. to develop a pattern of dealing with similar problems!), then a digital computer should too! :) Anyways, this wasn't said in all seriousness! I very much value your time and effort you put into answering his, hence, I'll accept your answer, even though I don't feel content with it. :)
Comment: Thanks - do ask that more general question.
Answer: Why don't you use again your sequences to derive a contradiction on $L$ value?
Or other idea, do you know $\lim\limits_{x \to 0} \frac{\sin x}{x}$?
Comment: I bet I would if I knew how, but thanks for trying :)
Comment: Sorry, I just now realized I typoed when I wrote the initial formula. Sorry. And, yes, I know the limit of sine of x divided by x, but that's not really helping because I need a specific way of proving it, not just any way, and I have problems with that particular way.


Urysohn's extension theorem

Question: Currently I am working my way through Ernest Michael's first article on continuous selections. Here, Urysohn's extension theorem is stated as follows:

For a $T_1$-space, the following properties are equivalent:

$X$ is normal.
The real line $\mathbb{R}$ is an extension space with respect to X. (i.e. every continuous function $f: A \rightarrow \mathbb{R}$, with $A \subseteq X$ closed, can be extended to a continuous function $f : X \rightarrow R$).

For the proof of this theorem, the author refers to Urysohn's original article, which is written in German (which is unfortunate since I don't speak German). If I am not mistaken, both Urysohn and Tietze proved similar properties. It seems to be that the so called Tietze extension theorem and its proof are widely known.
Since I am trying to prove Urysohn's extension theorem as stated above, I was wondering what the best approach would be. Is it in any way simpler (less technical) than Tietze's extension theorem? I'd appreciate any help, whether it'd be in the form of a hint or (an initiation to) a full proof.
Comment: ??? The fact that 1 implies 2 is exactly the Tietze extension theorem proved at that place you link to. What's the problem? (It's trivial that 2 implies 1: Given disjoint closed sets $A_1$ and $A_2$ let $A=A_1\cup A_2$ and define $:A\to\Bbb R$ too equal $0$ on $A_1$ and $1$ on $A_2$...)
Comment: @DavidC.Ullrich My fault, I guess I should've read through the problem thoroughly before posting here. Now the stated Urysohn's extension theorem is "more specific" in the sense that it states the characterization of normality for $T_1$-spaces only. Since the implication of (1) by (2) doesn't use the fact that $X$ is a $T_1$-space (or am I missing something here?), it seems to be quite unnecessary to restrict the Tietze extension theorem to this specific case. This was why I was wondering if there was an alternate proof of the implication of (2) by (1), using the fact that $X$ is $T_1$.
Answer: As David C. Ullrich says in the comments, this is the Tietze extension theorem, which is also known as the Tietze-Urysohn theorem. I hadn't seen Urysohn's proof before, but I just tracked it down and took a look; he gave essentially the same proof that you've seen elsewhere. I never liked that proof, and years ago I came up with one that uses the same basic idea as the usual proof of Urysohn's lemma. (Others may also have discovered this argument, though I've not seen it elsewhere.) You can find it in 'A "More Topological" Proof of the Tietze-Urysohn Theorem', The American Mathematical Monthly, Vol. $85$, No. $3$ (Mar., $1978$), pp. $192$-$193$. It's still quite technical, but if you've worked through the proof of Urysohn's lemma, the basic structure of the argument will be familiar.
Comment: @Kaspar: The Tietze extension theorem does not require that $X$ be $T_1$. My best guess is that Michael was using the alternate terminology in which *normal* means what I would call $T_4$, meaning that it implies $T_1$. Since $(2)$ only implies that $X$ is normal in my sense (i.e., not necessarily $T_1$), to get an equivalence with normality in the stronger sense he needs to assume that the space is $T_1$.
Comment: That's interesting, I will definitely take a look at your proof! As I pointed out in the comment section, I was wondering if the fact that Urysohn originally proved the theorem for $T_1$-spaces only, would have any utility? But as far as I can tell, it was just unnecessary and the theorem stated in my question can just be generalized to all topological spaces without making the proof any harder?
Comment: That makes a lot of sense!

Urysohn's extension theorem


How to Solve this Integral $\int_{\mid x\mid =r} xdz$?

Question: This is NOT a duplicate question.
I need some help computing the integral
$\int_{\mid z\mid =r} xdz$
But I really want to use the fact that
$x=\frac{1}{2}(z + \frac {r^{2}}{{z}})$ when the circle is oriented counter-clockwise in the integral.
Should I just plug that into the integral?
I have seen the similar question to this and understand how to use parameters to get that the integral equals $r^{2}i\frac{\pi}{2}$.  However, I am interested in using the fact mentioned above, which requires a different method than the solutions already discussed on this site, so it is not a duplicate.
How would I go about this?
Comment: No it's not a duplicate. Please read what I'm asking before you jump to that.
Comment: By $x$ do you mean the real part of $z$???
Comment: Yes that is what I mean
Comment: The problem I am having is that if $x$ is the real part of $z$ and $|z|=r$, we have $x=\frac{1}{2}\left(z + \frac{r^2}{z}\right)$.
Comment: Please help. This question is not a duplicate
Comment: Note that you should have ${1 \over 2} (z + {r^2 \over z})$. You have $|z|$ in your question.
Comment: Ah, my mistake. I've fixed that.
Comment: Why is this question ignored??
Comment: Circle ? What circle ? All I see is two verticals.
Comment: Do you know how to compute $\int_\gamma {dz \over z}$?
Comment: I presume by $|x|=r$ you mean $|z|=r$?
Comment: I'm terribly sorry for not seeing that typo earlier. You are correct
Answer: $|x|=r$ is $x=-r\lor x=r$ and the integral can be translated to
$$\int_{|x|=r}x\,dz=-\int_{z=-r-i\infty}^{-r+i\infty}r\,dz+\int_{z=r-i\infty}^{r+i\infty}r\,dz,$$ assuming "counterclockwise traversal".
I guess that this can be said to equal zero in the Cauchy sense.

Assuming a typo in the problem statement,
$$\int_{|\color{red}z|=r}x\,dz=\int_{t=0}^{2\pi}r\cos(t)\,d(re^{it})=r^2\int_{t=0}^{2\pi}\cos(t)ie^{it}dt=\\r^2\int_{t=0}^{2\pi}(i\cos^2(t)-\cos(t)\sin(t))\,dt=i\pi r^2$$
by the average values of $\cos^2(t)$ and $\cos(t)\sin(t)$. The sign is positive for a counterclockwise traversal.
Comment: I would presume the OP meant $|z|=r$ for want of better notation.
Comment: @copper.hat: I raised that issue in a comment, and in the meanwhile showed that the current problem statement is absurd.
Answer: The solution depends on the tools you have. Using this fact makes me suspect that you can use the residue theorem:
$\int_{|z|=r} \Re z dz = {1\over2}\int (z+r^2/z) dz = {1\over2}(\int z dz + r^2\int z^{-1} dz) = {1\over2}(0+r^22\pi i)$
To just go ahead and just plug it into the integral by using $\Re z = {z + r^2/z\over2}$ doesn't make much sense:
$\int\Re z dz = \int{z + r^2/z\over2}dz = \int_0^{2\pi}  {re^{i\varphi}+r^2/(re^{i\varphi})\over2}ire^{i\varphi}d\varphi = \int_0^{2\pi}r{e^{i\varphi}+e^{-i\varphi}\over2}ire^{i\varphi}d\varphi = \int_0^{2\pi}r\cos(\varphi) ire^{i\varphi}d\varphi$
that is a complicated way to arrive at the same integral as if we didn't use that fact and just went ahead and evaluated the integral (and instead using the fact that $\Re re^{i\varphi} = r\cos\varphi$):
$\int\Re z dz = \int_0^{2\pi} r\cos(\varphi) ire^{i\varphi}d\varphi$
Comment: The last integral is $0$.
Comment: @YvesDaoust Yes, I missed the $\gamma'$ term, that's now corrected. The point was that you arrive at the same integral if you just plug in $\Re z={z+r^2/z\over2}$ as if you don't (except it's more work).
Comment: It would be nice if whoever voted down this explained why so I can improve the answer if there's still a problem.


how to prove $\left(\frac{n}{3}\right)^n\leq\frac{1}{3}n!$

Question: i am asked to prove this statement:

$$\left(\frac{n}{3}\right)^n\leq\frac{1}{3}n!$$

Now after several attempts, i am lost not knowing where and how to start. if I use induction, i am stuck on the way. how can i solve this in an easy way? i have huge difficulties when i have to find something which is bigger than the latter term or so, because i lack some important source of maths in my brain. i am very likely to give up on the way if it becomes tough. for any guidance how to overcome this phase i will be very very thankful. i am trying for proficiency in math. Thanks
Comment: $\left(\frac{1}{3}\right)^n \leq \frac{1}{3}$
Answer: $$\left(\frac{n}{3}\right)^n\leq\frac{n!}{3}\Longleftrightarrow X_n:=\frac{n^n}{3^{n-1}n!}\leq 1$$
But
$$\frac{X_{n+1}}{X_n}=\frac{(n+1)^{n+1}}{3^n(n+1)!}\cdot\frac{3^{n-1}n!}{n^n}=\left(1+\frac{1}{n}\right)^n\frac{1}{3}\xrightarrow [n\to\infty]{}\frac{e}{3}<1$$
So that the infinite positive series $\,\displaystyle{\sum_{n=1}^\infty X_n}\,$ converges and thus $\,X_n\xrightarrow[n\to\infty]{}0\Longrightarrow X_n<1\,$ , at least
from a certain index $\,n\,$ on.
Answer: If we consider the last term in the Taylor expansion of $e^x$, we have
$$e^x\ge\frac{x^n}{n!}$$
and let $x=n$ that yields
$$e^n\ge\frac{n^n}{n!}$$
and the conclusion follows.
Comment: This is a nice way. But the question has $3^{n-1}$
Comment: Unless you meant that for sufficently large $n$, we have $e^n<3^{n-1}$ .Nice answer +1
Comment: @Amr: this is correct. Thanks.
Answer: We would like to prove
$$\left(\frac{n}{3}\right)^n \leq \frac{1}{3}n!.$$
This is equivalent to
$$n^{n-1} \leq 3^{n-1}(n-1)!.$$
It is obviosly true for $n = 1$. However, as $n$ increases, left side rises slower that the right-hand side (thus the inequality will still hold). To put this formally, consider the ratio
$$\frac{(n+1)^{n}}{(n)^{n-1}} \leq \frac{3^{n}n!}{3^{n-1}(n-1)!} = 3n$$
which simplifies to
$$\left(\frac{n+1}{n}\right)^{n} \leq 3.$$
and is true because $\left(1+\frac1n\right)^n$ is increasing in $n$ (e.g. see this post) and converges to $e < 3$.
Cheers!
Comment: wow, amazing power of maths!! thanks a lot
Comment: @doniyor Observe that you could easily substitute 3 with $e$. Moreover with similar technique you could derive the inverse bound $\frac{1}{2}n! \leq \left(\frac{n}{2}\right)^n$. Check also the [Wikipedia](http://en.wikipedia.org/wiki/Factorial).
Answer: Using logarithms, the inequality $ \left( \frac{n}{3} \right)^n \leq \frac{1}{3} n!$ is equivalent to $\sum\limits_{k=1}^{n-1} \ln \left( \frac{3k}{n} \right) \geq 0$. But $$\sum\limits_{k=1}^{n-1} \ln \left( \frac{3k}{n} \right) \geq 1+ \int_1^{n-1} \ln \left( \frac{3x}{n} \right) dx = 1+ (n-1) \ln \left( \frac{3(n-1)}{ne} \right) >0$$ for $n >5$.
Answer: First we'll prove that
$(\frac{k+1}{3})^k\leq k!\Leftrightarrow (k+1)^k\leq 3^k k!$
base of the induction:
for $k=0$ it is true
If it's true for $k$ we'll prove it is true for $k+1$: that is $3^{k+1}(k+1)!\geq (k+2)^{k+1}$.
$3^{k+1}(k+1)!=3(k+1)3^{k}k!\geq 3(k+1)(k+1)^k=3(k+1)^{k+1}\geq (k+2)^{k+1}$.
Since $3(k+1)^{k+1}\geq (k+2)^{k+1}\Leftrightarrow log 3(k+1)^{k+1}\geq log (k+2)^{k+1} \Leftrightarrow (k+1)log 3(k+1)\geq (k+1) log(k+2)\Leftrightarrow  log\frac{3k+3}{k+2}\geq 0$.
which is true
For the main conclusion now:
For $n=0$  it is true.
suppose it is true for $n=k$
$(\frac{k}{3})^k\leq \frac{1}{3}k!$
we'll prove it is true for $n=k+1$
$(\frac{k+1}{3})^{k+1}=(\frac{k+1}{3})^k\cdot\frac{k+1}{3}\leq k!\cdot \frac{1}{3} (k+1) =\frac{1}{3}(k+1)! $
By induction it is true for all $n\in\mathbb{N}$.
Comment: $(\frac{k+1}{3})^k\cdot\frac{k+1}{3}\leq (\frac{k}{3})^k\cdot\frac{k+1}{3}$? Am I missing something?
Comment: I think all the details are ok now... I really needed that cup of coffee