Python property decorator not working, why?

Question: For some reason the 'obj._max_value' and 'obj._current_value' are not getting set. I have looked at many tutorials and it seems that I am doing it correctly. Does anyone know why it is not working?
See code: https://gist.github.com/matthew-campbell/5561562
(Python 2.7)

Update:
class Progress():

  @property
  def progress_bar_length(self):
    return self._progess_bar_length

  @progress_bar_length.setter
  def progress_bar_length(self, length):
    self._progress_bar_length = length

  @progress_bar_length.deleter
  def progress_bar_length(self):
    del self.progress_bar_length

Comment: Don't use huge mostly irrelevant code samples, and definitely don't post links to Gists. It's recommended to reduce your problem down to its essentials, and post a code sample (as simple as you can make it) in your question. Your problem could easily have been demonstrated with <10 lines of code.
Answer: The property decorator doesn't work with old-style classes. Inherit your class from object to get a new-style class:
class Progress(object):
    # ...

Comment: @MattCampbell Also, Python is not Java. You most likely don't need all those properties, they only serve to slow down your program and make it *harder* to maintain (because of loads of unnecessary boilerplate).
Comment: @user4815162342 Why would you say so? I find it convenient to use. How do you know it slows down the computer?
Comment: @Valentyn Properties are fine when they actually make sense in your program, but you don't need to use them _everywhere_, e.g. to expose a "private" slot as a "public" property. This slows down the program (not the computer!) because CPython is interpreted, so there's no JIT compiler to inline all those accessor function calls. Also, in Python you can always start off with a public attribute and migrate it to a property later without loss of API compatibility. There's no reason to use a property because you *might* need to add logic in the future - you'll add it if/when you actually need it.


Making an AR(3) model weakly stationary

Question: I have a model as:$$r_t=0.05+\frac{7}{6}r_{t-1}+\frac{1}{6}r_{t-2}-\frac{1}{3}r_{t-3}+a_t$$
When checking for stationarity:
$$1-\frac{7}{6}x-\frac{1}{6}x^2+\frac{1}{3}x^3=0$$ I get $x\in \{-2,1,1.5\}$. Since the absolute value of 1 is not greater than 1, this is not stationary.
My question is how can I make this stationary? I can't deduct the mean from $r_t$'s because of the non-stationarity, the mean is not time-invariant.
Any helps would b appreciated!
Answer: You can't make your process stationary. It is simply not stationary, because it has a unit root. However, there is a related process which has no unit root, and is stationary.
Your process can be written like this, with the backshift operator $B$:
$$\left(1-\frac{7}{6}B-\frac{1}{6}B^2+\frac{1}{3}B^3\right)r_t = 0.05 + a_t$$
As you computed, the characteristic polynomial has roots 1, -2 and 1.5. You can use synthetic division to compute the result of factoring out the unit root, which you can use here to write:
$$\left(1-\frac{1}{6}B-\frac{1}{3}B^2\right)\left(1-B\right)r_t = 0.05 + a_t$$
You can then define the differenced process $y_t := (1-B)r_t$, so you have:
$$\left(1-\frac{1}{6}B-\frac{1}{3}B^2\right)y_t = 0.05 + a_t$$
The roots of the characteristic polynomial for $y_t$ are just the ones we didn't factor out, -2 and 1.5, so $y_t$ is stationary.
Comment: Thanks Chris. One question though. Is $B=r_{t}-r_{t-1}$ and $B^2={r_{t-1}-r_{t-2}}$? Which then this would yield: $y_t=0.05+\frac{1}{6}y_{t-1}+\frac{1}{3}y_{t-2}+a_t$?
Comment: @statwoman The last equation you show is correct, but the notation before that is wrong (maybe you meant that $B^2y_t = y_{t-2} = r_{t-2} - r_{t-3}$?).
Answer: If your process contains a unit root, consider differencing it. Instead of $r_t$, you can study
$$y_t:=\Delta r_t=r_t-r_{t-1}.$$
Once you have learned about $y_t$, you can extend inference to $r_t$ by noting that
$$r_t=r_0+y\sum_{\tau=1}^t y_\tau$$
or
$$r_t=r_{t-1}+y_t$$
depending on what is easier to work with / more relevant in your situation.
Comment: Thanks. But even if I differentiate it, the coefficient would stay the same right? So in that case, the process is again not stationary.
Comment: @statwoman The coefficient on $r_{t-1}$ should be $\frac{1}{6}$ after differencing.
Comment: @statwoman, the point of differencing (not differentiation, though they are related) is that your unit root process loses the unit root and becomes stationary. The coefficients do not stay the same.

Making an AR(3) model weakly stationary


Non-existence of non-trivial clopen set in $\mathbb R$ without using connectedness

Question:
Show that the set of real numbers has no nontrivial clopen set without using connectedness of $\mathbb R$.

I tried to show this by showing that an open set in $\mathbb{R}$ is strictly contained in its closure.
My attempt:

Let $U$ is open in $\mathbb{R}$. Then $U$ can be written as union of disjoint open intervals. $U =  \bigcup_{n=1}^{\infty}A_n$ , where $A_n = (a_n, b_n)$. Now Closure of $U, Cl(U) = Cl( \bigcup_{n=1}^{\infty}A_n) =  \bigcup_{n=1}^{\infty}Cl(A_n)$ [ not true in general ] = $ \bigcup_{n=1}^{\infty}[a_n, b_n] \supsetneq U$. So the problem thus reduces to the problem, whether $Cl(\bigcup_{n=1}^{\infty}A_n) =  \bigcup_{n=1}^{\infty}Cl(A_n)$ holds for countably infinite intervals in $\mathbb{R}$. This surely holds for finitely many sets, but doesn't hold for countably infinitely many sets in general. Is this true? or there's another proof of this?
Comment: It is not true that $\operatorname{cl}\bigcup\limits_{n\in\Bbb N}(a_n,b_n)=\bigcup\limits_{n\in\Bbb N}[a_n,b_n]$. For instance, consider $a_n=\frac1{n+1}$ and $b_n=\frac1n$. $$\bigcup_{n\in\Bbb N}(a_n,b_n)=(0,1)\setminus\{1/n\,:\,n\in\Bbb N,\ n\ge 2\}\\\bigcup_{n\in\Bbb N}[a_n,b_n]=(0,1]\\ \operatorname{cl}\bigcup_{n\in\Bbb N}(a_n,b_n)=[0,1]$$
Comment: You're right. On the other hand, the answer to your question is negative. Take $A_1=(1/2,1)$, $A_2=(1/4,1/2)$, $A_3=(1/8,1/4)$, and so on. Then $0$ belongs to the closure of the uniont, but not to the union of the closures.
Comment: Your proof is actually very close to being correct. You do not need the (false) equation $Cl(U) = Cl( \bigcup_{n=1}^{\infty}A_n) =  \bigcup_{n=1}^{\infty}Cl(A_n)$ to prove that $U$ is not closed. You only need the (true) inclusion  $Cl(U) = Cl( \bigcup_{n=1}^{\infty}A_n) \supset  \bigcup_{n=1}^{\infty}Cl(A_n)$ together with the observation you have already made that the endpoints of each $A_n$ are not elements of $U$.
Comment: Why do you assert that $\bigcup_{n=1}^\infty[a_n,b_n]\neq U$?
Comment: Because the points a_n, b_n aren't in U
Comment: The problem is that the family need not be locally finite, it holds when every point of the reals has a neighbourhood intersecting at most finitely many of the intervals. Then the closure of the union is the union of the closures. But in the example given the intervals cluster round $0$.
Comment: @HennoBrandsma Can you please explain a little bit more?
Comment: @user398623 look up "locally finite family" and "closure preserving family" online.
Answer: Let $U, V$ be non-empty open subsets of $\Bbb R$ with $U\cap V=\emptyset$ and $U\cup V=\Bbb R$.
Pick $u\in U$, $v\in V$.
Wlog. $u<v$. Let $w=\inf\bigl(V\cap [u,v]\bigr)$.
If $w\in U$ then $(w-\epsilon,w+\epsilon)\subseteq U$ for some $\epsilon>0$, and so $[w,w+\epsilon)\cap V=\emptyset$, contradicting the definition of infimum.
Hence $w\in V$, in particzular $w>u$. But then $(w-\epsilon,w]\subset V$ for some $\epsilon>0$, again contradicting the definition of infimum.


linux command explain du -h --max-depth=1

Question: Can someone explain to me the following command in linux? (I know that with that command you can find the total space taken by each of the directories)
du -h --max-depth=1

Can you suggest a good way to understand in depth these commands?
thanks.
Comment: It's one command, `du` (disk usage) with the option `-h` (human readable) and limit the search to `1` subdirectory level. See [man 1 du](https://man7.org/linux/man-pages/man1/du.1.html)
Answer: I assume that you want to know about this command in brief so, I'll just break it up for you:

du: this command is used to estimate file space usage
-h: this parameter is short for --human-readable to print sizes in human readable format
--max-depth=1: this parameter defines how deep in terms of folder structure level you want to see the output like is its level 1 then,
output will show the size for all the files and folders in current
directory but not for the content inside the folders the current
directory has

You can use this website to learn more about linux commands: https://explainshell.com/explain?cmd=du+-h+--max-depth%3D1
Answer: I recommend you to use du --help or man du to get help, and try these command yourself. You can remove or change any arguments and find out the differences between them.
-h means human readable, it will display the size like 1K or 3.5G, rather than only a number.
--max-depth=1 means it will only count the files and directories in current directory, sub-directories and sub-files will not display.


Converting Strings of formatted text, Is there a better way to do this?

Question: Here is the text file that I am parsing

//(*
      Set Table Limits Min + color code *
      1,3
      2,3
      5,0
      10,5
      15,6
      25,8
      50,7
      100,10
      * Set Table Limits Max*
      100
      200
      300
      500
      1000
      2000
      3000
      5000
      10000
      <>

and here is code
private void addMinBets(String aDataRow) {

    // Process Min limits
    // Does aDataRow start with "!= *"
    // process string
    // else do nothing
    // Process Max limits
   if (!aDataRow.contains("*")){
            // Find the index of ","
             // Get string before ","
             // Get string After ","
       if (aDataRow.contains(",")){
                 // Add Max bet to maxArraylist
           String parts[] = aDataRow.    split("\\,");
           Log.d("Split"," Match must be min =  $" + parts[0]);
           Log.d("Split"," Match must be min color = " + parts[1]);
       }
       if (!aDataRow.contains("*")){

           if (!aDataRow.contains(",")){

               if (!aDataRow.contains("<")){

                 Log.d("Split"," Match must be max bet = $ " + aDataRow);

               }

           }

       }

   }

Is there a more efficient way to do this in code?
Thanks in advance
Comment: Did you tried using regex?
Answer: It seems to me that you only want to log strings that are of the form:

digit(s)
digit(s),digit(s)

Then you want to use regex like @Thusitha Thilina Dayaratne suggested.
Made a quick sample using link as example.
private void addMinBetsV2(String aDataRow) {
    //[one or more digits]
    String numRegex = "(\\d)+";
    //[one or more digits],[one or more digits]
    String commaNumRegex = numRegex + "," + numRegex;

    if (aDataRow.matches(numRegex)) {
        Log.d("Split"," Match must be max bet = $ " + aDataRow);
    } else if (aDataRow.matches(commaNumRegex)) {
        String parts[] = aDataRow.    split("\\,");
        Log.d("Split"," Match must be min =  $" + parts[0]);
        Log.d("Split"," Match must be min color = " + parts[1]);
    }
}

Comment: Thanks it works great and expandable without the overhead.. need to get better grasp on formatting expressions.


PHP: filter_input com REQUEST

Question: Como a maioria deve saber, no PHP 5.2 foi implementada a função filter_input.
Estou trabalhando tranquilo com ela, sem nenhuma dúvida muito alarmante.
O problema é que: eu consigo trabalhar bem com ela, utilizando no 1º parâmetro as flags INPUT_GET ou INPUT_POST quando preciso validar utilizando o FILTER_SANITIZE_ENCODED.
Porém, na aplicação que estou trabalhando também preciso validar o INPUT_REQUEST (que não está implementado), e aí vem o erro.

Detalhe que a versão do PHP que estou utilizando é a 5.5.6.
Gostaria de saber se alguém conhece ou tem algum método que faça o filtro do $_REQUEST assim como o filter_input deveria fazer.
Comment: Posta a parte do código que está dando erro.
Answer: A variável $_REQUEST é uma supervariável que contém as variávels $_GET, $_POST e $_COOKIE, na ordem definida pela diretiva request_order do PHP.
Sendo assim, não vejo a necessidade de usar a constante INPUT_REQUEST se você souber de qual das outras supervariáveis o valor que você quer filtrar está vindo.
Comment: Também tava sabendo dessa falha de segurança pelo `REQUEST` mas resolvi tentar assim mesmo, e desisti. Fiz uma função bem simples pra tratar isso: `switch ($_SERVER['REQUEST_METHOD']) {
        case 'GET':
            return filter_input(INPUT_GET, $val, FILTER_SANITIZE_ENCODED);
        default:
        case 'POST':
            return filter_input(INPUT_POST, $val, FILTER_SANITIZE_ENCODED);
    }`
Comment: Não sei onde li que usar a variável `$_REQUEST` constitui uma falha de segurança, pois a variável pode vir de três maneiras diferentes. Além disso, se você usa `$_GET`, `$_POST` ou `$_COOKIE`, você está sendo explícito no seu código de onde a variável está vindo. Pessoalmente, não vejo problema em optar por um desses em vez do `$_REQUEST` :)
Comment: A questão é que às vezes, em parte do código, eu faço uma chamada via ajax pra uma página `query.php?key1=val1&key2=val2` e ainda passo parâmetros POST, ou seja, ela recebe GET e POST, logo, seria mais rápido tratar o request.
Answer: Esse é um tópico bastante antigo, mas já que este foi trazido à tona novamente deixarei duas possíveis soluções para o problema.
Como você bem descobriu, a funcionalidade de INPUT_REQUEST não foi implementada, então diferentemente do sugerido pelo Marcio, você não pode utilizar filter_input_array() pois terá o mesmo erro.
A primeira solução apoia-se na função filter_var_array(). Sua aplicabilidade é mais apropriada quando:

Todas as entradas puderem receber o mesmo tipo de tratamento
Você não souber o que pode vir por $_REQUEST

Para usar função filter_var_array() você deve criar um array associativo tendo como chaves os índices presentes em $_REQUEST (ou em outro array que precise) e como valores os filtros a serem aplicados.
Mas, como precisamos do memso dinamismo proporcionado por pela flag que usaríamos em filter_input() e filter_input_array(), não podemos criar esse array manualmente, então usaremos array_combine(), array_keys() e array_fill() que, juntos, permitirão a criação de um novo array em runtime, de comprimento variável e com a mesma estrutura de $_REQUEST:
$args = array_combine(

    array_keys( $_REQUEST ),

    array_fill( 0, count( $_REQUEST ), FILTER_SANITIZE_ENCODED )
);

array_combine() espera dois arrays como argumento. Um para servir de chaves e outro de valores.
Usamos array_keys() para obter todas as chaves de $_REQUEST e, como não sabemos quantos elementos existem em $_REQUEST para podermos montar a contra-parte necessária, usamos array_fill() que cria um novo array com uma quantidade pré-definida de elementos, aqui obtidos contando a quantidade de entradas em $_REQUEST. Todas as entradas terão o mesmo valor, no caso, a flag FILTER_SANITIZE_ENCODED.
E passaremos esse array para filter_var_array():
$filtered = filter_var_array( $_REQUEST, $args );

Isso num arquivo acessado com uma URL propositalmente nociva como http://localhost:8080/test.php?foo=, resulta um var_dump() com:
array (size=1)
  'foo' => string '%3Cscript%3Ealert%28%27hi%27%29%3B%3C%2Fscript%3E' (length=49)

A segunda alternativa é iterar o array desejado ($_REQUEST) e aplicar filter_var() em cada entrada gerando um novo array limpo.
Ela é mais apropriada quando:

Algumas entradas não puderem ser validadas por uma flag em particular -OU- requerer uma flag específica que não justificaria aplicar aos outros valores

O array a ser filtrado/validado/sanitizado é pequeno, porque iterar arrays grandes é ruim para performance
 $cleansed = array();

 foreach( $_REQUEST as $offset => $entry ) {
     $cleansed[ $offset ] = filter_var( $entry, FILTER_SANITIZE_ENCODED );
 }

A saída desse array será a mesma acima.
Quanto à primeira consideração de aplicabilidade feita sobre essa segunda técnica, você não necessariamente precisa levar ela em consideração para optar por essa técnica.
Você pode muito bem usar o primeiro método e, logo em após criar o array a ser usado ($args), sobrescrever um ou mais índices previamente conhecidos manualmente antes de informar esse array como argumento para filter_var_array():
$args = array_combine(

    array_keys( $_REQUEST ),

    array_fill( 0, count( $_REQUEST ), FILTER_SANITIZE_ENCODED )
);

$args['algum_campo_de_URL'] = FILTER_SANITIZE_URL;

// Ou

$args['algum_campo_sem_tratamento'] = NULL;

Nota: Não remova o índice com unset() caso contrário a entrada correspondente. ao invés de ser mantida intocada, será removida do array resultante.

Agora que o problema foi solucionado em gostaria de deixar uma palavrinha sobre o porquê de usar $_REQUEST poder ser prejudicial.
Os chamados HTTP Verbs foram criados em sua vasta especificidade para servir cada um para um propósito único. E apesar de atualmente nenhum browser respeitar todos os verbos quando definidos no atributo method de um formulário, não significa que você deva programar de forma errada também.
Sendo assim, se é POST, usemos $_POST. Se é GET, usemos $_GET. Precisamos de algum cookie? $_COOKIES.
Agora veja um cenário hipotético onde usar $_REQUEST ao invés de um dos três superglobais corretos é prejudicial:
Imagina uma situação na qual você coincidentemente tem uma variável de nome X que DEVE transitar exclusivamente via GET e outra, também chamada X, exclusivamente por POST.
Usando $_GET e $_POST, você pode perfeitamente utilizar os nomes idênticos. Mesmo que não pareça muito certo, às vezes, por harmonia léxica (sou tarado por isso com programo :P), é justificável.
Mas se você codificar seu script inteiramente com $_REQUEST, um sobrescreverá o outro e pela sutileza do procedimento, o debug seria complicado.
Veja um exemplo (bem porco) ilustrando isso:
var_dump( $_REQUEST, $_POST, $_GET );

echo '<form method="post">';
echo '<input type="hidden" name="nome" value="Bruno" />';
echo '<input type="submit" value="Vai" />';

echo '</form>';

Ao acessar a página pela primeira vez haverão três arrays vazios, afinal não existe informação ainda.
Colocando um parâmetro GET nome na URL (Bruno Augusto, para ilustrar), você verá Bruno Augusto saindo de $_REQUEST e outro, no terceiro, de $_GET. O segundo, referente à $_POST, continuará vazio.
Submeta o formulário. Será mostrado Bruno duas vezes e Bruno Augusto uma.
Isso porque o $_REQUEST mescla tudo e, graças à ordem das variáveis, o Bruno do campo oculto vindo de $_POST sobrescreverá o Bruno Augusto vindo de $_GET, porque nos arrays superglobais, possuem o mesmo índice.
Você também é afetado por esse problema bastante sutil ao usar JavaScript pois dados GET e POST são basicamente cabeçalhos e também estão sujeitos a sobrescrita.
Ainda não está convencido quanto ao seu caso por transitar dados por AJAX? Tá bom:
test.html
$(function(){

    $.ajax({

        method: 'post',
        url: 'http://localhost/test.php?var1=value1',
        data: { var1: 'some content', var2: 'doh' }

    }).done( function( data ) {

        console.log( data );

    }).fail( function( xhr, status ) {

        console.log( status );
    });

});

test.php
O console response após a Requisição de sucesso:
"{"var1":"value1"}

{"var1":"some content","var2":"doh"}

{"var1":"some content","var2":"doh"}"

var1 em $_REQUEST por padrão preenchida com var1 de $_GET foi sobrescrita pelo var1 vindo de $_POST.
Answer: Você pode tentar utilizar filter_input_array(). Por exemplo:
$vars = array(
    'key1' => FILTER_SANITIZE_NUMBER_INT
);

$entradas = filter_input_array(INPUT_REQUEST, $vars);

echo $entradas['key1'];

Outra opção é utilizar filter_var(), o uso é simples:
echo filter_var($_REQUEST['key1'], FILTER_SANITIZE_NUMBER_INT);

Mas lembre-se que os filtros estão longe de garantir que sua aplicação está segura, você deve procurar parametrizar suas querys via PDO e escapar caracteres especiais de acordo com o seu banco de dados.

PHP: filter_input com REQUEST


Exist way notify when custom UIView will be presented or removeFromSuperview()?

Question: I am create custom UIView using this code:
lazy var temporary: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
        view.backgroundColor = .white
        return view

    }()

Exist way use NotificationCenter notify when this view will be presented and removed from VC if I am use:
self.view.addSubview(temporary)

or
temporary.removeFromSuperview()

Answer: I'm not totally sure what you are asking. I think you're asking for a way to tell when your custom view is added as a subview of another view.
The easiest way to do that is to make your view a custom subclass of UIView, and implement didMoveToSuperview() or willMove(toSuperview:). Those methods get called when your view is added as a child view of another view.
If you really want to use the notification center you could have your custom view class broadcast a notification when it gets added to a superview.


To find eigenvalues of matrix with all same element

Question: How many distinct eigenvalues are there in the matrix.
$$
    \begin{bmatrix}
    1 & 1 & 1 & 1 \\
    1 & 1 & 1 & 1 \\
    1 & 1 & 1 & 1 \\
    1 & 1 & 1 & 1 \\
    \end{bmatrix}
$$
I was wondering that is there any specific eigenvalues for matrices like this??
I hope I wouldn't have to find the determinant of this 4×4 matrix.
Comment: Moreover the multiplicity of the eigenvalue $0$ can be determined to be $3$ since this map collapses $\mathbb{R}^4$ onto a one-dimensional subspace.
Comment: Well, the determinant is clearly 0.  How clear that is depends on what topics you've already covered, but basically since the rows are linearly dependent then the determinant is 0.
Comment: https://math.stackexchange.com/questions/217521/what-are-the-eigenvalues-of-matrix-that-have-all-elements-equal-1
Comment: Once you know the fact from Tob Ernack, it's clear the other eigenvalue is 4 since the trace is the sum of eigenvalues.
Answer: Note that $$\left(\begin{matrix}1&1&1&1\\ 1&1&1&1\\ 1&1&1&1\\ 1&1&1&1\end{matrix}\right)\left(\begin{matrix} a\\ b\\ c\\ d\end{matrix}\right)=\left(\begin{matrix} a+b+c+d\\ a+b+c+d\\ a+b+c+d\\ a+b+c+d\end{matrix}\right)$$
If $a=b=c=d$, then $$\left(\begin{matrix}1&1&1&1\\ 1&1&1&1\\ 1&1&1&1\\ 1&1&1&1\end{matrix}\right)\left(\begin{matrix} a\\ a\\ a\\ a\end{matrix}\right)=4\left(\begin{matrix} a\\ a\\ a\\ a\end{matrix}\right)$$
Hence $4$ is an eigenvalue.
Also see that since all the columns of the matrix are same, the rank of the matrix is $1$. So $4$ is the only non zero eigenvalue. $0$ is the other eigenvalue, with eigenvector, for example $(a~-a~a~-a)^t$.
Answer: If $A$ is an $n$ by $n$ all-one matrix, then $A^2=nA$. If $\newcommand{\la}{\lambda}\la$ is an eigenvalue, with an eigenvector $v$ then $A^2v=nAv$, that is $\la^2 v=n\la n$. From this we get $\la=0$ or $n$. The other solutions show how to find eigenvectors for these eigenvalues. As the trace of $A$ is $n$, the eigenvalue $n$ appears with multiplicity one.
Answer: Let $e=(1,1,1,1)^T$ then $A=e e^T$.
Note that $\dim\ker A = 3$ and so $A$ has three eivenvalues at zero.
Suppose $Av=\lambda v$ for some non zero $v$  and $Av \neq 0$. We see that we can take $v=e$ (since ${\cal R} A = \operatorname{sp} \{ e \}$), and so
$Ae = 4 e$ and so $\lambda = 4$.
Hence the eigenvalues are $0,0,0,4$.
In general, matrices of the form $uv^T$ are called dyads, and a similar analysis shows that they have $n-1$ zero eigenvalues and
a single eigenvalue of $v^Tu$ (which could also be zero) corresponding to eigenvector $u$.


Google App Engine. Python. NDB. BadValueError: Expected string, got

Question: I've been trying to understand this error for a little while, but cannot find the answer.
I have a Model - Address - for which I am creating a new entity in the Datastore.
Here's the Model:
class Address(ndb.Model):
    """
    model for storing the addresses of the club, both physical and for mailing
    """
    club_key = ndb.KeyProperty(kind="Club")
    address_type = ndb.StringProperty()  #: physical, mailing
    street = ndb.StringProperty()  #: or PO Box if necessary
    city = ndb.StringProperty()
    province = ndb.StringProperty()
    region = ndb.StringProperty()
    post_code = ndb.StringProperty()
    country = ndb.StringProperty()
    coordinates = ndb.GeoPtProperty()  #: for physical address
    date_added = ndb.DateTimeProperty(auto_now_add=True)

    #: method to save a new address
    @classmethod
    def save_address(cls, club_key, address_type, street, city, province, region, post_code,
        country, coordinates, id_string):
        new_address = cls(club_key=club_key, address_type=address_type, street=str,
        city=city, province=province, region=region, post_code=post_code, country=country,
        coordinates=coordinates,
                          id=id_string).put()
        return new_address.id()

Here is the Handler for creating the Address entity:
class AddNewAddressHandler(BaseHandler):
"""
a handler to add the address info for a club
"""
def post(self):
    club_key = self.get_url_string(-1)
    club_key = ndb.Key(urlsafe=club_key)
    address_type = self.request.get("type")
    street = self.request.get("street")
    city = self.request.get("city")
    province = self.request.get("province")
    region = self.request.get("region")
    postcode = self.request.get("postcode")
    country = self.request.get("country")
    coordinates = self.request.get("coordinates")
    coordinates = ndb.GeoPt(coordinates)
    club = self.get_url_string(-2)
    club = unquote(club)  # from urllib2
    id_string = address_type + "-" + club
    id_string = id_string.strip().replace(" ","-").lower()
    db.Address.save_address(club_key, address_type, street, city, province, region,
        postcode, country, coordinates, id_string)
    redirect_str = self.get_url_string(-3)
    self.redirect("admin/club_dashboard/%s" % redirect_str)

This then throws the following error:
Traceback (most recent call last):
  File "C:\Program Files\Google\google_appengine\lib\webapp2 2.5.2\webapp2.py", line 1535, in __call__
rv = self.handle_exception(request, response, e)
  File "C:\Program Files\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 1529, in __call__
rv = self.router.dispatch(request, response)
  File "C:\Program Files\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 1278, in default_dispatcher
return route.handler_adapter(request, response)
  File "C:\Program Files\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 1102, in __call__
return handler.dispatch()
  File "C:\Program Files\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 572, in dispatch
return self.handle_exception(e, self.app.debug)
  File "C:\Program Files\Google\google_appengine\lib\webapp2-2.5.2\webapp2.py", line 570, in dispatch
return method(*args, **kwargs)
  File "C:\Users\Me\PycharmProjects\my_app\admin\admin.py", line 95, in post
id_string)
  File "C:\Users\Me\PycharmProjects\my_app\admin\database\models.py", line 62, in save_address
id=id_string).put()
  File "C:\Program Files\Google\google_appengine\google\appengine\ext\ndb\model.py", line 2927, in __init__
self._set_attributes(kwds)
  File "C:\Program Files\Google\google_appengine\google\appengine\ext\ndb\model.py", line 2973, in _set_attributes
prop._set_value(self, value)
  File "C:\Program Files\Google\google_appengine\google\appengine\ext\ndb\model.py", line 1128, in _set_value
value = self._do_validate(value)
  File "C:\Program Files\Google\google_appengine\google\appengine\ext\ndb\model.py", line 1075, in _do_validate
value = self._call_shallow_validation(value)
  File "C:\Program Files\Google\google_appengine\google\appengine\ext\ndb\model.py", line 1267, in _call_shallow_validation
return call(value)
  File "C:\Program Files\Google\google_appengine\google\appengine\ext\ndb\model.py", line 1314, in call
newvalue = method(self, value)
  File "C:\Program Files\Google\google_appengine\google\appengine\ext\ndb\model.py", line 1764, in _validate
(value,))
BadValueError: Expected string, got <type 'str'>

I'm sure it's obvious and I just can't see it.
Answer: In save_address(), 'street=str' should be 'street=street'.
Comment: Thanks, cannot believe I didn't see that.
Answer: I think you want street=street
Answer: In Python when you write string.method(), the return of the method is automatically passed to the string, you don't need to say newString = string.method(). Actually, string.method() isn't intended to return anything so it returns the "type" of the variable not the new value of the string.
Just replace
id_string = id_string.strip().replace(" ","-").lower()

with
id_string.strip().replace(" ","-").lower()


Problema no projeto angular

Question: Fui tentar instalar o socket.io-client no meu projeto e estragou o meu sistema
Está dando a seguinte mensagem:

Unhandled promise rejection Error: Zone.js has detected that
  ZoneAwarePromise (window|global).Promise has been overwritten.

Ja removi a pasta node_modules e o package-lock.json e o problema continua
Como resolver o problema?
[EDIT]
Meu app.module.ts está assim:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { AppRoutingModule } from './app-routing.module';

import { FrameComponent } from './shared/frame/frame.component';
import { HeaderComponent } from './shared/header/header.component';
import { FooterComponent } from './shared/footer/footer.component';
import { EnergiaServiceService } from './shared/provider/energia-service.service';
import { HttpClientModule } from '@angular/common/http';
import { FusionChartsModule } from 'angular-fusioncharts'
//import import FusionChart library and chart modules
import * as FusionCharts from 'fusioncharts'
import * as Charts from 'fusioncharts/fusioncharts.charts' //barras
import * as Widgets from 'fusioncharts/fusioncharts.widgets'; //gauge
import * as FusionTheme from 'fusioncharts/themes/fusioncharts.theme.fusion';
import { GaugeComponent } from './shared/gauge/gauge.component';
import { MedidorComponent } from './medidor/medidor.component'
import { LocationStrategy, HashLocationStrategy } from '@angular/common';
import { AlertComponent } from './shared/alert/alert.component';

//Pass the fusioncharts library and chart modules
FusionChartsModule.fcRoot( FusionCharts, Widgets, FusionTheme )

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    FrameComponent, HeaderComponent, FooterComponent, GaugeComponent, MedidorComponent, AlertComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    FusionChartsModule
  ],
  providers: [
     EnergiaServiceService
     //{provide: LocationStrategy, useClass: HashLocationStrategy}
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Meu package.json está assim:
{
  "name": "poraque-monitoramento",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^4.0.0",
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "core-js": "^2.4.1",
    "rxjs": "^5.4.1",
    "zone.js": "^0.8.14"
  },
  "devDependencies": {
    "@angular/cli": "1.2.7",
    "@angular/compiler-cli": "^4.0.0",
    "@angular/language-service": "^4.0.0",
    "@types/jasmine": "~2.5.53",
    "@types/jasminewd2": "~2.0.2",
    "@types/jquery": "^3.3.29",
    "@types/jquery-knob": "^1.2.31",
    "@types/node": "~6.0.60",
    "admin-lte": "^2.4.9",
    "angular-fusioncharts": "^3.0.1",
    "codelyzer": "~3.0.1",
    "fusioncharts": "^3.13.4",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "jquery": "^3.3.1",
    "jquery-knob": "^1.2.11",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.0.4",
    "tslint": "~5.3.2",
    "typescript": "~2.3.3"
  }
}

Meu .angular-cli.json está assim:
{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "poraque-monitoramento"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "../node_modules/admin-lte/bower_components/bootstrap/dist/css/bootstrap.min.css",
        "../node_modules/admin-lte/bower_components/font-awesome/css/font-awesome.min.css",
        "../node_modules/admin-lte/bower_components/Ionicons/css/ionicons.min.css",
        "../node_modules/admin-lte/dist/css/AdminLTE.min.css",
        "../node_modules/admin-lte/dist/css/skins/_all-skins.min.css",
        "../node_modules/admin-lte/bower_components/jvectormap/jquery-jvectormap.css",
        "../node_modules/admin-lte/bower_components/bootstrap-datepicker/dist/css/bootstrap-datepicker.min.css",
        "../node_modules/admin-lte/bower_components/bootstrap-daterangepicker/daterangepicker.css",
        "../node_modules/admin-lte/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css",
        "styles.css"
      ],
      "scripts": [
        "../node_modules/admin-lte/bower_components/jquery/dist/jquery.min.js",
        "../node_modules/admin-lte/bower_components/jquery-ui/jquery-ui.min.js",
        "../node_modules/admin-lte/bower_components/bootstrap/dist/js/bootstrap.min.js",
        "../node_modules/admin-lte/bower_components/jquery-sparkline/dist/jquery.sparkline.min.js",
        "../node_modules/admin-lte/plugins/jvectormap/jquery-jvectormap-1.2.2.min.js",
        "../node_modules/admin-lte/plugins/jvectormap/jquery-jvectormap-world-mill-en.js",
        "../node_modules/admin-lte/bower_components/jquery-knob/dist/jquery.knob.min.js",
        "../node_modules/admin-lte/bower_components/moment/min/moment.min.js",
        "../node_modules/admin-lte/bower_components/bootstrap-daterangepicker/daterangepicker.js",
        "../node_modules/admin-lte/bower_components/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js",
        "../node_modules/admin-lte/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js",
        "../node_modules/admin-lte/bower_components/jquery-slimscroll/jquery.slimscroll.min.js",
        "../node_modules/admin-lte/bower_components/fastclick/lib/fastclick.js",
        "../node_modules/admin-lte/dist/js/adminlte.min.js"
      ],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "project": "src/tsconfig.app.json",
      "exclude": "**/node_modules/**"
    },
    {
      "project": "src/tsconfig.spec.json",
      "exclude": "**/node_modules/**"
    },
    {
      "project": "e2e/tsconfig.e2e.json",
      "exclude": "**/node_modules/**"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "css",
    "component": {}
  }
}

Comment: vc utilizou este pacote ngx-socket-io ?
Comment: Tentei, mas foi com ele que deu problema, por isso mudei para o socket.io-client
Comment: O ideal é utilizar este  ngx-socket-io pois eles tem os wrappers necessários do Angular.... olhei aqui no github deles e parece tranquilo configurar https://github.com/rodgc/ngx-socket-io, vc consegue incluir os seus modulo principal, pra eu tentar reproduzir aqui?
Comment: ou criar aqui https://stackblitz.com
Comment: Editei e adicionei o `app.module.ts`, o `package.json` e o `angular-cli`
Comment: É que eu não gostaria de recomeçar meu projeto por causa dessa falha
Comment: Coloquei uma resposta, teste e me fala o resultado, pf.
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/96858/discussion-between-cezar-and-adventistaam).
Comment: Me passa teu e-mail no chat
Answer: Tente isso:
npm install ngx-socket-io
Seu app module deverá ficar assim:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { AppRoutingModule } from './app-routing.module';

import { FrameComponent } from './shared/frame/frame.component';
import { HeaderComponent } from './shared/header/header.component';
import { FooterComponent } from './shared/footer/footer.component';
import { EnergiaServiceService } from './shared/provider/energia-service.service';
import { HttpClientModule } from '@angular/common/http';
import { FusionChartsModule } from 'angular-fusioncharts'
//import import FusionChart library and chart modules
import * as FusionCharts from 'fusioncharts'
import * as Charts from 'fusioncharts/fusioncharts.charts' //barras
import * as Widgets from 'fusioncharts/fusioncharts.widgets'; //gauge
import * as FusionTheme from 'fusioncharts/themes/fusioncharts.theme.fusion';
import { GaugeComponent } from './shared/gauge/gauge.component';
import { MedidorComponent } from './medidor/medidor.component'
import { LocationStrategy, HashLocationStrategy } from '@angular/common';
import { AlertComponent } from './shared/alert/alert.component';

//Pass the fusioncharts library and chart modules
FusionChartsModule.fcRoot( FusionCharts, Widgets, FusionTheme )
const config: SocketIoConfig = { url: 'http://localhost:8988', options: {} };

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    FrameComponent, HeaderComponent, FooterComponent, GaugeComponent, MedidorComponent, AlertComponent
  ],
  imports: [
    BrowserModule,
    SocketIoModule.forRoot(config),
    AppRoutingModule,
    HttpClientModule,
    FusionChartsModule
  ],
  providers: [
     EnergiaServiceService
     //{provide: LocationStrategy, useClass: HashLocationStrategy}
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

E vc deve utilizar assim:
import { Injectable } from '@angular/core';
import { Socket } from 'ngx-socket-io';

@Injectable()
export class ChatService {

    constructor(private socket: Socket) { }

    sendMessage(msg: string){
        this.socket.emit("message", msg);
    }
     getMessage() {
        return this.socket
            .fromEvent("message")
            .map( data => data.msg );
    }
}

Como fica sua aplicação agora?

Problema no projeto angular


Como colocar uma div embaixo da outra?

Question: Senhores, estou tentando inserir uma div embaixo da outra, a mesma deve ficar conforme imagem em anexo, porém quando executo não está dando certo.
Segue um trecho do meu código, deve ser algum detalhe que devo estar deixando passar e não estou conseguindo identificar.

html, body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}
.jumbo {
 background-image: url(https://unsplash.it/600/300);
 background-size: cover;
}
.container {
  width: 60%;
  margin: 0px 160px ;
  box-sizing: border-box;
  border: 1px solid red;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  padding-top: 1rem;
}
.box {
  width: calc(50% - 2rem);
  height: 2rem;
  margin: 1.0em 1em;
  box-sizing: border-box;
  border: 1px solid black;
  display: flex;
}

.p1, .p2, .p3 {
  display: flex;
  align-items: center;
  justify-content: center;
  color: blue;
  font-family: sans-serif;
  font-weight: bold;
  background-color: #ffffff;
}

.p1 {
  flex-grow: 2;
  background-color: cyan;
  position: right;
}

.p2 {
  flex-grow: 1;
  background-color: blue;
  color: #fff;
  position: right;
}

.p3 {
  flex-grow: 1;
  background-color: white;
  position: right;
}

   GABRIEL P

   10.000,00

   55%

   texto1

   texto2

   texto3

   texto1

   texto2

   texto3

Answer: Tenta
.container {
    width: 60%;
    margin: 0px 160px;
    box-sizing: border-box;
    border: 1px solid red;
    display: block;
    justify-content: center;
    align-items: center;
    flex-wrap: wrap;
    padding-top: 1rem;

Comment: usar essas propriedades " css border-bottom-left-radius, border-bottom-right-radius, border-top-left-radius,   border-top-right-radius "
Comment: Deu certo @anacvignola, aproveitando, sabe como eu posso utilizar o border-radius sem comprometer a div por inteira? e deixar conforme a imagem sugere? Pois tentei usar mais nessa minha estrutura atual ela quebra a linha em 3.

Como colocar uma div embaixo da outra?


Dissonance across different octaves

Question: When I play to keys that form a dissonant interval (for example a major second using C and D) in the lower octave, I perceive the dissonance to be very strong.  But, when I move up to higher C's and D's the dissonance intensity seems to diminish.
Am I correct with my observation? And, if so, why is that happening?
Answer: This may be due to the interferences that the tone combination generates. When you tune in a string to another, you can hear a vibration getting slower as you approach unison. This effect is known as kick and the resulting interference is the difference between the two frequencies.
According to wikipedia, differences above 15 Hz are not perceived as vibrations anymore, rather as a "roughness".
When the difference reaches the hearing span of frequencies, a tone can be heard instead.
If you play C3 and D3 together, the frequency difference is approximately 16 Hz. The chord sounds rough.
If you play C6 and D6 together, the tone difference is approximately 128 Hz. You hear a third tone (a quite low C3) instead of a vibration or a "roughness".
The higher the frequency of two tones that are a whole tone apart, the greater the frequency difference is between them. The higher the tones, the less "rough" their sound.
Note that I have no other sources than the wikipedia page I linked to earlier, but this answer makes sense to me.
Comment: That's quite interesting, and I do believe you're right that the beat frequency can appear to be a third note.
Comment: @MatthewRead: yes, the third note is a combination tone. See http://en.wikipedia.org/wiki/Combination_tone or my answer to http://music.stackexchange.com/questions/5824/is-it-possible-to-create-the-illusion-of-a-sub-harmonic .
Comment: @Gauthier: the "roughness" is an effect of the construction of the ear. The two tones stimulate overlapping regions of the basilar membrane. The frequency bandwidth sensitive for overlap is increasingly greater at low frequencies (below 1000 Hz). I've written a longer explanation in another answer. :-)
Answer: Yes, you are correct!
At least there is a physiological explanation.
The construction of the human hearing apparatus causes a quality that is called critical bands.
A critical band represents a bandwidth in which a sounding frequency has to be alone for us to hear or perceive it clearly.
This bandwidth is, relatively speaking, increasingly wider for lower frequencies (less than 1000 Hz) and thus close notes are more likely to be perceived as dissonant in low musical registers.

More detail
If two tone frequencies are close to each other they disturb overlapping regions of the basilar membrane - where the hair cells are located - within the cochlea in the inner ear; but if the frequencies are far apart they stimulate two separate regions. The range of frequencies, in relation to a base frequency, that have a stimuli overlap is called the critical band for that base frequency.
If two tones are close enough - within approximately 10 Hz - they are fused and perceived as one tone with a beating, i.e modulation of the amplitude. (Unless they have the exact same frequency which will only generate a louder single tone.)
Increasing the frequency difference of the two tones to more than 10 Hz, but still with overlapping critical bands you pretty much hear one tone but with an unpleasant roughness (constituted by very fast beating).
When approaching a separation of the two tones' critical bands they will be perceived as two separate tones.
For frequencies above cirka 1000 Hz the critical bandwidth (in Hz) is a fixed fraction of roughly 15% of the frequency, so for higher octaves there shouldn't be a physiological difference in the perception of dissonance for the same tones.
But for frequencies below this the critical bandwidth is constant at about 100 Hz. This means that the critical band of a musical scale tone will encompass more and more surrounding notes as the frequencies get low and the frequency differences become small. That is; an interval (or chord) that was quite consonant in a high register might become dissonant in a low register because the tones' critical bands overlap there.
The highest amount of roughness or dissonance is perceived when the frequency difference is about 30% of the appropriate critical bandwidth. Which means about 30 Hz apart for tones below 1000 Hz.
Further, all of this applies to all overtone partials of a tone from a musical instrument.
Example
Lets look at an example with frequencies (in Hz) for C and D and their first set of overtone partials. First the C and D one octave below middle-C:

    Note    1st     2nd     3rd     4th     5th     6th
    C3    130.8   261.6   391.4   523.3   654.1   784.9
    D3    146.8   293.7   440.5   587.3   734.2   881.0

The first partials are 16 Hz apart which is within the critical band and yet more than 10 Hz apart, and thus will be perceived with roughness; i.e. as dissonance. The second partials are about 30 Hz apart, which here is 30% of the critical bandwidth and will therefor be perceived as rather much dissonant. The higher partials up to the sixth have increasing frequency differences, and since the critical bandwidth here is still (almost) constant they have decreasing roughness (with frequency differences representing about 50% to 80% of the critical bandwidth.) Also the higher partials are likely weaker for the tone on the instrument and therefor have a smaller impact on the dissonace perception.
Now let's look at the frequencies of the C and D one octave above middle-C:

    Note    1st     2nd     3rd     4th     5th     6th
    C5    523.3    1047    1570    2093    2616    3140
    D5    587.3    1175    1762    2349    2937    3524

The frequency difference of the first partials is at about 64% of the critical bandwidth. For the rest of the partials it's at about 82% of the critical bandwidth. This causes roughness or dissonance but not nearly as much as frequency differences at the roughness peak at 30% of the critical bandwidth such as was present in the C3-D3 chord.
Therefor the C3-D3 is perceived as more dissonant than the C5-D5!
I suppose different individuals might have different critical bands distribution over their hearing range, and of course the perception of dissonance is subjective (and cultural), but this is a general physiological explanation of why hauptstadt and others perceives greater dissonance for the same interval in lower registers than in high.
Sources:
 1. Musical Acoustics s.e, by Donald E. Hall, Brooks/Cole Publishing
    Company, CA.
 2. http://hep.physics.indiana.edu/~rickv/consonance_and_dissonance.html
I hope I got this right. It was a long time since I studied these kind of things.
Answer: There is no "correct" when it comes to dissonance; it's a subjective phenomenon.  If we're talking about a mathematical measure of dissonance, then the dissonance is the same in both cases since the ratio of the frequencies is the same.  (See Is there a way to measure the consonance or dissonance of a chord?)
I can guess at why it seems this way to you though.  The absolute frequency difference is greater for the higher pair of notes than the lower pair which may make the comparison "harder"; you perceive them less as nearby notes that are off from each other.  Though I can't find a reference at the moment I believe that in general it's harder to distinguish high notes so there may be a sort of mental blending effect that lowers the dissonance.
Comment: If the reference notes are on a piano, then one might take into account the 'bar' like timbre of the piano in the highest octaves vs the string like timbre in the lowest octaves.
Answer: As Matthew has pointed out "dissonance" is quite subjective. One potential objective metric could be "frequency components that are very close together". For example some consider a flat-five interval (say E to Bb) to be somewhat dissonant. This could be because the third harmonic of the and he second harmonic of the F# are just a half step apart and create some tension. As you add more notes you get more and more frequency combinations and the few close ones matter less. So you can add a low C and G to the mix and you get yourself a nice C7 chord.
Comment: You are absolutely correct about the flat-five. :-)

Dissonance across different octaves


How to run a cron task at the last minute of each day?

Question: Is this the correct way to run a cron task at the last minute of each day? This is to be used on node-cron.
<code>* 59 23 * * *
</code>
Answer: No, your Cron expression means, every second, at 59 minutes past the hour, between 11:00 PM and 11:59 PM
<code>59 23 * * *
</code>
Above is the one you are looking for.This means Every day At 11:59 PM


resultados diferentes usando rpart e caret

Question: Olá,
estou testando algums modelos de regressão e não entendi bem uma coisa:
usei o rpart do pacote rpart, e depois usei o train com metodo rpart do pacote caret
resultRPart <- rpart(EVADIU ~ ., data = data.rose)
resultCaret <- train(EVADIU ~ ., data = data.rose, method = "rpart")

eu esperava que os dois dessem o mesmo resultado (precision, recall, etc) mas não é o que aconteceu
o primeiro deu

precision : 0.599
recall : 0.412

o segundo

precision : 0.1439
recall : 0.6759

isso é normal ou estou comparando laranjas com bananas aqui?
Answer: O caret por padrão faz tuning de alguns hiperparâmetros de cada modelo. Ele tenta fazer isso de uma forma inteligente, mas que nem sempre é o adequado para o seu problema. Já o rpart ajusta o modelo exatamente como você definiu.
O caret não é muito claro com isso mesmo, e as vezes gera confusão...
No caso, para o rpart irá tunar o hiperparâmetro cp (complexidade). Ele decide um grid para testar de acordo a a seguinte função:
> getModelInfo("rpart")[[1]]$grid
function (x, y, len = NULL, search = "grid")
{
    dat <- if (is.data.frame(x))
        x
    else as.data.frame(x)
    dat$.outcome <- y
    initialFit <- rpart(.outcome ~ ., data = dat, control = rpart.control(cp = 0))$cptable
    initialFit <- initialFit[order(-initialFit[, "CP"]), , drop = FALSE]
    if (search == "grid") {
        if (nrow(initialFit) < len) {
            tuneSeq <- data.frame(cp = seq(min(initialFit[, "CP"]),
                max(initialFit[, "CP"]), length = len))
        }
        else tuneSeq <- data.frame(cp = initialFit[1:len, "CP"])
        colnames(tuneSeq) <- "cp"
    }
    else {
        tuneSeq <- data.frame(cp = unique(sample(initialFit[,
            "CP"], size = len, replace = TRUE)))
    }
    tuneSeq
}

Essa função basicamente:

ajusta um modelo com todos os parâmetros iguais ao rpart padrão exceto o cp(complexidade), usando cp = 0.
pega o item cptable retornado, que por definição é:

cptable: a matrix of information on the optimal prunings based on a
  complexity parameter.

ajusta um modelo para uma sequencia de cp's de acordo com o argumento tuneLength da função train.

Esse comportamento pode ser alterado. Leia aqui para mais informações: http://topepo.github.io/caret/model-training-and-tuning.html#customizing-the-tuning-process


What does a bitwise AND do with no value infront of it?

Question: I am using Verilog. Say you have the term:
<code>& A
</code>
or
<code>~& A
</code>
What does this do? Does it just compare it to an all empty array?
Answer: It performs a bitwise operation on all bits of the operand
e.g.:
<code>//let x = 4'b1010
&x //equivalent to 1 & 0 & 1 & 0. Results in 1'b0
|x //equivalent to 1 | 0 | 1 | 0. Results in 1'b1
^x //equivalent to 1 ^ 0 ^ 1 ^ 0. Results in 1'b0
</code>
More about verilog operators: https://web.engr.oregonstate.edu/~traylor/ece474/beamer_lectures/verilog_operators.pdf


Reading console input in MonoDevelop

Question: I am trying to a simple C# program that takes input and passes it as output. For instance, the output should be:
What is your name?
{user input}
Your name is {user input}

The program is:
public static void Main(string[] args)
{
    Console.WriteLine("What is your name?");
    string name = Console.ReadLine();
    Console.WriteLine("Your name is: " + name);
    Console.ReadKey();
}

This is enclosed in a class called 'MainClass'
Its output is:
What is your name?
Your name is:

Why is this not working and how can I make it work?
P.S. I am using MonoDevelop and I added Console.ReadKey(); after the last WriteLine. No change.
Comment: How are you running the program?
Answer: You are trying to type in the Application Output window in MonoDevelop and it is read-only.
You can configure MonoDevelop to automatically run the program at the command prompt by right clicking on the "options" menu item of your project and checking Run on external console under the Run > General tree.
alt text http://psf.biz/public/monodevelop_run_on_external_console.jpg
I guess the guy that gave me the -1 was blinded by that huge "Works on My Machine" emblem, nevertheless this is the correct and only answer.
Comment: I agree. When the question was posted, and my original answer was given, it said nothing about MonoDevelop
Comment: this does not work for a single file only non-project program.
Answer:
(source: typepad.com)
Is your problem that the program quits immediately after reading the console input? If so, then add a Console.ReadKey(); after the last WriteLine so the program will wait for a keypress. Otherwise, I don't know what the problem is; I copy+pasted the code and it worked.

Reading console input in MonoDevelop


Select por horário de programação

Question: Boa tarde, Pessoal!
Estou construindo uma aplicação de grade horária televisiva. Existe uma tabela no banco de dados que contem informações de (Nome do programa, descrição e horário). Na minha aplicação, o sistema ordena essa tabela de programação com base no horário atual de Brasília, e exibe o programa que está passando ao vivo, e a programação que irá passar a seguir.
O Problema é que no meu select atualmente é esse:
"SELECT *, TIME(horario) as horario FROM Programacao where horario >= '$gh_data' order by horario"

Onde a variável $gh_data é a hora atual do sistema e "horario" é o horário do programa na tabela "programação" do banco de dados.
Exemplo do problema acontecendo:
Um programa A começa as 14:00 e o programa B começa as 15:00. Quando o horário do sistema é 14:01 ele mostra que o programa atual é o B, invés do A.
Como solucionar esse problema?
Answer: Creio que fazendo uma subquery para pegar a primeira programação menor que o horário atual possa resolver.
Por exemplo, a primeira programação menor ou igual a 14:01 é a de 14:00, correto? Então o select abaixo irá retornar a programação das 14:00:
SELECT horario AS a
FROM Programacao
WHERE horario <= '$gh_data'
ORDER BY horario DESC LIMIT 1

Agora, colocando isso numa subquery você conseguirá condicionar o WHERE para retornar os registros cujos horários sejam maiores ou iguais ao horário do select acima, ou seja, o das 14:00:
SELECT *, TIME(horario) as horario
FROM Programacao,
(
   SELECT horario AS a
   FROM Programacao
   WHERE horario <= '$gh_data'
   ORDER BY horario DESC LIMIT 1
) AS b
WHERE horario >= a ORDER BY horario

Comment: Muito obrigado pela ajuda! Funcionou!!!

Select por horário de programação


Mean and variance after transformation

Question: A psychology teacher has given an exam in which the highest score possible is 200 points. the mean score for the 30 students who took the exam was 156, and the standard deviation was 24. Because there was one question that every student answered incorrectly, the teacher decides to give each student 10 extra points and then divide each score by 2, so the total possible score is 100. What will the mean and the standard deviation of the scores be after this transformation?
I cannot figure out how to solve this question, I know it might seem easy and simple but I tried to figure out how to at least come up with the first step but failed to do so. I would appreciate if someone can elaborate or give me guidance on how to solve this question
Comment: 1. Every post here is seeking help with a stats question (otherwise it's off topic). As a result your title does nothing to help people figure out whether it's a question they want to try to help with. Please edit your title to reflect what the question is about. 2. Please read the [help/on-topic] on homework-style questions, which are treated differently. If you can't show any attempt you're going to need to ask something very specific about your difficulties. If you can't do that, you need to do some [search and research](https://stats.stackexchange.com/help/how-to-ask) (including ... ctd
Comment: Yes, I read that already; as I explained you have two choices in that case; you either need to ask a very specific question that would allow you to start, or you need to do more search and research. A very general "how do I do this" on a homework style question makes it not quite suitable for our site, even if you're seeking guidance. A more specific question, addressing the first thing you don't understand may well be suitable, though it's probably more productive to do more research yourself and move the specific question further along the process.
Comment: @Michael Glen reopened it quickly.  I just wanted to thank you for your generous help in the comments you have posted.
Comment: I have fixed the title and reopened but I would like the OP to undertake the other requested edits (i.e. to idenitfy a specific issue to ask about, something that will enable them to make some progress).
Comment: @Glen_b I am not sure what the best advice to the OP should be. The question is very elementary & it wouldn't take much research to find the properties that explain how a linear transformation affects the mean and standard deviation of a random with a finite mean and standard deviation. I would have thought that this question is appropriate if the self study tag is used. Almost any hint that could be given as an answer would make it very obvious how to get the solution. I think I gave the hint that would serve as an answer but I felt too embarrassed to do more than make a comment.
Comment: Since you subtract 10 & then divide by 2 the linearity of expectations tells you that for a sample with mean m the mean of the transformed data will be (m-10)/2. In this case plug in 156 for m. Regarding the standard deviation we know that the variance of a random variable multiplied by a constant is the square of the constant ties the original variance. The standard deviation is the square root of the variance. So in your case the standard deviation is 1/2 times the original standard deviation. In your case 24/2.
Comment: ctd... reading your notes and textbook, looking at examples, checking Wikipedia, searching our site and the internet more generally). For example, see [here](https://en.wikipedia.org/wiki/Expected_value#Linearity) and [here](https://en.wikipedia.org/wiki/Variance#Basic_properties). Please edit your question.
Comment: @Glen_b first of all the reason I did not show any attempt was because I did not know how to start working about the question. Second of all, I did not ask for someone to write or give me the answer but rather help me figure out how to start solving the question, as my textbook was not helpful and I could not find a website than answered my questions (I did do research) and I usually ask here when I am out of options meaning did my research, looked at my book and attempted to solve it. I won't ask for help just because I am lazy to solve this question
Comment: @MichaelChernick she added 10 points so will this mean that it would be (m+10)/2?
Comment: Yes in that case the the new mean would be (m+10)/2.
Comment: @Glen_b Now that the OP has added the self study do you think the question should remain closed. If so what is your reason. I am thinking about voting to reopen it.
Answer: Since this is self-study, some hints:

You have the number of students, and the mean. So calculate the total from that
Every student was given 10 extra points. Using this you can get the new total
This was divided by 2. New total should be easy then!
Having the new total the new mean should be easy.

The new standard deviation cannot be got from only the new total, but the same linear transformation was used on each students score. Adding the same number of points to each cannot change the standard deviation ... so the only relevant is the division by two. How does dividing each sample point with 2 change the standard deviation?

Mean and variance after transformation


How to pass Primefaces Tab as UIComponent in bean method?

Question: I'm trying to pass a Tab component to a bean method as UIComponent (for some permission issues that I'm developing), but I'm getting a instance of TabView instead of a Tab.
I'm using Tab as an example but I tried to call the same method in a p:outputLabel and I'm receiving a UIComponent PanelGrid instance.
Is it possible or should I need to pass the id too when it was as tab?
I'm running Primefaces 5.3.

        ...

//Bean Method
public boolean isUserHasView(UIComponent component) {
    System.out.println(component);
    return false;
}

I expect get Tab as UIComponent but I'm getting TabView with all their children.
Answer: A tab is not a UIComponent (does not have its own renderer) so the 'component' variable does not point to the tab but to its parent tabview which is the real component and renders the tab. But even if it was possible, a new instance will be created every time the user opens the page, so checking via an 'instance' is not logical (unless you'd like to retrieve the id from the component). So since you should use something like an id anyway, using the id explicit is a good thing to do (and at least what I use).


How to fetch only latest specific data from Firebase?

Question:
Please see the attached image. As you see there 8 are tables. How can I fetch the latest user-entered data? I can fetch all data from one table but hows its possible to get only the latest entered data from the table individually ?**
Answer:
to get only the latest entered data from the table individually?

Simply by adding a Timestamp field under each object, ordering the results descending and finally passing 1 as a parameter to Query's limitToFirst(int limit) method.


Remover elemento/função Corona SDK

Question: tenho arquivo form.lua com o código:
local _M = {}

function _M.calc( a )

    local quad = display.newRect(100,100,100,100)
end
return _M

e o arquivo scene2.lua com o código:
local form = require "form"

form.calc( )

Eu preciso que o quad / function seja removido da tela, quando for para outra cena.
Answer: Se você estiver usando o composer, coloca o objeto que você quer deletar dentro de um grupo de exibição e na função hide do composer você põe o objeto para ser removido (display.remove(objeto)). Assim toda vez que esta cena que contêm o quad, vai ser removida quando for "escondida" para que outra cena apareça.

Remover elemento/função Corona SDK


Best approach to predict how far into process a subject will progress?

Question: I have a seven step process that users can complete but can stop at any time - basically a marketing funnel. At each point along the funnel I am collecting more data.
I want to be able to predict how far into the the funnel a subject with x set of attributes will go.
Is linear regression a valid approach where my y variable is the final step the person completed? Each step is not necessarily equal as some steps ask for more personal information that other steps.
I've done k-means clustering on the last step to understand the groups that exist for the final step. My next step is to do k-means clustering across steps, excluding my dependent variable and doing a confusion matrix afterwards to see if the groups align to the stages of the funnel.
An ANOVA test would tell me if there are differences among the groups based upon their completion step - but I don't think that would give me predictive capabilities if there were differences. True?
Other ideas for generating a predictive model and assumption issues you see?
I'd appreciate any code examples in R, if possible.
Comment: If your question has been answered to your satisfaction, you can accept an answer by clicking the check mark under the voting arrows.
Answer: Linear regression is certainly the first thing to try, although you rightly point out that it may be hampered by how $Y$ isn't on an interval scale. Ordinal regression exists to correct this problem, so that's a logical thing to try, too. Use cross-validation to find the most predictively accurate model of the models that you'd like to consider and go with that one.
$k$-means clustering and ANOVA seem of little value to you here. There's no reason to think that the clusters produced by $k$-means would be predictively useful, and ANOVA is really just a significance test, which has no relevance to prediction, as you've guessed.


Como mudar o encode no Java?

Question: Estou consumindo a API do IBGE para pegar os municípios por estado. Quando imprimo os municípios os acentos ficam errados. O que eu posso fazer para arrumar isso? Abaixo o código que pega o nome dos municípios.
JSONArray jsonarray = new JSONArray(jsonString);
List municipios = new ArrayList();
for (int i = 0; i < jsonarray.length(); i++) {
    JSONObject jsonobject = jsonarray.getJSONObject(i);
        municipios.add(jsonobject.getString("nome").);
}

Answer: Acredito que você pode fazer isso na hora de adicionar o texto à lista:
JSONArray jsonarray = new JSONArray(jsonString);
List municipios = new ArrayList();
for (int i = 0; i < jsonarray.length(); i++) {
    JSONObject jsonobject = jsonarray.getJSONObject(i);
    municipios.add(new String(jsonobject.getString("nome").getBytes(), "UTF-8"));
}

Pegando os bytes da palavra e criando uma string em formato UTF-8, os acentos e caracteres serão exibidos.
Comment: Funcionou! Obrigado, cara!

Como mudar o encode no Java?


Ionic Storage is not working on Android device

Question: I'm new to the Ionic Framework, and I'm doing an app that preserves the user login so it can show a different page when user is logged. And for doing this, I'm saving the user ID into the local storage.
This works fine when I do ionic serve and testing the code on browser, but it doesn't work on my Android device (so I run ionic cordova run android). Why? I have set the Storage right by using IonicStorageModule.forRoot() in app.module.ts -> imports[...]. Here's my code and my Ionic specs:
Comment: I'm assuming you're setting the local storage in the login page? also, what does the console log state with the storage variable?
Comment: @StephenRomero yes, I'm setting the userID inside the login page. Unfortunately I don't know how to get the log from my phone
Comment: You can plug your android phone in to your computer and if you're using chrome you can go to developer tools and remote devices and click on your device. This link will help:https://medium.com/@michaelgannon_89769/beginners-guide-to-remote-debugging-android-devices-using-chrome-ded1d3aca11a
Comment: @Sebatino, I second with Stephen. Did you store it in the localStorage? Could you please share the code for setting values to storage
Comment: I found the solution to my problem: I just added a `catch()` just after the first `get` and now it works fine. The problem was the result of `userLoggedID` on the very first access that wasn't returning nothing at all, neither  `undefined` nor `null`
Answer: I just figured out my problem and built a solution. On the very first access in my app userLoggedID is completely empty (it wasn't neither undefined nor null), so I attached a catch() instruction and now the code works fine.

LOG:


Importance sampling - approximation of an integral in R

Question: So I am given this integral $$\mathrm{I}=\int_{38}^{\infty} \mathrm{f}(\mathrm{x}) \mathrm{d} \mathrm{x}=\int_{38}^{\infty} \mathrm{e}^{-\mathrm{x}} \mathrm{x}^{2} \mathrm{dx}$$
and i am also given this p.d.f $$g(x)=e^{-(x-38)}, \quad x \geq 38$$ from where i am supposed to sample from.
I have seen the formula of that inverse sampling is all about which is the following one:
$$\int h(x) \frac{\pi(x)}{g(x)} g(x) d x$$ .
I cannot understand how this can be applied to my integral above. I guess that h(x) if my original $\mathrm{e}^{-\mathrm{x}} \mathrm{x}^{2}$ function and that g(x) is where i sample from but what is $\pi(x)$ ?
How can I get an estimate of this?
Here is my code in R so far
original_function <- function(x){exp(-x)*x^2}

#inverse sampling to sample from g(x)
u <- runif(1000, -1, 0)
inverse_function <- function(u){-log(-u)+38}
values_derived_from_inverse_CDF <- inverse_function(u)

#i use R's function integrate to calculate the integral
integrate(original_function, 38, Inf)

#results
4.777715e-14 with absolute error < 1.3e-14

#I plug the X that came from g(x) to the original function in the numerator
#and in the
#denominator I plug in the values that derived from g(x). The results are not
#even close.

mean(original_function(values_derived_from_inverse_CDF) /
values_derived_from_inverse_CDF)

#results
6.237939e-16

Comment: is tis a home work?
Answer: Importance sampling approximates the integral $\mathbb E_{\pi(x)}[h(x)]$, so $\pi(x)$ is the original distribution. It makes sense if the original problem is to calculate an expected value of a function wrt distribution, $\pi(x)$. Instead of sampling from $\pi(x)$, we sample from a proposal distribution, $g(x)$ and calculate the expected value of the ratio $\frac{h(x)\pi(x)}{g(x)}$. In integral estimation, the actual $h(x)$ and $\pi(x)$ doesn't matter. You'll again find the expected value of the ratio above.
Your code needs the following change:
mean(original_function(values_derived_from_inverse_CDF) / exp(-values_derived_from_inverse_CDF+38))

You were averaging $\frac{h(x)\pi(x)}{x}$, but you should have averaged $\frac{h(x)\pi(x)}{g(x)}$.
Comment: You don't have to specify $\pi(x)$ directly, you need $e^{-x}x^2/g(x)=h(x)\pi(x)/g(x)$. Take samples from $g(x)$ and calculate the expectation $e^{-x}x^2/g(x)$.
Comment: You should add it to your original post, not as an answer.
Comment: Thank you a lot for your time
Comment: My goal is to calculate this integral above by using importance sampling. I do not know what my $\pi(x)$ is i am not given such a thing. I guess then that my $h(x)$ is $e^{-x} x^{2}$ and my $g(x)$ is $g(x)=e^{-(x-38)}$. So i am missing one function and cannot compute it. If you could show me how you could code this in R or python i would be greatefull.
Comment: I will add a proper comment with code below
Answer: There may be confusion between inverse (cdf) sampling which means simulating from a distribution with cdf G by taking the quantile transform of a uniform $$X=G^{-1}(U)\qquad U\sim\mathcal U(0,1)$$
and importance sampling which means replacing the expression of an expectation under a given distribution with pdf $f$ by an identical expectation under a different distribution with pdf $g$ :
$$\int h(x) \pi(x)\,\text{d} x= \int h(x) \frac{\pi(x)}{g(x)} g(x) \,\text{d} x$$
and its Monte Carlo approximation
$$\int h(x)\frac{\pi(x)}{g(x)} g(x) \,\text{d} x\approx \frac{1}{N} \sum_{i=1}^N \frac{h(x_i)\pi(x_i)}{g(x_i)}\qquad x_i\sim g(x)\quad i=1,\ldots,N$$
which can be rewritten as
$$\int h(x)\frac{\pi(x)}{g(x)} g(x) \,\text{d} x\approx \frac{1}{N} \sum_{i=1}^N \frac{h(G^{-1}(u_i))\pi(G^{-1}(u_i))}{g(G^{-1}(u_i))}\qquad u_i\sim \mathcal U(0,1)\quad i=1,\ldots,N$$
to merge inverse sampling and importance sampling. The correction in the R code is obvious.
Comment: if it would be obvious to me I would not post this question.
Answer: In principle Monte Carlo works as follows for integration:
$$I=\int_a^bf(x)dx=\int_a^bf(x)\frac{b-a}{b-a}dx=(b-a)\int_a^bf(x)\pi(x)dx= (b-a)E[f(x)]$$ where $\pi(x)$ is PDF of uniform distribution on $[a,b]$. Therefore, we can approximate the integral by sampling from uniform:
$$I\approx \frac {b-a} n \sum_{i=1}^n f(\xi_i)$$ where $\xi\sim U(a,b)$
Now you can change the variable, but sampling from a different distribution with PDF $g(x)$:
$$I=(b-a)\int_a^bf(x)\frac{\pi(x)}{g(x)}g(x)dx= E[f(y)\frac{1}{g(y)}]$$
where $y$ is sampled from $g(y)$.
Again, we can approximate the integral by sampling:
$$I\approx \frac 1 n \sum_{i=1}^n \frac{f(y_i)}{g(y_i)}$$ where $y_i$ is from distribution PDF $g(y)$


Reusable component using theme-based Box features

Question: I'd like to create a reusable component using Material-UI's api (not using styled-components.)  I got this far - and it almost works - but the settings that use theme variable don't work (e.g, bgcolor and padding).  Am I doing something wrong - or is this not possible?
  const BigPanel = styled(Box)({
    display: 'flex',
    width: '100%',
    flexgrow: 1,
    bgcolor: 'background.paper',
    borderRadius: 10,
    boxShadow:'1',
    p:{ xs: 4, md: 8 }
  });

Answer: The object passed to styled is intended to be CSS properties, but you have a mixture of CSS properties and Box props (bgcolor, p). Even the ones that are valid CSS properties (display, width) are also valid Box props, so the most straightforward solution is to specify all of them as props.
One way to handle this is to use defaultProps. This makes it very easy to override some of the props when using the component by specifying them explicitly as shown in the example below.
import React from "react";
import Box from "@material-ui/core/Box";
import CssBaseline from "@material-ui/core/CssBaseline";
import { styled } from "@material-ui/core/styles";

const BigPanel = styled(Box)({});
BigPanel.defaultProps = {
  display: "flex",
  width: "100%",
  borderRadius: 10,
  flexGrow: 1,
  bgcolor: "background.paper",
  p: { xs: 4, md: 8 },
  boxShadow: "1"
};
export default function App() {
  return (
    <>
      <CssBaseline />
      <BigPanel>Default BigPanel</BigPanel>
      <BigPanel bgcolor="primary.main" color="primary.contrastText">
        BigPanel with explicit props
      </BigPanel>
    </>
  );
}

In the example above, styled isn't really serving any purpose anymore except to create a new component type. Though it isn't less code, below is an alternative way to get the same effect without using styled:
const BigPanel = React.forwardRef(function BigPanel(props, ref) {
  return <Box ref={ref} {...props} />;
});
BigPanel.defaultProps = {
  display: "flex",
  width: "100%",
  borderRadius: 10,
  flexGrow: 1,
  bgcolor: "background.paper",
  p: { xs: 4, md: 8 },
  boxShadow: "1"
};


How can I use Bessel's equation to solve the Lengthening Pendulum differential equation?

Question: Taking a small extract of this previous bounty question of mine:

It can be shown that the differential equation: $$\fbox{$y^{\prime\prime}+\left(\frac{1-2a}{x}\right)y^{\prime}+\left[\left(bcx^{c-1}\right)^2+\frac{a^2-p^2c^2}{x^2}\right]y=0$}\tag{1}$$ has the solution $$\fbox{$y=x^aZ_p\left(bx^c\right)$}\tag{2}$$ where $Z_p$ stands for $J_p$ or $N_p$ or any linear combination of them, and $a,b,c,p$ are
  constants.

To see how to use this, let us "solve" the differential equation: $$y^{\prime\prime}+9xy=0\tag{3}$$ If $(3)$ is of the type $(1)$, then we must have $$1-2a=0$$ $$2(c-1)=1$$ $$(bc)^2=9$$  $$a^2-p^2c^2=0$$ from these $4$ equations we find
  $$a=\dfrac12$$ $$c=\dfrac32$$ $$b=2$$ $$p=\dfrac{a}{c}=\dfrac13$$
Then the solution of $(3)$ is $$y=x^{1/2}Z_{1/3}\left(2x^{3/2}\right)$$ This means that the general solution of $(3)$ is $$y=x^{1/2}\left[AJ_{1/3}\left(2x^{3/2}\right)+BN_{1/3}\left(2x^{3/2}\right)\right]$$ where $A$ and $B$ are arbitrary constants.

The differential equation of a lengthening pendulum is $$l\dfrac{d^2\theta}{dl^2}+2\dfrac{d\theta}{dl}+\dfrac{g}{v^2}\theta=0\qquad\quad\tag{4}\longleftarrow\text{proved in this former question}$$
I have to solve this differential equation for $\theta$ by comparing $(4)$ with $(1)$ in the same manner as used to find the solution to $(3)$

So here is my attempt:
First I begin by writing $(1)$ in terms of the new variables $\theta$ and $l$ $$\frac{\mathrm{d}^2\theta}{\mathrm{d}l^2}+\left(\frac{1-2a}{l}\right)\frac{\mathrm{d}\theta}{\mathrm{d}l}+\left[\left(b\,c\,l^{c-1}\right)^2+\frac{a^2-p^2c^2}{l^2}\right]\theta=0\tag{5}$$
Now I compare $(4)$ with $(5)$ to obtain
$$l=1$$
$$\frac{1-2a}{l}=2\implies a=-\frac12\qquad\text{since $l=1$}$$
$$\left(b\,c\,l^{c-1}\right)^2+\frac{a^2-p^2c^2}{l^2}=\frac{g}{v^2}\tag{6}$$
Substituting $a=\frac12$ and $l=1$ into $(6)$
$$\implies b^2c^2+\frac14 -p^2c^2=\frac{g}{v^2}\tag{7}$$
Now if $l=1$ we must have $$c=1$$
Substituting $c=1$ into $(7)$
$$\implies b^2+\frac14 -p^2=\frac{g}{v^2}\tag{8}$$
But I am unable to proceed from here and I have made a mistake anyway as I can tell you that the correct answer is $$\theta=l^{-1/2}Z_1\left(\frac{2{g}^{1/2}}{v}l^{1/2}\right)$$ Comparison with
$$\fbox{$y=x^aZ_p\left(bx^c\right)$}\tag{2}$$
shows that $$a=-\frac12, \quad c=\frac12, \quad b=\frac{2{g}^{1/2}}{v},\quad p=1$$
Could someone please help me find the correct values of $a,b,c,p$?
Any hints or advice is well appreciated.
Comment: Why are you drawing the conclusion that $c = 1$ at $(7)$? Doesn't the expression $6$ allow $c$ to be anything given that the $l$ is 1? Don't we have $4 c^2 (b^2 - p^2) = \dfrac{4g}{v^2} -1 \implies 4 c^2 (b+p)(b-p) = 1\left(\dfrac{2 g^{1/2}}{v}+1\right)\left(\dfrac{2 g^{1/2}}{v}-1\right)$? This gives$4 c^2 = 1 \implies c = \dfrac{1}{2}, b \ \dfrac{2 g^{1/2}}{v}, p = 1$.
Comment: Oops, that is $b = \dfrac{2 g^{1/2}}{v}$.
Answer: Hint: In the pendulum example the variable $l$ plays the role of $x$ and $\theta$ the role of $y$.

Keeping this in mind and comparing
  \begin{align*}
\frac{d^2\theta}{dl^2}+\frac{2}{l}\frac{d\theta}{dl}+\frac{g}{v^2}\frac{\theta}{l}=0
\end{align*}
  with
  \begin{align*}
\frac{d^2\theta}{dl^2}+\left(\frac{1-2a}{l}\right)\frac{d\theta}{dl}+\left[(bcl^{c-1})^2+\frac{a^2-p^2c^2}{l^2}\right]\theta=0
\end{align*}
  we get the following conditions:
  \begin{align*}
1-2a&=2\\
2(c-1)&=-1\\
b^2c^2&=\frac{g}{v^2}\\
a^2-p^2c^2&=0
\end{align*}
  and conclude
  \begin{align*}
a=-\frac{1}{2},\quad c=\frac{1}{2},\quad b=\sqrt{\frac{4g}{v^2}}=\frac{2}{v}\sqrt{g},\quad   p=\sqrt{\frac{a^2}{c^2}}=1
\end{align*}

We  finally obtain
\begin{align*}
\theta=l^aZ_p\left(bl^c\right)=\frac{1}{\sqrt{l}}Z_1\left(\frac{2}{v}\sqrt{gl}\right)
\end{align*}
Comment: @BLAZE: The division by $l$ was done just to make the relationship with (1) better visible. In (1) we have the term $\left(\frac{1-2a}{x}\right)y^\prime$. Since $x$ is in the denominator it seems quite natural to also divide by $l$ and put it in the denominator since $l$ plays the role of $x$. Of course you are free to do it in any other way as long as you perform equivalence transformations
Comment: @BLAZE: (cont.) . Your setting $l=1$ is not valid, since $l$ corresponds with $x$. Proposal: Transform the pendulum differential equation by exchanging $\theta$ with $y$ and by exchanging $l$ with $x$. Then you will better see what's going on.
Comment: Excellent answer! I have just one further question: Can it be done without dividing the differential equation by $l$? _If_ it can be done could you please show me? I ask this because it was the way I tried to solve it. Many thanks! :)
Comment: Makes perfect sense now, thank you for taking the time to explain that to me.
Comment: Any ideas on [this](http://math.stackexchange.com/questions/1804280/verify-y-xaz-p-leftbxc-right-is-a-solution-to-y-left-frac1-2ax-ri) one yet? Best regards :-)
Comment: @BLAZE: Any open aspects? The answers already given seem to be quite useful.


bloquear acesso a um determinado diretório via htacess

Question: Bom tenho uma pasta na raiz do meu site chamada de logs.
Dentro dela vou salvar os logs que erros personalizados que monte.
Bom preciso bloquear essa pasta para não ser acessa por ninguém, apenas por mim via ftp.
Porém o php pode criar arquivos com log de erros lá dentro.
Achei várias formar de colocar senha nela com htacess, porém não quero por senha, quero bloque ela definitivamente para não ser acessada via browser.
Tem alguma forma de fazer isso com htacess?
Estou usando o apache.
Eu tentei fazer assim:
<Directory "Logs">
   Order allow,deny
   Deny from all
</Directory>

Porém deu erro interno no servidor.
Answer: Bloquear o acesso completamente
Criar o ficheiro .htaccess dentro da pasta que se pretende proteger
Deny from all

NOTA: inclusive, nenhum script tem acesso a esta pasta
Bloquear o acesso parcialmente
Criar o ficheiro .htaccess dentro da pasta que se pretende proteger
<IfModule mod_rewrite.c>
    Options -Indexes
</IfModule>

NOTA: Ao aceder à pasta através do browser dá acesso negado (error 403), no entanto, o PHP consegue ter acesso.
Comment: dentro dessa pasta vai ficar alguns logs, preciso que o php tenha permissão para criar os arquivos. se eu usar o `Deny from all` o php vai ter essa permissão?
Comment: @HugoBorges a resposta está de acordo com a pergunta original onde dizes "...não ser acessa por ninguém, apenas por mim via ftp". Reformula p.f. a tua pergunta.
Comment: Desculpa, esqueci de informar essa situação. Já alterei minha pergunta.
Comment: @HugoBorges atualizei a minha resposta. Verifica p.f. se funciona.
Answer: entre no seu apache2.conf ou httpd.conf use a diretiva Define para apontar aonde seu pacote está instalado.
 Define INSTALL_DIR [diretorio a ser instalado]

Ex :
Windows
Define INSTALL_DIR c:\wamp64

Depois use a seguinte configuração.
<Directory "${INSTALL_DIR}/www/Logs/">
   Deny from all
</Directory>

Lembrando que Define [nome] [conteudo]
  então caso queira pode dar outro nome, ou procurar uma diretiva já configurada.Quando for manutenir ou configurar Directorys tente sempre dar todo caminho da configuração

Se não for Windows fale, mas acho que serve para Linux também.
Comment: dentro dessa pasta vai ficar alguns logs, preciso que o php tenha permissão para criar os arquivos. dessa forma o php vai ter essa permissão?
Comment: Sim o php tem acesso a criação de pastas lá dentro com essa configuração.
Comment: Bom dessa forma deu erro 500, estou usando linux, vou ver o que pode estar acontecendo. Mas vlw pela ajuda.


does bp need to be simultanious? - XOR learning problem

Question: I have a problem with XOR learning.
I have 2(inputs),2,1(output) neuron neural network with sigmoidal function and normal sets
(0,0.9)->0.9
(0.9,0.9)->0.1
(0.9,0.1)->0.9
(0.1,0.1)->0.1

of learning sets, plus bias neuron with 1.0 output connected to hidden layer and output layer. Despite changing biased neuron output and randomizing order of using learning set, the usual output of this network is like:
0.5070491199305279
0.506573763380741
0.5065628483577969
0.5070403151187465

which is zero given to sigmoidal function and mostly they tend to return almost the same output.
like
0.4308536422848425
0.4308546005321358
0.43085460201816195
0.4308536440377257

Do you think that this is problem concerned with a fact that my backpropagation isn't simultaneous (I change weights every one case not after full set). Or maybe my network is missing something?
Values of inputs and outputs for third case;
Answer: I've got analog problem myself, when I was looking for the minimal neuron network architecture required to learn XOR which should be a (2,2,1) network. In fact, maths shows that the (2,2,1) network can solve the XOR problem, but maths doesn't show that the (2,2,1) network is easy to learn. That said, I've got easily good results with (2,3,1) or (2,4,1) network architectures.
The problem seems to be related to the existence of many local minima. Look at this 1998 paper, «Learning XOR: exploring the space of a classic problem» by Richard Bland. Maybe you could try different random initialization of the weights or change your loss function.
It works fine with Keras or TensorFlow using loss function 'mean_squared_error', sigmoid activation and Adam optimizer. Furthermore weights initialization with random number between 0.5 and 1.0 helps to converge. Even with pretty good hyperparameters, I observed that the learned XOR model is trapped in a local minimum about 15% of the time.


Cocos2d portrait mode not working on iPhone

Question: I'm building a cocos2d game which is supposed to be in portrait mode. I changed the RootViewController.m to portrait mode, and everything works fine, both on the simulator and on my iPad. However, when I run the game on my iPhone, it defaults back to landscape mode.
Any ideas on how to fix this?
Thanks.
Answer: I have a better solution that will work 100%:
Replace all the stuff that was in the RootViewController.m /
shouldAutorotateToInterfaceOrientation Method with following:

return ( UIInterfaceOrientationIsPortrait( interfaceOrientation ) );

And if I ever want to change the orientation during runtime / switching scene:

[[CCDirector sharedDirector] setDeviceOrientation:CCDeviceOrientationLandscapeLeft];

Note that Auto Rotation is now on longer supported
Comment: hey alexander, i've tried that, but the upside down mode is also enabled. so how can i ONLY enable the portrait mode?
Comment: are you using Cocos2D 1.x or 2.0 beta?
Answer: in GameConfig.h:
use the director for autorotation
#if defined(__ARM_NEON__) || TARGET_IPHONE_SIMULATOR
#define GAME_AUTOROTATION kGameAutorotationCCDirector

instead of
#if defined(__ARM_NEON__) || TARGET_IPHONE_SIMULATOR
#define GAME_AUTOROTATION kGameAutorotationUIViewController

and in the AppDelegate.m
- (void) applicationDidFinishLaunching:(UIApplication*)application
{
...
[director setDeviceOrientation:kCCDeviceOrientationPortrait];

Answer: Inside the RootViewController return false from the method below:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {

    return false;

   // other code...

}

Answer: In RootViewController.m
return ( UIInterfaceOrientationIsLandscape( interfaceOrientation ) );

change this line to
return ( UIInterfaceOrientationIsPortrait( interfaceOrientation ) );

Comment: Yes, this is exactly what I did already. It works fine in the Simulator and on my iPad, but for some reason it's not working on my iPhone.
Comment: but now working only for portrait mode , I want  both orientations
Answer: in GameConfig.h:
For 1st and 2nd generation devices, value is set to kGameAutorotationNone, change it to kGameAutorotationUIViewController.

// ARMv6 (1st and 2nd generation devices): Don't rotate. It is very expensive
#elif __arm__
#define GAME_AUTOROTATION kGameAutorotationNone


removing a css class from group of li elements

Question: This Meteor client code needs to remove the class select from all li elements which are children of ul which has id sub-menu, the class format is class1 class2 select
any ideas? thx
$('ul#sub-menu > li').each(() => {
        const classProp = $(this).className;
        if (classProp.indexOf('select') >= 0) { //de-selecting
          const lastIndex = classProp.lastIndexOf(" ");
          $(this).className = classProp.substring(0, lastIndex);
        }
      });

Answer: Use removeClass() method instead of making it complex.
$('ul#sub-menu > li').removeClass('select');

There are several bugs in your code className is the property of DOM element so remove the jQuery wrapping.
this.className

Although there is build in method to remove class name from DOM element by getting classList property.
this.classList.remove("select");

Answer: You can also use like this
$('ul#sub-menu li').removeClass('select');

OR
$('ul#sub-menu').find('li').removeClass('select');


Prove existence of pair of points on compact surface such that distance is maximized?

Question: Let $M_m$ be a compact $C^1$ surface in $\mathbb{R^n}$. Prove that there exists $x,y,\in M_m$ such that the distance between them is greatest among all pairs on the surface. Then show that the diameter joining them intersects the surface perpendicular at both points $x$ and $y$.
I think the first part can be shown because the distance function $d(x,y)=||x-y||$ on a compact set has a maximum. I am not sure how to approach the second part of the question.
Answer: OK for the first part (and a product of two compact sets is compact). For the second, fix $y$ and take any smooth curve on $M$ passing through $x$ at $t=0$. Express the fact that the distance from $y$ to $x(t)$ has a maximum at $x = x(0)$. Use that to show that the vector from $x$ to $y$ is orthogonal to any vector tangent to the surface at $x$.
Edit: a few more details... Let $x(t)$ be a smooth parameterized curve on M, with $x(0) = x$. For any tangent vector to $M$ at $x$ there is such a curve so that the tangent vector equals $\frac{{\text d} x(t)}{{\text d} t}|_{t=0}$. Now the function $f(t) = \| x(t) - y \|^2$ has a maximum at $t=0$. The derivative of $f$ at $0$ is 2 times the dot product of the vector $\vec {yx}$ and the "velocity vector" of the curve (which is a tangent vector to the surface).
Comment: Thanks for the answer, can you please give the details for the second part?
Comment: I am adding to the answer above; I don't do others' homework though, I will not write a full proof.
Comment: I'm just unfamiliar with the mechanics here, thx. My hw has lots of questions this is just to get started


Auto populate of column on the visualforce page

Question: I designed a VF page to display a list of field records of a custom object. There are two number fields in my object I designed VF page to display these number fields with total at the bottom of the page . In future if an additional number field is add to same object then how can I write a code to add a column which in turn should be automatically populate on the visualforce page. Is it possible in salesforce.
Answer: Please find some code below. Note, this is not tested but shall give you a complete idea!
VF Page:
<apex:form>

      <apex:column value="{!Sum}"/>
</apex:form>

Apex Class:
//Your class will contain the below method
    public String getSum(){
             Double Sum;
            //Return a list of the object
            List <Custom_Object__c> listCustom = [Select Num1, Num2 from Custom_Object__c];
            for(Custom_Object__c co : listCustom){
                Sum = co.Num1 + co.Num2;
              }
             return String.valueOf(Sum);
    }

The answer will be something along these lines. Please give it a try, if it does not work reply and I shall be happy to help!
Answer: If you have a controller / controller extension on this page you could use describe calls to learn the list of all fields in the object, check their types and decide which ones you want to display & summarize.
Schema.DescribeFieldResult f = Account.NumberOfEmployees.getDescribe();
System.assertEquals(Schema.DisplayType.INTEGER, f.getType());

But relying on results of a describe call will have some limitations (hitting governor limit of 100 describes per request, fields will be sorted by name which might not be the order you want to display them...).
Since you want dynamic Visualforce you could consider making a fieldset or custom setting that would list the fields you want and then if you're using Apex to calculate subtotals - refer to it from code. That way when you need to update it later you won't have to touch the controller.


Bernoulli distribution question

Question: $X$ is a Bernoulli random variable with $\mathrm{Pr}(X=1)= p = 0.99$.
$Y$ is distributed $N(0,1)$. $W$ is distributed $N(0,100)$ and $X, Y, W$ are independent.
Let $S=XY+(1-X)W$, that is $S=Y$ when $X=1$ and $S=W$ when $X=0$.
a) Show that $E(Y^2)=1$ and $E(W^2)=100$.
b) Show that $E(Y^3)=0$ and $E(W^3)=0$.
Comment: Your question does not make sense because you defined $X$ and $S$ but never use them in your question. Please edit to clarify.
Comment: Those are for the questions c and d. I only need the solutions of a and b.
Comment: So please do not define them in your post. The first two questions are about [computing the moments of a gaussian](https://math.stackexchange.com/questions/92648/calculation-of-the-n-th-central-moment-of-the-normal-distribution-mathcaln)
Answer: The moments of $Z\sim\mathcal{N}(0,\sigma^2)$ are
$$\mathbb{E}[Z^n] =
\begin{cases}
\sigma^n(n-1)!!\quad&\text{if}\;n\;\text{is even}\\
0\quad&\text{if}\;n\;\text{is odd}\\
\end{cases}$$
You should check the following post. Your questions sets $n=2,3$ and $\sigma^2 = 1,100$.
Comment: Thank u so much for your help.
Comment: Can you please help me out on these two as well? Derive E(S), E(S^2), E(S^3) and E(S^4). Hint: Use the law of iterated expectations conditioning on X=0 and X=1.
Comment: [What should I do when someone answers my question?](https://stats.stackexchange.com/help/someone-answers).
Comment: Please create another question.

Bernoulli distribution question


Is there way to prove that non-abelian group of order $p^3$ has non-trivial center using $G/Z(G) \cong Inn(G)$?

Question: I know that $|Z(G)| \neq p^2$ or $p^3$ due to contradictions with $G$ being non-abelian.
Therefore, the remaining possibilities are $1$ or $p$. I aim to prove $∣Z(G)∣=p$ without resorting to the class equation, for example, by using the theorem $G/Z(G) \cong Inn(G)$.
I took a look over books as Contemporary abstract algebra by Joseph Galian or Abstract Algebra by Foot and Dummit to search for theorems concerning $Inn(G)$ that would help but I didn't find.
I just want hints because I love learning by doing efforts.
Comment: Are you familiar with "every p group of order > 1 has a non-trivial center"?
Comment: There's a way to use the class equation in this case. I mean using Abstract Algebra 01, you can prove that equation for this special case. I can give you hints if you want.
Comment: @Mahmoudalbahar So Let's say $x\sim y$ iff $x$ is conjugate to $y$. Prove that this is an equivalence relation. Then prove that for any $x\in G$, size of the equivalence class containing $x$, equals $|G:C_G(x)|$. Please let me know when you prove all these, they can all be proved using Abstract Algebra 1.
Comment: @Mahmoudalbahar Now which elements are in class of order $1$? Now on the contrary assume that $Z(G)=1$, knowing the fact that $G$ is a $p$-group, try to reach a contradiction using the fact that $|G|=\sum|cl(x_i)|$ where $x_i$'s are class representatives. Have this $|cl(x)|=|G:C_G(x)|$ in your mind.
Comment: There is an incredibly useful lemma for this and many many other things related to finite $p$-groups: When a $p$-group $P$ acts on a set $X$, then
\begin{equation*}
|X^P|\equiv |X|\pmod{p}
\end{equation*}
where $X^P$ is the subset of fixed points. This is easy to prove, since the orbit-stabilizer theorem says every orbit of size $>1$ must have size divisible by $p$. You could use this lemma with $P=G$ acting on $X=G$ by conjugation.
Comment: @agent_cracker103:  Yes I know, but I am asking about idea of proving it other than using class equation, I want to try proving it using $Inn(G)$.
Comment: @Ash   Give me hint, I am grateful for your help.
Comment: @agent_cracker103  $Inn(G) \cong Z_{p} \oplus Z_{p}$ since it cannot be cyclic, because that would mean that $G$ is abelian.
Comment: @Ash    Ok, thank you, I will do it now, and tell you when I finish proving.
Comment: @Ash: I have finished the first hint, by proving what you have asked me to prove.
Comment: @Ash I put solution using your hints, please, give your opinion when you have time.
Comment: @SteveD Thanks for your help, I will try your idea in future.
Answer: Solving using hints of @Ash:
(But my original question is about whether it is possible to try calculate $Inn(G)$ and by it showing that $|Z(G)|$ must be $p$).
Define the equivalence relation:
$x \sim y$ iff  there exists $g \in G: x=gyg^{-1}$.
proof:
Reflexive: $x \sim x$ because $x=exe^{-1}$.
Symmetric: Assume $x \sim y \rightarrow \exists g: x=gyg^{-1} \rightarrow y=g^{-1}x(g^{-1})^{-1} \rightarrow y \sim x$.
Transitive: Assume $x \sim y $ and $y \sim z \rightarrow \exists g_{1},g_{2}: x=g_{1}yg_{1}^{-1}$ and $y=g_{2}zg_{2}^{-1} \rightarrow x=(g_{1}g_{2})z(g_{1}g_{2})^{-1} \rightarrow x \sim z $.
Now, $cl(x)= \{y: \exists g: x=gyg^{-1} \}=\{y: \exists g: xg=gy \}$.
For $m \in cl(x)$:
If $m=x$, then $x \sim x$ because $x=gxg^{-1} \forall g \in C_{G}(x)$.
If $m \neq x$, then $x \sim m$ because $x=gmg^{-1} \forall g $ in the coset $ gC_{G}(x)$.
Thus, number of conjugates of x which is $|cl(x)|$ equals number of cosets of $C_{G}(x)$ which is $|[G:C_{G}(x)]|$.
Let $|G|=p^n$ where $n \in \mathbb{N}$ (I choose to generalize the problem instead of p^3)
Now, assume $|Z(G)|=1$.
Recall that: $Z(G)= \bigcap_{x \in G} (C_{G}(x))= \{e \}$ because $|Z(G)|=1$.
$|G|= \sum |cl(x_{i})|$.
If $x_{i}=e$, then $|cl(x)|=|cl(e)|=1$
So, $|G|=p^n=1+\sum cl(x_{i})$. where $x_{i} \neq e$.
Thus: $p^n-1=\sum cl(x_{i})$. where $x_{i} \neq e$
$|x_{i}|=p^{j} $ for some $1 \leq j \leq n-1$ (note $j \neq n$ becuase $G$ is non-cyclic).
Now:$p$ divides $|x_{i}|$ divides $|C_{G}(x_{i})| < p^n$, by Lagrange's Theorem.
We have $p$ divides $\sum cl(x_{i})$. where $x_{i} \neq e$, so $p$ divides $p^{n}-1$ which is contradiction.
Comment: Nice job. Now we get that $Z(G)>1$, and as you mentioned $|Z(P)|\notin \{p^2,p^3\}$, which means $Z(p)\cong C_p$. So that's about it. The class equation is nothing more than what you did here with conjugacy classes (those equivalence classes are called conjugacy classes.). If you got time just take a quick look at groups actions. You can use "A Course on Group Theory" by John S. Rose, and for more motivation brother, you've just proved Theorem 4.28 of that book. Sorry I wasn't notified for this answer.
Comment: @Ash: Give your opinion about the solution.