Divisibility in complex numbers

Question: I'm wondering if the concept of "divisibility" also works in complex numbers.
For example, if I say $a+bi$ is divisible by $c+di$. Does this mean that there exists another complex number $\alpha+\beta i$ such that $$\begin{align*}
(c+di)(\alpha+\beta i)=a+bi
\end{align*}$$If this is true, can I say that $5i$ is divisible by $5$ and is divisible by $i$ since $$\begin{align*}
5i=(5+0i)(0+i)
\end{align*}$$
Comment: This could make sense if we assume that all numbers appearing are integers , otherwise there is always such a complex number unless $c+di=0$
Comment: The definition of divisibility clearly  [works in any monoid](https://math.stackexchange.com/a/3576252/242), and many divisibility properties are purely multiplicative and can be studied at the monoid level.
Comment: For $~0 + i(0) \neq z = x + iy, ~x,y \in \Bbb{R},~$ let $~\overline{z}~$ denote $~x - iy,~$ and let $~|z|~$ denote $~\displaystyle \sqrt{x^2 + y^2}.~$  Then, at first glance, your divisibility question becomes trivial because, given any $~w \in \Bbb{C},~$ you have that $$\frac{w}{z} = \frac{w \times \overline{z}}{|z|^2} \implies w = \frac{w \times \overline{z}}{|z|^2} \times z.$$
Comment: The method in the prior comment (viewable similarly to rationalizing the denominator) works for division by any algebraic number - as explained at lenght [here](https://math.stackexchange.com/a/100201/242).
Answer: You certainly can do this. You can do this in any situation where multiplication makes sense -- although you have to watch out that in other settings, divisibility might not work the way you're used to.
If you use this definition for all complex numbers, you get something very boring: every complex number $z$ is divisible by every non-zero complex number $a$ because
$$
z = \frac za \times a.
$$
(You get something equally boring if you use all real numbers.)
However, if you limit yourself to complex numbers $a + bi$ where $a, b$ are integers, you get the Gaussian integers, and there divisiblity is certainly interesting.
Comment: Gaussian integers are fun.  When I first saw them, I noticed that $10 = (3 + i)(3 - i)$ and I thought "factorization is not unique".  Actually it is (in a sense) but $2$ is not prime in this context as $2 = (1 + i)(1 - i)$.  Similarly, $5$, $3 + i$, and $3 - i$ are not prime either.
Comment: related: [this answer to *determining if a coincident point in a pair of rotated hexagonal lattices is closest to the origin?*](https://math.stackexchange.com/a/3829536/284619) and [How did Gaussian and Eisenstein integers get their names?](https://hsm.stackexchange.com/q/12560/3869)

Divisibility in complex numbers


Show that $A \in \mathbb C^{n \times n}$ is diagonalizable and has real eigenvalues if and only if $A=BC$ where $B \succ 0$ and $C$ is Hermitian.

Question: Here's my work so far.
($\Leftarrow$)
Since $B \succ 0$ we know $B^{1/2} \succ 0$ (and $B^{-1/2}$ exists).  Then
$A=BC=B^{1/2}(B^{1/2}CB^{1/2})B^{-1/2}$
so $BC$ is similar to $B^{1/2}CB^{1/2}$ which implies they have the same eigenvalues. Then
$(B^{1/2}CB^{1/2})^*=(B^{1/2})^*C^*(B^{1/2})^*=B^{1/2}CB^{1/2}$        (Since $B$ and $C$ are both Hermitian)
$\Rightarrow B^{1/2}CB^{1/2}$ is diagonalizable $\Rightarrow BC$ is diagonalizable $\Rightarrow A$ is diagonalizable.
The only issue I'm having is showing that A has all real eigenvalues.  I'm not really sure where to start for that.
($\Rightarrow$)
I really don't know where to start with this direction.  Since $A$ is diagonalizable I write $A=PDP^{-1}$ where $D$ is a diagonal matrix.  My professor gave me a hint to use the fact that since $P$ is non-singular we know that $PP^* \succ 0$, but I don't really know where to take it from there.
Answer:
You proved that $B^{1/2} C B^{1/2}$ is hermitian. So its eigenvalues are real.
$A$ being similar to $B^{1/2} C B^{1/2}$ implies that the eigenvalues of $A$ are real.
$A = P D P^{-1} = P P^{*} ( P^{-*} D P^{-1} )$. So $B = P P^{*}$ and $C = P^{-*} D P^{-1}$.


Is there a piano method that uses movable Do when the students are learning tunes/pieces?

Question: Is there a piano method that uses movable Do when the students are learning tunes/pieces?
Most of the time, in my experience, teachers never really use the movable Do system when teaching new tunes/pieces. If a tune is in A major the note B is never really refered to as Re.
Comment: NNS uses a similar system, but numbers not solfege, for chords and single notes. A comment, as it's not exactly what the question asks, but related.
Comment: 'In my experience...' - what is your experience - what part of the world did you learn in? Have you had piano lessons? To what extent? For me at least, these factors give some foundation on which to build answers that will be relevant.
Comment: I have taken piano lessons in Scandinavia.
Answer: I always used this method  when sight reading and analyzing a piece, or when transposing it in (all) other keys to test whether I have learnt it and really understood it.
I also apply this method when reading orchestra scores, and also  when I play with the right hand a Bb-instrument - accompanying myself with the left hand on the piano.
Play and learn in moveable Do makes a lot of sense and is very benefit for beginners. When teaching keyboard in groups and in singing classes I dictated a song in movable Do and  asked the children to notate it in C, F or G major. (of course very simple tunes like e.g. the choral of Beethoven's 9th symphony.
Answer: Not exactly the same thing, but years ago I helped develop a software course (for all instruments, not specifically piano) that used movable Do for developing improvisational skills.
It was called Improvisation By Degrees and it used movable Do to help students learn and think of musical phrases in different modes.
For example, if you're in A major, and the harmony has a B minor chord, you treat a B note as Re, and from there (wherever the B note is, that's Re) you can improvise up and down from that point thinking in terms of Do Re Mi and their relative intervals.
Obviously this is a sort of crutch initially, but with practice one doesn't need to think consciously and explicitly in terms of movable Do, it sort of becomes instinctive, guided by your ear rather than by an intellectual process.
Answer: I don't know if they still use it but when I learned sight singing at Berklee College of Music a few decades ago we learned a moveable Do system. There were specific syllables for notes that were out of the major scale, for example, Mi is a major 3rd, Me (pronounced may) is a minor 3rd. I personally liked this system where Do was always the tonic regardless of the key. I find it helped develop a good ear for learning intervals.
Comment: The word me in English is pronounced the same as the solfege note mi. The point was to have a distinction in pronunciation between different intervals.I speak fluent Spanish and me sounds different in Spanish than in English but we are discussing this in English so I am trying to answer in a way that is understood in that language.
Comment: The point is that every interval had its own specific pronunciation, which I thought was a great idea. Even enharmoníc notes like #4 and b5 were different. The problem with the English language is someone decided it was a good idea for vowels to have 3 or 4 different pronunciations. lol!
Comment: Why should me be pronounced like "may"? Shouldn't it be pronounced like "me"? I always say "me". I would never want to sound like an Englishman in this case. Perhaps English speaking people often cannot say "me" but as a Scandinavian I can.
Comment: ok I understand


Delete state from redux using createSlice

Question: I have a reducer 'setOrder' that sets the initial state of 'order', however, I now want to create a reducer that deletes 'order' from the initial state. How would I go about doing this?
<code>    const checkoutSlice = createSlice({
      name: 'checkout',
      initialState: {
        customer: {
          firstName: '',
          lastName: ''
        },
        order: {
          wardrobeSize: ''
        }
      },

      reducers: {
        setCustomer(state, { payload }) {
          state.customer = payload;
        },

        setOrder(state, { payload }) {
          state.order = payload;
        }
      },
      extraReducers: hydrateServerToClient('checkout')
    });

    export const { setCustomer, setOrder } = checkoutSlice.actions;

    export default checkoutSlice.reducer;
</code>
Answer: I'd suggest just assigning an empty object to it as:
<code>emptyOrder(state) {
  state.order = {};
}
</code>


Como configurar o phpunit com Scrutinizer?

Question: Seguindo a documento do Scrutinizer realizei a criação do arquivo .scrutinizer.yml no projeto em PHP. Analisando outros sites cheguei ao resultado final do arquivo demonstrado abaixo:
build:
  environment:
    php:
      version: 7.2
  nodes:
    coverage:
      tests:
        before:
          - "cp .env.example .env"
          - "echo 'END_POINT =your_webhook' > .env"
        override:
          - command: 'php ./vendor/bin/phpunit'
            coverage:
              file: 'phpunit.xml'
              format: 'php-clover'

filter:
  paths:
    - 'src/*'
  excluded_paths:
    - 'vendor/*'
    - 'tests/*'

Esta é minha primeira experiência com o Scrutinizer. Isso significa que o resultado final deste arquivo está mais para tentativa e erro do uma ação consciente para cada linha de configuração colocada arquivo.
Como podem ver realizei algumas especificações no arquivo, como:

Indicar a versão do php usada no projeto.
A necessidade de existir um arquivo .env e criação de uma variável local porque utilizo nos testes
O comando para rodar o teste php ./vendor/bin/phpunit
O arquivo de configuração do phpunit phpunit.xml - Não sei porque ter isso na verdade.
E o formato do teste php-clover. Não sei pra que serve isso.

No decorrer da execução do Scrutinizer é rodado todos os testes com sucesso, mas a opção .
O que está faltando fazer para funcionar?
Obs.: Coloquei todas as informações que considerei úteis, mas se precisar de mais detalhes vou adicionando conforme pedirem.
Answer: Vamos lá, iremos utilizar como ponto de partida que sua máquina tenha a versão php7.2 com o xdebug instalado e configurado. Ao digitar o comando php -v a saída no terminal será semelhante a esta:
PHP 7.2.11-1+ubuntu18.04.1+deb.sury.org+1 (cli) (built: Oct 24 2019 18:23:23) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.11, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.3.11-1+ubuntu18.04.1+deb.sury.org+1, Copyright (c) 1999-2018, by Zend Technologies
    with Xdebug v2.8.0, Copyright (c) 2002-2019, by Derick Rethans

Antes ainda de fazer o Scrutinizer funcionar. Será preciso fazer os testes funcionarem, então:

Instale o phpunit via composer. Veja a versão do phpunit a ser utilizado de acordo com a versão dos seu php.

  "require-dev": {
    "phpunit/phpunit": "8.0.*",
    "mockery/mockery": "0.9.*"
  },

Configure seu arquivo phpunit.xml.

    <?xml version="1.0" encoding="UTF-8"?>
    <phpunit
            backupGlobals="false"
            backupStaticAttributes="false"
            bootstrap="tests/bootstrap.php"
            colors="true"
            convertErrorsToExceptions="true"
            convertNoticesToExceptions="false"
            convertWarningsToExceptions="true"
            processIsolation="false"
            stopOnFailure="false"
    >
        <testsuites>
            <testsuite name="Package Test Suite">
                <directory suffix=".php">tests</directory>
            </testsuite>
        </testsuites>
    </phpunit>

Tenha seu arquivo bootstrap configurado sua pasta de teste na raiz do projeto, por ex: test/bootstrap.php. Caso não tenha muitas configurações a serem feitas ou nenhuma um simples arquivo como demonstrado abaixo será o suficiente

 <?php
  if (!defined('ROOT_DIR')) {
      define('ROOT_DIR', __DIR__);
  }
  require_once __DIR__ . '/../vendor/autoload.php';

Crie e rode seus testes unitários. Nenhum dos passos descritos aqui é mais importante do este rsrsrs

Para analisar a cobertura de código algumas configurações ainda são necessárias.

Em seu arquivo phpunit.xml adicione as configurações whitelist e logging.

    <filter>
        <whitelist>
            <directory suffix=".php">src/</directory>
        </whitelist>
    </filter>
    <logging>
        <log type="coverage-html" target="target/coverage.html" lowUpperBound="35" highLowerBound="70" />
        <log type="coverage-clover" target="target/coverage.xml"/>
        <log type="coverage-text" target="target/coverage.txt"/>
    </logging>

Crie na raiz do projeto a pasta target/. Essa pasta servirá para armazenar os arquivos configurados em logging no arquivo phpunit.xml gerados na cobertura de código. Não esqueça de adicionar essa pasta no arquivo .gitignore. Não precisa commitar ela.
Para facilitar sua vida. Crie os scripts no arquivo composer.json para não precisar lembrar do comando toda hora. No caso, temos dois scripts. Um para rodar os testes normais e o outro para rodar os teste de coverage.

  "scripts": {
    "test": "php ./vendor/phpunit/phpunit/phpunit --bootstrap ./tests/bootstrap.php --configuration ./phpunit.xml",
    "test-coverage": "php ./vendor/phpunit/phpunit/phpunit --bootstrap ./tests/bootstrap.php --configuration ./phpunit.xml --coverage-clover ./target/coverage.xml",
  }

Agora sim chegamos onde queremos. Para configurar o Scrutinizer:

Faça o login com git ou bitbucket
Crie o arquivo .scrutinizer.yml na raiz do seu projeto e adicione as configurações necessárias. Links que te ajudaram: melhores práticas, estrutura geral do arquivo .yml, cobertura de código. Seguem um arquivo de exemplo:

  build:
    environment:
      php:
        version: 7.2
    nodes:
      coverage:
        tests:
          override:
            - command: 'php ./vendor/phpunit/phpunit/phpunit --bootstrap ./tests/bootstrap.php --configuration ./phpunit.xml'
              coverage:
                file: './target/coverage.xml'
                format: 'clover'

  filter:
    paths:
      - 'src/*'
    excluded_paths:
      - 'vendor/*'
      - 'tests/*'

No arquivo .scrutinizer.yml repasso algumas configurações, como:

A versão do php que os testes devem rodar
O comando a ser rodado
O arquivo ./target/coverage.xml que o Scrutinizer irá utilizar ler as informações de cobertura de código
O formato do teste utilizado clover
As pasta que o coverage rodou src/*
E as pastas que o Scrutinizer não deve levar em consideração referente ao coverage vendor/* e tests/*

Segue também um projeto de exemplo para ver na prática.


error while using @Valid in spring mvc 3.0

Question: here what i do in a model class
<code>private Integer height;

@NotBlank
@Length(min = 2, max = 3)
public Integer getHeight() {
    return height;
}

public void setHeight(Integer height) {
    this.height = height;
}
</code>
but there is a validation error in the jsp page while running, it says that cannot validate the integer value.
in the message.properties file

NotBlank.modelClassName.height=Required in cm.
  Length.modelClassName.height=min {0} max (1).
  typeMismatch.modelClassName.height=numbers only.

help me please
Comment: what exactly does it say? what's the message? Is there any stacktrace. Which version of hibernate validator (or which jsr 303 provider) ?
Comment: ok tell me how i validate an integer value in spring which is inputted from jsp page.
Answer: Both annotations @NotBlank and @Length must be applied to an String attribute not to an Integer one, as it is stated in the links. Maybe you can use @NotNull, @Min or @Max that could be used for numbers.


How would I make this program two players in python?

Question: Could anyone help me on how to change this program so that 2 players can play it?
Define a procedure to simulate the dice throw
def dice(sides):
# Get a random number between 1 and 6
    throw=random.randint(1,6)
    print("score",throw)
    return throw
#Welcome messages
print("Snakes and ladders")
#Main program for the game
Player1=input("What is the name of player 1? ")
import random
position=0
#eeping it all in a loop will allow the players to keep rolling the dice until the game has finished
while position<49:
    throw=input("Roll the dice")
    dice1=dice(6)
    dice2=dice(6)
    total=dice1+dice2
#If the total of the dice thrown is not a double the player will move the total numbers of squares
    if dice1!=dice2:
        print("You are now on space", position+total)
        position=total+position
    if position>=49:
        print("You have won")
        if position<=0:
            print("You are on square 0")
#Now I will check to see if the player has rolled a double
    if dice1==dice2:
        print("This is a double you will now move back",total,"spaces")
        if position<=0:
                print("You are on space 0")
        else:
                print("You are now on space", position-total)
#This means that if the vaule of dice1 is the same as dice2 then it will move back and if not it will move forward

Comment: Welcome to Stack Overflow! Please take the [tour](https://stackoverflow.com/tour), have a look around, and read through the [help center](https://stackoverflow.com/help), in particular [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) and [What topics can I ask about here?](https://stackoverflow.com/help/on-topic). From that second link: "Questions asking for homework help must include a summary of the work you've done so far to solve the problem, and a description of the difficulty you are having solving it."
Answer: You could learn a lot by implementing this code using classes.
As far as keeping the code as similar as possible to the one you are using, there are many ways in which you could add a second player.
You could for example add another variable position_p2 to store player 2's position, and repeat the same check you do for player one on player2, as follows:
def dice(sides): # NOTE function names should start with verbs, e.g. roll_dice
# Get a random number between 1 and 6
    throw=random.randint(1,6)
    print("score",throw)
    return throw
#Welcome messages
print("Snakes and ladders")
#Main program for the game
Player1=input("What is the name of player 1? ") #NOTE variables should be lower case

# Ask player2 for it's name
player2 = input("What is the name of player 2? ")
import random #NOTE imports should go at the beggining of the script
position_p1=0 # rename so that is easy to remember that it refers to p1
# store p2 position
positoin_p2 = 0
#eeping it all in a loop will allow the players to keep rolling the dice until the game has finished
while position<49:
    throw_p1=input("Player 1: roll the dice") #same as above
    dice1=dice(6)
    dice2=dice(6)
    total=dice1+dice2
#If the total of the dice thrown is not a double the player will move the total numbers of squares
    if dice1!=dice2:
        position_p1=total+position_p1 # you can use position_p1 += total
        print("You are now on space", position_p1)

    if position_p1>=49:
        print("Player 1 won") # Change so that you know which player has won
        if position_p1<=0:
            print("You are on square 0")
#Now I will check to see if the player has rolled a double
    if dice1==dice2:
        print("This is a double you will now move back",total,"spaces")
    position_p1 -= total
        if position_p1<=0:
                print("You are on space 0")
        else:
                print("You are now on space", position_p1)
#This means that if the vaule of dice1 is the same as dice2 then it will move back and if not it will move forward

    throw_p2=input("Player 2: roll the dice")
    dice1=dice(6)
    dice2=dice(6)
    total=dice1+dice2
#If the total of the dice thrown is not a double the player will move the total numbers of squares
    if dice1!=dice2:
        position_p2=total+position_p2 # you can use position_p1 += total
        print("You are now on space", position_p2)

    if position_p2>=49:
        print("Player 2 won") # Change so that you nkow which player has won
        if position_p2<=0:
            print("You are on square 0")
#Now I will check to see if the player has rolled a double
    if dice1==dice2:
        print("This is a double you will now move back",total,"spaces")
    position_p2 -= total
        if position_p2<=0:
                print("You are on space 0")
        else:
                print("You are now on space", position_p2)
#This means that if the vaule of dice1 is the same as dice2 then it will move back and if not it will move forward

This is not the best way to do this, but it should work and it is similar to the code you posted. If you want to improve the code you can try and put the parts that are the same for the 2 players in a function. You could also store player positions in a dictionary so that you can extend the game to n players. If you want to practice you can make a class for each thing in your game (the game itself, the player etc.). THen there are a bunch of other things you could do but start with some simple generalizations, like making it for n players.


Finding out if panelizer displays are in use

Question: Does Drupal keep track of exactly where panelizer display(s) are in use? Basically, I would like to identify all pages across content types that use a particular display.
Is this information stored? Is there a way to get it programmatically or via the UI?
Comment: I am just guessing but did you try check output of http://api.drupal.org/api/drupal/includes!theme.inc/function/theme_get_registry/7 ?
Comment: If you have admin_devel module enabled, there is a very helpful theme registry viewer at devel/theme/registry. otherwise, I'd look for hook_theme_registry_alter (not sure is that what you really need though)
Comment: I am able to look through the theme registry but I don't see that it has the info I'm seeking. When I browse it, I see that my template name is in the array but the only info for it is variables, path to template, name, file, type, includes, process and preprocess functions. No paths or page names where it's invoked.
Answer: This info is not saved in the theme registry, and it's not really available per page or per node. However, it is stored per configured Panels display. Many don't have a title but since I'm using Panelizer, they do have a Panels display ID. Here's a query that returns those:
select did, title from panels_display where layout = 'mytemplate';

Entity IDs correspond to DIDs in the panelizer_entity table. Once you have queried for the DID you can query for the entity ID using the DID, like so:
select entity_id from panelizer_entity where did = 1234;

Where you replace '1234' with the DID you got from the previous query.
I have to do that second one for each DID that the first one returns in order to find all entities using mytemplate.


Upload large files using aws sdk multipart upload

Question: While I am trying to upload a large file using the high level API code provided on the AWS site using the AWS SDK I am unable to do so and the application stops with unexpected error although I have provided the right parameters.
This is my code:
<code>static string existingBucketName = "xxxxxxxxxxxxxxxx";
static string keyName            = "filename";
static string filePath           = "D:\file.txt";

try
{
    TransferUtility fileTransferUtility = new TransferUtility(new AmazonS3Client(Amazon.RegionEndpoint.USEast1));

    TransferUtilityUploadRequest fileTransferUtilityRequest = new TransferUtilityUploadRequest
    {
        BucketName = existingBucketName,
        FilePath = filePath,
        StorageClass = S3StorageClass.ReducedRedundancy,
        PartSize = 6291456, // 6 MB.
        Key = keyName,
        CannedACL = S3CannedACL.PublicRead
    };

    fileTransferUtilityRequest.Metadata.Add("param1", "Value1");
    fileTransferUtilityRequest.Metadata.Add("param2", "Value2");
    fileTransferUtility.Upload(fileTransferUtilityRequest);
    Console.WriteLine("Upload 4 completed");
}
catch (AmazonS3Exception s3Exception)
{
    Console.WriteLine(s3Exception.Message, s3Exception.InnerException);
}
</code>
The same file when uploaded with low level API gets uploaded without error but takes lot of time . So I was hoping that the high level API might get it uploaded faster. Or is there any other method for uploading large files using the SDK?
Answer: Just needed to upgrade my app from .Net version 4.0 to .Net version 4.5 and it works.


unable to create new mailboxes on Exchange 2010 after resetting DNS permissions in the domain controller

Question: I have exchange 2010 and a couple of domain controllers. I retested the permissions in AD and DNS (very brilliant thing to do, indeed.. just mocking), we are no longer able to manage exchange server, neither able to add any new mailboxes, error is as follows: Active directory response: 00002098: SecErr: DSID-03150E49, problem 4003 (INSUFF_ACCESS_RIGHTS)
I no longer see any security groups for excahnge anywhere in the domain controllers. What can I do to restore the correct permissions?
Comment: Give us some details on exactly what you did that caused this problem.
Comment: But the Exchange Schema is still in place... means Exchange is working fine?
Comment: yes, it works fine.. rather the issue is that no one can create a mailbox..
Comment: Joe, wt details do u need?
Comment: What permissions did you change and where did you change them from?
Answer: Well, any details about "resetting the permissions in AD and DNS"?
It's helpful for troubleshooting, or test it in lab to fix it.
Normally, we can re-run Exchange installation with ".\setup /Preparead" only to prepare AD object, not install Exchange server.
Answer: setup /adprep doesn't work. SP version in Exchange server 2010 installation media is different. In my case, setup /adprep will never work because I have already updated my servers to SP3.
To make a long story short, I did the following:
1. setup /PrepareLegacyExchangePermissions from Exchange Server 2010 installation media.
2. Under "Active Directory Users and Computers", expand System container, right click for properties on AdminSDHolder, go to Security tab, click Advanced, click "Enable Inheritance".
and that's it. I am happy to find out that it is possible to clean the rubbish caused by others, finally!!
P.S. Enable Inheritance was required because, under many circumstances after getting Exchange Server 2003/7 upgraded to 2010, permissions had to be applied not just "on this object only", rather on all descendants as well.


Distribution of p-values from scipy ks-test

Question: I wast trying to understand how kstest works using scipy. I generated chi2 random variables and then checked if the values follow the chi2 distribution. The codes are shown below.
from scipy import stats
pl = []
for i in range(1000):
    pl.append(stats.kstest(stats.chi2(1).rvs(size=20000), stats.chi2(1).cdf))
plt.hist(pl[1], bins=20)
plt.show()

I expected that the p value would be distributed continuously between 0 and 1. But as you can see in the figure, this is not the case.

Is something wrong with my test codes, or could you please explain why the p-value distribution is not uniform nor continuous?
Comment: Your histogram indicates there are only two data points. This is likely because when you ask to plot the histogram for `pl[1]`, you are actually plotting the tuple returned from the second call to `stats.kstest` in the loop (which is the test statistic and p-value), rather than all 1000 p-values.
Comment: @B.Liu You're right! Now the distribution looks uniform. When write this comment as an answer, then I would select that. Thank you.
Answer: (Expanded from initial comment) Your histogram indicates there are only two data points.
This is because when you plot the histogram for pl[1], you are actually plotting the tuple returned from the second call to stats.kstest() in the for loop (which contains the test statistic and p-value of the second K-S test), rather than all 1000 p-values.
To plot all 1000 p-values, you can modify the code snippet to the following:
from scipy import stats
from matplotlib import pyplot as plt

pl = []
for i in range(1000):
    pl.append(stats.kstest(stats.chi2(1).rvs(size=20000), stats.chi2(1).cdf)[1])
plt.hist(pl, bins=20)
plt.show()

which moves the [1] from the plt.hist line to the pl.append line.
On my first run of the code above I obtained the following histogram:

... which demonstrates a sort-of uniform shape as expected.


probability of frog moving exactly 6 meters away

Question: A confused frog has lost its way. Every 10 seconds it decides where to turn to. With probability $\frac{1}{3} $ it jumps one meter to the right, with probability $\frac{1} {3}$it jumps on meter to the left, otherwise it says in its place. Assume that all decisions are mutually independent. Find the probability that after 1 minute and 40 seconds the frog will be at the distance of exactly 6 meters from its initial location.
The way I approach this problem is that I see in the time there can be 10 jumps, and to be 6 meters to one direction, there are 6 possibilities, either 2 jumps to the left and 8 to the right, 1 to the left, 2 pauses and 7 to the right, or 4 pauses and 6 to the left. All of this can be for the opposite directions as well. With each jump being a 1/3 probability, of going in a certain direction the total probability of being exactly 6 meters away would be
$$ (6) \times \left( \frac{1}{3}\right)^{\!10} $$
Is this right?
Comment: I suggest you check this logic on a much smaller problem where you can write out all the possible sequences of jumps and count the ones that succeed. Perhaps four jumps with a goal of landing two meters away.
Answer: That is close, but you have to account for the number of ways each of those different possibilities can occur. Two jumps to the left and eight to the right can occur in ${10\choose{2}} = 45$ ways. 4 pauses and 6 to the left can happen in ${10\choose{4}} = 210$ ways. For 1 to the right, 2 pauses and 7 to the left, there are ${10\choose{3}}$ ways to order the left jumps, and then ${3\choose{2}}$ ways to order the other three jumps, giving ${10\choose{3}}{3\choose{2}} = 360$ ways. So there are 615 ways to end up 6 meters to the left and thus 1230 ways to end up 6 meters away. So the answer is $1230\times(\frac13)^{10}$
Answer: It's not right.
Guide:
You forgot to take order of action into considerations. For example, if we know that there are $2$ jumps to the left and $8$ to the right. We will have to decide when to make the left jump and when to make the right jump. There are $\binom{10}2$ such choices.
Take order of actions into consideration for the other possibilities as well.


Locally compact allows shrinking compact neighborhood without hausdorff property?

Question: Let $X,Y$ be topological space and $Y$ locally compact. Define $\alpha$ relation on $X$. Consider identity relation on $Y$.(i.e. $Y/1=Y$.)
Let $T\subset X\times Y/(\alpha\times 1)$ be open. Then $T'$ preimage of $T$ in $X\times Y$ is product of open sets $U\times V$ with open sets $U\subset X,V\subset Y$. Then the book claims we can assume $V$ to be compact set.
$\textbf{Q:}$ How can one assume $V$ to be compact? Normally, I knew there is a $V'$ smaller neighborhood of $V$ contained in $K$ with $K$ compact by $Y$ locally compact. However, I need to trim down this $\bar{V'}\subset V$ to reduce $K$ to $\bar{V'}$. This is achieved by $Y$ hausdorff property.
Ref. Pg 2 Algebraic Topology Switzer
Comment: Switzer is not very explicit in Chapter 0. I believe he assumes that locally compact includes Hausdorff. However, for general topological spaces the only **reasonable** definition of local compactness is that of your first comment. Using this definition, the statement remains true. Try to adapt the proof!
Comment: Let us reformulate what Switzer says: If $p : X \to X'$ is a quotient map and $Y$ is locally compact, then $p \times id_Y : X \times Y \to X' \times Y$ is a quotient map. Now what is your question? Whether this is true for non-Hausdorff $Y$? If so, what is your definition of locally compact?
Comment: @PaulFrost The main problem I have is that I do not know which definition of locally compactness is being used here. I knew several of them. However, I am guessing he is using the one saying every open neighborhood contains a compact neighborhood.
Comment: @PaulFrost The other question is how to deduce shrinking $K$ to a smaller one without hausdorff property if I am assuming standard definition(i.e. There is a neighborhood contained in a compact set.)
Comment: @PaulFrost Ah in that case, then trimming down procedure is trivial and that 2 definitions are equivalent. Thanks for clarification.
Comment: I suggest that you write a short answer and also accept it. This makes it visible at first glance that the question is no onger open,
Answer: It suffices to demonstrate 2 definitions of local compactness are equivalent under assumption of hausdorff property.
(a) Every open neighbourhood has a compact neighborhood(i.e. $\forall U,\exists K\subset U$ with $U$ open and $K$ compact.)
(b) For every point there is a compact set containing an open set.
Clearly $a)\implies b)$. It suffices to deal with converse implication.
Take $U\subset K$. It suffices to produce $\bar{W}\subset U$ with $\bar{W}$ compact. Now consider $\partial U\subset K$ is compact by $K$ compact. Use hausdorff property to find a open set $V$ disjoint from $\partial U$'s covering and containing a point $x\in U$. Here we need to use compactness of $\partial U$ to ensure finite intersection. Now $W=U\cap V$ is an open set containing $x$. Note that $\bar{W}\neq K$ for sure as we have removed $\partial U$. So we have found $\bar{W}$ compact neighborhood contained in $U$.
The general case can be handled similarly.


How to find important features in this problem

Question: I was just thinking how ML techniques can be applied in the retail industry. Suppose we have data from a retailer who deals with apparel and cloth in this format
and for each item there are pre-defined features, for example a shirt will have features like color, half/full sleeves etc.. I want to understand how to extract important features of "most sold items" from this data. For example if I find that shirts are the most commonly sold item, then which kind of shirt : Black in color, Half Sleeves, etc...
I was thinking to use decision trees here. I am not sure if this is a good approach.
Comment: Hi Amit; I made a couple of edits to clarify your post, but I was not sure what to do with "apparel and cloths", which in this context might be "apparel and cloth" (cloth being a mass noun, doesn't gain a plural in this context, in the same way that 'rice' doesn't), or it might perhaps have been intended as "apparel and clothing". I assumed the first, but please alter it if I misunderstood.
Comment: Why do you need such a model?  I ask this because many shops now lack diversity, probably since they use some statistical methods to determine the most commonly sold items and then sell only these items. As a result, the market immediately becomes oversaturated with these items.
Answer: Lasso seems like it would be good.  Lasso (Least Absolute Shrinkage and Selection Operator) is like OLS, but it penalizes the "length" of the final coefficients by including a "regularizer" term.
The actual paper is Tibshirani (1996).
The Lasso package and demo in R is http://cran.r-project.org/web/packages/genlasso/vignettes/article.
The lasso is great because it penalizes a large number of coefficients to be exactly zero, and you can adjust the tuning parameter to see what drops out first and stays as you become more strict about learning relevant features.
EDIT:
But as the commenter said, be careful of what you are actually learn from a model.   Additionally, if you are a larger firm and begin to change your production...be aware of https://en.wikipedia.org/wiki/Campbell%27s_law
Answer: Just get the data, decide how you want to define feature groups (colours per shirt type, or shirt type seperately, colors seperately, etc' ) and encode thema s features using sci-kit learn.
http://scikit-learn.org/stable/modules/preprocessing.html#encoding-categorical-features


Error when trying to set Grid.Background to accent colour

Question: In my application the user can choose what colour they would like a particular feature of the app to be.
They can choose from a variety of colours which works fine, however when trying to set the Grid's background to the accent colours; when chosen, a NullReferenceException was unhandled error appears.
The code I am using is:
Color accentColour = (Color)Application.Current.Resources["PhoneAccentColor"];
gridColour.Background = new SolidColorBrush(accentColour);

Anyone know what I am doing wrong? (I've also tried using a Rectangle and it's .Fill property).
Thanks.
[SOLVED: Post solved in comments.]
Comment: Are you running this code at startup?  The only thing I can think of is that the app resources haven't loaded yet ...
Comment: That was why, there was a check box where the user could choose a colour for an in-app feature. The grid is just a graphical display to show the user the selected colour. However by default the checkbox was already checked so the Checked event was triggered too early on in the process; before the recources had loaded! Cheers.
Comment: That might be why, I can give it a try!
Answer: You can try that code in OnNavigatedTo Event. Its Working.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
    Color accentColour = (Color)Application.Current.Resources["PhoneAccentColor"];
    ContentPanel.Background = new SolidColorBrush(accentColour);
}

Answer: I guess you can easily do this by binding the PhoneAccent color within your XAML for your Grid.
These threads would be helpful:
Windows Phone 8 Change Accent and Theme Colour
windows phone 8 xaml set the color of a button on click
Hope it helps!
Comment: Yeah I know how to do it via XAML however in this particular situation the colour of the grid is defined by user actions so must be done via c#.


Exibir qtd de números lidos, média, maior e menor valor lido

Question: Tenho o seguinte código:
qtdNumeros = int(input())
if qtdNumeros <= 0:
    menor = "Nenhum"
    media = "Nenhuma"
    maior = "Nenhum"
else:
    menor = maior = soma = float(input())
    for proximo in range(1, qtdNumeros):
        valor = float(input())
        soma += valor
        if valor < menor:
            menor = valor
        elif valor > maior:
            maior = valor
    media = soma / qtdNumeros
print("Menor Lido:", menor)
print("Média dos Lidos:", media)
print("Maior Lido:", maior)

Ao invés de passar uma quantidade de números que ele vai ler e exibir a media, o menor e maior, gostaria de inserir números até que uma linha vazia fosse digitada, e também, exibir a quantidade de números que foram lidos.
Como posso implementar isso?
Answer: É algo como isso que você deseja ?
import os

numbers = []

while True:
    os.system("cls") # Esse comando só serve para limpar a tela, então ignore caso você ainda não conheça sobre o módulo "os"

    num = input("\n Digite um número: ")
    if not num: break #Sai do bloco caso o usuário apenas aperte ENTER

    num = float(num)
    numbers.append(num) # Acrescenta o número à lista de números
    numbers.sort() # Organiza os números na lista em ordem crescente

    # Calcula a média dos números inseridos
    media = 0
    for num in numbers:
        media += num
    media /= len(numbers)

    input("\n Maior número: {} \n Menor número: {} \n Média: {}".format(numbers[-1],numbers[0],media))

Talvez você não tenha aprendido ainda sobre listas, mas o que eu fiz nesse código foi colocar todos os números dentro de uma sequência, na qual, será organizada de tal forma que os números fiquem em ordem crescente. Após isso basta eu pegar o valor do primeiro elemento da lista e do último elemento da lista. E em relação a média, eu apenas fiz o cálculo percorrendo e somando cada valor da lista e no final eu dividi pela quantidade de elementos na lista.


Gerar valores dinamicamente em uma tabela

Question: Estou listando o numero de equipamentos salvos no meu sistema em uma tabela, só que nem sempre terão equipamentos salvos, posso ter uma tabela vazia, ou imcompleta. O que eu preciso é listar as listas dessa tabela. Minha tabela pode ter 5 ou 10 valores, ou seja, sempre 5 ou 10 linhas para ser preenchidas. Entao gostaria de gerar dinamicamente a quantidade de linhas dessa tabela.
Conforme imagem abaixo:

Ao invez de esta listando 1,1,1,1,1,1... seria 1,2,3,4,5,6...
Minha tabela html:
#{extends 'main.html' /}

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

 Dashboard

 Patch panels

 Detalhes do patch
            panel

                         Detalhes Patch panels

                                    Porta
                                    Equipamento

                                #{list items:p.portas, as:'porta'}

                                    ${porta.descricao}

                                                 Ativar  Reiniciar  Desativar

                                #{/list}

Comment: Cara, tá fixo o número ali dentro da `td` (`1`), se tem que ser dinâmico faz dinâmico...
Comment: Eu sei, deixei ai pra exibir na imagem, mas sei que ta estatico. O pro eh que nao sei fazer isso dinamicamente, voce pode ajudar?
Comment: Ah, bom. Mas isso não deveria vir do _backend_? Ou você só precisa que seja sequencial?
Comment: Pelo que eu entendi você quer mostrar a posição(index) de cada item da lista?
Comment: Preciso que seja sequencial. Ate pq o ele ja esta sendo listado na ordem correta. Ou seja eu cadastrei o equipamento 1 na porta 7, ele veio na posiçao 7 da tabela
Answer: Execute a função organizarIndices assim que a página tiver sido carregada e pronto

organizarIndices();

function organizarIndices(){
  var table = document.getElementById('tabela');
  var total = table.rows.length;
  for(var i=0; i<total; i++){
      if(i > 0){
          table.rows[i].cells[0].innerHTML = i;
      }
  }
}

        Porta
        Equipamento

          Equipamento

          Equipamento

Comment: organizarIndices(); entra dentro do script? coloquei o script na parte superior do html e coloquei o id na tabela e nao rodou certo
Comment: Tem que ser depois que a página estiver sido carregada, jovem. No começo do HTML não dá, né.
Comment: Deu certo moral, sou novo em JQ e porisso nao domino a sintaxe.


@override error: The method onClick(View) of type new View.OnClickListener(){} must override a superclass method

Question: I wanted to navigate to a new page when clicking a button. Below are my both activities I have created. I am using eclipse and I am getting an error saying The method onClick(View) of type new View.OnClickListener(){} must override a superclass method on the main activity.
This is my main activity.
package com.example.grammer;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.support.v4.app.NavUtils;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    Button grammerButton = (Button)findViewById(R.id.grammar);

   grammerButton.setOnClickListener(new View.OnClickListener() {

       @Override
      public void onClick(View view) {
        Intent intent = new Intent(MainActivity.this, Grammer.class);
        startActivity(intent);
      }

    });
}
}

This is my second activity.
package com.example.grammer;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.support.v4.app.NavUtils;
import android.annotation.TargetApi;
import android.os.Build;

public class Grammer extends Activity {

    @Override
            public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_grammer);

         Button grammerButton = (Button) findViewById(R.id.grammar);

         grammerButton.setOnClickListener(new View.OnClickListener() {

          //    @Override
              public void onClick(View view) {
                finish();
              }

            });
          }
    }

Removing the @override will remove the error, but then app is not working as intended.
Comment: add this `import android.view.View.OnClickListener;`. And add the @Override annotaion. Why do you need to call `finish()`?. Hardware back button does the job.
Comment: //    @Override -> remove // in the second class
Comment: @faz see the full answer , only need to change layout name and button id.
Answer: Check this
OnClickListener() must override a superclass method?
Uncheck "Enable project specific settings", click "Configure Workspace Settings..." and change "Compiler Compliance Level" to 1.6 or above
Have this import statement
 import android.view.View.OnClickListener;

There is no need to remove @Override Annotation.
Also calling finish() is not necessary. The hardware back button does the job.
When you press back button in Grammar Activity your current activity is popped from the back stack and the previous activity in the back stack takes focus. So there is no need to call finish() on button click.
http://developer.android.com/guide/components/tasks-and-back-stack.html
Also if you have a Button with id grammar in activity_grammer.xml it is ok.
Make sure you have a button with id grammar in activity_grammer.xml
You can read the topic id
http://developer.android.com/guide/topics/ui/declaring-layout.html
An ID need not be unique throughout the entire tree, but it should be unique within the part of the tree you are searching.
Answer: Change "Compiler Compliance Level" to 1.6. of java from project properties.
Answer: Place this code::
Just replace then name of layout and button id by your
   import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.alayout);

    Button grammerButton = (Button)findViewById(R.id.aId);

   grammerButton.setOnClickListener(new OnClickListener() {

       @Override
      public void onClick(View view) {
        Intent intent = new Intent(MainActivity.this, Grammer.class);
        startActivity(intent);
      }

    });

}
}

Just replace then name of layout and button id by your
    import android.os.Bundle;
import android.app.Activity;

import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Grammer extends Activity {

    @Override
            public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.blayout);

         Button grammerButton = (Button) findViewById(R.id.aId);

         grammerButton.setOnClickListener(new OnClickListener() {

             @Override
              public void onClick(View view) {
                finish();
              }

            });
          }

    }

Comment: no not correct. id must be unique under the current view tree. Quoting docs "An ID need not be unique throughout the entire tree, but it should be unique within the part of the tree you are searching". http://developer.android.com/guide/topics/ui/declaring-layout.html
Comment: why should layout named by changed. wrong. they are 2 different layouts again
Comment: @Raghunandan yes dude, I have done in previous a little mistake. So I have been edited the full answer. It is the solved code. Thanks for your that correction.
Comment: @Raghunandan what? can you explain in brief......... because what I have written here I have tested this and then write here. Please see his post in brief , he is also given two different layout name but same id for button. I have also done the same thing for his facility.
Comment: if its different layout with the same ids there is no problem. and op already has different layouts
Comment: If you have two different layouts and within those layout if you have same id then no problem. Its find the id from `setContentView(R.layout.layoutid);` only matter is which layout you have set.
Comment: I also say the same thing and same work...... so now what you are asking is there any difference? See my answer and then comments before that not given any bad idea. Because your comments and my work is same.
Comment: Why You have written this **Just replace then name of layout and button id by your** what is meaning of this line ??? Isn't you contradict your latest statement?? And by the way OP has different layout so having same id has no problem.
Comment: @user3110424 what are you saying I have also done the same thing. I have taken two different layouts but in both cases I have given same ID of button , and it's work fine. What you are saying I have done this. So why you are given wrong comments and also given -1 vote . I have been run this code. It really bad manner . I am very much upset .
Comment: @user3110424 please see his layout name "activity_main" "activity_grammer" and button id "grammar" for both layout, but in my code layout name "alayout" and "blayout" and button id "aId" . For this reason I have been told him to replace the layout name and button id by your . Is it anything wrong?
Comment: @SatyakiMukherjee Dont be upset my friend.
Comment: @user3110424 no you are given wrong judgement the people , 1st time I was wrong, so i have edited, but you people saying some wrong thing. Don't do that, please see first then do this. If you are given -1 vote, it's nothing for me, but you are given wrong message in StackOverflow site. Be aware .
Comment: @SatyakiMukherjee dont take this so seriously i was told what i have seen first. And if you are talking abt -1 i have given it when it was wrong. Edit your answer will give you upvote but dont take it so personal.
Comment: @user3110424 no dude after edit the vote is given, because I have watched this. I am not taking this personal , but I am upset about your -1 prove here that my answer is wrong but actually it's right. Nothing else.
Comment: @SatyakiMukherjee its not about right or wrong. Its about solving op's problem. You are suggesting op to use a different layout when op already has a different layout. Instead of commenting if you have a problem take it up @ meta.stackoverflow.com
Comment: @Raghunandan why are commenting too much before see the answer. You are a talented person, but don't loose this in such a way. Please read my answer and as well as my comments to another person --- "@user3110424 please see his layout name "activity_main" "activity_grammer" and button id "grammar" for both layout, but in my code layout name "alayout" and "blayout" and button id "aId" . For this reason I have been told him to replace the layout name and button id by your . Is it anything wrong?"
Comment: No need of +1 dear, your +1 or -1 not need for me. It's about right and wrong. nothing else. Please leave this topics. I know I am right and also know that your 1st comment was right but after that you people are totally wrong. Thanks.
Comment: @SatyakiMukherjee http://meta.stackexchange.com/questions/63895/who-has-downvoted-me-and-why and this http://meta.stackexchange.com/questions/2451/why-do-you-cast-downvotes-on-answers.
Comment: @Raghunandan I have no interest about this, if I do anything wrong then you tell me I will try to solve the wrong thing-- I think you have been already see this, but if I do right after that they tell me wrong or take any revenge I don't care those people. If your is big then you can think also big-- I believe this opinion. Good luck.
Answer: All you need is to import the library for OnClickListener. Just press ctrl + Shift + O in your eclipse and it will import the import android.view.View.OnClickListener file for you.
Answer: Try this..
First, You havn't import OnClickListener
import android.view.View.OnClickListener;

and second one
Button grammerButton = (Button) findViewById(R.id.grammar);

you are giving same name for both Button Ids in different layouts. Make sure you have a button with id grammar in activity_grammer.xml present are not.
Comment: no need for different button ids if `activity_grammer.xml` has a button with id `grammar`.
Comment: http://developer.android.com/guide/topics/ui/declaring-layout.html. edit your second part of the answer
Comment: @Raghunandan you are correct friend. i checked it it's working if there is no button in another xml it'll give NPE. and also i edited my ans.
Answer: You are suppose to import the ViewClickListener namespace in your code.
Just Press ctrl + shift + O and it will add the relevant and missing namespaces in your project.


Showing there exists just one $x \in \mathbb{R}$ such that $x^3 + ax + b = 0$

Question: In my course on real analysis, I have this problem I just can't figure out:
Problem: Let $a, b \in \mathbb{R}$ with $a > 0$. Show that there exists just one $x \in \mathbb{R}$ such that $x^3 + ax + b = 0$.
I don't know how to begin. I was looking for a theorem to use but there's not enough conditions given for them to able to apply. Any suggestions or help?
Comment: Hint: What can you say about $f'(x)$?
Comment: $f'(x) = 3x^2 + a$, so that $f'(x) > 0$ for all $x$. So this means the function is strictly monotone. So this means it can have only one zero?
Comment: Well, that means it can only have at most one zero.  You still need to show that it has a zero.
Answer: Let $f(x) = x^3 + ax + b$ which is continuous since it is a polynomial. Now, it is clear that
$$\lim_{x \to -\infty} f(x) < 0$$
and
$$\lim_{x \to \infty} f(x) > 0.$$
By the Intermediate Value Theorem, these exists $-\infty < c < \infty$ such that $f(c) = 0$.
Furthermore, $f'(x) = 3x^2 + a > 0$ since $a > 0$. Thus, $f$ is a strictly increasing function, so $c$ can be the only root.
Comment: Thanks for the help. Are you using Lagrange's mean value theorem here, or the normal one?
Comment: @Kamil Are you familiar with the Intermediate Value Theorem?
Answer: This is a partially intuitive proof. I'll leave the rigor up to you.
Let $p(x) = x^3 + ax+ b$
For $p(x)$ to have only 1 "zero", it can only cross the X-axis once.
Let's look at $p'(x) = 3x^2 + a$
As $a > 0$,
$p'(x) > 0$ for all $x$
If the derivative of $p(x)$ is always more than 0, that means $p(x)$ is an increasing function for increasing values of x. Which means once it crosses the X-axis, it can't go back down.
Answer: First of all note that it is an odd degree polynomial (and obviously a continuous function of $x$). Thus:
$$
\lim_{x\rightarrow+\infty}(x^3 + ax + b = 0)=+\infty \\
\lim_{x\rightarrow-\infty}(x^3 + ax + b = 0)=-\infty
$$
By Bolzano's theorem, we get that there exists at least one real root.
On the other hand, $f'(x)=3x^2+a>0$ for any $x\in\mathbb{R}$. This implies that $f(x)=x^3 + ax + b $ is a strictly increasing function, so it has at most one real root.
Consequently, $f(x)=x^3 + ax + b =0$ has exactly one real root.
Comment: I think you mean it is an *odd* degree polynomial.
Comment: of course! thanks for noticing.
Answer: You may find useful to see a proof not using derivatives:
Let $f(x)=x^3+ax+b,$ with $a\ge0$. As already said in the other answers, by Bolzano's theorem there exists at least one root $x_0$ of $f$. We have \begin{align}f(x_0+\varepsilon)&=(x_0+\varepsilon)^3+a(x_0+\varepsilon)+b \\ &=x_0^3+ax_0+b+3\varepsilon x_0^2+3\varepsilon^2x_0+a\varepsilon+\varepsilon^3\\&=3\varepsilon x_0^2+3\varepsilon^2x_0+a\varepsilon+\varepsilon^3,\end{align} thus $\Delta=9\varepsilon^4-12\varepsilon^4-12a\varepsilon^2=-3\varepsilon^2(4a+\varepsilon^2)$ being negative for all $\varepsilon\ne0$ yields $f(x_0+\varepsilon)\ne0$ for all $\varepsilon\ne0$, whence the uniqueness of $x_0$.
Answer: Another proof without derivatives, allowing the value $a=0$: The function $x^3$ is strictly increasing, and $ax$ is increasing. It follows that $x^3 + ax$ is strictly increasing. The addition of the constant $b$ does not change this. Thus if there is a zero, it must be unique. Set $f(x) = x^3+ax + b.$ You can check that $f(|b|+1) > 0, f(-(|b|+1)) < 0.$ By the intermediate value theorem, $f$ must have have a zero, and we're done.


How to equate ['1'] with 1 in flask

Question: I have 2 variables
a=['1'] # This is an array
b=1 # This is a integer

I want (a==b) to be true.
Answer: In your array a=['1'] is a String not an integer so it won't become equal
a = [1]
b = 1
for i in a:
    if i == b:
        print('a==b')
    else:
        print('a!=b')

How to equate ['1'] with 1 in flask


AWS Elastic Beanstalk container_commands in Python 3.4 Docker Container

Question: I have a Django 1.6 application running on Python 3.4 that I'd like to deploy on AWS Elastic Beanstalk, so I've selected "Preconfigured - Docker/Python" (i.e., Python 3.4) as my configuration but deployments fail on the container_command to run django-admin.py. The same placeholder app bundle runs as expected on the "Preconfigured/Python" configuration (i.e., Python 2.7) without error.
According to the documentation .ebextension config container_commands are run after the application and web server have been set up and the application version file has been extracted, but before the application is deployed. That appears to be the case for the Python 2.7 container but not the Python 3.4 Docker container.
To test the theory, I added a script to my bundle to peek at the environment and executed it as a container_command. The Python 2.7 container uses Python 2.7, has pip packages installed from requirements.txt, and finds django-admin.py as expected. The Python 3.4 Docker container, however, uses Python 2.6 during the container_command phase and thus doesn't have the environment set up to find django-admin.py or installed pip packages.
How can I get the the Preconfigured - Docker/Python (3.4) container to execute container_commands in the intended environment? Is there a step missing to activate the container and/or it's virtualenv before triggering container_commands?
Answer: AWS Support pointed me to adding a custom Dockerfile.  I used my Dockerfile's ENTRYPOINT to override the default from the base image so I could slip in my own script to trigger the syncdb command.
ref: https://forums.aws.amazon.com/message.jspa?messageID=595630
Comment: Isn't this undesirable, since it would lead to every machine in your pool running the startup scripts for something that you maybe want to only be `leader_only`?


Derivative with respect to inner function with differing inputs?

Question: There's a conceptual deal with derivatives of composite functions that I'm really struggling to understand.

Let $g(t)$ be some continuous, differentiable function.

$f(t) = g(t) + g(t + 1) + g(t^2)$

Now, $\frac{df}{dt}$ is trivial to solve with the chain rule. What's $\frac{\bf df}{\bf dg}$?

Naïvely, treating $g$ as just the input into $f$, it seems analogous to $\frac{d}{dx}(x+x+x) = 3$. But in the equation for $f$ above, it doesn't seem right that the three $g$ terms, which could all represent vastly different quantities for any given input, should have the same instantaneous rate of change. Is it really true that for an infinitesimal change to the output of $g$, the output of $f$ simply changes by 3 times as much, for any value of x?
Or am I wrong? Or am I asking a completely nonsensical question?
(For context, I'm working on some homebrewed alternative neural network structures, and I'm treating some neurons as compositions of functions. For error measurement purposes, it would be great to take derivatives of the outer functions with respect to the inner function alone.)
Comment: If you meant that the map is $g \mapsto f(g)$ is defined by $(f(g))(t) =\text{ the above}$, then $f$ is linear and in appropriate spaces is trivially differentiable.
Comment: The question is not clear. Did you mean to write $(f(g))(t)$ rather than $f(g(t))$?
Comment: Your definition of $f(g(t))$ is not valid: Let e. g. be $g(t)=t^2$. So, think about what $f(1)$ is in this case. It turns out there are two possible answers: On the one hand, you have $f(1)=f(g(1))=g(1)+g(2)+g(1)=6$ but on the other hand you also get $f(1)=f(g(-1))=g(-1)+g(0)+g(1)=2$.
Comment: @copper.hat Of course that wouldn't help for computing the derivative w.r.t to $t$ using the chain rule...
Comment: ${df \over dt}$ makes no sense with my interpretation, so I would reiterate that the question is far from clear.
Comment: @copper.hat My mistake! I got my notation switched up; hopefully it's clearer now.
Comment: I don't understand what you are asking.
Answer: As discussed in the comment section, your problem is a bit ambiguous / ill-defined. However, according to me, you can take two points of view, depending on whether you are interested in a local or global dependence between $f$ and $g$.
1. Local variation
If you want to find the local/instantaneous variation of the output $f$ due to the one of the input $g$, you can simply apply the following trick :
$$
\frac{\mathrm{d}f}{\mathrm{d}g} = \frac{\mathrm{d}f/\mathrm{d}t}{\mathrm{d}g/\mathrm{d}t} = \frac{g'(t) + g'(t+1) + 2tg'(t^2)}{g'(t)}
$$
2. Global variation
On the other hand, if you are interested in the global variation of $f$ due to $g$, in other words, if you want to study how $f$ changes when the whole function $g$ varies, then you need to consider $f$ as a functional and to take its functional derivative in consequence, as follows :
$$
\frac{\delta f(t)}{\delta g(\tau)} = \delta(t-\tau) + \delta(t+1-\tau) + \delta(t^2-\tau)
$$
where $\delta$ is the Dirac delta.
In the present case, you may consider the first case, since $f$ is somewhat defined locally (i.e. through a unique parameter $t$), even if it depends on the three different points $t$, $t+1$ and $t^2$. However, you might construct other models for your neural network in the future, where the dependence of $f$ on $g$ will be based on more points (or even on all the points, through integration for instance), so that you might need to study it non-locally as in the second case.
Comment: Thank you—this math *is*, in fact, a bit over my head, but knowing that they're isn't a simple, intro-calc-level solution is actually quite helpful for my work. So sorry again for the ambiguity!


Parametros multiplos em xmlhttp.send();

Question: Estou fazendo uma inserção no banco de dados com ajax, o ajax esa funcionando, porém a inserção não está sendo feita corretamente, acredito que seja porque estou passando os parametros de forma incorreta no método send();. Preciso passar o nome e a idade no método. Eis o código:
HTML:

 Cadastre-se em nosso site

        <form action="servico.php?p=cadUsr" method="POST" id="frmCadUsr">
            Nome: <input type="text" maxlength="255" name="txtNome" id="txtNome"/>
            Idade: <input type="text" maxlength="3" name="txtIdade" id="txtIdade"/>

            <input type="submit" value="Enviar" />
        </form>

o PHP:
function cadUsr(){
    require("dbCon.php");
    require("mdl_usuario.php");

        $usr = $_POST["txtNome"];
        $idade = $_POST["txtIdade"];

        $resultado = usuario_cadastrar($con,$usr,$idade);

            if($resultado){
                echo "Cadastro efetuado com sucesso";
            } else {
                echo "O cadastro falhou";
            }
    }

Funçao PHP para inserir:
function usuario_cadastrar($conexao,$nome,$idade){

        if($nome == "" && $idade == ""){
            return false;
        }

        $sql = sprintf("insert into usuario (nome,idade) values ('%s',%s)",$nome,$idade);

        $resultado = mysqli_query($conexao,$sql);

            return $resultado;
    }

E o AJAX:
window.onload = function(){

            var xmlhttp;
            var frm = document.querySelector("#frmCadUsr");
            var url = frm.getAttribute("action");
            var nm = document.querySelector("#txtNome").value;
            var idade = document.querySelector("#txtIdade").value;

            frm.addEventListener("submit",function(e){
                e.preventDefault();

                try{
                    if(window.XMLHttpRequest){
                        xmlhttp = new XMLHttpRequest();
                    }

                    xmlhttp.open("POST",url,true);
                    xmlhttp.send(nm+idade);

                    xmlhttp.onreadystatechange = function(){
                        if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
                            alert("Deu certo");
                        }
                    }
                } catch(err){
                    alert("Ocorreu um erro.
"+ err);
                }
            });

}

Recebo o alert com a mensagem "Deu certo", porém a inserção não é realizada.
Comment: @anuseranother não foi grosseiro não, fique tranquilo. Parabéns pela resposta, a dica do `application/x-www-form-urlencoded` é muito importante :)
Comment: Onde defines esta função:         $resultado = usuario_cadastrar($con,$usr,$idade); ?
Comment: @Sergio, acabei de atualizar o código com a função em questão !
Comment: Onde estás a chamar `cadUsr()`? dá-te algum erro no PHP?
Comment: @Sergio, obrigado pela ajuda, encontrei o verdadeiro problema e já postei a resposta !
Comment: possível duplicata de [Como passa a variavel via $\_POST](http://pt.stackoverflow.com/questions/34648/como-passa-a-variavel-via-post)
Comment: @GuilhermeNascimento a checar pela resposta (da minha pergunta) é claramente notável que está pergunta nada tem a ver com a minha. O meu problema acontecia devido a ausência do método xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");, que eu desconhecia ser obrigatório, e isso não é citado em momento algum na outra pergunta.
Comment: @anuseranother uma pergunta ser duplicidade de outra não a torna "pior" ou algo do tipo, apenas "linka" uma na outra. Não leve a mal por favor.
Comment: Não levo, desculpe se fui rude, minha intenção certamente não foi essa ! Só queria explicar mesmo. Mais uma vez me desculpe se fui grosseiro e obrigado pela atenção !
Answer: Para além do que o @sergio referiu, faltava inserir o cabeçalho xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");.
Este cabeçalho é padrão na de todos os forms em html, porém ao desabilitar o padrão do formulario, ele perde esse valor. Retirei o formulario e deixei apenas os campos de texto, e adicionei. A função ajax() ficou desta forma:
function ajax(){

            var xmlhttp;
            var nm = document.querySelector("#txtNome").value;
            var idade = document.querySelector("#txtIdade").value;

                try{
                    if(window.XMLHttpRequest){
                        xmlhttp = new XMLHttpRequest();
                    }

                    xmlhttp.open("POST","servico.php",true);

                    /*setRequestHeader(Content-type, application/x-www-form-urlencoded), esta
                    função adiciona ao cabeçalho que o request feito ao servidor será um conteudo,
                    e o conteudo sera levado pela url como em um form.
                    o application/x-www-form-urlencoded é um dos cabeçalhos para enviar dados
                    através de HTTP. Ele faz com o que os dados enviados sejam guardados em uma
                    querystring(parametros de url), e é essencial quando se envia um dado para
                    o servidor.

                    Para enviar um dado para o servidor é necessário atribuir algum tipo de
                    cabeçalho para o HTTP.*/
                    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                    xmlhttp.send("txtNome=" + nm + "&txtIdade="+idade + "&p=cadUsr");

                    xmlhttp.onreadystatechange = function(){
                        if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
                            alert("Deu certo");
                            //console.log(xmlhttp.responseText);
                        }
                    }
                } catch(err){
                    alert("Ocorreu um erro.
"+ err);
                }
}

Answer: Tens de colocar os dados que queres enviar no formato query string. Ou seja:
chave1=valor1&chave2=valor2

Assim em vêx de nm + idade deves usar assim:
var dados = 'txtNome=' + nm + '&txtIdade=' + idade;
xmlhttp.send(dados);

Comment: Obrigado ! Porém ainda não funcionou. Dando um console.log, ele mostra que fez a query corretamente, e o ajax também me da um retorno positivo porém não insere no banco de dados !
Answer: Eu estava tendo dificuldades com o meu também, aí coloquei o código sugerido:
 xmlreq.open("POST","inserir.php",true);
 xmlreq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 var dados = 'questao=' + num + '&resposta=' + resposta;  //dados que estou enviando
 xmlreq.send(dados); //xmlreq = xmlhttp

Funcionou corretamente, obrigado. Se o seu não estiver enviando dê uma olhada nos campos do banco de dados, os que forem NOT NULL ou VARCHAR se estão recebendo valores de acordo.

Parametros multiplos em xmlhttp.send();


Is there any way to update My gtalk status message using any RSS feed?

Question: I want to know about any possibilities of updating the Gtalk status message by any means? (may be by subscribing to RSS feed, or by just adding a file which gtalk recognizes)?
Is there any gtalk API ?
Answer: Gtalk is compatible with XMPP, so you can use any XMPP library to set user status.
UPD
XMPP is covered by RFC3920 and RFC3921
Comment: You have linked the Russian (i guess) version of wiki article!! I edited and changed it to english version, but you have edited that again!
Comment: @Vijay Oh, sorry, copy/paste problem =) Fixed.
Comment: Thanks. I'll look in to it and i've think of a solution where my visitors can click a link (like twitter share or Facebook like) so that their status message is updated
Comment: Hi 4ndrew, thanks for your answers. That helped me to go in a right path, so i mark yours as accepted answer for this question.


Problema na execução do pyautogui no pycharm

Question: codigo:
   import pyautogui

   pyautogui.alert("a")   `

o erro da execução;
NOTE: You must install tkinter on Linux to use MouseInfo. Run the following: sudo apt-get install python3-tk python3-dev

já rodei o comando que mostra na msg de erro, infelizmente não funcionou, rodei outros comandos como;  sudo apt-get install python3-tk
estou em busca de soluções.
Answer: Isso está acontecendo porque você não está rodando uma persão completa do python.
Minha recomendação é quando for fazer uma instalação de python, e não quiser preocupações, intalar o anaconda, que vai trazer praticamente tudo o que precisa.
Neste caso instale o pip:
sudo apt install python3-pip
Depois tente instalar essa dependência do seu projeto através do pip utilizando:
pip install pyautogui
O problema não está no PyCharm e sim no seu ambiente de desenvolvimento.


Finding c in probability density function

Question:
Suppose that the p.d.f. of a random variable $X$ is as follows: $$ f(x)
 = \ \begin{cases}
        \dfrac{c}{(1−x)^{1/2}} & \text{for } 0 < x < 1 \\[10pt]
       0 & \text{otherwise}    \end{cases} \ $$
Solution: $ \displaystyle \int_0^1 \frac{c}{(1−x)^{1/2}} \, dx=2c=1$, $c=\dfrac{1}{2}$

I don't understand how $c$ is $\frac{1}{2}$ and not $\frac{-1}{2}$ because in integrating it should be $-2c$ and not $2c$. Is this a property of p.d.f?
Comment: I guess you know that $d\sqrt{1-x}$ is $(-1/2)dx/\sqrt{1-x}$ and wonder where the minus sign went.  But the end-point calculation $\left. \sqrt{1-x}\right|_0^1$ works out to $0-1 = -1$ which "cancels" the first minus sign.
Comment: Use `\ge` for $\ge$ and `\text` to render $\text{otherwise}$ instead of $otherwise$.
Comment: be careful, you are integrating a positive function if $c$ is positive, over $[0,1]$. so it may well be $-2c$ as well but then $c$ must be negative. The property of density is $\int f(y)\mathrm{d}y =1$.
Comment: So it doesn't matter?
Comment: oh got it thanks!
Comment: How did you conclude it should be $-2c$? The integral $$ \int_0^1 \frac{dx}{\sqrt{1-x}} $$ is the integral of a nonnegative function over a positively oriented interval ($0$ to $1,$ not $1$ to $0$), so it must be positive.
Answer: $$
\int_0^1 \frac{dx}{\sqrt{1-x}}
$$
In this integral, note that if $0<x<1$ then $\dfrac 1 {\sqrt{1-x}}$ is positive. And it's $\displaystyle\int_0^1,$ not $\displaystyle \int_1^0.$ Therefore the value of the integral must be positive.
\begin{align}
u & = \sqrt{1-x} \\
u^2 & = 1-x \\
2u\,du & = -dx \\
\text{As } x & \text{ goes from $0$ to $1$, $u$ goes from $1$ to $0$.} \\[10pt]
\int_0^1 \frac{dx}{\sqrt{1-x}} & = \int_1^0 \frac{-du}{\sqrt u} = \left. -2\sqrt u \vphantom{\frac 1 1}~\right|_1^0 = -2(0-1) = 2.
\end{align}


Proving that the set of real numbers with digit 5 appearing infinitely often is Borel by using a Borel measurable function

Question: I am trying to prove the following statement:
Show that the set of real numbers that have a decimal expansion with the digit 5 appearing infinitely often is a Borel set.
$\textbf{using a Borel measurable function}$ (similar questions have been asked before but none (as far as I have been able to see) have tried to prove it in this way.
The only thing that I have been able to come up with after several tries is to use the indicator function $\chi_{E}:\mathbb{R}\to\mathbb{R}$,
$\chi_{E}(x):=\begin{cases} 1 & \text{if }x\in E\\ 0 &\text{if }x\notin E\end{cases}$
where $E:=\{x\in \mathbb{R}: x \text{ has a decimal expansion with the digit 5 appearing infinitely often} \}$.
Then if $B$ is a Borel set we have that $\chi_E^{-1}(B)=\begin{cases}E &\text{ if }0\notin B\text{ and }1\in B\\ \mathbb{R}\setminus E & \text{ if }0\in B\text{ and }1\notin B\\ \mathbb{R} & \text{ if }0\in B\text{ and }1\in B\\ \emptyset & \text{ if }0\notin B\text{ and }1\notin B\end{cases}$ so in particular if we set $\mathcal{S}:=\{\emptyset,E,\mathbb{R}\setminus E,\mathbb{R}\}$ this should be an $\mathcal{S}$-measurable function and $\textbf{I was wondering if it is also a Borel measurable function}$ so I can say that $\chi_{E}^{-1}(\{1\})=E$ is Borel.
So, I would be very grateful if someone either gave me an hint about how to do this or disproved my approach explaining to me why this isn't a feasible approach.
Comment: This will only work if $\chi_E$ is measurable, which unfortunately is equivalent to $E$ being measurable. So there is no progress.
Comment: @GiuseppeNegro As I suspected, that is where I got stuck and I was hoping there would be an easy way out I couldn't see at the moment, but alas it seems that the road to prove this result is a bit more longwinded. Thank you for your interest in my question.
Answer: This is rather long to be a comment, so I post it as an answer.
Let $E:=\{x\in \mathbb{R}: x \text{ has a decimal expansion with the digit 5 appearing infinitely often} \}$
For any $n \in \Bbb N$, $n>0$, let $E_n:=\{x\in \mathbb{R}: x \text{ has a decimal expansion with the digit 5 appearing in the $n$th position} \}$.
It is easy see that, for any $n \in \Bbb N$, $n>0$, $E_n$ is a Borel measurable set, so $\chi_{E_n}$ is a Borel measurable function.
Now, note that $\chi_E= \limsup_{n \to \infty} \chi_{E_n}$. So $\chi_E$ is a Borel measurable function. So $E$ is a Borel measurable set.
Remark: The above argument can be done directly with the sets, but the OP requested to use Borel measurable functions. Directly with the sets, we would have:
$$ E = \limsup_n E_n = \bigcap_{k=1}^{\infty} \bigcup_{n=k}^{\infty} E_n$$
Since, for any $n \in \Bbb N$, $n>0$, $E_n$ is a Borel measurable set, it follows that $E$ is a Borel measurable set.
Comment: @lorenzo , Yes, if you define
$$E_1:=\bigcup_{n_0 \in \Bbb N}[-n_0.6,-n_0.5]\cup [n_0.5,n_0.6], E_2:=\bigcup_{n_0 \in \Bbb N}\bigcup_{n_1=0}^{9}[-n_0.n_1 6,-n_0.n_1 5]\cup [n_0.n_15, n_0.n_1 6], ...E_k=\bigcup_{n_0 \in \Bbb N}\bigcup_{n_1,\dots n_k=0}^{9} [-n_0.n_1n_2...n_{k-1}6,-n_0.n_1n_2...n_{k-1}5]\cup [n_0.n_1n_2...n_{k-1}5, n_0.n_1n_2...n_{k-1}6]$$
we have that each $E_k$ is Borel since closed sets are Borel and $\mathcal{B}$ is closed under unions and since it is also closed under intersections we have that $E=\bigcap_{k=1}^\infty\bigcup_{n=k}^\infty E_n$ is Borel, hence the claim.
Comment: So, if I understand correctly, if I define $$E_1:=\bigcup_{n_0=0}^{9}[-n_0.6,-n_0.5]\cup [n_0.5,n_0.6], E_2:=\bigcup_{n_0,n_1=0}^{9}[-n_0.n_1 6,-n_0.n_1 5]\cup [n_0.n_15, n_0.n_1 6], ...E_k=\bigcup_{n_0,n_1,\dots n_k=0}^{9} [-n_0.n_1n_2...n_{k-1}6,-n_0.n_1n_2...n_{k-1}5]\cup [n_0.n_1n_2...n_{k-1}5, n_0.n_1n_2...n_{k-1}6]$$ we have that each $E_k$ is Borel since closed sets are Borel and $\mathcal{B}$ is closed under unions and since it is also closed under intersections we have that $E=\bigcap_{k=1}^{\infty}\bigcup_{n=k} E_n$ is Borel, hence the claim. Is this correct?
Answer: Unfortunately the issue of measurability requires a careful (but simple) look at the decimal expansion of numbers.
By using the fractional part function $\phi:x\mapsto x-\lfloor x\rfloor$ ,which is measurable, it is enough to consider numbers between $0$ and $1$. Every number $x$ has a unique decimal expansion $x=\sum^\infty_{n=1}10^{-n}a_n(x)$, where $a_n(x)\in\{0,1,\ldots,9\}$ and where the number of $a_n$'s different from $0$ is infinite (for example $.5=.4999\ldots$)
The functions $x\mapsto a_n(x)$ are measurable. For example
\begin{align}
A^5_1=\{x\in(0,1):a_1(x)=5\}&=(.5,,.6]\\
A^5_2=\{x\in(0,1):a_2(x)=5\}&=\bigcup^9_{a=0}(.a5,.a6]\\
A^5_3=\{x\in(0,1):a_3(x)=5\}&=\bigcup^{9,9}_{a,b=0}(.ab5,.ab6]\\
etc.
\end{align}
Now the measurability of some important sets is established, you can proceed as you planned. For instance, one may consider $$F(x)=\sum^\infty_{n=1}\mathbb{1}_{A^5_n}(x)$$
which is a measurable function with values in $\mathbb{Z}_+\cup\{\infty\}$. You are interest in
$$\begin{align}
E=\{x:F(x)=\infty\}&=\{x:a_n(x)=5\,\text{infinitely often}\}\\
&=\{x:\limsup_n\mathbb{1}_{A^5_n}(x)>0\}=\bigcap^\infty_{n=1}\bigcup^\infty_{m=n}A^5_m
\end{align}$$
From this, you can see that $E$ is indeed measurable. Notice that the a similar procedure works for any other digit.
Hope this helps to clarify a few things.


Grouping and number rows separated by a blank row

Question: I'm hoping to get some help automating a process that takes a lot of time. Basically I have a report where groups of related rows are separated by a blank row. I would like to have a way to identify or assign a number to each group either with a formula or macro. The end goal would be to have a sum for each separate group. There is essentially no other way to distinguish what goes in each group aside from the fact that they are separated by a blank row. Thanks!
Comment: Assuming data starts on row 3 this formula will work: `=IF(ISBLANK(B3),"",IF(ISBLANK(B2),A1+1,A2))`
Answer: I would try something like this
Public Sub GroupCells()
    Dim myRange As Range
    Dim rowCount As Integer, currentRow As Integer
    Dim firstBlankRow As Integer, lastBlankRow As Integer
    Dim currentRowValue As String
    Dim neighborColumnValue As String
<code>'select range based on given named range
Set myRange = Range("rngList")
rowCount = Cells(Rows.Count, myRange.Column).End(xlUp).Row

firstBlankRow = 0
lastBlankRow = 0
'for every row in the range
For currentRow = 1 To rowCount
    currentRowValue = Cells(currentRow, myRange.Column).Value
    neighborColumnValue = Cells(currentRow, myRange.Column - 1).Value

    If (IsEmpty(currentRowValue) Or currentRowValue = "") Then
        'if cell is blank and firstBlankRow hasn't been assigned yet
        If firstBlankRow = 0 Then
            firstBlankRow = currentRow
        End If
    ElseIf Not (IsEmpty(currentRowValue) Or currentRowValue = "") Then
        'if the cell is not blank and its neighbor's (to the left) value is 0,
        'and firstBlankRow hasn't been assigned, then this is the firstBlankRow
        'to consider for grouping
        If neighborColumnValue = 0 And firstBlankRow = 0 Then
            firstBlankRow = currentRow
        ElseIf neighborColumnValue <> 0 And firstBlankRow <> 0 Then
            'if firstBlankRow is assigned and this row has a value with a neighbor
            'who isn't 0, then the cell one row above this one is to be considered
            'the lastBlankRow to include in the grouping
            lastBlankRow = currentRow - 1
        End If
    End If

    'if first AND last blank rows have been assigned, then create a group
    'then reset the first/lastBlankRow values to 0 and begin searching for next
    'grouping
    If firstBlankRow <> 0 And lastBlankRow <> 0 Then
        Range(Cells(firstBlankRow, myRange.Column), Cells(lastBlankRow, myRange.Column)).EntireRow.Select
        Selection.Group
        firstBlankRow = 0
        lastBlankRow = 0
    End If
Next
</code>
End Sub


Prove that the Legendre polynomial satisfies $\int_{-1}^1(1-x^2) P_m' P_n' dx=0$

Question: My attempt:
$P_m$ and $P_n$ satisfy the Legendre equation, so
(1)
\begin{equation} \label{1} (1-x^2)P_m''-2xP_m'+m(m+1)P_m=0 \end{equation}
(2)
\begin{equation} (1-x^2)P_n''-2xP_n'+n(n+1)P_n=0 \end{equation}
Multiplying (1) by $P_n'$ and (2) by $P_m'$ and adding and simplifying gives me:
$\frac{d}{dx} [(1-x^2) P_n' P_m']=2xP_n'P_m'+m(m+1)P_mP_n'+n(n+1)P_nP_m'$
I see that integrating from $-1$ to $1$ twice will give me desired LHS, but I can't prove RHS is $0$. Please help!
Answer: You have the right idea (using the definition by ODE) but are applying it in the wrong place. Let's instead integrate by parts:
$$\int_{-1}^1 (1-x^2)P_m'P_n'dx = (1-x^2)P_m'P_n \Bigr |_{-1}^1 - \int_{-1}^1 [(1-x^2)P_m']'P_ndx = -\int_{-1}^1 [(1-x^2)P_m']'P_ndx $$
Then we have
$$ [(1-x^2)P_m']' = (1-x^2)P_m'' - 2xP_m' = -m(m+1)P_m$$
$$\implies -\int_{-1}^1 [(1-x^2)P_m']'P_ndx = \int_{-1}^1 m(m+1)P_mP_ndx = 0$$
by orthogonality.


Pointer from derived class to base class C#

Question: I have 100 classes that will inherit 1 base class. Derived class can have A and B property, just A or B property, or don't have them at all. I need a pointer, from derived class to base class, that will trigger every time I call A or B property from derived classes.
class D1 : Base
{
    int A { get; set; } // Point to Base A
}

class D2 : Base
{
    int A { get; set; } // Point to Base A
    int B { get; set; } // Point to Base B
}

class Base
{
    int A => ExampleA();
    int B => ExampleB();

    int ExampleA()
    {
        return 10;
    }

    int ExampleB()
    {
        return 15;
    }
}

static void Main(string[] args)
{
    D1 d1 = new D1();
    D2 d2 = new D2();

    d1.A; //return 10
    d2.A; //return 10
    d2.B; //return 15
}

Comment: I don't quite understand, `Derived class can have A and B property, or just A or B property`, no they can't they will have both, no matter what, that's how inheritance works. If you want to override the behaivour of a base class, then you'll need to make the base properties `abstract` of `virtual`
Comment: This sounds like a bad idea in terms of design. https://stackify.com/solid-design-liskov-substitution-principle/#:~:text=The%20Liskov%20Substitution%20Principle%20in,the%20objects%20of%20your%20superclass.
Comment: The "managed pointer" here is: `this` - it is the same for the instance, regardless of whether that is talking about `Base`, `D1`, or `D2`; you *might* want to make `A` / `B` on the base-class `virtual` or `abstract`, and `override` them in the derived types? but: what do you expect to happen if someone has a `D2` instance and sets `B` to `25`, then fetches `B`? is it `25`? or is it `15`? or does it matter whether the caller is thinking about `D2` vs `Base`?
Comment: Plus, your base class currently forces all classes that inherit from it to have their properties `A` and `B` be read-only (as there is no setter for them on the base class)
Answer: If You want to inherit not everything but sometimes A, sometimes B and only sometimes A and B then it looks like You should not inherit from the base class at all. Looks more like You should create 2 interfaces and for example:
class D1 : IBaseA

class D2 : IBaseA, IBaseB

Answer: You'll want to make the properties on the base class virtual, so then classes that inherit from it can optionally override the behaivour. (Or you could also make the methods ExampleA and ExampleB virtual and optionally override that behaivour instead), like so:
public class Base
{
    // Made these properties get and set, instead of get (read) only
    // default values are for illustration purposes
    public virtual int A { get; set; } = 1;
    public virtual int B { get; set; } = 1;
}

public class Foo : Base
{
    public override int A { get; set; } = 10;
}

public class Bar : Base
{
    public override int B { get; set; } = 10;
}

Let's test it:
var a = new Foo();
var b = new Bar();

Console.WriteLine($"a.A: {a.A}, a.B: {a.B}");
Console.WriteLine($"b.A: {b.A}, b.B: {b.B}");

If you don't specify anything, Foo and Bar will implicitly have A and B with the same visibility as A and B in the Base class. You can't change the visiblity of a member of a class "after the fact" (i.e without changing it in the base class), so if only some of your classes should expose A or B you'll want to follow what CherryQuery said in their answer
Comment: So, you want read and write properties, where the default value is the return value of a method in the base class? If you're solving a problem using reflection, then all simplicity has already gone out the window a long time ago
Comment: You are the closest one. I tried virtual and override and its not what I want. Nothing is assigned in `A` and `B` properties in derived class, all of the information is in base class. They are just pointers to methods in base class. And I don't want to assign methods in 100 derived classes just to point to methods in base class, example @Piotr Wojsa . I know that I can do this with reflection and check if `A` and `B` is present in derived class then assign methods to them. I want a simple solution.
Comment: Is it possible to write `public int A { get; set; }` in all of my 100 classes and every time I call `Foo().A` it triggers the method in base class `int ExampleA()`, without me writing manually `public int A => base.ExampleA();` in all of my 100 classes?
Answer: Actually in Base class you don't need A and B. Subclasses should then look like (assuming ExampleX methods are at least protected):
class D1 : Base
{
    public int A => ExampleA(); // note this is get-only property
}

Comment: You have 100 classes and you have to write `ExampleA()` from base class every time? Would you do it?
Comment: That's just an example - one might add BaseA : Base with this code and 50 classes should just inherit from it, and another 50 might inherit from BaseB: Base and so on, and so forth.


An example that a Riemannian manifold that is complete, non compact and has finite volume.

Question: I can't think of such an example, which is a complete, non compact Riemannian manifold and has finite volume.
Answer: Take the graph of the function $x \mapsto e^{-x^2}$ and rotate it around the $x$-axis in $\mathbb{R}^3$. You get a submanifold of $ \mathbb{R}^3$ which can be endowed with the Euclidean metric of  $ \mathbb{R}^3$. It's an easy exercise to show that it is complete, non compact and that its area is finite
Answer: Any cusped (finite-volume --- so the volume in the cusp falls off exponentially, as the volume of the upper-half-space model of $\mathbb{H}^n$ falls of as $z\to\infty$) hyperbolic manifold.  For example, the complement of a hyperbolic knot, or a punctured Riemann surface --- http://en.wikipedia.org/wiki/Hyperbolic_knot, http://en.wikipedia.org/wiki/Riemann_surface#Hyperbolic_Riemann_surfaces.


Invertibility of inertia matrices

Question: The inertia matrix is defined, for a discrete body composed of material points $P_i$ of mass $m_i$ whose position vector $\overrightarrow{CP_i}$ with respect to the centre of mass $C$ has Cartesian coordinates $(x_i,y_i,z_i)$, as the matrix $$I:=\left( \begin{array}{ccc} \sum_im_i(x_i^2+z_i^2) & -\sum_im_i x_iy_i & -\sum_im_i x_iz_i \\ -\sum_im_i x_iy_i & \sum_im_i(y_i^2+z_i^2) & -\sum_im_i y_iz_i \\ -\sum_im_i x_iz_i & -\sum_im_i y_iz_i & \sum_im_i(x_i^2+y_i^2) \end{array} \right).$$
For a continuous body extending on a domain$V\subset\mathbb{R}^3$, with density $\rho:V\to\mathbb{R}$ and centre of mass having coordinates $(x_C,y_C,z_C)$, the inertia matrix is expressed -I do not write the argument $(x,y,z)$ of $\rho$ and synthesise $dxdydz$ as $dV$ for formatting reasons- as
$$\left( \begin{array}{ccc}
\int_V\rho[(y-y_C)^2+(z-z_C)^2]dV & -\int_V\rho\cdot(x-x_C)(y-y_C)dV & -\int_V\rho\cdot(x-x_C)(z-z_C)dV \\
-\int_V\rho\cdot(x-x_C)(y-y_C)dV & \int_V\rho[(x-x_C)^2+(z-z_C)^2]dV & -\int_V\rho\cdot(y-y_C)(z-z_C)dV \\
-\int_V\rho\cdot(x-x_C)(z-z_C)dV & -\int_V\rho\cdot(y-y_C)(z-z_C)dV & \int_V\rho[(x-x_C)^2+(y-y_C)^2]dV \end{array} \right).$$
I read that a solid body, i.e. a body not contained in a plane, has an invertible inertia matrix.
I have tried to show that $\det(I)\ne 0$ by writing $$I=\left( \begin{array}{ccc} I_{xx} & I_{xy} & I_{xz} \\I_{xy} & I_{yy} & I_{yz} \\I_{xz} & I_{yz} & I_{zz} \end{array} \right)$$ and calculated $\det(I)=I_{xx}I_{yy}I_{zz}+2I_{xy}I_{xz}I_{yz}-(I_{xx}I_{yz}^2+I_{xy}^2I_{zz}+I_{xz}^2I_{yy})$, but I cannot prove its non-nullity.
How can we see that $I$ is invertible? I am asking here because I am interested in a mathematical proof. Thank you very much for any answer!
Answer: Don't know if this is the best way, but here goes: Your inertia matrix is real and symmetric. Therefore its eigenvalues must be real, and the determinant $\Delta = \omega_1 \omega_2 \omega_3$, the product of your eigenvalues.
So find the eigenvalues of your matrix and you will find that none of them is 0, thus $\Delta$ will also be non-zero.
Comment: Gram-Schmidt algorithm might help.
Comment: @Self-teachingDavide Actually, it is sufficient to find the eigenvalues and prove that none of them is zero  - thus their product, the determinant, cannot be 0.
Comment: How can we explicitly build the diagonalising orthogonal matrices by using the coefficients $I_{xx},I_{xy},...,I_{zz}$? $\infty$ thanks again!
Comment: Proving that no eigenvalue can be 0 is the same as proving that the determinant $I_{xx}I_{yy}I_{zz}+2I_{xy}I_{xz}I_{yz}-(I_{xx}I_{yz}^2+I_{xy}^2I_{zz}+I_{xz}^2I_{yy})$ cannot be null, but that doesn't seem so easy for my abilities... How can we prove that? $\infty$ thanks!
Comment: Although I don't like the following physical explanation much, I see that, for any $\boldsymbol{\omega}\in\mathbb{R}^3$, $\frac{1}{2}\boldsymbol{\omega}\cdot I \boldsymbol{\omega}$ represent the kinetic energy of a body rotating around $C$ with angular velocity $\boldsymbol{\omega}$ and therefore it's strictly positive for $\boldsymbol{\omega}\ne\mathbf{0}$, i.e. $I$ is a definite positive matrix, with strictly positive eigenvalues
Answer: We're going to show positive definiteness of the inertia tensor.
Moment of inertia with respect to an axis through the origin along the unit normal $n$ is
$$I_{n}=\int d^{3}x\,\rho(x)r^{2}(x)$$
where $r^{2}(x)=\Vert x\Vert^{2}-\langle x,n\rangle^{2}$ is the distance
between the mass at $x$ and the axis. We see that $$\forall n:\;I_{n}>0$$
and we're going to show that $$I_{n}=\langle n,I(n)\rangle$$ where $I$
is the inertia tensor thus proving the positive definiteness of its
matrix.
The inertia tensor for a continuous body is given by
$$I=\int_{V}\rho(x)\left(\langle x,x\rangle^{2}E-x\otimes x\right)\, dV,$$
where E is the identity tensor,
$E=e_{1}\otimes e_{1}+e_{2}\otimes e_{2}+e_{3}\otimes e_{3}.$
The 2-tensors act on vectors as $(a\otimes b)(v)=a(b\cdot v)$, and the
matrix representation of $a\otimes b$ in coordinates is $ab^{T}$ which acts on
column vectors. And so we have
$$I(n)=\int d^{3}x\,\rho(x)[\langle x,x\rangle^{2}n-x\langle x,n\rangle]$$
$$\langle n,In\rangle=\int d^{3}x\,\rho(x)[\langle x,x\rangle^{2}-\langle x,n\rangle^{2}]=I_{n}.$$
Comment: @Self, I think the relation of moment of inertia around an axis to the inertia matrix, similar to $I_{n}=\langle n,I n \rangle$, can be found in most textbooks on mechanics,  even without tensor notation.
Comment: I haven't got the tools to understand your proof yet, but I thank you for it very much!

Invertibility of inertia matrices


Show delete link on comments

Question: I have a page which shows the comments posted by all users. Here I need to show a delete link on the side of the comments posted by that current logged in user and he should be able to delete that comment too (like in Facebook, Orkut or any Blogging site). The sample code which I have tried is:
<?php
$user_id = 1;
$con = mysql_connect("localhost","root","root");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("blog", $con);

$result = mysql_query("SELECT * FROM replies");

while($row = mysql_fetch_array($result))
  {
  $replies = $row;
  if($replies['poster_id' == $user_id]){
      $delete = 'Delete';
  }

  echo $replies['poster_id']?> ¦ <?php echo $replies['reply_text']?> ¦   <?php echo $delete?>

  <?php echo "
";
  }

mysql_close($con);
?>

Here I have given the user_id which is hardcoded here. What I got is, delete link is displayed on all comments. I need to display delete link for user_id with "1" only. Can anyone suggest me to get the solution...Thanks in Advance...
Comment: if($replies['poster_id' == $user_id]){
need to be

if($replies['poster_id'] == $user_id){
Answer: if($replies['poster_id' == $user_id]){

need to be
  $delete ='';
  if($replies['poster_id'] == $user_id){
      $delete = 'Delete';
  }

you need to unset the $delete variable in every loop, if not once its get a value and present it in every cycle of loop
Comment: @Haim Evgi: I am getting the delete link for each comment. It should be shown for comments which have user_id 1
Comment: i understand this, did u try to change this line ?
Comment: yes i changed..Now the code looks like: $replies = $row;
  $delete ='';
   if($replies['poster_id' == $user_id]){
    $delete = 'Delete';

   }
Comment: the if condition need to be :   if($replies['poster_id'] == $user_id){  did its work ?
Comment: here its showing all the comments with delete link near by it.
Comment: Then you still need to unset / reset $delete in the loop. That should be the first or second statement in the loop (at least before the if-statement).

Show delete link on comments