Como criar página para cada usuário com PHP?

Question: Hoje eu vi uma pergunta do usuário marcio.sx sobre criar um sistema de referência, a pergunta foi desativada pois estava com ZERO de detalhes do que ele queria mas eu acredito que peguei a ideia, mas como foi desativada achei interessante criar uma nova pergunta e responder logo abaixo pois acredito que isso possa ajudar muitas pessoas.
A questão é a seguinte:
Como criar um formulário para o usuário pode criar uma página em meu site (meusite.com.br/linkdousuario)?
Além disso como mostrar botões no site onde irão levar para a página desse usuário?
A pergunta estava assim por isso a falta de detalhes fez com que fosse desativada mas abaixo segue uma resposta que talves ajude quem estiver precisando disso.
Eu já tive o mesmo problema há um tempo atrás então fiz essa nova pergunta porém mais específica e vou colocar também uma resposta baseado no que eu fiz no meu caso e conto com outras respostas e métodos diferentes para isso.
Então a pergunta aqui seria:
Como criar uma área em meu site onde usuários cadastrados tivessem uma página de perfil para que outras pessoas pudessem ver seus dados de contato, descrição, foto de perfil e até pontuação por exemplo?
Lembrando que o usuário seria cadastrado no Banco de Dados com os campos necessários mas eu preciso saber como pegar esses dados e apresentar na página do perfil desse usuário (ex. www.meusite.com.br/usuario1).
Uma vez que tiver a resposta sobre como configurar essa página de perfil eu precisaria saber também como ENVIAR as pessoas para lá... por exemplo aqui no site ao clicar no nome de um usuario eu sou enviado para a sua página, seria mais ou menos isso... após configurar a página de perfil como 'linkar' para que as pessoas cheguem até lá?
O site seria uma espécie de Mural de Comentários onde as pessoas fazem um cadastro e então podem participar deixando seus comentários, essa parte está OK eu preciso apenas criar agora a página do perfil e saber como enviar as pessoas para lá.
LEMBRANDO QUE ABAIXO ESTOU COLOCANDO A RESPOSTA E EXPLICANDO DETALHE POR DETALHE ok...
Comment: Acho até legal fazer alguma graça como fez na resposta (desde que não seja uma tentativa de ironia, claro), até acho que falta um pouco mais dessa descontração no site. Mas isso não dispensa de melhorar a pergunta. Melhorando a pergunta, aí você vai estar realmente ajudando os outros com a resposta também, e isso é algo a ser incentivado (com votos inclusive). Mas tudo parte da pergunta autosuficiente e completa de maneira a qualquer um com expertise no tema proposto poder responder sem adivinhações. Então, fica a sugestão de [edit] com o que foi pedido, pra ficar tudo legal.
Comment: Na forma atual só o autor pode responder a pergunta por não ser específica.
Comment: Se a pergunta foi desativada, é por que ela não estava correta. Reposta-la só vai fazer com que a mesma seja novamente desativada. Se queria ajudar o usuário, poderia ter comentado sobre os problemas com a pergunta e como ele deveria melhorar, e talvez votar negativo... Poderia também procura-lo fora da comunidade ou no chat.
Comment: Olá Leandro, tudo bem? Então, mesmo colando a resposta eu acho que sua pergunta não está clara. Será que poderia adicionar à pergunta alguns detalhes que adicionou na resposta? Assim você poderia conseguir outras respostas de pessoas que pensam diferente de você. É normal em perguntas desse tipo conhecer novas formas de resolver o mesmo problema. xD
Answer: vi que sua pergunta está com poucos detalhes para que possamos ajudá-lo, para que possamos dar a melhor solução para você é necessário ao menos entender finalidade disso que está pedindo... quer criar uma página no seu servidor (salvar um arquivo .PHP nele) ou somente uma página padrão (por exemplo perfil.php) onde o conteúdo será preenchido de acordo com o 'usuário' informado no link?
Eu ACREDITO que o segundo caso é o que você procura, nesse caso você cria uma página onde será preenchida com um conteúdo que está no seu banco, por exemplo:
Ao acessar perfil.php será apresentado uma página inicial com os perfis e botões como você mencionou, e ao clicar em um botão será redirecionado para perfil.php?u=marciosx
Nesse caso a página perfil.php vai verificar que a variável u (de usuário mas você pode colocar qualquer coisa) foi preenchida e vai efetuar uma busca no seu banco de dados.
Aí você deve criar uma tabela com os campos que precisa (nome, nome de usuário, foto, outros conteúdos que deseja) e o site vai pesquisar por exemplo a linha que possui o 'nome de usuário' = 'marciosx' e encontrando essa linha você pode colocar as informações que você deseja no site.
Eu vou deixar abaixo alguns scripts para você mas caso não seja isso que deseja retorne com mais detalhes que assim poderemos ajudá-lo ok. Grande abraço.

<?php
# FileName="Connection_php_mysql.htm"
# Type="MYSQL"
# HTTP="true"
$hostname_conexao = "";
$database_conexao = "";
$username_conexao = "";
$password_conexao = "";
$conexao = mysql_pconnect($hostname_conexao, $username_conexao, $password_conexao) or trigger_error(mysql_error(),E_USER_ERROR);
?>

Agora é só incluir a página conexao.php no início ok.
<? include('conexao.php'); ?>

Depois disso você vai verificar se a variável 'u' foi indicada ou não.
<? if(isset($_GET['u'])){}

else{

echo "<meta HTTP-EQUIV='Refresh' CONTENT='0; URL=index.php'>";
} ?>

Bom, como a dúvida é sobre apresentar os dados dos usuários vou direto para essa parte... vamos buscar no banco o usuário marciosx ok.
Isso ficará dentro do campo IF que é o código para quando a variável for indicado que eu comentei acima ok.
$usuario = $_GET['u'];
$sql = mysql_query("SELECT * FROM perfis WHERE usuario = '$usuario' ");

Agora que encontramos eles vamos pegar o conteúdo criado por ele por exemplo, isso você que vai definir pois na pergunta não ficou claro o que será apresentado nesse 'link'.
while($linha = mysql_fetch_array($sql)){
$nome = $linha['nome'];

$foto = $linha['foto'];

$usuario = $linha['usuario'];
    }

Bom, agora é só você montar uma página 'padrão' que será praticamente igual para todos os usuários que 'criarem uma página' em seu site, só que o conteúdo será preenchido de acordo com o conteúdo do banco.
Ao colocar uma foto assim:

Coloque:
<img src="<? echo $foto; ?>" width="100"/>

Sendo assim a foto será sempre aquela informada pelo usuário quando 'criou' a página entendeu... o link da foto será salvo no banco junto com o seu nome de usuário, email, descrição, ou qualquer outro conteúdo.
Você pode colocar um valor padrão para o caso do usuário não quiser informar nenhuma foto naquele momento (caso nada seja informado salve img/fotodeperfil.php por exemplo).
Pronto, assim você já consegue pegar através do link o conteúdo da página e montar do jeito que você precisar, agora quanto ao formulário você deverá apenas pegar o conteúdo e salvar no banco, caso não saiba como fazer isso segue abaixo:
<form id="cadastro" method="post" action="salvarCadastro.php">
<input name="nome" type="text" />
<input name="usuario" type="text" />
<input name="foto" type="text" />
<input type="submit" value="Enviar" />
</form>

Nesse formulário de exemplo pegamos 3 campos (nome, usuário e foto) e agora vamos criar a página salvarCadastro.php para incluir isso no banco, lembrando que precisará da conexão com o banco no início também ok.
<?

include('conexao.php');

$insertSQL = sprintf("INSERT INTO perfis (id, nome, usuario, foto) VALUES (%s, %s, %s, %s)",

                       GetSQLValueString("a", "text"),

                       GetSQLValueString($_POST['nome'], "text"),

                       GetSQLValueString($_POST['usuario'], "text"),

                       GetSQLValueString($_POST['foto'], "text"));

  mysql_select_db($database_conexao, $conexao);

  $Result1 = mysql_query($insertSQL, $conexao) or die(mysql_error());

echo "<meta HTTP-EQUIV='Refresh' CONTENT='0; URL=index.php?u=". $usuario ."'>";

?>

Note que na hora de informar os valores para serem salvos no banco o primeiro está com "a" pois será o ID de seu banco que geralmente é um valor numérico e que é salvo automaticamente pois é a chave primária, então informando "a" o banco vai desconsiderar isso e colocar o próximo número da sequência ok. Sabe criar tabelas no banco né?
Bom... até aqui já temos o formulário para salvar o usuário no banco 'criando sua página'... a página que irá apresentar o conteúdo do usuário e o que falta é somente os botões com o link de cada usuário, isso depende de como você vai fazer, quer abrir uma página com TODOS os usuários do banco?
Aí pode usar o famoso recordset, vou deixar um script seco abaixo (só ajustar para ficar do jeito que vai precisar ok).
<?
$maxRows_rsUsuarios = 9999; //Aqui é o limite de resultados que deseja, se colocar 10 serão apresentados somente os 10 primeiros (ou últimos dependendo da forma que definir) resultados.

$pageNum_rsUsuarios = 0; // Se precisar paginar sugiro pesquisar um pouco mais sobre isso para fazer de forma adequada ou fazer uma nova pergunta no site.

if (isset($_GET['pageNum_rsUsuarios'])) {

  $pageNum_rsUsuarios = $_GET['pageNum_rsUsuarios'];

}

$startRow_rsUsuarios = $pageNum_rsUsuarios * $maxRows_rsUsuarios;

mysql_select_db($database_conexaomural, $conexaomural);

$query_rsUsuarios = "SELECT * FROM perfis ORDER BY id DESC"; //Aqui eu defini a ordem por ID - ou seja, ordem que as páginas foram criadas - sendo que pode colocar a ordem do mais novo para mais antigo ou o inverso (DESC ou ASC). Assim está o mais novo primeiro ok. Você pode ordenar por nome em ordem alfabetica também, fazendo assim (ORDER BY usuario ASC)

$query_limit_rsUsuarios = sprintf("%s LIMIT %d, %d", $query_rsUsuarios, $startRow_rsUsuarios, $maxRows_rsUsuarios);

$rsUsuarios = mysql_query($query_limit_rsUsuarios, $conexaomural) or die(mysql_error());

$row_rsUsuarios = mysql_fetch_assoc($rsUsuarios);

if (isset($_GET['totalRows_rsUsuarios'])) {

  $totalRows_rsUsuarios = $_GET['totalRows_rsUsuarios'];

} else {

  $all_rsUsuarios = mysql_query($query_rsUsuarios);

  $totalRows_rsUsuarios = mysql_num_rows($all_rsUsuarios);

}

$totalPages_rsUsuarios = ceil($totalRows_rsUsuarios/$maxRows_rsUsuarios)-1;

$queryString_rsUsuarios = "";

if (!empty($_SERVER['QUERY_STRING'])) {

  $params = explode("&", $_SERVER['QUERY_STRING']);

  $newParams = array();

  foreach ($params as $param) {

    if (stristr($param, "pageNum_rsUsuarios") == false &&

        stristr($param, "totalRows_rsUsuarios") == false) {

      array_push($newParams, $param);

    }

  }

  if (count($newParams) != 0) {

    $queryString_rsUsuarios = "&" . htmlentities(implode("&", $newParams));

  }

}

$queryString_rsUsuarios = sprintf("&totalRows_rsUsuarios=%d%s", $totalRows_rsUsuarios, $queryString_rsUsuarios);
?>

Agora que o código já pegou todos os usuários do banco é só você escolher o local do site que eles vão aparecer... pode colocar isso em uma lista (que pode ser muito extensa dependendo da quantidade de cadastro então vai precisar usar paginação) ou até usar uma div para ir rolando, usando o overflow scroll onde todos os resultados ficarão dentro dela e o usuário poderá ir rolando os resultados, se abrir o WhatsApp Web verá que as últimas conversas ficam fixas no canto esquerdo da tela e você apoia o mouse ali e rola pra baixo mexendo somente o que está dentro daquela div sem afetar o restante da página, seria mais ou menos isso, mas não precisa ser fixo nem no canto esquerdo, pode colocar em qualquer local da página que quiser, por exemplo.

Agora vamos colocar dentro dessa div o conteúdo com TODOS os usuários do banco ok.

<?php do { ?>

<?php } while ($row_rsUsuarios = mysql_fetch_assoc($rsUsuarios)); ?>

O codigo para repetição é esse acima agora vamos montar um exemplo ok:

<?php do { ?>

<img src="<?php echo $row_rsUsuarios['foto']; ?>" width="100" />

Usuário: <?php echo $row_rsUsuarios['usuario']; ?> - <a href="perfil.php?<?php echo $row_rsUsuarios['usuario']; ?>">Clique aqui para acessar a página desse usuário.

<?php } while ($row_rsUsuarios = mysql_fetch_assoc($rsUsuarios)); ?>

É isso, o formulário salva os dados 'criando a página' do usuário, o código acima mostra TODOS os usuários que possuem uma 'página' em seu site e ao clicar no link será aberto a página perfil.php já informando a variável "u" que seria a página daquele usuário ok.
Agora é só adaptar o código com os dados que você precisa e montar isso dentro do seu site (não me preocupei com aparência é claro, coloquei o código seco ok, aí você vai montando de forma bacana com um bom layout).
Espero ter ajudado e espero que seja isso mesmo que você esteva procurando.


Populate and update a table with data from a different table

Question: My site allows for a user to search for a term which returns a table of associated songs. When the "Add Track" button in a particular row is clicked after the search, the respective track name and trackId are added to the table "playlist". The problem I am having is that once "Add Track" is clicked within a different row, the data from that row is not added to the "playlist" table, but rather it just replaces the previous information. I need to be able to generate a cumulative table. Any help would be great and thanks in advance!

      {{ error }}
        <form name="search" ng-submit="searchiTunes(artist)">
         <input type="search" required placeholder="Artist or Song" ng-model="artist"/>
            <input type="submit" value="Search"/>
        </form>

                   Album Artwork
                   Track

                   Track Id
                   Preview
                   Track Info
                   Track Price

                    {{song.trackName}}
                    <button ng-click="handleAdd(song)">Add Track</button>
                    {{song.trackId}}
                    Play
                    View Track Info
                    {{song.trackPrice}}

                   Playlist

            {{song.trackName}}
            {{song.trackId}}

itunes_controller.js
    var iTunesController = function($scope, $http){
     $scope.searchiTunes = function(artist){
             $http.jsonp('http://itunes.apple.com/search', {
                params: {
                    'callback': 'JSON_CALLBACK',
                    'term': artist,
                limit: 5,
                }
            }).then(onSearchComplete, onError)
        }
        $scope.handleAdd = function(song) {
        // this song object has all the data you need
        console.log("handle add ", song)
         $scope.addedtracks = [{song:'trackName', song:'trackID'}]
         $scope.addedtracks.push(song)
      }

    var onSearchComplete = function(response){
            $scope.data = response.data
            $scope.songs = response.data.results
        }

        var onError = function(reason){
            $scope.error = reason
        }

    }

Answer: I saw some issues with your code. First the code below
$scope.addedtracks = [{song:'trackName', song:'trackID'}]
$scope.addedtracks.push(song)

Acording to your html, you are passing the song object to the handleAdd. So just remove the first line from code above. After that step, declare addedtracks array before handleAdd like below
$scope.addedtracks = [];

Modify the ng-repeat for the playlist like below:

   {{song.trackName}}
   {{song.trackId}}

And that's it. Note that I used track by $index because ngRepeat does not allow duplicate items in arrays. For more information read Tracking and Duplicates section.
Finally this is working plunker


Correct DNS settings for my server setup

Question: I am struggling to understand the correct DNS settings for my server setup.
I have a web server with a single IP and 6 domains hosted on it. I got IIS6's SMTP virtual server working yesterday and sent out a single email from my server to my gmail account which got put in the spam folder because the gmail check for Received-SPF: failed.
I changed some DNS records as per a tutorial I was following, sent another email which was marked as spam with a Received-SPF: softfail. I made some more changes to my DNS records, sent a third email from my server which didn't get put into the gmail spam folder and, according to the gmail email header was declared a Received-SPF: pass.
Great, or so I thought, because today I installed hMailServer and quickly realised that my DNS settings were still not right, so I began trying to work out why I couldn't send or receive any email.
In doing so I found out that, according to mxtoolbox.com and some other DNS record checking sites, my IP address is now blacklisted by CBL (the only one in a long list but not a good start). I checked at the cbl.abuseat.org lookup utility and it claims the last instance of SPAM being sent from this IP was recorded at the same time I was testing the SMTP server on my web server yesterday. Annoying because we are literally talking 2 test emails that were stamped SPAM by google and 1 that was ok.
Anyway, not wanting to make matters worse, I wanted to make sure ALL my DNS records are in order before I ask to be de-listed and again attempt to send and receive emails.
DNS records:
domain1.co.uk
(A records all pointing to my single IP Address)
mail.domain1.co.uk    A    188.8.131.52
pop3.domain1.co.uk    A    18.104.22.168
smtp.domain1.co.uk    A    22.214.171.124
imap.domain1.co.uk    A    18.104.22.168

MX record for domain1.co.uk pointing to mail.domain1.co.uk
TXT record for mail.domain1.co.uk containing the following:
v=spf1 a:mail.domain1.co.uk ~all
I want to be able to send and receive emails on all my domains so I have set others up like this:
(A records all pointing to my single IP Address)
mail.domain2.co.uk    A    18.104.22.168
pop3.domain2.co.uk    A    22.214.171.124
smtp.domain2.co.uk    A    220.127.116.11
imap.domain2.co.uk    A    188.8.131.52

MX record for domains.co.uk pointing to mail.domain1.co.uk
There is NO txt record with spf information for domain2.co.uk
Where should I go from here?
Answer:
Check your logs, make sure your SMTP server has only sent out the mail you think it has. Otherwise, we've all just learned to not test our email configurations with GMail addresses...
Your SPF record as it stands appears to be correct.

I suggest taking a couple hours and setting up a mail server on Amazon EC2 or the like. You can use a micro instance, pay a few cents for the machine, and hit delete when you're done. Then you can have something that is running SPF verification rules and see both side of the transaction from the mail server's point of view.
Comment: Hi Jeff. Thanks for getting back.
Checked logs & that was the only set of emails sent. I only set the server up a couple of weeks ago & only installed SMTP a few days ago.

I don't know what Amazon EC2 is (I am new to web hosting and even newer to mail hosting). If I need to I will dedicate the hours you suggest but for now I want to understand the DNS problems I have.

I used www.mxtoolbox.com/SuperTool.aspx
to check my IP (126.96.36.199) and my domain (smtp.distinguisheddesign.co.uk)
Everything is reported as fine except I get this message:
Warning - Reverse DNS does not match SMTP Banner
Answer: Your DNS is correct. No worries about that. Probably there are PTRs missing but this can only be done by the IP address provider. This affects deliverability.
What you should worry about is the fact that you are blacklisted. This has nothing to do with your DNS setup. And really nothing to do with your particular test mails. This is just a timely coincidence. Probably you opened your firewalls for your tests and now it revealed that you have one (or more) rogue machines in your network which are infected with malicious code.
The CBL listings are serious. They don't occur just because you mail some samples to Google. CBL and Google are not affiliated. CBL runs their own fully automated Spam traps without user interaction (or Google interaction). If the CBL site states that you are infected with some kind of trojan you can be sure that this statement is correct with more that 95% probability.
Comment: My server is a virtual server hosted with a company called Memset. It's a completely fresh setup. I am confused as to how I could have picked up a trojan almost immediately. There were no logs of any emails other than mine being sent out from my server.
You say PTR's are missing, do you mean for my other domains?
Comment: @user1001107 I said "probably". As you do not provide the domains and IPs this was just a guess.
Comment: I was wary of posting actual IP's and domain names.
I have 6 domains and a single IP.
IP: 22.214.171.124
various .co.uk domains.
Comment: @user1001107 This IP has a PTR. So no problem with that.
Comment: @ mailq
I have gone through the various checks listed here: http://cbl.abuseat.org/advanced.html
and although I'm not an expert, I can't see any tel-tale signs that my server is being abused.
Comment: @user1001107 No problem then. Unlist yourself and get back to normal.
Comment: Hi,Sent an email to my gmail account from my server with 'from address' as 'firstname.lastname@example.com'.
Got it in my gmail inbox (not marked SPAM) but the email header says this:

Received-SPF: neutral (google.com: 126.96.36.199 is neither permitted nor denied by best guess record for domain of firstname.lastname@example.com) client-ip=22.214.171.124;
Authentication-Results: mx.google.com; spf=neutral (google.com: 220.127.116.11 is neither permitted nor denied by best guess record for domain of email@example.com) firstname.lastname@example.com

Why?
Comment: @user1001107 Because you don't have a SPF record for the-friday-group.co.uk. But this chat gets off-topic right now. So I will refuse any further comment.
Comment: I don't see how it's off topic. I'm trying to get my DNS records in order. Through my reading online I thought you should only have ONE SPF record per IP address?
Comment: @user1001107 One PTR per IP, one SPF per (sub)domain.
Comment: Ah, ok. I think I've been getting the PTR and SPF records confused.


error when using itertools.count() to count

Question: I have the following code:
counter = itertools.count()

dtype = [('clf', object), ('accu', float), ("counter", int)]
self.models = np.zeros((n_randoms*n_boot, n_estimators), dtype=dtype)

for i in tqdm(range(n_randoms*n_boot)):
    for j in range(n_estimators):
        clf = DecisionTreeClassifier(random_state = j, criterion="entropy")
        clf.fit(X_train_list[i], y_train_list[i])
        accu_list[i, j] = clf.score(X_test_list[i], y_test_list[i])
        self.models[i, j] = (clf, accu_list[i, j], next(counter))

self.sorted_models = np.sort(self.models, axis=1, order=["accu", "counter"])

where n_randoms is 10, n_boot is 7, and I received an error that TypeError: '<' not supported between instances of 'DecisionTreeClassifier' and 'DecisionTreeClassifier' when I set n_estimators to 19, it goes well up to 18.
Theoretically, whenever two Classifier have the same accuracy, I use a next(counter) to index every Classifier so that when I use np.sort(), it sort based on the order ["accu", "counter"], which I think is fine. In addition, if I use -next(counter) instead of a plus sign here, I can only set n_estimators up to 16, and it gets the same error beginning from 17. Based on this, I think there is an error probably when I deal with next(counter).
My question is, 1.where is my error? 2.Any hints on fix it? Thank you.
Edit:
I do some more experiments, this time I set n_randoms to 100, and n_estimators to 5, which is larger than the above error numbers of iterations in total(5*100*7 > 19*10*7), but it works fine, so I guess only when the number of estimators goes up will cause an error.
Comment: ["A single field can be specified as a string, and not all fields need be specified, but **unspecified fields will still be used, in the order in which they come up in the dtype, to break ties**."](https://docs.scipy.org/doc/numpy/reference/generated/numpy.sort.html)
Comment: @user2357112supportsMonica, thanks, "but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties.", my understanding is that because next(counter) will always goes up from 0, there will not be any ties, so "clf" field will not be considered. In addition, if your statement is True, why there is no problem when n_estimators is small?
Comment: I would guess either you're hitting a case where an element happens to be compared to itself, or the sort routine is comparing the extra fields eagerly.
Comment: What NumPy version is this?
Comment: @user2357112supportsMonica I am using NumPy: 1.18.2, and run on Google Colab Pro
Answer: numpy.sort doesn't promise not to compare elements against themselves. The partition logic in the quicksort will sometimes perform self-comparisons at the end of a partition, since the element comparison happens before the pointer comparison:
/*
 * Generic comparisons may be buggy, so don't rely on the sentinels
 * to keep the pointers from going out of bounds.
 */
for (;;) {
    do {
        pi += elsize;
    } while (cmp(pi, vp, arr) < 0 && pi < pj);
    do {
        pj -= elsize;
    } while (cmp(vp, pj, arr) < 0 && pi < pj);
    if (pi >= pj) {
        break;
    }
    GENERIC_SWAP(pi, pj, elsize);
}

Here, vp is a pointer to a copy of the pivot, and the pivot is placed at the initial value of pj. If the pivot is the highest value in the range from the initial pi to the initial pj, then pi advances all the way to the pivot and self-comparison occurs.
Pivot selection would have guaranteed the existence of a value higher than the pivot, except that that higher value is placed immediately after the initial pj.

In a self-comparison, the counter values will be equal, and the comparison will try to ask whether a classifier is less than itself.
Partitions only start happening at all once the sort axis grows beyond the insertion sort threshold, which is why you only saw the problem when your sort axis got long enough.
Avoiding self-comparison would be handy. I'm pretty sure the built-in sorted function avoids self-comparison, and I don't think it would be too difficult to avoid self-comparison in numpy.sort. This might be worth an enhancement request.


Problem with formulating the negation of a statement

Question: The excersise asks us to prove with an Indirect Proof that if $abc$ is an irrational number then at most two of $a,b,c$ are rational numbers.
So we have,
Let $P$ denote "$abc$ is irrational" and let $Q$ denote "at most two of $a,b,c$ are rational numbers". We want to prove: If $P$ then $Q$, but indirectly, i.e. $\neg P => \neg Q$. Formulating the negation of $P$ we have
$\neg P := $ "$abc$ is rational"
But i don't know how to formulate the negation of $Q$. I figured that it should be "at least three of $a,b,c$ are rational numbers", but then $\neg P $ doesn't imply $ \neg Q$ because we could have $a=b=\sqrt2$ and $c=1$ and so
$abc=1\sqrt2 \sqrt2 =2$
which is a rational number even though $a,b$ are irrational and clearly, this disproves $\neg P => \neg Q$. How should I formulate $\neg Q$? And in general, if we have more than one conditions in a statement, which conditions become negatives?
Answer: First of all $P$ implies $Q$ is not the same as $\neg P $ implies $\neg Q$. It is $\neg Q $ implies $\neg P$.
The negation of $Q$ is 'all three of $a,b,c$ are rational'.
Answer: The negation of $P\implies Q$ is $P$ and not $Q$
Thus you need to assume that $abc$ is irrational and all three of them are rational and derive a contradiction out of that.


ACE fails at Linker in MAC OS X 10.9 (and higher)

Question: I am trying to compile and run the following simple code in MAC OS X 10.9 with CLANG++:
#include "ACE_wrappers/ace/MEM_Stream.h"
#include <iostream>

int main()
{
        std::cout << "Hello World" << std::endl;
        ACE_MEM_Stream m(3);
        m.close_reader();
        return 0;
}

But I get the following error:
QAs-MacBook:aceTestLinking Moamen$ clang++ myTest.cpp
Undefined symbols for architecture x86_64:
  "ace_os_main_i(int, char**)", referenced from:
       _main in moamen-511a28.o
  "ACE_SOCK::ACE_SOCK()", referenced from:
       ACE_MEM_IO::ACE_MEM_IO() in moamen-511a28.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

The compile line:
clang++ myTest.cpp

The CLANG Compiler version I am using:
QAs-MacBook:aceTestLinking Moamen$ clang++ --version
Apple LLVM version 6.0 (clang-600.0.54) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin13.4.0
Thread model: posix

Notice - I have also tried to compile with "-std=c++11", "-stdlib=libstdc++", as in the following topic:
C++ linking error after upgrading to Mac OS X 10.9 / Xcode 5.0.1
  but did not solve the issue.
Thanks,
Moamen
Comment: possible duplicate of [What is an undefined reference/unresolved external symbol error and how do I fix it?](http://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix)
Comment: Apparently you aren't linking with ACE library.
Comment: Notice same code worked before in older OS X (10.8 and below), but after CLANG compiler update, it's not working (before I used g++, not clang++).
Comment: I have tried to run **clang++ myTest.cpp -I ACE_wrappers/lib** still getting the same error
Comment: `-l` and `-L` are different compiler options, I believe you have to specify them both with correct values.
Comment: You have to link the ACE library with -lACE, else it will not work. See how we compile and link one of the ACE unit tests
Comment: Thanks for the replies, after some investigation on Linux Ubuntu, I succeeded to compile the code with the following command **g++ -o m.out myTest.cpp ACE_wrappers/lib/libACE.a  -I ACE_wrappers/ -lpthread -ldl**. Seems some default libs were missing!
Comment: For MAC OS X - it was my mistake, I needed to include correctly some libs / header files, i.e. **clang++ myTest.cpp ACE_wrappers/lib/libACE.a -I ACE_wrappers/**.
Answer: Thanks for the replies, after some investigation on Linux Ubuntu, I succeeded to compile the code with the following command g++ -o m.out myTest.cpp ACE_wrappers/lib/libACE.a -I ACE_wrappers/ -lpthread -ldl. Seems some default libs were missing!


Applying AIC to determine appropriate ARIMA model

Question: If I somehow know that a variable $Y$ is explained by an ARIMA process, and I know the number of times that the observations must be "differenced" to obtain a stationary series, I have read that it is appropriate to use AIC to determine the number of regressor variables in the model.
The formula for AIC is $AIC=2p + 2ln(L)$, where $p$ is the total number of regressors, and $L$ is the maximum of the likelihood function, and the best number of regressors is the one which minimizes the AIC.
My question is, if I determine for example that AIC is lowest when $p=5$, how do I know which of these five regressors are lagged $y$ variables, and which of the five regressors are lagged error terms?
Answer: AIC is used to compare particular models against each other. How could you even arrive to the conclusion that AIC lowers at p=5 without actually fitting the model that gives such low AIC?
Also, I would not use AIC as the only criterion to determine model selection. If you already know that your series follows an ARIMA process, just pick the simplest model that leaves no significant autocorrelations on its residuals (you may also want to check the squared residuals to confirm no heteroskedasticity)


Como funciona Abstract States no angular

Question: Estou trabalhando em um APP e ainda estou conhecendo as funcionalidades do angular.
Tenho um arquivo de rotas e me foi sugerido adicionar o parâmetro abstract: true para impedir a navegação por url. Porém fui pesquisar mais sobre o mesmo e não entendi muito bem o que de fato ele faz.
Em nada do que eu li, diz que ele impede a navegação pela url. Então gostaria de saber qual é a real funcionalidade dessa propriedade?
Comment: AngularJS ou Angular2? São duas coisas distintas.
Comment: Pensei q fosse o mesmo. Mas no meu caso é para o angularjs. Vou editar!
Answer: Um exemplo prático talvez ilustre algumas possibilidades.
Imagine que você possui uma aplicação onde acesso a um dado estado seja controlado por permissões - por exemplo, #/usuarios é um estado que exibe a lista de usuários, porém apenas usuários com permissão de administração pode vê-lo.
Você pode criar um estado abstrato - acessoNegado, por exemplo - que é invocado quando o estado usuarios é acessado sem as devidas permissões.
Assim, a URL presente no browser continua sendo #usuarios, porém o usuário está visualizando o conteúdo de #acessoNegado.
Comment: essa parte ficou clara pra mim agora. Mas esse acessoNegado seria uma variável de controle. Por exemplo: 'abstract: acessoNegado'?


Counting Sequence of Lattice Paths going through a point

Question:
The length of a lattice walk is the number of steps taken. Write the counting
  sequence --- including the general term and starting from the walks of length zero --- for walks of length $n$ that start at $(0, 0)$ and include point $(2, 2)$ with allowable steps $\rightarrow$ and $\uparrow$. Written in terms of $n$, the general term will require restrictions on what $n$ are allowable.

For $n = 0, 1, 2, \dotsc$ what I've got is:
$$0, 0, 0, 0,\ \frac{4!}{2!2!},\ 6 \cdot 2 \cdot 2 \cdot 2!,\ 6 \cdot \frac{3!}{2!},\dotsc,\ 6 \cdot 2^{|x-y|} \cdot \frac{n!}{(x-2)!(y-2)!}$$ where $n \geq 4$ and the path ends at $(x,y)$ (this is the general term).
Is this correct? If not, any tips on where I went wrong would be appreciated. Thank you!
Comment: Deleted my comment, sorry I misread the question as "ending on" instead of "including" $(2,2)$.
Comment: The original question seems to ask the number of walks of length $n$ that start at $(0,0)$ and include $(2,2)$ while your answer seems to provide the number of walks of length $n$ that start at $(0,0)$ and include $(2,2)$ AND end on $(x,y)$. Which of the two are you trying to solve?
Answer: Since you can only go right and up, you cannot visit $(2, 2)$ after you pass out of the box defined by the two corners $(0, 0)$ and $(2, 2)$. Thus, from $(0, 0)$, you must take some steps to reach $(2, 2)$ and then you can take any steps you want. There are 6 ways to do the first part as you calculated. For the second part, at each step you have two choices (right and up) so for $k$ steps you have $2^k$ choices.
Multiplying these two, you get $6\cdot 2^{n-4}$ when $n \geq 4$ and 0 otherwise.


How to do SQL write in document that is largely javaScript and JQuery

Question: I'm trying to figure out how to get a SQL DB write into my file that is largely javaScript and JQuery.  I've found some php info online, but I'm having trouble getting the php into my code with everything else that's there.  I'm trying to utilize an array where I put user entered info from an html table, and call a method that uses the array as a parameter.  I have made my entire file a php file, but I'm having trouble figuring out where to put the php <?php ?> delimeters without having my bigTableRows array go out of scope, or other run-time error messages.  After I figure this out I need to do a MS SQL write. Right now, I see this error message, but no table.  Line 83 is the line after the <?php, where I have echo(bigTableRows[0];
Parse error: syntax error, unexpected '[' in E:\visE\jqproject\web\BigTable.php on line 83

If I take away the [0] part, I get a syntaxError, but see the table ok:
missing; before statement.

This is what it looks like:
BigTable.php:
<!DOCTYPE html>

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

 Visual Evaluation Entry Table

            Edit/Save	Bands @263mm Y	Bands @263mm M	Bands @263mm C	Bands @263mm K	Comments

            <button class="editbtn">Edit</button>

Some examples I've found are:
php sql write,
and
put html table data into array
I know that if I take away the <?php delimeters, it would run ok (minus echo) (and access the array data), but I need them to do the php part.  If I'm off-base on any of this, which I'm sure something is, feel free to let me know.  I have a little php experience with xml/html, but I'm learning javaScript and JQuery, and I've never tried to put it all together before.
Comment: No, it's Microsoft SQL
Comment: The "InsertData" function is suposed to be Javascript or PHP?
Comment: Javascript.  I got the idea from the link above in the question.
Answer: OK, im really trying to be constructive here, i never used the Microsoft SQL connector on PHP but looking on the documentacion is very similar to the MySQL connector (i think is meant to be that way).
So, you need to create the connection first, if your doing it, you need to iterate the dataset to obtain data or pass the data to an array.
In your example code i see a mix of JS with PHP, that's just not right.
the only thing you need to do is read this link: this link!
1.- Create the connection.
2.- run the query.
3.- fetch the dataset to an array (this is only my personal recomendation).
4.- Use the data inside the PHP or save it on a variable like this.
<?php
    echo "var val = " . $myArray[0][0] . ";"; /** Here you are "printing" the variable declaration into the HTML document. **/
?>

In fact, if you want your data on JSON to be used in a javascript object, you can do it this way.
<?php
    echo "var myObj = '" . json_encode($myArray) . "';";
?>

If i missed something let me know.
Comment: OK, here's a mayor confusion about PHP and Javascript.
I will add another answer to this.
Comment: Sorry, a long time has passed but, this is the thing, you are trying to  run php code AFTER the page is loaded, and thats imposible, php is server side so you need to save the data in a server instance, like sending the new data through ajax to the php server and update it. the php server first runs all the code and then renders the page, so, after the page is visible on the explorer you cant run php code.

You need to create another page to recieve the new info.
Comment: I am going in the other direction.  I got the data from the table and need to write it to the SQL DB using PHP.
Comment: Thanks! I had wound up going to another page when I hit the submit button after entering data in the table. Then in that php file I used Post/Get to handle the data and put it in an array of oo tableData objects, then I send it to another php file where I loop through the data to send it to the SQL db.


pass value from form to modal in php

Question: 	';
echo"$imagedesc $id	";
echo"$pestname	";
echo"$pesticide	";
echo"
<form action='editpest.php?id=$id' method='POST'>
<button  data-toggle='modal' class='btn btn-primary btn-sm btn-block' data-target='#update-modal'>Edit</button>

<form action='../php/deletepest.php?id=$id' method='POST'>
    <button class='btn btn-danger btn-sm btn-block'>Delete</button>
</form>
	";
echo'
';

<button type="button" class="close" data-dismiss="modal">×</button>

Update Picture Pest

<?php echo" <form action='../php/updateImage2.php?id=$id' method='POST'>;"?>

    <input type="text" class="form-control image-preview-filename" disabled="disabled">

        <button type="button" class="btn btn-default image-preview-clear" style="display:none;">
             Clear
        </button>

            Browse
            <input type="file" accept="image/png, image/jpeg, image/gif" name="input-file-preview"/>

<button type="submit" class="btn btn-primary btn-lg">Update Picture</button>

</form>

Hi I want to pass the value of $id retrieved from the database to the modal, so I can use it as a Where Clause when I Update the Image.
This is my first question hope somebody will answer
Comment: Please consider to fix the code format.
Comment: Ok I will watch the question of other to know the right format.
Answer:

    <?php echo $imagedesc.''.$id;?>
    <?php echo $pestname;?>
    <?php echo $pesticide;?>

        <a class='editClass' href="#form_modal" data-toggle="modal" data-id="<?echo $id;?>">
                Edit

        <form action='../php/deletepest.php?id=$id' method='POST'>
            <button class='btn btn-danger btn-sm btn-block'>Delete</button>
        </form>

JS

footer (Place this code in footer or below your

)

editpest.php
<?php
$id = $_GET['id'];
// Now, write your query here
?>

  <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Update

    .
    .
    <?php echo "Id: ".$id;?>
    .
    .
   // Write code here to update

  <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

Comment: Thanks I get a lot of idea from your code sir .,
Comment: If you think this answer helped you. Please tick this answer as correct answer. As, it will help other user to find it easily. Thanks @JersonBabieraGevera. *Glad to help* `:)`

pass value from form to modal in php


mvc 4 asp.net c# passing boolean value from controller to view

Question: How can i get Boolean value or the true or false from controller to a Checkbox in View using this:
@Html.CheckBox("condition", @ViewData["Condition"])

or
<input type = "checkbox" checked = "**true or false?**">

I have this in my Controller..
public ActionResult Member(string sortOrder, string filter, string searchString, int? page, **bool? condition = false**)

and in my view is like this

please help me for this...
Comment: It just needs to be `@Html.CheckBox("condition")` And the parameter needs to be `bool condition` (not `nullable`). If the value of `condition` is true, the checkbox will display as checked, otherwise it will be unchecked. But I recommend you use a view model and pass it to the view so you can use the strongly typed HtmlHelper - `@Html.CheckBoxFor(m => m.Condition)`
Comment: `checked` is bool attribute. It's mere existence ensures the input is checked. So you don't want to `checked=anything` if false because it shouldn't be there i.e. a non checked checkbox would be ``  whereas  `` will tick the box as will `` If the `checked` attribute exists, it will be checked regardless of the value.
Answer: update your controller
public ActionResult Member(string sortOrder, string filter, string searchString, int? page,bool condition)
{
    ViewData["Condition"] = condition;
    // code line 1
    // code line 2
       ...
}

If you are looking for checkbox check/uncheck code for Razor view
@Html.EditorFor(x => x.condition)

Will generate:
<input id="condition" type="checkbox" value="true" name="condition" />
<input type="hidden" value="false" name="condition" />

How does it work:
If checkbox not checked, form submit only hidden (false)
If checked, then form submit two fields (false and true) and MVC set true for bool property
<input id="condition" name="condition" type="checkbox" value="@ViewData["Condition"]" />

This will always send default value, if checked
reference : https://stackoverflow.com/a/14731571/2318852
Comment: Thank you so much @BhavikPatel for this well detailed answer! Helped me out!
Comment: it's possible that <input type = "checkbox" checked = "true or false?" pass the checked value to a controller?


Can multivariate Gaussians KL divergence be a negative value?

Question: I'm trying to find if two hidden neurons in RBF Network overlap with each other or not? It's an online classification problem, it means data come to our network one-by-one and then discard completely. so I already know the mean and covariance of each neuron. I want to measure the distance between every two neurons. as long as this network is RBF and each neuron show a distribution, I want to use KL divergence as a measure of distance. ( I know KL can't be a measure, because the KL(P||Q) is not equal with KL(Q||P), but assume that I fix this problem.)
I read this question about how to calculate multivariate Gaussians KL divergence and I use the formula:
$$
\begin{aligned}
KL = \frac{1}{2}\left[\log\frac{|\Sigma_2|}{|\Sigma_1|} - d + \text{tr} \{ \Sigma_2^{-1}\Sigma_1 \} + (\mu_2 - \mu_1)^T \Sigma_2^{-1}(\mu_2 - \mu_1)\right].
\end{aligned}
$$
I also implemented the matlab code as below.
ans1=log(norm(CovarianceMatrix(:,:,NrSNumberindx(i)))/norm(CovarianceMatrix(:,:,NrS)))-(size(A,2))+trace(pinv(CovarianceMatrix(:,:,NrSNumberindx(i)))*CovarianceMatrix(:,:,NrS));
ans1=ans1+(CenterTem-CenterNeuron(NrS,:))*CovarianceMatrix(:,:,NrSNumberindx(i))*(CenterTem-CenterNeuron(NrS,:))';
ans1=ans1*0.5;

I can't find any implementation problem in my code.  But it gives me a negative value for KL which we already know, KL is always positive.
I trace the code. At the first of training, covariance matrix of data is equal to zero so I add the epsilon to each element of the covariance matrix. But still trace of these values are really small and if the dimensions of data are huge then the value of (size(A,2)) is huge too.
So the trace is a small value, the log is equal to zero (because each value of the covariance matrix is equal to epsilon) and value of (size(A,2)) is large and negative, then the result of KL become negative which doesn't have any meaning!!
Answer:
ans1=log(norm(CovarianceMatrix(:,:,NrSNumberindx(i)))/norm(CovarianceMatrix(:,:,NrS)))

The formula says $ \ln { | \Sigma_2 | \over | \Sigma_1 | } $ to mean the determinant, not the norm of the matrices.

ans1=ans1+(CenterTem-CenterNeuron(NrS,:))*CovarianceMatrix(:,:,NrSNumberindx(i))*(CenterTem-CenterNeuron(NrS,:))';

The formula says $(\mu_2 - \mu_1)^\intercal \Sigma_2^{-1} (\mu_2 - \mu_1)$, but you seem to have forgotten to invert the covariance matrix.
Does it work once you fix the errors above?
Comment: I changed it to a unity matrix, but it has an effect on accuracy, not in a good way.
Comment: your right about the problems.thanks. but can you help me more? when I use `det` the value of the log part is equal to NAN because all covariance matrix elements are equal and determinant of these value is equal to zero. so we have (zero/zero) which is NAN
Comment: If the covariance matrix is all zeroes, it means that there is no variance in the data at all. (If the data was orthogonal, you would at least get non-zero diagonal values!) Constant data is, indeed, not multivariate normal, so trying to use it as such leads to errors. Why do your neurons have constant data? Shouldn't it mean that such neurons have no effect on the result?
Comment: No it's not like that. the network is self-struct. it means it can add new neuron or delete neuron by itself. data come to network one-by-one. center and covariance matrix of each neuron which is more close to data are changing. I just initialize covariance matrix with zero. it changes with data
Comment: I am not an expert on RBF networks, but perhaps initializing the covariance matrix with a unity matrix instead of zero matrix may help?
Comment: Perhaps it would be best to start a new question on initial values in neurons of RBF Networks. Sorry for not being able to help further.


What is the procedure to play (amateur) football for a foreign club?

Question: Currently, I am a football player for a Dutch amateur club. This summer, I might move abroad and for sure I want to keep playing football. What is the formal procedure to be eligible for, say an English, amateur squad?
In this example, would it be sufficient to sign up at the team and the FA or is there some transfer action required with the KNVB (Dutch FA) and my Dutch club?
Notice that this has in no means to do with professional football transfers but everything with an average kid searching for a possibility to keep playing football in his spare time.
Any answers on how this works in other countries are appreciated as well.
Answer: Rules and regulations will differ from country to country, but provided you aren't a professional footballer (have a contract with your existing club) you are free to move to another league at will. Different federations will have some other restrictions (for example, I believe within most European leagues you cannot play for more than two clubs in a single season) but generically movement of amateur players is unrestricted. A transfer request needs to be submitted for professional players, or players moving between clubs within the same federation.
In Australia, and likely other countries with reputable football federations, you will be required to undergo an international clearance. This will be requested by the club you join in your new country and will be processed by their football association. They will liaise with the federation the player last played in (the parent federation) to determine whether the player is under any form of suspension or ban. No action is required by the player themselves, other than to inform their new club of the last club they played for.
When I have had to submit these forms, the usual response time from submission to clearance for play was 2-5 working days. If a request elapsed 3 weeks without a response from the parent federation, as can be the case with less organised federations from developing countries, the clearance is usually granted as de facto.


Automagically relating nodes of a single content type

Question: I have a content type (e.g. Target) which has a title and body. I will have about a 1000 nodes of this content type. I want to be able to create a view that renders not not only the title and body of this type of node, but also associated/related nodes.
I don't want to have to manually associate nodes (based on taxonomy or by adding an entity reference). Instead, I want the view to automatically search for the Title of a given node in the Body field of all other nodes of this type and associate those nodes that contain the given node's Title.
I'm new to Drupal, but believe I've gotten my head around the basics and have several Views configured and working. But I can't seem to find any guidance on achieving the above and not sure how to do that in Drupal/Views, although I know this is achievable in straight SQL.
Any ideas, advice?
Answer: Remeber that views is some kind a query builder, even better it gives you tools to alter its content, query and so on. See hook_views_query_alter
Comment: I am not at all familiar with using Drupal hook-alters. Is there no way to do this via the Views UI then?
Comment: Without a field relationing them I think no, at least one I can think of


jQuery animate complete not working

Question: The animation itself is working but why isn't my complete function working?
fiddle: https://jsfiddle.net/jzhang172/5kfbw066/1/

$(".ok").animate({
height:"300px"

},{
 duration:2000
 }, {complete:function(){
alert('hey');
}
});
.ok{
  background:blue;
  height:100px;
  width:200px;
}

Answer: complete is a property just as duration

$(".ok").animate({
  height: "300px"

}, {
  duration: 2000,
  complete: function() {
    alert('hey');
  }
});
.ok {
  background: blue;
  height: 100px;
  width: 200px;
}

Answer: complete callback should be passed as the method on the second param object to the animate(), not as a different object.
Updated Fiddle
$(".ok").animate({
  height: "300px"
}, { // <--- Pass `complete` callback as part of this object.
  duration: 2000,
  complete: function() {
    alert('hey');
  }
});

$(".ok").animate({
  height: "300px"
}, { // <--- Pass `complete` callback as part of this object.
  duration: 2000,
  complete: function() {
    alert('hey');
  }
});
.ok {
  background: blue;
  height: 100px;
  width: 200px;
}

Or, it can also be passed as last parameter to animate
$(".ok").animate({
    height: "300px"
  }, 2000,
  function() {
    alert('hey');
  }
);

$(".ok").animate({
    height: "300px"
  }, 2000,
  function() {
    alert('hey');
  }
);
.ok {
  background: blue;
  height: 100px;
  width: 200px;
}

jQuery animate complete not working


how to stop interpolating the values that are missing in plotly?

Question: So I created the area plot of my data in plotly. My data has the whole year of the time block and the data which we have in the table is only for 84 days( 7 days per month), so it's like for the rest of the days we don't have the data(not zero, it's missing). So when I plot the area graph for this data its not showing 0 for the missing values in the rest of the days. for example:

You can see in the graph that the straight lines are actually the rest of the days where the data is missing and the clustered lines are the actual data that we have in the table. So is there a way so that we can tell the plotly that don't interpolate the values for the missing data or something like that or may be we can put zero in place of missing data?
My code for this graph is:
import pandas as pd
import plotly.graph_objs as go
import plotly.offline as pyo
from plotly.subplots import make_subplots
import xlwings as xw
import logging
import glob

year = 2025
case = 'MNRE'
path1 = glob.glob("detailed output/"+str(year)+"/"+str(case)+"/with storage/[a-z]*.xlsx")
path2 = glob.glob("detailed output/"+str(year)+"/"+str(case)+"/without storage/[a-z]*.xlsx")

#Reading the data
app = xw.App(visible=False)
try:
    wb1 = app.books.open(path1[0])
    sheet = wb1.sheets['Fuel Wise Chart']
    dateWithStorage = sheet.range('A2:A8065').value
    coalWithStorage = sheet.range('D2:D8065').value
    nuclearWithStorage = sheet.range('E2:E8065').value
    gasWithStorage = sheet.range('F2:F8065').value
    bagasseWithStorage = sheet.range('G2:G8065').value
    hydroWithStorage = sheet.range('H2:H8065').value
    windWithStorage = sheet.range('I2:I8065').value
    solarWithStorage = sheet.range('J2:J8065').value
    bessCharging = sheet.range('L2:L8065').value
    bessDischarging = sheet.range('M2:M8065').value

    importSheet = wb1.sheets['Fuelwise Dispatch']
    importWithStorage = importSheet.range('CF2:CF8065').value

    wb2 = app.books.open(path2[0])
    sheet = wb2.sheets['Fuel Wise Chart']
    dateWithoutStorage = sheet.range('A2:A8065').value
    coalWithoutStorage = sheet.range('D2:D8065').value
    nuclearWithoutStorage = sheet.range('E2:E8065').value
    gasWithoutStorage = sheet.range('F2:F8065').value
    bagasseWithoutStorage = sheet.range('G2:G8065').value
    hydroWithoutStorage = sheet.range('H2:H8065').value
    windWithoutStorage = sheet.range('I2:I8065').value
    solarWithoutStorage = sheet.range('J2:J8065').value

    importSheet = wb2.sheets['Fuelwise Dispatch']
    importWithoutStorage = importSheet.range('CF2:CF8065').value

except Exception as e:
    logging.exception("Something awful happened!")
    print(e)
finally:
    app.quit()
    app.kill()
#Creating the area plot for with and without storage cases
fig = make_subplots(rows=2, cols=1, subplot_titles=("Without Storage(With min run constraints relaxed for old plants)", "With Storage"), shared_xaxes=True,
                    vertical_spacing = 0.06, y_title='Fuel Wise Dispatch')

trace1 = go.Scatter({'x': dateWithStorage,'y': coalWithStorage, 'name': 'Coal', 'mode':'lines', 'line' : dict(width = 0.5, color = 'rgb(71, 69, 69)'), 'stackgroup': 'one'})
trace2 = go.Scatter({'x': dateWithStorage,'y': nuclearWithStorage, 'name': 'Nuclear', 'mode':'lines', 'line' : dict(width = 0.5, color = 'rgb(255, 0, 0)'), 'stackgroup': 'one'})
trace3 = go.Scatter({'x': dateWithStorage,'y': gasWithStorage, 'name': 'Gas', 'mode':'lines', 'line' : dict(width = 0.5, color = 'rgb(0, 235, 227)'), 'stackgroup': 'one'})
trace4 = go.Scatter({'x': dateWithStorage,'y': bagasseWithStorage, 'name': 'Bagasse', 'mode':'lines', 'line' : dict(width = 0.5, color = 'rgb(154, 3, 255)'), 'stackgroup': 'one'})
trace5 = go.Scatter({'x': dateWithStorage,'y': hydroWithStorage, 'name': 'Hydro', 'mode':'lines', 'line' : dict(width = 0.5, color = 'rgb(0, 145, 255)'), 'stackgroup': 'one'})
trace6 = go.Scatter({'x': dateWithStorage,'y': windWithStorage, 'name': 'Wind', 'mode':'lines', 'line' : dict(width = 0.5, color = 'rgb(5, 252, 14)'), 'stackgroup': 'one'})
trace7 = go.Scatter({'x': dateWithStorage,'y': solarWithStorage, 'name': 'Solar', 'mode':'lines', 'line' : dict(width = 0.5, color = 'rgb(246, 255, 0)'), 'stackgroup': 'one'})
trace8 = go.Scatter({'x': dateWithStorage,'y': bessCharging, 'name': 'BESS Charging', 'mode':'lines', 'line' : dict(width = 0.5, color = 'rgb(145, 77, 4)'), 'stackgroup': 'one'})
trace9 = go.Scatter({'x': dateWithStorage,'y': bessDischarging, 'name': 'BESS Discharging', 'mode':'lines', 'line' : dict(width = 0.5, color = 'rgb(21, 102, 24)'), 'stackgroup': 'one'})
trace10 = go.Scatter({'x': dateWithStorage,'y': importWithStorage, 'name': 'Import', 'mode':'lines', 'line' : dict(width = 0.5, color = 'rgb(255, 161, 220)'), 'stackgroup': 'one'})

trace11 = go.Scatter({'x': dateWithStorage,'y': coalWithoutStorage, 'name': 'Coal', 'mode':'lines', 'line' : dict(width = 0.5, color = 'rgb(71, 69, 69)'), 'stackgroup': 'one', 'xaxis': 'x', 'showlegend': False})
trace12 = go.Scatter({'x': dateWithStorage,'y': nuclearWithoutStorage, 'name': 'Nuclear', 'mode':'lines', 'line' : dict(width = 0.5, color = 'rgb(255, 0, 0)'), 'stackgroup': 'one', 'xaxis': 'x', 'showlegend': False})
trace13 = go.Scatter({'x': dateWithStorage,'y': gasWithoutStorage, 'name': 'Gas','mode':'lines', 'line' : dict(width = 0.5, color = 'rgb(0, 235, 227)'), 'stackgroup': 'one', 'xaxis': 'x', 'showlegend': False})
trace14 = go.Scatter({'x': dateWithStorage,'y': bagasseWithoutStorage, 'name': 'Bagasse','mode':'lines', 'line' : dict(width = 0.5, color = 'rgb(154, 3, 255)'), 'stackgroup': 'one', 'xaxis': 'x', 'showlegend': False})
trace15 = go.Scatter({'x': dateWithStorage,'y': hydroWithoutStorage, 'name': 'Hydro','mode':'lines', 'line' : dict(width = 0.5, color = 'rgb(0, 145, 255)'), 'stackgroup': 'one', 'xaxis': 'x', 'showlegend': False})
trace16 = go.Scatter({'x': dateWithStorage,'y': windWithoutStorage, 'name': 'wind','mode':'lines', 'line' : dict(width = 0.5, color = 'rgb(5, 252, 14)'), 'stackgroup': 'one', 'xaxis': 'x', 'showlegend': False})
trace17 = go.Scatter({'x': dateWithStorage,'y': solarWithoutStorage, 'name': 'solar','mode':'lines', 'line' : dict(width = 0.5, color = 'rgb(246, 255, 0)'), 'stackgroup': 'one', 'xaxis': 'x', 'showlegend': False})
trace18 = go.Scatter({'x': dateWithStorage,'y': importWithoutStorage, 'name': 'Import', 'mode':'lines', 'line' : dict(width = 0.5, color = 'rgb(255, 161, 220)'), 'stackgroup': 'one', 'xaxis': 'x', 'showlegend': False})
# trace2 = go.Scatter({'x': dateWithStorage,'y': bessCharging, 'name': 'BESS Charging', 'mode':'lines', 'line' : dict(width = 0.5, color = 'brown'), 'stackgroup': 'one'})
# trace2 = go.Scatter({'x': dateWithStorage,'y': bessDischarging, 'name': 'BESS Discharging', 'mode':'lines', 'line' : dict(width = 0.5, color = 'orange'), 'stackgroup': 'one'})

fig.add_trace(trace1, 2, 1)
fig.add_trace(trace2, 2, 1)
fig.add_trace(trace3, 2, 1)
fig.add_trace(trace4, 2, 1)
fig.add_trace(trace5, 2, 1)
fig.add_trace(trace6, 2, 1)
fig.add_trace(trace7, 2, 1)
fig.add_trace(trace8, 2, 1)
fig.add_trace(trace9, 2, 1)
fig.add_trace(trace10, 2, 1)

fig.add_trace(trace11, 1, 1)
fig.add_trace(trace12, 1, 1)
fig.add_trace(trace13, 1, 1)
fig.add_trace(trace14, 1, 1)
fig.add_trace(trace15, 1, 1)
fig.add_trace(trace16, 1, 1)
fig.add_trace(trace17, 1, 1)
fig.add_trace(trace18, 1, 1)

fig.update_layout(title_text=""+str(year)+' '+str(case)+" Scenario",legend = dict(
    font=dict(
        family="Arial",
        size = 9
    )
))

# fig = go.Figure({'data': trace2}) #, 'layout': layout})
# fig.show()

pyo.plot(fig, filename= str(year)+' '+str(case)+' Plot with updated start up cost.html')

Answer: I know this question is old but since it is the first answer on duckduckgo when looking for the topic I think it is worth adding an answer. the behaviour of stackgaps is defined in the respective option. It is described as follows:

stackgaps – Only relevant when stackgroup is used, and only the first stackgaps found in the stackgroup will be used - including if visible is "legendonly" but not if it is false. Determines how we handle locations at which other traces in this group have data but this one does not. With infer zero we insert a zero at these locations. With "interpolate" we linearly interpolate between existing values, and extrapolate a constant beyond the existing values.

https://plotly.com/python-api-reference/generated/plotly.graph_objects.Scatter.html
If you set stackgaps="interpolate" your plot should look as expected.


Filter in ui-sref

Question: I am trying to apply a filter on a parameter in my ui-sref reference.

However, the above is not working. How to I apply the slugify filter to item.name?
Answer: Use parentheses for filter:

Comment: Best Answer!!! No Controller coding, especially when you already made a filter and just want to also implement it in the `ui-sref` attribute.
Answer: You can use a function:

And in your controller, something like that:
$scope.getSlugifiedName = function (item) {
    return $filter('slugify')(item.name);
}

Comment: Hi, isn't there another way? Currently, my links are not in any controller. I would have to create that function in the `$rootScope`. I have the same issue: I want to use *slugify* in url titles.

Filter in ui-sref


Pearson Correlations in time series between time and value

Question:
I'm wondering if it make sense, or simply your opinion about this: I have a dataset with a value, and a time variable. let's suppose that the time variable is month, like time = c(1,2,3,4,5), and the value = c(2,3,5,2,4).
In this case:
time = c(1,2,3,4,5)
value = c(2,3,5,2,4)

In your opinion (if months increase more than 12 in the next years), is it correct and does it make sense to calculate the Pearson Correlation
cor(time,value)
[1] 0.3638034

between time and value to see if there is positive, negative or not correlation (in this case positive)?
 I think that as a formula could works, but I do not know it's an error to force the month a qualitative ordinal variable, to months in number, a quantitative interval variable and use them to Correlation.

EDIT

I've thought this because:
I have a big quantity of"moving" small time series (add one incoming month, remove first month) long 6 months. I need to see,for each of these time series, if the trend is growing or decreasing without an inferential point of view (think about the small time series as is, not a sample of a stocastic process, I suppose).
I've thoght that the Correlation could help to see if there is a linear relationship between time and values, but reading all those answer, it does not seems the best way.
Comment: If your value vector itself is function of t, then simple method of moments estimator diverges as partial sums as function of t grow.
Comment: Hi, I'm missing the point, sorry: could you be more explicit? Thanks.
Comment: Think of model y(t)=a+b*t+e
Answer: You seem have several questions here, so I'll make sure to separate them and consider them separately.
"I do not know it's an error to force the month a qualitative ordinal variable, to months in number, a quantitative interval variable and use them to Correlation."
It's not an error to treat months as a "quantitative interval variable" as you say because the time difference between adjacent measured months is the same and known (it's one month). Labeling them as "1,2,3,..." doesn't change that fact.
"is it correct and does it make sense to calculate the Pearson Correlation"
Correct depends on what you're trying to do with your data (the context).
The correlation between the time vector and the time series doesn't really make sense, in terms of quantifying relationships between variables. This is because with time-series data we expect statistical dependencies that make it hard to interpret the sample correlation as an estimator of a population correlation. Another issue is that correlation is a possible indicator of causal mechanisms, which doesn't make sense in your example (not that correlation proves a causal relationship, it may suggest it depending on the context).
That doesn't mean that interpretation is impossible. The correlation coefficient indicates the strength of a linear fit between two variables, both statistically and geometrically. Ignoring the statistical distributions aspect, a large value of the correlation suggests that a line could be drawn through the scatterplot of the bivariate data.
If you have a large correlation value between time and a time series, it could indicate a linear (mean) trend in the data. Investigating the mean trend supersedes interest in the correlation coefficient here.
Comment: My context: I've several small time series (more or less like the one in the example) made as "moving" small time series (add one incoming month, remove first month). I've not got any inferential issue, but want to read each small time series as is. So I was wondering if a Correlation is proper to see the bond between time and series. However do you think that looking a the angular coefficient of a trend could be the best way to see the relationship between time and values? Thanks.
Answer: First of all, why? Correlation with time means that is a trend. For checking if there is a trend you can use this topic: How to test for presence of trend in time series?
Correlation does not have sense in non stationary data. Obviously, time is not stationary. If distribution is changing in time, there is no point to measure anything across whole period.
Comment: You're saying it could be better to calculate the angular coefficient of the trend line calculate with for example OLS? Thanks.
Comment: OLS is another technique that should be used only on stationary data. Check autocorrelation, if there is any with lag 1, there is a trend.
Comment: My main problem is that I have  "moving" small time series (add one incoming month, remove first month), and I have only to have a number to define if the trend is positive and negative. This is why I've approached with correlation.  I can test the autocorrelation, but is it useful for very small time series and my task? (I'm going to update my question).
Comment: How small is the time series? You can try Mann Kendall test. I've never used it, but it seems reasonable and should be helpful in your case. https://vsp.pnnl.gov/help/vsample/Design_Trend_Mann_Kendall.htm
Comment: They are some thousands of time series of 6 months (moving, i.e. adding one month is going to remove the first one).The tests seems fitting, but I did not know it, I need to test it a bit.
Comment: What about the Spearman's rank correlation coefficient? And also, I've read that [It may also be noted that usual Pearson correlation is fairly robust and it usually agrees well in terms
of statistical significance with results obtained using Kendall's rank correlation (pag 5)](https://cran.r-project.org/web/packages/Kendall/Kendall.pdf) . Is it saying (in general term) that it's like to use Pearson Correlation like my original question?
Comment: All correlations measurements (Person, Kendall, Spearman) are dedicated for two random variables with distributions constant in time. It's hard to consider time as a random variable. That's why I don't recommend to use correlations there especially there are a few tests dedicated to trend without those restrictions.


On the generalization of polar coordinates for $n-$dimensions?

Question: I am acquainted with polar coordinates and their reason of being, that is: Taking a vector in $2-$dimensions, we can normalize it:
$$\cfrac{1}{|(x,y)|}(x,y)=(x',y')$$
And we can clearly see that:
$$(x,y)=|(x,y)|(x',y')$$
And we can choose suitable $x',y'$ such as $x'=\cos \theta, y'=\sin \theta$ because $\cos^2\theta + \sin^2\theta=1$ and $|(x',y')|=1$. But how should we proceed for $(n>2)-$dimensions? For example, for $3-$dimensions, my guess is that it's a repetition of the previous argument, but now we must have $x'^2+y'^2+z'^2=1$.
My problem is:

What will be the suitable functions for $x',y,'z'$ in terms of angles?
What will be the suitable functions for $n-$dimensional polar coordinates?
Can we find suitable functions such for some other parameter instead of angles?

I'm supposing that such generalization is possible, but I'm actually not sure it is. From the sources I've found, there is only for $2,3$ dimensions.
Comment: In 3D, there are 2 systems that could be thought of as generalizations of polar coordinates, namely, cylindrical coordinates, and spherical coordinates. I imagine both generalize easily to $n$ dimensions.
Answer: Let us consider case by case.
Case: $n=2$.
We have
\begin{align}
x=&\ r\cos\theta, \\
y=&\ r\sin\theta
\end{align}
Case: $n=3$.
We have
\begin{align}
x=&\ r\cos\theta \sin\phi,\\
y=&\ r\sin\theta \sin\phi, \\
z=&\ r\cos\phi.
\end{align}
Case: $n=4$.
We have
\begin{align}
x_1=&\ r\cos\theta \sin\phi\ \sin \tau,\\
x_2=&\ r\sin\theta \sin\phi\ \sin\tau,\\
x_3=&\ r\cos\phi \sin\tau, \\
x_4=&\ r\cos\tau.
\end{align}
Case: $n=5$.
We have
\begin{align}
x_1=&\ r\cos\theta \sin\phi\ \sin \tau \sin \psi,\\
x_2=&\ r\sin\theta \sin\phi\ \sin \tau \sin \psi,\\
x_3=&\ r\cos\phi \sin\tau  \sin\psi, \\
x_4=&\ r\cos\tau \sin\psi.\\
x_5=&\ r\cos\psi
\end{align}
... I hope you see the pattern.
Edit: Just to be clear. For each of the above cases, I have provided a parametrization of the $n$-spheres which respect the underlying euclidean metric.
Comment: @JackyChong You make it sound like there's is a unique (or at least prevalent) choice of angles in each dimension $n$, which isn't necessarily the case. You may want to elaborate that point some more.
Comment: I suppose $\theta$ is the angle between $x,y$. What is $\phi$? The angle between $y,z$ or $x,z$?
Comment: Change that angle and see how the point moves.
Comment: $\phi$ is the angle between the $z$-axis and the $xy$-plane.
Comment: @dxiv I don't quite understand your question.
Comment: See for example the notes at [Spherical Coordinates](http://mathworld.wolfram.com/SphericalCoordinates.html) about ambiguities between the math and physics notations for $\theta$, $\phi$ azimuthal/polar angles.
Comment: @OppaHilbertStyle I don't know if I have answered your question.
Comment: @JackyChong It seems perfectly fine. Now I just need to put my had to work on it for a bit.


Exchange 2013 clients receive error 500 or unable to send mails

Question: We have windows 2012R2 with Exchange 2013, we had public ssl certificate that was used both for external and internal users. We decided to not renew certificate and sign a new one with our domain controller CA.I followed this article to configure split-dns (https://practical365.com/exchange-server/avoiding-exchange-2013-server-names-ssl-certificates/)
So I've configured all the same way as in article, requested and signed a new certificate for web-server from our domain controller CA, applied new certificate in IIS to "default web page", all worked ok, but on the next day different errors appeared: from error 500 when trying to connect owa to unable to login in ecp with admin account ( it just redirected you to broken owa), and now some users cant send mails via owa or receive it via outlook. I'm just don't know where to look.
To be clear we have people that have access to exchange servers but their computers not in domain so they don't trust our new certificate.
Comment: from time to time I can't login to ecp using new url https://mail.example.com/ecp it redirects me to the owa, but if Im trying access ecp via ip - it works great.
Answer: Have you run iisreset as administrator in Command Prompt on Exchange servers to take effect after you binding a new certificate in IIS?
If it persists, open IIS and check on the Application Pools to view whether MSExchangeOWAAppPool and MSExchangeECPAppPool is running on .NET Framework v2.0, and recycle virtual directory for test. Here is the similar thread about 500 error, please refer to: Unable to access OWA or ECP. - "Something went wrong" or "500 unexpected error"
In addition, run below command to remove and recreate owa/ecp virtual directory.
To remove: Remove-OwaVirtualDirectory -Identity "exchange server name\owa (default Web site)"
To recreate: New-OwaVirtualDirectory –WebSiteName
Moreover, check into IIS log file to find any error related to MSExchange on the Exchange 2013 Client Access Server, locate the folder "c:\inetpub\logs\logfiles\W3SVC1".
Comment: I'll try recreation today, but interesting thing is that, if you use ip addresses and not domain-names ALL works great, confirmed with different people
Comment: Have urls set in the virtual directory of owa and ecp pointing to the A record of the exchange server correctly?
Run the following command to check urls: Get-OwaVirtualDirectory | fl ExternalUrl,InternalUrl
, Get-EcpVirtualDirectory | fl ExternalUrl,InternalUrl
You can get A record value in DNS manger.
Comment: yes it's correct, Owa and ECP virtual directories pointing to the mail.example.com/ecp and mail.example.com/owa, and on my dns server in example.com zone I have two records for name "mail" that pointing to ips of exchange servers
Comment: By the way, all application pools in iis use netframework v4 and about logs, I cant read anything from it, these logs files completely unreadable D:
Comment: Oh my god, do I need to change FQDNS in connectors settings as well ? For now there is old FQDNS like maiserver.example.com and not a new one mail.example.com
Comment: So, basically after recreation of certificates and owa/ecp directories the only problem remains is non-domain users cant log in or send mails after log in (no internet connection error), BUT it works, If I add our CA certificate to the non-domain computer, to be honest I don't see connection here, I mean it should be just warning that it's not secure and nothing more.
Comment: You cannot send emails, have any NDR?  What errors show?
Has your new certificate been successfully applied? Open browser and check if the certificate is the new one.
Answer: The only reason this doesn't work is because non-domain users don't have CA certificate and that's why they can't start a TLS session


How to monitor multiple music instruments via headphones?

Question: I'm relatively new to the technological side of music. My guitar amp has a speaker cable output, as does my keyboard. I would like to be able to plug both of those, and also a microphone into a device which I can plug headphones into and listen while I play and sing. I'm trying to keep quiet because of apartment neighbors.
What kind of device would allow me to do this? I did some googling and searching here and I saw a lot of recommendations for JamHub, but it seems that company has gone under. A lot of those recommendations were for devices with multiple outputs whereas I only need one headphone output for myself to listen to. Any help would be appreciated, I have no idea where to start.
I looked on Amazon, is something like this (Alto Professional ZMX52) what I'm looking for?
Answer: As you say, you don't really need something like the jamhub, which provides multiple headphone outs. You're correct that all you really need is a small analogue mixer - like the one you linked to, but there are many, many models available.
If your guitar amp really only has a speaker out, you won't want to plug that directly into the mixer, as it will be too powerful to be plugged into the 'line level' inputs on the mixer. If your amp has a line out or even a headphone out, that would be more appropriate to plug into the mixer.
If you're not wanting to get distortion or other effects on your guitar, and you just want to be able to hear it, a mixer with a high impedance or "hi-Z" input would let you plug the guitar straight in. (Hi-Z channels are often the same ones as the mic channels - the particular mixer you linked to only seems to have one mic channel, so it might not be the best choice for plugging your guitar straight in to).
One more suggestion - it might sound a little 'claustrophobic' to listen for long periods to your 'dry' voice and guitar through headphones. A mixer with some built in effects (for example, the Yamaha MG06X - manual here) might make it more fun to use for extended periods.
Comment: Thanks for the response! Yeah I completely overlooked the fact that there's a headphone out on the amp, sorry about that! I will use that for the mixer. For the headphone out, would I use a 3.5mm to trs splitter like this? https://www.amazon.com/UGREEN-Splitter-Computer-Multimedia-Speakers/dp/B00ZKM3S4S/
Comment: @Jax if your headphone socket is 3.5mm, yes, it does look like the right thing - you'd then be able to plug it in to (for example) 2/3 or 4/5 on the Alto mixer. (just to be accurate that's a 3.5mm *trs **to*** 6.35mm **ts**).
Answer: I have the Mackie version of that mixer but it has 3.5mm input so you can wire in your phone , computer or whatnot. It also has USB, which is handy. They should be less than $200. It has high x channels 1 and 2. Nice little unit and it's always nice to have a mixer, especially a small one.


Are fielders (non-catchers) allowed to start from foul territory, and where should the catcher be?

Question: Are fielders (not being the catcher) allowed to start in foul territory? This is actually something that I did. As a left outfielder I played/started on foul territory, because of a very strong and low sun in my eyes elsewhere. It could also be useful for right fielders with very fast pitchers. Or place a fielder at the back-stop for a wild pitch.
Also, is it allowed to have the catcher at the back-stop (fence), or right next to the home dug-out (say, for catching foul balls), or somewhere right of the right foul-line but 60 yards away from home plate, or in the infield six feet away from the plate?
Which rule applies, if any?
Comment: So, these are actually two questions, of which both you seem to know the answer already. Please read more [about] asking questions in the [help]. Welcome to Sports beta !!
Comment: @JacobJanTuinstra Thanks for the welcome! However, I do not know the answers. I only assume that, if they are covered, they are covered by the same rule. I have my intuition, but that's about it.
Answer: American Softball Association:
Ref: http://files.leagueathletics.com/Text/Documents/13338/35721.pdf
The American Softball Association does not actively publish their Official Rules - Umpire Edition, but I was able to find a 2005 legacy copy at the ref link above.
On Page 84 (PDF page 86):

Section 5. DEFENSIVE POSITIONING.

A. The pitcher shall not deliver a pitch unless all defensive players are positioned in fair territory, except the catcher who must be in the catcher's
    box.
B. A fielder shall not take a position in the batter's line of vision or, with
    deliberate unsportsmanlike intent, acts in a manner to distract the batter.
    A pitch does not have to be released. The offending player shall also be
    ejected from the game.

The rules on Defensive Positioning are found in each type of pitching rule sections (Fast Pitch, Modified Pitch, Slow Pitch, 16-inch Slow Pitch)
Comment: Makes sense.  The rule presumably exists to prevent players from pretending to be off the field but actually being a live player (to confuse the batter/runners).
Answer: Major League Baseball:
Ref: http://mlb.mlb.com/mlb/downloads/y2014/official_baseball_rules.pdf

Question 1: On page 32 (PDF page 38):

4.03 When the ball is put in play at the start of, or during a game, all fielders other than the catcher shall be on fair territory.

(a) The catcher shall station himself directly back of the plate. He may
    leave his posi- tion at any time to catch a pitch or make a play
    except that when the batter is being given an intentional base on
    balls, the catcher must stand with both feet within the lines of the
    catcher's box until the ball leaves the pitcher's hand. PENALTY: Balk.
(b) The pitcher, while in the act of delivering the ball to the
    batter, shall take his legal position;
(c) Except the pitcher and the
    catcher, any fielder may station himself anywhere in fair territory.

Question 2: On page 3 (PDF page 9) the catcher's box is drawn out.
On page 13 (PDF page 19) the definition is defined as

The CATCHER'S BOX is that area within which the catcher shall stand
  until the pitcher delivers the ball.
Comment: This is a good answer for MLB, but the question was tagged [tag:softball], which would have a separate rulebook.
Comment: @Joe Good Call... I'll see what I can find.  However, the user is no longer a valid account so it is highly likely to get accepted or additional views.


How to create an Observable inside another Observable to receive part of the data?

Question: By subscribing to getOrderBook I am getting data via Netty and Websocket. The first time a full OrderBook arrives, and then incremental updates follow. As a result, I get the complete OrderBook with all the changes.
Please tell me how can I create another Observable so that I can receive separately the data that comes in the update (incrementalUpdateData) through a subscription?
private final Map<Instrument, OrderBook> orderBookMap = new HashMap<>();

  public Observable<OrderBook> getOrderBook(Instrument instrument) {
    return service.subscribeChannel(instrument).flatMap(jsonNode -> {
      if (jsonNode.get("action").asText().equalsIgnoreCase("snapshot")) { //first update - full snapshot
        OrderBook orderBook = mapper.treeToValue(jsonNode.get("data"),
                mapper.getTypeFactory().constructCollectionType(List.class, Orderbook.class));
        orderBookMap.put(instrument, orderBook);
        return Observable.just(orderBook);
      } else { //second update and later - incremental update
        OrderBook orderBook = orderBookMap.getOrDefault(instrument, null);
        PublicOrder incrementalUpdateData = mapper.treeToValue(jsonNode.get("data").get(0).get("asks"),
                mapper.getTypeFactory().constructCollectionType(List.class, PublicOrder.class));
        orderBook.update(incrementalUpdateData);
        return Observable.just(orderBook);
      }
    });
  }

What do I expect.
getOrderBook.subscribe(some instrument) - get full orderBook
getOrderBookUpdate.subscribe(some instrument) - get only incremental data
Comment: Welcome to Stack Overflow.
Please take the [tour] to learn how Stack Overflow works and read [ask] on how to improve the quality of your question.
Then [edit] your question to include your source code as a working [mcve], which can be compiled and tested by others.
Answer: Done via publishsubject
Result code looks like:
  private final Map<Instrument, PublishSubject<OrderBookUpdate>> orderBookUpdatesSubscriptions;

  private final Map<Instrument, OrderBook> orderBookMap = new HashMap<>();

  public Observable<OrderBook> getOrderBook(Instrument instrument) {
    return service.subscribeChannel(instrument).flatMap(jsonNode -> {
      if (jsonNode.get("action").asText().equalsIgnoreCase("snapshot")) { //first update - full snapshot
        OrderBook orderBook = mapper.treeToValue(jsonNode.get("data"),
                mapper.getTypeFactory().constructCollectionType(List.class, Orderbook.class));
        orderBookMap.put(instrument, orderBook);
        return Observable.just(orderBook);
      } else { //second update and later - incremental update
        OrderBook orderBook = orderBookMap.getOrDefault(instrument, null);
        PublicOrder incrementalUpdateData = mapper.treeToValue(jsonNode.get("data").get(0).get("asks"),
                mapper.getTypeFactory().constructCollectionType(List.class, PublicOrder.class));
        orderBookUpdatesSubscriptions.computeIfPresent(instrument, (a,b) -> b.onNext(new OrderBookUpdate(incrementalUpdateData)));
        orderBook.update(incrementalUpdateData);
        return Observable.just(orderBook);
      }
    });   }

  public Observable<OrderBookUpdate> getOrderBookUpdates(Instrument instrument) {
    return orderBookUpdatesSubscriptions.computeIfAbsent(instrument, v -> PublishSubject.create());
  }


Get query between two datetimes

Question: This is the code I have:
$qry = "SELECT *
          FROM parties
         WHERE schoolid = $schoolid AND
         WHERE timestart BETWEEN '$dateStart 00:00:00' AND '$dateEnd 23:59:59'
      ORDER BY timestart, attending";

This is what I get when I echo the query:
  SELECT *
    FROM parties
   WHERE schoolid = 100 AND
   WHERE timestart BETWEEN '2013-08-13 00:00:00' AND '2013-09-12 23:59:59'
ORDER BY timestart, attending

It doesn't work. And when I manually run the code in PHPMyAdmin it just tells me I have an error in my syntax. What is wrong?
Answer:   SELECT *
    FROM parties
   WHERE schoolid = 100 AND
         timestart BETWEEN '2013-08-13 00:00:00' AND '2013-09-12 23:59:59'
ORDER BY timestart, attending

Remove the AND WHERE, it's syntactically incorrect - the correct one is a lonely AND on that spot.
Answer: you are typing WHERE twice and it has to be only once.
should be like this:
  SELECT *
    FROM parties
   WHERE schoolid = 100 AND
         timestart BETWEEN '2013-08-13 00:00:00' AND '2013-09-12 23:59:59'
ORDER BY timestart,attending

Answer: There should be only one WHERE in query unless subquery is used.

Get query between two datetimes


Programming and platform dependance for c++ questions

Question: Not sure if this is the right place to ask this:
How do programs written in c++ run on other computers if you don't write them specifically to do that? I saw something about not just sending the .exe, but also sending other things with it?
Is there a high level programming language that is as fast or nearly as fast (in run speed) as c++ while also being platform independent?
See above.
Comment: I think the question could do with a bit more clarity but C++ itself is platform independent, the C++ runtime will make the translation from (the C++ abstract machine) to the underlying OS. You will still need to compile your code for a specific OS.
Comment: You can run compiled programs on other systems by using emulators, such as Wine on Linux. This won't be as fast as using the program on the platform it was compiled for.
Comment: https://stackoverflow.com/questions/65618221/what-does-platform-independent-languages-really-mean
Comment: https://www.quora.com/Are-compiled-programs-platform-independent
Comment: Are you concerned about having to send .dlls with the .exe (you can avoid that), or about the .exe not working on different OSes?
Answer: You compile your code for all the platforms you target and deploy a number of executables. Hence, Write once, compile anywhere.
Answer: C++ allows you to write portable source code. So assuming you write portable code to start with, you can compile it for some target platform, and run the resulting binary on that target.
Now, depending on what your program uses, you may have to package other "stuff" with the executable. What you mention ("I saw something about not just sending the .exe, but also sending other things with it?") would arise if your program used some dynamic link libraries that were not part of the OS (presumably Windows, based on the mention of <code>.exe</code>). But, it's kind of up to you to decide whether to use a library that's packaged as a DLL or not. If you don't want to package DLLs with your executable, don't use them (but sometimes, you may decide it's less trouble to use and package the DLL than do without).
As far as another language goes...doesn't really make a lot of difference as a rule. If you write code that depends on something else, you have to satisfy that dependency on the target computer. Some languages require you to add some DLLs to support the language itself, but most C++ compilers don't. On other OSes, those dependencies won't be called "DLLs", but most reasonably modern OSes provide something similar.


Need help with his advance dice probability scenario(concept)

Question: So the question goes-

Mr.Bhallu rolls $3$ standard $6$ sided fair dice together.
He wins if the total sum of the outcomes after rerolling once is $7$.
Mr.Bhallu can choose to reroll any number of dice
$\left(0-3\right)$.
He always plays to maximize his chances of winning, calculate the probabilty of him rerolling $2$ dices.

Can someone please explain the concept(s) at use here along with probability for choosing to reroll each ( no dice ), ( $1$ dice) and ( $3$ dice ) as well $?$.
Comment: You have to make a list of the possibilities, and calculate the probability that he wins.  He can re-roll all three dice, or he can have a total of $1$ through $6$ and re-roll two dice, or a total of $2$ through $6$ and roll  $1$ die.  Once you know those probabilities, you can figure out what's best to do for any of the original rolls.
Comment: Devansh: You have some answers that interpret the question in a couple of different ways.  Please look at them and clarify which interpretation you have in mind.
Answer: I understand the rules of the play as follows:
a) you roll three dice a first time: if you get a sum of $7$ you win, if you get more you loose, if you get less you can proceed with step b) ;
b) you are allowed to re-roll $1$ or $2$ or $3$ dice, deciding in advance how many, to try and complement to $7$ the sum previously obtained;
c) the decision in b) is taken as to optimize the probability of getting the needed complement.
Now, the probability of getting a sum $s$ when throwing $m$ dice is given by
$$
\eqalign{
  & p(s,m) = {{N_b (s - m,5,m)} \over {6^{\,m} }}\quad \left| {\;0 \le {\rm integers  }m \le s} \right.\quad  =   \cr
  &  = {1 \over {6^{\,m} }}\sum\limits_{\left( {0\, \le } \right)\,\,k\,\,\left( { \le \,{{s - m} \over 6}\, \le \,m} \right)}
 {\left( { - 1} \right)^k \left( \matrix{  m \hfill \cr   k \hfill \cr}  \right)
 \left( \matrix{  s - 1 - k6 \cr   s - m - k6 \cr}  \right)}  \cr}
$$
as explained in this post
When you tabulate this for the case of interest you get

and it is clear that if you do not get $7$ at the first instance, then you have better just to reroll only one dice.
In fact you have :

$\approx 0.07$ to center $7$ with the first three dice;
$\approx 0.05$ to get $6$ with the first three dice, then to get the missing $1$ the best and only way is to roll one die ;
$\approx 0.03$ to get $5$ with the first three dice, then to get the missing $2$ the best way is to roll one die ;
....
Comment: Am I misunderstanding the question?  If one rolls (say) $17$ with three dice, it surely cannot be optimal to re-roll only one die.  The lowest one can get with a single re-roll would be $12$.
Comment: @BrianTung: I added on top of the answer my understanding of the rules.
Answer: It's possible I don't understand the problem correctly, because I get a different answer from the one provided by G Cab.  Here's how I understand it: The player rolls three ordinary fair six-sided dice.  If the total is $7$, they stop (or equivalently, they re-roll zero dice).  This happens with probability $5/72$.
Otherwise, they are allowed to re-roll any number of dice: one, two, or three.  They are assumed to select optimally.  We want to find the probability that their choice is to re-roll two dice.

With that understanding, let us consider strategy.  The probability of winning when re-rolling three dice is the probability of rolling a $7$ on those three dice: again, $5/72$.  That will always be an option.
Re-rolling a single die is an option when the lowest two dice total no more than $6$.  Under those circumstances, the probability of winning is $1/6$, because exactly one result on the re-rolled die will work.  Note that $1/6 > 5/72$, so we always prefer to re-roll one die rather than three, when one is an option.
What about re-rolling two dice?  This is an option whenever the lowest die is no more than $5$.  However, if the lowest die is $5$, the probability of winning when re-rolling the two other dice is the probability of getting a $2$ on two dice: $1/36$.  This is lower than $5/72$.  Likewise, if the lowest die is $4$, the probability of winning when re-rolling the two other dice is the probability of getting a $3$ on two dice: $1/18$.  This again is lower than $5/72$.  Only when the lowest die is no more than a $3$ is it better to re-roll two dice than three.
How does re-rolling two dice compare to re-rolling one?  The easiest win when re-rolling two dice is when the lowest die is a $1$.  Then the probability of winning is that of getting a $6$ on two dice: $5/36$.  This is better than with three dice ($5/72$), but worse than with one die ($1/6$).  Therefore, we always prefer to re-roll one die when that is an option.
So here's our strategy:

If the lowest two dice sum up to no more than $6$, then re-roll the other die.
Else, if the lowest die is no more than $3$, then re-roll the other two dice.
Else, re-roll all three dice.

To find out the desired probability, therefore, enumerate those cases where the lowest two dice sum up to more than $6$, but where the lowest die is no more than $3$.  There are not that many cases.  Be sure to account carefully for all of the permutations.  For example, there are three permutations of a single $1$ and a pair of $6$s, but there are six permutations of a $2$, a $5$ and a $6$.  Count up all of the cases and divide by $6^3 = 216$, and there's your probability.
Comment: the difference with my understanding, is that by re-rolling a certain die you mean to delete the contribution of that die (which one ?) in the previous sum, while I understand that it is retained.
Comment: @GCab: Ahh, I see.  Well maybe we'll have to ask OP to clarify.
Comment: yes, indeed, that should be clarified
Answer: I only reroll no dice if the sum is $7$ already.  The chance of getting $7$ on a roll of all three dice is $\frac 5{72}$ so I need something better to reroll $1$ or $2$ dice.  If I have two dice that sum to less than $7$, I can reroll the other and get a probability of $\frac 16$.  This is better than $\frac 5{72}$, so if I have two that sum to less than $7$ I don't reroll all three.
If I have a $1$ I can reroll the other two and have a chance of $\frac 5{36}$ to win.  This is the best case and is still less than $\frac 16$, so if I can reroll just one it dominates over rerolling two.  If I have a $2$ I can reroll the other two and have a chance of $\frac 4{36}$ and if I have a $3$ I can reroll the other two and have a chance of $\frac 3{36}$.  Both of these beat rerolling all three.  All of these are less than $\frac 16$, so we have a nice algorithm:
If the dice sum to $7$, stop here.
ElseIf the two lowest dice sum to less than $7$, reroll the other one.
ElseIf the lowest die is $3$ or less, keep it and reroll the other two.
Else, reroll all three.
Compute the probability of each line, and you want the chance of the second.
Comment: We came to the same conclusion. :-)


Is it possible to use video games to help improve one's singing?

Question: I've decided that I want to improve my singing. In order to give me incentive to practice (and regular feedback), I thought getting a video game might be of help. I know that it's no substitute for actual voice lessons, but I'm not shooting for Carnegie Hall, and I've accompanied various choirs for over a decade, so I know a fair bit about technique. My biggest problem is pitch, and that's what I'm primarily looking to improve.
Is it possible (or, perhaps, reasonable) to use video games in this way? If so, is there any game in particular that's good for real-world vocal improvement (i.e., that rewards traits that are desirable in actual singing), or are they all essentially the same?
Comment: Are you looking for a game that will help you learn to sing, something like rock band or a karaoke machine? Or just a game with good music. Please be more specific.
Comment: @ReinaAbolofia I really don't care about the music selection - I'm just trying to improve my voice. I wouldn't think a karaoke machine would help much with that - there aren't karaoke machines that give you feedback on how you did, are there? I'm also thinking this is going to be a by-myself thing, not a social thing.
Answer: The Singstar series on the Playstation 2 and 3 monitors your pitch, gives you visual feedback of that, and a score. Similar titles exist for other platforms.
At the easiest difficulty level, you don't need to be all that accurate, but at the higher difficulty levels it does demand very accurate pitching and timing.
Whether this would help you depends on your particular goals, motivations and learning style.
Bear in mind that the game has no concept of tone. You could sound awful and still get high scores as long as you're in tune and on time.
Comment: @VolcanoLotus Any two singers can sound good despite having wildly different tone, and "good" is subjective, so you won't be able to find software that does anything like that.  Some sort of speech recognition might be possible but I'd expect it to be even harder to do for singing than regular speech so you'd be unlikely to get usable results with that either.
Comment: There is PC software (Google "voice training software") that shows a live frequency analysis of your voice through the microphone. You can look at what your idea of a "good" voice sounds like, and watch visual feedback of your own. It depends -- rich -> lots of harmonics; pure -> few harmonics.
Comment: Are there any games that do have concept of tone, or even something like inflection or enunciation? That was part of why I asked; I watched a friend ace Rock Band vocals once by...well, it's hard to describe what he was doing; calling it "humming" would be a bit of an insult to humming. I was wondering if any of the singing-specific ones did it better.
Comment: @MatthewRead Fair point, thanks. I just wasn't sure if any of them were empirically better than others. It sounds like not, so I guess maybe the answer in my particular case is just to find whichever one has the song list I like most.
Answer: Video games are a great way to practice singing, but I would not recommend them to learn pitches. Singing or pitch-matching in video games doesn't really teach you the pitches because the notes are not long enough to sustain for longer than a few seconds.
To improve pitch and overall quality of your singing, try using software specifically designed for that purpose (e.x. SingingCoach ). Slim has the right idea- in most games you can hum the audio and as long as it is in tune, you'll score points.
I highly recommend using audiobooks on singing while driving. It is a great time to exercise your voice and learn new ways to improve it. You may get some weird looks from other cars though.
Comment: If you want to get some singing software, do some research on the different applications available. I only use SingingCoach as an example; I am not recommending it over others.
Comment: What's different about SingingCoach compared to the games? Is it just less forgiving, or does it feature something like the frequency analysis @slim mentions in the comments above?
Comment: SingingCoach is designed to help you improve your singing ability (in the same sense that Rosetta Stone teaches you new languages), while video games are more designed for recreational use (i.e. Rockband, Guitar Hero- those games that allow a singing part- which gives you practice, but not instruction.)