Consulta no SQL SERVER 2017

Question: Preciso realizar uma consulta no SQL Server 2017, onde preciso trazer as seguintes informações: Codigo do chamado, Data Abertura, Interação, Analista, UltimaInteração(seria a data da última interação) e Empresa; preciso dessas informações somente dos chamados que estão abertos, utilizei o filtro(where) no campo sta_codigo = '1' que significa que o chamado esta aberto, pois o numero 1 representa o código de chamados em aberto. Porém, quando eu tento realizar o select, ele traz apenas todos os chamados abertos, com todas as interações, porém eu só quero a última interação que o chamado que está em aberto teve.
Segue o select que eu fiz:
select c.cha_codigo [Codigo do chamado], c.cha_dtabertura as [Data
Abertura],
Convert(varchar(5000),i.int_descricao) as [Interação], u.usu_nome
[Analista],
r.int_dtinteracao as UltimaInteração,
e.emp_fantasia as [Empresa]
from (select distinct max(int_dtinteracao) as int_dtinteracao from
interacoes) as r, interacoes as i
inner join chamados as c on c.cha_codigo = i.cha_codigo
inner join usuario as u on  u.usu_cod  = i.log_codigo
inner join empresa as e on e.emp_codigo = c.emp_codigo
where c.sta_codigo = '1'
group by i.cha_codigo, c.cha_codigo, c.cha_dtabertura,
Convert(varchar(5000), i.int_descricao), u.usu_nome, e.emp_fantasia,
r.int_dtinteracao
Order By c.cha_codigo desc

Comment: Além do que o @rbz comentou, quem lê na sua pergunta *"Utilizando o filtro de chamados em aberto"* não faz o menor ideia do que é isso.. .você comentou algo que você conhece, mas para nós que estamos lendo não faz sentido, precisaria explicar melhor e claro colocar a estrutura da tabela. De qualquer forma, isso você resolve no `where`, e para trazer apenas o um valor, no caso "o último", você pode usar `max`
Comment: Você irá usar o `MAX`. Veja mais aqui [Operadores Max, Min, Count, Update e Delete com Subqueries - Union e Subquery](https://www.devmedia.com.br/operadores-max-min-count-update-e-delete-com-subqueries-union-e-subquery-sql-server-2008-parte-3/19168)
Comment: Ola Ricardo, desculpa por não explicar direito, já estou arrumando.
Comment: Ola rbz, eu já realizei o MAX no Where, porem ele traz apenas 1 registro, eu preciso que o select traga todos os chamados em abertos, representado pelo c.sta_codigo = '1' onde 1 é o codigo dos chamados que estão abertos, e desses chamados em aberto, trazer apenas a ultima interação, pois os chamados podem ter 'n' interações, porem eu só quero a ultima.
Answer: Você só precisa utilizar a cláusula EXISTS em conjunto com NOT no WHERE para determinar que quer apenas a interação que não possui  ou com data maior:
SELECT c.cha_codigo [Codigo do chamado]
      -- DEMAIS CAMPOS CAMPOS
  FROM chamados c
      INNER JOIN interacoes i ON i.cha_codigo ON i.cha_codigo
      -- DEMAIS JOINS
WHERE c.sta_codigo = '1'
  AND NOT EXISTS(SELECT 1
                    FROM interacoes i2
                  WHERE i2.cha_codigo = c.cha_codigo
                    AND i2.int_dtinteracao > i.int_dtinteracao)

EXISTS
Quando uma subconsulta é apresentada com a palavra-chave EXISTS, a subconsulta funciona como um teste de existência. A cláusula WHERE da consulta externa testa se as linhas retornadas pela subconsulta existem. A subconsulta não produz de fato nenhum dado; ela retorna um valor TRUE ou FALSE.
Comment: Funcionou Sorack, muito obrigado. !
Comment: @JoãoPedroFernandes Não esqueça de marcar a resposta como aceita. Pra fazer isso é só clicar no ✓ do lado esquerdo da mesma (abaixo do indicador de up e down votes).
Answer: O código funcionou com a orientação do Sorack.
O código ficou assim:
select c.cha_codigo [Codigo do chamado], c.cha_dtabertura as [Data Abertura],
Convert(varchar(5000),i.int_descricao) as [Interação], u.usu_nome [Analista],
i.int_dtinteracao as UltimaInteração,
e.emp_fantasia as [Empresa]
from interacoes as i
inner join chamados as c on c.cha_codigo = i.cha_codigo
inner join usuario as u on  u.usu_cod  = i.log_codigo
inner join empresa as e on e.emp_codigo = c.emp_codigo
where c.sta_codigo = '1' AND NOT EXISTS
(Select 1 from interacoes i2 where i2.cha_codigo = c.cha_codigo and i2.int_dtinteracao > i.int_dtinteracao)
group by i.cha_codigo, c.cha_codigo, c.cha_dtabertura,  Convert(varchar(5000), i.int_descricao), u.usu_nome, e.emp_fantasia,
i.int_dtinteracao
Order By c.cha_codigo desc

Consulta no SQL SERVER 2017


audio playing from within python crashes due to msvcr90.dll exception

Question: I wrote a program that uses pyaudio to record and play audio signal simultaneously.
for some unknown reason sometimes when playing signals the program crashes with this error:
Unhandled exception at 0x72A6AE7A (msvcr90.dll) in python.exe: 0xC0000005: Access violation reading location 0x02F4DB94.

the program uses the libraries pygame, pyaudio, numpy
is there a way to understand where exactly is the problem ?
Thank you,
Netanel
Answer: This is more a workaroud than a proper answer, but:
The problem ceased to exist when the signal was played by using the "blocking" mechanism of pyaudio, ie:
opening a stream something like:
stream = self.player.open(format = pyaudio.paFloat32, channels = 2, rate = FS, output = True, frames_per_buffer = CHUNK)

and then playing with something like:
while True:
    a = self.chunk_queue.get_nowait()
    self.stream.write(a)

the use of the non blocking mode play (by configuring a callback function for the stream) seems to have be the source for the crashes.


Why is an indexing function required to be surjective? (Munkres "Topology 2nd Edition")

Question: I am reading "Topology 2nd Edition" by James R. Munkres.
The following definition is in this book. (on p.36 section 5)

Definition. Let $\mathcal{A}$ be a nonempty collection of sets. An indexing function for $\mathcal{A}$ is a surjective function $f$ from some set $J$, called the index set, to $\mathcal{A}$. The collection $\mathcal{A}$, together with the indexing function $f$, is called an indexed family of sets. Given $\alpha\in J$, we shall denote the set $f(\alpha)$ by the symbol $A_\alpha$. And we shall denote the indexed family itself by the symbol $$\{A_\alpha\}_{\alpha\in J},$$ which is read "the family of $A_\alpha$, as $\alpha$ ranges over $J$." Sometimes we write merely $\{A_\alpha\}$, if it is clear what the index set is.

Why is an indexing function required to be surjective?
I think we have no trouble without the requirement to be surjective.
Comment: If you want to list your entire collection have to take $f$ surjective.
Comment: @KaviRamaMurthy Let $f$ be not surjective. If we say $f$ is an indexing function for $\mathcal{A}$, I feel it is strange.
Comment: If the indexing is injective, it's often called a "faithful" indexing (every set in a set of sets then occurs once and only once in the indexing). This can be handy in some proofs. Set theory does this alot when we enumerate every subset in some well-ordered sequence using cardinals in order to do constructions of strange objects by transfinite recursion (like Bernstein sets). Topologists are also quite fond of it sometimes...
Comment: @KaviRamaMurthy I think we can require $f$ is surjective only when we want to list our entire collection.
Comment: @KaviRamaMurthy Thank you very much for your comment.
Comment: @HennoBrandsma Thank you very much for your comment.
Answer: Surjectivity is needed in order that every element of the set $\mathcal A$ is associated to a label, which is something that we want.
Comment: I'm glad I could help.
Comment: Jose Carlos Santos, thank you very much for your answer.
Answer: In my opinion it is not really relevant whether one requires $f$ to be surjective or not. As José Carlos Santos has pointed out in his answer, if $f$ is not surjective, then some $A \in \mathcal A$ remain unindexed which we probably do not want.
What does Mukres do with $f$? He writes $A_\alpha$ for $f(\alpha)$ and defines

the union $\bigcup_{\alpha \in J} A_\alpha$

the intersection $\bigcap_{\alpha \in J} A_\alpha$

the Cartesian product $\prod_{\alpha \in J} A_\alpha$

This can be done for any function $f : J \to \mathcal A$, i.e. for any indexed collection of sets $(A_\alpha)_{\alpha \in J}$ in  $\mathcal A$.
But why do we need index functions at all? Why doesn't it suffice to work with collections of sets $\mathcal A$? In other words, why don't we simply index $\mathcal A$ by itself (i.e. take $J = \mathcal A$ and $f = id$)? Yes, we can do that, and in this case we get for example

the union $\bigcup_{A \in \mathcal A} A = \bigcup \mathcal A$

the intersection $\bigcap_{A \in \mathcal A} A = \bigcap \mathcal A$

For an arbitray function $f : J \to \mathcal A$ we get

$\bigcup_{\alpha \in J} A_\alpha = \bigcup_{A \in f(J)} A = \bigcup \mathcal f(J)$

$\bigcap_{\alpha \in J} A_\alpha = \bigcap_{A \in f(J)} A = \bigcap \mathcal f(J)$

and this shows that the surjectivity of $f$ is a useful property.
Note that we can always replace $\mathcal A$ by the subset $\mathcal A' = f(J) \subset \mathcal A$ and thereby get a surjective index function $f' : J \stackrel{f}{\to} \mathcal A'$ which is essentially the same as $f$.
The main point is that in an indexed collection sets may occur repeatedly (which is impossible in $\mathcal A$ itself). For example, if $\mathcal A =\{A\}$ has only one member, we can nevertheless form arbitrary indexed collections $(A_\alpha)_{\alpha \in J}$ with $A_\alpha = A$ and consider the Cartesian product $\prod_{\alpha \in J} A_\alpha$. This does not agree with $\prod_{A \in \mathcal A} A$ (which is just $A$).
Let us finally observe that in practical applications it may even be even inconvenient to require index functions to be surjective. For example, in a topological space $X$ one often assigns to each point $x \in X$ an open neigborhood $U_x$ of $x$ in $X$. This may be regarded as a function $f : X \to \mathfrak T_X, f(x) = U_x$, where $\mathfrak T_X$ is the topology of $X$. In general such functions will not be surjective and we do not explictly know what $f(X)$ looks like. Nevertheless I tend to accept $f$ as index function.
Comment: Paul Frost, Thank you very much for your answer.


Como chamar uma ACTION de uma CONTROLLER específica através de um Button?

Question: Utilizando o o seguinte código:
    $this->Html->link(
          'Meus Dados', array(
                   'controller' => 'Groups',
                   'action' => 'index'
           )
     );

O link HTML é criado normalmente, porém se eu quiser colocar um BUTTON no lugar do LINK, para fazer com que ao clicar no mesmo ele seja redirecionado para uma ACTION específica de uma CONTROLLER, não funciona.
Estou fazendo assim:
    echo $this->Form->button(
        'Meus Dados', array(
             'label' => '',
             'style' => 'width: 100%, color: lightslategray',
             'class' => 'topnav input-append fa fa-twitter fa-fw',
             'url' => array(
                      'controller' => 'Groups',
                      'action' => 'index')
         )
    );

Mas não acontece nada ao clicar no botão, o que estou fazendo de errado?
Answer: A URL da página tem que ser no FORM e não no BUTTON
echo $this->Form->create($row, [
    'url' => [
        'controller' => 'Groups',
        'action' => 'index'
        ]
    ]);

    echo this->Form->button('Enviar');

echo $this->Form->end();

Comment: Perfeito, era exatamente isso que eu queria @jeferson-assis !!


Permutações e ficheiros

Question: Estou a trabalhar numa brincadeira que envolve permutações, para criar uma lista de palavras, em vários ficheiros à parte. Os problemas começam a surgir quando requisito palavras com mais de 4 letras, pois o ficheiro correspondente fica muito pesado. O que eu queria é que cada vez que um dado ficheiro chegasse às 499 999 (por exemplo) que abri-se outro ficheiro com o mesmo nome mas com uma extensão. Por exemplo palavras de 4 caracteres "wl4_1.txt, wl4_2.txt ..." onde o "wl4_2.txt" é a continuação do "wl4_1.txt", e a primeira linha deste ("wl4_2.txt") seria a linha de número 500 000 do "wl4_1.txt", ou seja, fecharíamos o "wl4_1.txt" e continuaríamos a nossa lista no "wl4_2.txt".
Este código em baixo funciona lindamente, só lhe queria adicionar essa funcionalidade que expliquei. Neste exemplo são palavras de 3 letras e já é pesado (830 584 linhas):
import itertools
import string

def main():

    alphabet = string.letters + string.digits + string.punctuation
    alphaLen = len(alphabet)

    print alphabet
    for i in range(3):
        NumToPerm = i+1 #remove 0 from the permutations function
        fileTest = open("word_lists/wl" +str(NumToPerm)+ ".txt", "w")

        perm(fileTest, alphabet, NumToPerm)

def perm(fileTest, alphabet, NumToPerm):

        for p in itertools.product(alphabet, repeat=NumToPerm):

            word = str(p)

            for char in word:
               if char in " (),'":
                  word = word.replace(char,'')

            fileTest.write(word+ '\n')

        fileTest.close()

main()

Answer: Em primeiro lugar, você não precisa chamar perm de dentro de get_file_extn: apenas retorne para função chamadora! Se você chamar perm de lá, você estará iniciando do zero, o que não é o que você quer (e sim continuar de onde está).
Apenas lembre de retornar o novo fileTest, pois o anterior foi fechado (se você tentasse utilizá-lo, daria erro). E não o feche duas vezes!
def get_file_extn(fileTest, alphabet, NumToPerm, countExtn):
    #fileTest.close()
    fileTest = open("word_lists/wl" +str(NumToPerm)+ "_" +str(countExtn)+ ".txt", "w")
    return fileTest

def perm(fileTest, alphabet, NumToPerm):
    ...
    if countWords == 999:
        fileTest.close()
        fileTest = get_file_extn(fileTest, alphabet, NumToPerm, countExtn)
        countExtn = countExtn + 1

Em segundo lugar, o countWords chegou em 999, mas se você não o resetar para zero, ele vai passar pro 1000 e continuar crescendo - sem nunca entrar no if de novo! Como a próxima linha já vai aumentá-lo em 1, atribua-o a zero no final do if:
    if countWords == 999:
        fileTest.close()
        get_file_extn(fileTest, alphabet, NumToPerm, countExtn)
        countExtn = countExtn + 1
        countWords = 0

    countWords = countWords + 1
    ...

Terceiro, você está atribuindo countExtn para 1 dentro do laço for. Para toda palavra lida, ele vai ser 1! Em vez disso, atribua-o antes do for:
    countExtn = 1
    for p in itertools.product(alphabet, repeat=NumToPerm):

Com isso você consegue a separação em arquivos. Um último detalhe: o primeiro arquivo aberto, no main, não usou sua convenção wl_X_Y.txt, mas simplesmente wl_X.txt. E ele vai receber as primeiras 999 palavras, enquanto o wl_X_1.txt vai receber da milésima em diante. Seria preferível que a main criasse o arquivo 1, e o perm já iniciasse countExtn com 2 (pois o 1 já foi criado):
def main():
    ...
    fileTest = open("word_lists/wl" +str(NumToPerm)+ "_1.txt", "w")

    perm(fileTest, alphabet, NumToPerm)

def perm(fileTest, alphabet, NumToPerm):
    ...
    countExtn = 2
    for p in itertools.product(alphabet, repeat=NumToPerm):

Comment: Obgado, mas algo se passa, esta-me a dar erro relativo ao ficheiro. Editei o código em cima, na tentativa e pus o que percebi que você me disse
Comment: @Miguel Que erro que está dando? Pela sua edição, vi que só corrigiu *parte* dos problemas, vários deles mencionados na resposta ainda estão lá (por exemplo, você está retornando `fileTest` da sua função, mas não está usando o retorno, por isso quando você tenta escrever na *stream* já fechada ele deve acusar um erro. É isso que está acontecendo?).
Comment: Sim é isso. ("...fileTest.write(word+ '\n')
ValueError: I/O operation on closed file"). Como implemento o retorno neste caso?
Answer: A proposta que apresento altera um pouco a abordagem de pergunta:

Simplificar a script para passar apenas a gerar as permutações do comprimento recebido via linha de comando, enviando para a stdout.
O sistema operativo faz a divisão em ficheiros
(comando split).

ou seja:
import itertools
import string
import sys

def main():
    alphabet = string.letters + string.digits + string.punctuation
    perm(alphabet, int(sys.argv[1]))

def perm(alphabet, NumToPerm):
    for p in itertools.product(alphabet, repeat=NumToPerm):
        print  "".join(p)

main()

Modo de utilização:
python x.py 3 | split -d --additional-suffix=.txt  -l 50000 - wl

Permutações e ficheiros


Como clicar no botão SEGUIR do Instagram com Selenium usando python

Question: O Instagram está cada vez mais dificultando o uso da automação em seu site.
Esse código clica no primeiro botão com o texto 'Seguir'
Você pode usar isso pra localizar e clicar:
    from selenium import webdriver
    from selenium.webdriver.common.by import By
    driver = webdriver.Firefox(executable_path=r"./geckodriver.exe")
    url="https://www.instagram.com/PERFIL/"
    driver.get(url)

    button_follow=driver.find_elements(By.CSS_SELECTOR, 'button')

    print(len(button_follow))#Conta quantos botões encontrou

    print(button_follow[0].text)#Imprime o nome que está no botão no índice [0] da lista

    #button_follow.click()# Caso queira clicar sem conferir o texto

    if button_follow[0].text == 'Seguir': #Se o texto for 'Seguir'
        button_follow[0].click()#Clica no botão
        print('Clicou')

Passei 5 horas pra fazer esse método acima.
Tinha usado todos esses abaixo e não encontrava:
button_follow =driver.find_element_by_xpath("//*[@id='react-root']/section/main/div/header/section/div[1]/div[2]/div/div/div/span/span[1]/button").click();
button_follow = driver.find_element_by_xpath('//button[contains(text(), "Seguir")]')
button_follow = driver.find_element_by_css_selector('button')
print(button_follow.text)
if button_follow.text == 'Seguir':
    button_follow.click()
Follow_Button = driver.find_element_by_xpath("//*[text()='Seguir']")
Follow_Button.click()
seguir = driver.find_element_by_css_selector('button')
seguir.click

driver.find_element_by_xpath('source=follow').click()

followButton = driver.find_element_by_tag_name('button')
print(followButton.text)
if followButton.text != 'Following':
        followButton.click()
        time.sleep(2)
else:
    print('Não achou')
driver.find_element_by_xpath('Seguir').click()
driver.find_element_by_xpath("//*[@aria-label='{}']".format('Seguir')).click()
#driver.find_element_by_xpath("/html/body/div[1]/section/main/div/header/section/div[1]/div/div/div/a/button").click()
#driver.find_element_by_css_selector('button._5f5mN.jIbKX._6VtSN.yZn4P').click()
#driver.find_element_by_xpath("//button[text()='Seguir']").click()
#driver.find_element_by_xpath("//button[contains(text(), 'Seguir')]").click()
#find_element_by_xpath('//button[text()="Seguir"]').click()
#wb2 = driver.find_element(By.XPATH("/html/body/div[1]/section/main/div/header/section/div[1]/div/div/div/a/button"))
#wb2.click()
sleep(10)

Answer: Utilizo a opção find_element_by_class_name para achar o botão e em seguida o código o aperta.
from selenium import webdriver
driver = webdriver.Firefox()
url = "https://www.instagram.com/PERFIL/"
driver.get(url) #Abre a url.
followButton = driver.find_element_by_class_name("sqdOP.L3NKy.y3zKF") #Melhor opção na minha opinião: acha o botão pelo nome de sua classe.
followButton.click() #Clica no botão.
input("Botão apertado, aperte enter para fechar a janela.") #Espera o usuário apertar enter e fechar o navegador e o código.
driver.close()

Testei e funcionou.


Change the name of a cloned VM without losing the source VM

Question: I have an ESXi host on a domain, and I am having some issues with cloning VMs that the IT consultants don't seem to be able to help with.
I am able to clone a VHD, make a new VM with that VHD, flag it as copied not moved (to get a new MAC address) and launch the resultant VM. But according to the IT folks I can't then change the computer name of that VM, without causing problems with the first VM. According to the consultants the ONLY way to get a new VM is to pay them to manually create a new VM, inlcuding the Windows install, which they do from a 5 year old ISO that requires a manual update of Windows version, plus all windows updates, plus joining the domain. They can't be bothered to automate ANYTHING. Of course not, they get paid not to.
But I am certain that both Cloning and Templates are viable VMware paths to new VMs on the domain. I just don't know the ins and outs of DNS/DHCP as it applies to a Windows Domain, and IT are not being helpful. Can anyone verify that I am not daft, and Cloning IS a viable route? And perhaps explain the process either I need to go through to rename the cloned VM myself (ideally) or the path that I need IT to go through to do the same (less ideal because getting them to do anything is like pulling teach)?
One thought I had was to log on to the VM, take it off the domain, change the name, then rejoin the domain, as mentioned here. Am I understanding that right, and this is viable? Will I have any issues then logging in from the original VM that still has the old name? I am hoping the issue is just with having two machines with the same name logged in at once, not with ever having two machines with the same name log in.
I should mention that I should be able to do that because I have, get this, DOMAIN ADMIN rights. As an external consultant for Autodesk installs IT gave me DOMAIN ADMIN rights. After I told them the ONLY thing I need is local admin rights when actually doing the installs, and the better approach would be to give me personally standard user rights and then have a dedicated user account with Local Admin only. But no, I have DA, and four other people in house, who actively do the Autodesk installs I am helping to automate have DA rights. ON THEIR REGULAR USER ACCOUNTS. The idiots are clueless, but it's what I have to work with and at least in this case those rights are useful.
Answer: They are right in a certain way, that is you can't directly use this cloned VM on a domain network without first dealing with the issue that after cloning you have two computers with the same name and domain account on the network.
But you can work around it. First, disconnect a clone from the network while it is powered off. Boot the system, login using local admin account, disjoin the machine from your domain. Change it's IP address and rename the computer. Alternatively, you can sysprep your clone to get things right.
Then, boot with the network connected and join the domain as usual.
Comment: You use esxi, so just uncheck `connected` and `connect at power on` checkboxes next to your network adapter in virtual machine properties. As for `sysprep`, running `sysprep /generalize /oobe /mode:vm` should suffice in your case
Comment: You need to join a domain when your cloned system has a different name, so if we're talking about templates then the VM inside template should not be a domain member.
Comment: You don't have to do that. You clone a VM that is a domain member. Then on the clone you disconnect the network, login as local admin account, leave the domain (it would allow you to do so in disconnected state), rename the computer or do a sysprep, then reboot the clone, connect it to the network and join a domain again.
Comment: After leaving the domain your domain account would not work on the machine. You have to login using local admin account, select join domain and then, when prompted, enter your domain admin account credentials.
Comment: Ah, looks like I was close. How do I "disconnect a clone from the network while it is powered off. "? As for SysPrep, I had no idea I could run that on an existing install disconnected from the domain. Seems I need to figure out how to do that.
Comment: So it looks like I have a couple of steps here. 1: create a local account on the machine that is an Administrator 2: Stop the VM and do the disconnect as described 3: Clone the VM (to a new host in this case) 4: Create new VM, also disconnected 5: Start VM, logon as local admin and disjoin from domain 6: Rename computer, reboot and shut down 7 Reenable network and reboot 8: Logon as local admin, Rejoin domain
Comment: Do I have that right? :)
Comment: Yes, that's it.
Comment: Woot! I hope to also have the clone sorted, and I can try it. Followup question, does the ESXi Template process automate any of this? I assume creating a new VM from a template means you have a new VM you can immediately use. Or do you need to do this procedure on the resultant VM before it's safe to use?
Comment: If using templates, you should `sysprep` your VM, shutdown it and only then convert it to template. Then this template could be used multiple times.
Comment: AHA! Totally makes sense to do the prep first. Monday morning, just had coffee brain.
Comment: Well, it seems there is one other nuance. I have to union the domain on the original VM before anything else, because that needs to be done WHILE I am connected to the domain, which makes sense.
Comment: And I can't clone with a snapshot, so if/when I screw something up, I REALLY screw up, because getting IT to rebuild a VM is a PITA.
Comment: I'm talking about even earlier than that. I need to clone a VHD that has already left the domain. But I worry about getting THAT VM back ON the domain. So I have made a backup clone of the HD on the domain, then I will log in to the machine as DA, leave the domain, log off & disconnect from the network, log in again as the local admin, change the machine name, and clone again for distribution. Then I will  join the domain again with the original VM and unchanged name, buy deleting that now modified VHD and cloning the backup back to the original location and name. I hope it all works. :)
Comment: I can see I am going to end up trying a number of things and learning a lot, while spending WAY too much time. :) I think what I got wrong was trying to leave the domain while logged in as DA. Next I'll try as you say, but I will have the backup, so I can clone the already workgroup VM and still restore (or try to restore) if need be. We have no backup on either host, and never will, so having some mechanism to backup VMs to an external USB HD seems appropriate.
Comment: Well, I thought I had the same problem again, but I forgot that my previous attempt to just rename while joined to the domain resulted in the old name being corrupted some how, as well as the new name being unavailable. So IT "fixed" the VM by just creating a new computer name, rather than actually fixing it. And I had forgotten that and was using the old computer name to try to log in locally. Got as far as leaving the domain, but now, just like previous attempt, my Domain Admin account has been locked, so I can't use it to rejoin the domain. I really hate these IT clowns.
Comment: Exactly, and at that point, logged in as local admin, joining domain with domain credentials, I was getting an error saying account locked. Which I got yesterday too, and it really was locked, because I couldn't use it for any logons, VM or physical machine. But in this case it's because I forgot to include the domain prefix, and Microsoft threw an unhelpful error, and by coincidence I had seen that error just yesterday, and I blew a gasket. This whole exercise has been daft, but once it's done I'll be able to look back and see all the things I have learned.
Answer: Take a look at vmware converter, that is able to do the job, but it requires vcenter. You can rename a windows device, but if it's a domain controller then it requires a more extended procedure.
With PowerShell it's one line:
Rename-Computer -NewName "Server044" -DomainCredential Domain01\Admin01 -Restart

Comment: Unfortunately vCenter is not an option here. I have to do it with a minimal ESXi install or not at all.
Comment: Checkout the StarWind V2V converter, it's free. But a domain controller needs extra carefulness. Search Google for cloning domain controller vm, or hire me hahahaha lol. I will make an extra post what you need to do before spinning up the cloned VM
Comment: VMware converter does not need vcenter, it's a standalone product. But it hasn't been updated in years, it may work with a modern ESXi, or it may not.


How to test hypothesis of no group differences?

Question: Imagine you have a study with two groups (e.g., males and females) looking at a numeric dependent variable (e.g., intelligence test scores) and you have the hypothesis that there are no group differences.
Question:

What is a good way to test whether there are no group differences?
How would you determine the sample size needed to adequately test for no group differences?

Initial Thoughts:

It would not be enough to do a standard t-test because a failure to reject the null hypothesis does not mean that the parameter of interest is equal or close to zero; this is particularly the case with small samples.
I could look at the 95% confidence interval and check that all values are within a sufficiently small range; perhaps plus or minus 0.3 standard deviations.
Comment: what do you mean by "this assumes the null hypothesis to be true" ?
Comment: If you want to be able to control the probability of declaring wrongly "there is a difference"  you need to separate the two hypothesis (did I already mentionned I love this quote: http://stats.stackexchange.com/questions/726/famous-statistician-quotes/728#728 ;) )
Comment: @Robin the p value of a null hypothesis significance test is the probability of seeing as or more extreme data than that observed assuming the null hypothesis is true; but perhaps I could word the statement above better.
Comment: @Robin I modified the question to try to make my point clearer
Answer: I think you are asking about testing for equivalence. Essentially you need to decide how large a difference is acceptable for you to still conclude that the two groups are effectively equivalent. That decision defines the 95% (or other) confidence interval limits, and sample size calculations are made on this basis.
There is a whole book on the topic.
A very common clinical "equivalent" of equivalence tests is a non-inferiority test/ trial. In this case you "prefer" one group over the other (an established treatment) and design your test to show that the new treatment is not inferior to the established treatment at some level of statistical evidence.
I think I need to credit Harvey Motulsky for the GraphPad.com site (under "Library").
Answer: Besides the already mentioned possibility of some kind of equivalence test, of which most of them, to the best of my knowledge, are mostly routed in the good old frequentist tradition, there is the possibility of conducting tests which really provide a quantification of evidence in favor of a null-hyptheses, namely bayesian tests.
An implementation of a bayesian t-test can be found here:
Wetzels, R., Raaijmakers, J. G. W., Jakab, E., & Wagenmakers, E.-J. (2009). How to quantify support for and against the null hypothesis: A flexible WinBUGS implementation of a default Bayesian t-test. Psychonomic Bulletin & Review, 16, 752-760.
There is also a tutorial on how to do all this in R:
http://www.ruudwetzels.com/index.php?src=SDtest

An alternative (perhaps more modern approach) of a Bayesian t-test is provided (with code) in this paper by Kruschke:
Kruschke, J. K. (2013). Bayesian estimation supersedes the t test. Journal of Experimental Psychology: General, 142(2), 573–603. doi:10.1037/a0029146

All props for this answer (before the addition of Kruschke) should go to my colleague David Kellen. I stole his answer from this question.
Comment: It may be worth updating this answer to include a reference to the awesome BayesFactor package for R.
Comment: For those interested in the tutorial, the website is no longer functional.  The Wayback Machine has a copy at https://web.archive.org/web/20090312002033/http://www.ruudwetzels.com/index.php?src=SDtest
Answer: Following Thylacoleo's answer, I did a little research.
The equivalence package in R has the tost() function.
See Robinson and Frose (2004) "Model validation using equivalence tests" for more info.
Answer: There are a few papers I know of that could be helpful to you:
Tryon, W. W. (2001). Evaluating statistical difference, equivalence, and indeterminacy using inferential confidence intervals: An integrated alternative method of conducting null hypothesis statistical tests. Psychological Methods, 6, 371-386.  (FREE PDF)
And a correction:
Tryon, W. W., & Lewis, C. (2008). An Inferential Confidence Interval Method of Establishing Statistical Equivalence That Corrects Tryon's (2001) Reduction Factor. Psychological Methods, 13,  272-278. (FREE PDF)
Furthermore:
Seaman, M. A. & Serlin, R. C. (1998). Equivalence confidence intervals for two-group comparisons of means. Psychological Methods, Vol 3(4), 403-411.
Answer: I have recently thought about an alternative way of "equivalence testing" based on a distance between the two distributions rather than between their means.
There are some methods providing confidence intervals for the overlap of two Gaussian distributions:
The overlap $O(P_1,P_2)$ of (between?) two distributions $P_1$ and $P_2$ has a nice probabilistic interpretation: $$1-O(P_1,P_2)= TV(P_1,P_2)$$
where $TV(P_1,P_2) = \sup_A \big|P_1(A) - P_2(A) \big|$ is the total variation distance between $P_1$ and $P_2$.
That means that, for example, if $O(P_1,P_2)>0.9$ then the probabilities given by $P_1$ and $P_2$ of any event do not differ more than $0.1$. Roughly speaking, the two distributions make the same predictions up to $10\%$.
Thus, instead of using an acceptance criterion based on a critical value for the difference between the means $\mu_1$ and $\mu_2$, as in classical equivalence testing, we could base it on a critical value for the difference between the probabilities of the predictions given by the two distributions.
I think there's an advantage in terms of "objectiveness" of the criterion. The critical value of $|\mu_1 - \mu_2|$ should be given by an expert of the real problem: this should be a value beyond which the difference has a practical importance. But sometimes nobody has a solid knowledge about the real problem and there's no expert able to provide a critical value. Adopting a conventional critical value about $TV(P_1,P_2)$ could be a way to a criterion not depending on the physical problem under consideration.
In the Gaussian case with same variances, the overlap is one-to-one related to the standardized mean difference $\frac{|\mu_1-\mu_2|}{\sigma}$.
Comment: @StumpyJoePete I have written something in the same spirit on my blog: http://stla.github.io/stlapblog/posts/EquivalenceExceedanceProbabilities.html
Comment: Do you have any resources showing overlap being _used_ in some real problems? This sounds incredibly promising, but it's not clear to me how one would apply it in a real problem (where your conclusions are potentially several steps removed from "this distribution is pretty similar to X", thereby making it a little hard to see how that 10% TV translates into size of impact on inferences).
Answer: In the medical sciences, it is preferable to use a confidence interval approach as opposed to two one-sided tests (tost). I also recommend graphing the point estimates, CIs, and a priori-determined equivalence margins to make things very clear.
Your question would likely be addressed by such an approach.
The CONSORT guidelines for non-inferiority/equivalence studies are quite useful in this regard.
See Piaggio G, Elbourne DR, Altman DG, Pocock SJ, Evans SJ, and CONSORT Group. Reporting of noninferiority and equivalence randomized trials: an extension of the CONSORT statement. JAMA. 2006, Mar 8;295(10):1152-60. (Link to full text.)
Comment: I wouldn't necessarily say that confidence intervals are preferred.  In fact the confidence intervals correspond to hypothesis tests.  TOST can be achieved by looking at the confidence intervals obtained by intersecting the two one sided confidence intervals that correspond to the two one-sided t tests that are used in the procedure.
Answer: Yes.  This is equivalence testing.  Basically you reverse the null and alternative hypothesis and base the sample size on the power to show that the difference of the means is within the window of equivalence.  Blackwelder called it "Proving the null hypothesis." This is commonly done in pharmaceutical clinical trials where equivalence of a generic drug to the marketed drug is tested or an approved drug is compared to a new formulation (often called bioequivalence).  The one sided version is called non-inferiority.  Some times a drug can be approved by just showing that the new drug is not inferior to the marketed competitor.  Shao and Pigeot have developed a consistent bootstrap approach to bioequivalence using crossover designs.
Answer: Bootstrap differences (e.g. the difference between the means) between the 2 sample groups and check for statistical significance. A more detailed description of this approach, albeit in a different context, can be found here http://www.automated-trading-system.com/a-different-application-of-the-bootstrap/
Comment: You are conflating the fallacy of *accepting the null hypothesis of no difference* and finding *evidence that two quantities are equivalent*.


How to approach this least square projection question?

Question: A simple linear regression model as follows,
\begin{align}
Y=\beta_0+\beta_1 X+\epsilon
\end{align}
Now I would like to replace $X$ with another variable $Z$. I only know $X$
and $Z$ are correlated but do not know the true functional form of the relationship between these two variables.
The new regression model with $Z$ is
\begin{align}
Y=\beta^*_0+\beta^*_1 Z+\epsilon^*
\end{align}
How can I show that (asymptotically)
1) $\beta^*_0=\beta_0$
2) $\beta^*_1=\beta_1*\rho$, where $\rho$ is the coefficient from least square model $X=\rho Z+ \nu$
3) $\epsilon^*=\beta_1 \nu + \epsilon$
Basically why it must be least square projection of $X$ on $Z$ when we replace $X$ with $Z$?
Any suggestion or references on how to approach this question will be appreciated!
Answer: Take the original equation:
$Y = \beta_0 + \beta_1X+\epsilon $
Sub in $X=\rho Z + v$ and re-arrange terms
$Y = \beta_0 + \beta_1(\rho Z + v)+\epsilon = \beta_0 + (\beta_1\rho) Z + (\beta_1 v +  \epsilon)$
This is equivalent to regressing Y on Z so the coefficients must be identical.


Can't resolve server by fqdn when search domain is enabled

Question: I have a server named site.dpt.myorg.local, which i want to access both with short name and with fqdn.
When i try to use short site or site.dpt form, everything works just fine. However when i use fqdn - lookup works when using dig or nslookup, but fails when i use web browser, ssh and other tools.
I.e. ssh and ping fail with following error:
$ ssh -vvvv site.dpt.myorg.local
OpenSSH_7.2p2, OpenSSL 1.0.2j-fips  26 Sep 2016
debug1: Reading configuration data /home/user/.ssh/config
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 25: Applying options for *
debug2: resolving "site.dpt.myorg.local" port 22
ssh: Could not resolve hostname site.dpt.myorg.local: Name or service not known

$ ping site.dpt.myorg.local
ping: unknown host site.dpt.myorg.local

I have a following resolv.conf file:
search myorg.local dpt.myorg.local
nameserver 10.0.0.1
nameserver 10.0.0.2

My OS is Opensuse 42.3
Can anyone point me to the cause of this problem? Thanks!
Comment: Are your nameservers configured to handle `dpt.myorg.local`?
Comment: Yeah, nameservers are correct, i'm pinging the same full addresses from other machines in network just fine. On a test centos 6 box with same resolv.conf i can use all hostname forms
Answer: I found the answer to my question: https://superuser.com/questions/704785/avahi-ping-cant-resolve-hostname-but-nslookup-can
the problem was in avahi service, configured by default for .local domain. fixing part of /etc/avahi/avahi-daemon.conf as
[server]
domain-name=.alocal

solved my problem.
Edit: Ended by disabling avahi since i had no need in it in my environment.
Comment: I think it's worth noting that the proper solution is to stop abusing `local` rather than changing avahi (or other mDNS implementation of choice) to operate in nonstandard ways or disabling it entirely (which might be a slightly cleaner middle ground).
Answer: The local TLD is reserved for use with mDNS and should not be used with regular DNS.
The proper solution would be to stop misusing local in this way.


Como decidir qual hash criptográfico usar?

Question: Gostaria de saber em que casos devo usar os diversos hash existente, pois pelo que sei existem diferenças grandes entre a segurança e processamento entre eles.
Existe algum considerado o melhor em relação velocidade x segurança?
Comment: Eu acho que isto já resposta isto: http://pt.stackoverflow.com/q/2402/101
Comment: Justamente isso que eu precisava. Devo remover a pergunta @bigown?
Comment: Acho que este caso seria bom.
Answer: O mais comum de todos é o MD5, a maioria dos bancos de dados já possuem funções nativas para gerar esse tipo de hash. Esse também é o seu principal problema pois já existem na internet bibliotecas de MD5, por isso se você pretender usa-lo acrescente um prefixo e/ou um sufixo algo como 123456.
O recomendado pela New European Schemes for Signatures, Integrity and Encryption (NESSIE), uma organização europeia e pela própria ISO é o Whirlpool-T.
Pessoalmente eu uso o MD5 após adicionar sufixos e prefixos e embaralhar a mensagem.
Comment: MD5 não é um algoritmo seguro, é possivel quebralo com algoritimos de colisão, o SHA-2 ou SHA-3 não mais indicados para se realizar um Hash. Quanto ao Salt, não é interresante que ele seja um valor estatico e previsivel, o ideal seria utilizar uma Guid para o serviço.
Answer: Gostaria de sugerir um algoritmo de Hash, no caso o BLAKE2.
O BLAKE, foi um dos candidatos finalistas para ser o algoritmo para o SHA-3, porém o Keccak saiu vitorioso.
Porém o mesmo sofreu algumas modificações, nascendo a segunda versão (BLAKE2), que diz ser mais rápido que o MD5 e tão forte quanto o atual SHA-3
Mais sobre:
https://leastauthority.com/blog/BLAKE2-harder-better-faster-stronger-than-MD5.html


Ignore Users Content with Flags>

Question: I am developing a network of websites for our nonprofit organization.
As with any membership site, we have some members who simply do not get along and often, their back and forth "drama" will detract from the other member's positive, supportive experiences.
Rather than simply banning members who can't get along with each other, we'd like to set up a way for members to flag a member and "mute" them, so that instead of seeing their content, they will see a message like "You have muted this member and cannot view their post. To unmute the member, visit your profile page." or something to that effect.
There was a module for 6 that is  ported to 7 called Ignore User, but it doesn't seem to be in a stable release for 7.
It seems to me that there has to be some way to do this with flags, rules, and views -- but I admit it is a bit above my knowledge level.
Has anyone ever done something like this on a Drupal 7 site? Can you help me make this work? I really do feel it will make a big difference for our chapters and minimize some of the "drama" we have to deal with on a regular basis.
Thanks
Heather
Comment: Do you mean comments and/or nodes with 'content'? How do you display them on your website now?
Comment: Mostly through views and panels: my group pages are made up of panels and views, as are my forums - the only content that doesn't go through a panel right now is just the basic article (which, honestly would be okay to leave alone as only certain roles can post it).

I am more interested in filtering out forum topics and my custom group forum topic content type, which is where the majority of the back and forth happens.

Is there a way to put a contextual filter on a view or panel that rewrites the body field to be the 'blocked content' message for users that the user viewing has flagged?
Comment: Which fields from the node do you display in your view? Only the title?
Comment: Well in the forum topic view, they will see the node title and body, then the comment titles and bodies.

I want it to replace the body of the node or comment (so whether it is a "new topic" or a "reply") with the "muted user" message if you have flagged that user as muted.
Comment: This is something that is available in phpbb3, if it helps to have an example of how it works. It is called the "foe" feature on their software.
Comment: Looks like a duplicate of http://drupal.stackexchange.com/questions/23426/is-there-a-module-solution-for-allowing-users-to-block-each-other-on-an-sns-site.
Answer: There is Ignore User, but for D7 there is only a dev version that hasn't seen any progress in over 2 years. Might be worth a look though, maybe you can start with that and even contribute back any improvements.
Everything else would require a considerable amount of configuration concerning the flags themselves, any views listings and node displays. Probably you will even need to do some custom coding.
Comment: It won't let me upvote you yet, but thank you for helping me!
Comment: Welcome to Drupal Answers :) I'm glad I could help. You should be able to accept this answer (a green icon somewhere) ;) if it was helpful.

Ignore Users Content with Flags>


WampServer Apache httpd.exe application was unable to start correctly (0xc0000142) after Windows 10 Creators Update (1703))

Question: The Windows 10 Creators update seems to have hosed Apache's httpd service, which now errors when I first start the WampServer.
The official form confirms this suspicion.
WampServer version 3.0.6.
However, none of the suggested solutions on the forum worked, as of the time of this post. Thus, I've opened this question so that us community members can work to find a solution here.
Note that downgrading Windows is not a viable solution here.
Comment: Note that will the service appears to start after clicking OK on the error message, there is functionality impacted by the issue - one example is ability to use commands such as exec() and popen().
Comment: Just FYI - a very similar question http://stackoverflow.com/questions/14522171/httpd-exe-application-error has been closed as off topic
Comment: OMG, how I hate the draconian Microsoft!  I come back and my machine is rebooted, to this type of error... no files saved, updates to the system *I* didn't approve.  Time to go back to Ubuntu...
Answer: Update: looks like the 3.0.8 patch resolves the issues with WampServer 3.0.6 and the Windows 10 Creators Update.
It's not well publicized on the website, (you need to click the SourceForge link on the website and navigate the folder structure to find it.) Direct link to the update here:
https://sourceforge.net/projects/wampserver/files/WampServer%203/WampServer%203.0.0/Updates/wampserver3_x86_x64_update3.0.9.exe/download
Update: looks like 3.0.8 has been pulled as 3.0.9 just came out; here's the link to 3.0.9:
https://downloads.sourceforge.net/project/wampserver/WampServer%203/WampServer%203.0.0/Updates/wampserver3_x86_x64_update3.0.9.exe?r=https%3A%2F%2Fsourceforge.net%2Fprojects%2Fwampserver%2Ffiles%2FWampServer%25203%2FWampServer%25203.0.0%2FUpdates%2F&ts=1498418727&use_mirror=pilotfiber
Comment: Worked for me too.  FYI, if you are installing, choose the same directory (mine was `C:\\wamp64`, not `C:\\wamp`, the default).
Comment: The link has been fixed to point at 3.0.9 update that replaces 3.0.8.


Easy way to pull fully qualified field names from a SELECT statement?

Question: In SQL Server, is there an easy way to output a list of fully qualified field names from a SELECT statement, even with aliases?
For example:
SELECT
      a.FieldName1
    , a.FieldName2
    , CASE WHEN a.FieldName9 = 'A' and b.FieldName10 = 'C' Then 'Yes' Else 'No' END as AliasedCase
FROM DatabaseA.dbo.Table1 a
JOIN DatabaseB.dbo.Table2 b on a.FieldName4 = b.FieldName4
WHERE b.FieldName8 Between 1 and 4

Output list would look like:

DatabaseA.dbo.Table1.FieldName1
DatabaseA.dbo.Table1.FieldName2
DatabaseA.dbo.Table1.FieldName4
DatabaseA.dbo.Table1.FieldName9
DatabaseB.dbo.Table2.FieldName4
DatabaseB.dbo.Table2.FieldName8
DatabaseB.dbo.Table2.FieldName10
Comment: No easy way, just the manual way.
Comment: Create a view out of your query, then take your information from [`sys.dm_sql_referenced_entities`](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-sql-referenced-entities-transact-sql?view=sql-server-ver15).
Answer: You can create a view or procedure with that SELECT, use the sys.dm_sql_referenced_entities function to get the information, then drop it afterwards.
create view dbo.MyTempView
as

SELECT
      a.FieldName1
    , a.FieldName2
    , CASE WHEN a.FieldName9 = 'A' and b.FieldName10 = 'C' Then 'Yes' Else 'No' END as AliasedCase
FROM DatabaseA.dbo.Table1 a
JOIN DatabaseB.dbo.Table2 b on a.FieldName4 = b.FieldName4
WHERE b.FieldName8 Between 1 and 4

select CONCAT(
  dep.referenced_server_name + '.',
  dep.referenced_database_name + '.',
  dep.referenced_schema_name + '.',
  dep.referenced_entity_name + '.',
  dep.referenced_minor_name)
from sys.dm_sql_referenced_entities('dbo.MyTempView', 'OBJECT') dep
where dep.referenced_minor_name is not null;

drop view dbo.MyTempView;

The use of CONCAT along with + '.' means that nulls will be ignored along with their associated ., so it will only tell you the actual reference you used, it will not work out which database or schema is used if you did not specify it (due to scoping issues, as it depends what your default database and schema is when executed).


What to do after learned scales positions?

Question: I'm playing 3.5 years and in last month I start to learn scales so first I learned all major scale positions. So now before I will learn more scales like minor,pentatonic, harmonic minor etc
What I need to do with the major scale? I'm feeling like stuck with patterns.
Comment: Out of interest, what have you been playing/learning in those 3.5 yrs?
Comment: @Pyromonk - Get handed increasingly difficult pieces to play. Rather like being handed "Mary Had a Little Lamb", a more difficult arrangement of that, then eventually that famous Minuet in G Major.
Comment: @piiperiReinstateMonica - I had to learn scales from my piano teacher, and even then, I kept mucking up the fingering. I only started noting what scales (not just keys) music was in after I stopped taking piano lessons.
Comment: Do you mean that you've learned lots of scale patterns, but haven't played any songs or melodies with them?
Comment: Hm yeah, I learn all the major patterns but now how can I use it?
Comment: Okay, that's like a pianist having discovered the white keys of the piano. :) Now you should make some music with what you have.
Comment: Only starting to learn scales after 3.5 years of playing is _very_ late. One of the best exercises for scales is improvisation. You can find or compose a backing track that uses the scale(s) that you are trying to practise and play over it. It can be an exercise of simply running through it, but you would also eventually need to pay attention to the chord changes and follow them.
Comment: @Pyromonk - Starting to learn scales only after at least 3 years of playing piano doesn't sound abnormal if you start learning the instrument when you're 6 years old.
Comment: @Dekkadeci, what would you do for the first 3 years though? Play "Mary Had a Little Lamb"?
Comment: I learned piano scales automatically by playing songs by ear and improvising in all keys! No boring scale exercises, only songs I liked. I simply hated playing wrong notes, and I hated not being able to play what I feel, in any key that might be requested. But how to create a "method" out of that? The most important thing - or perhaps the _only_ important thing - is _motivation_ IMO, and that's different for each person. And it varies between different parts of the world and the surrounding culture.
Comment: Not an answer, just a suggestion to help you stay positive and keep learning: Don't let people make you feel bad for where you are in your guitar learning journey. We all play for different reasons and learn at our own pace. Also, it's normal to hit plateaus and feel stuck in any course of learning. You might do well to learn those other scales, or something else entirely, then come back to major scale and see if you have any fresh perspectives on it.
Comment: Ok, so in these 3.5 years I learned songs and solos by ear or tabs, learn and improve my techniques (right hand, timing, finger picking, little flamenco techniques etc) for studio recording, learn guitar neck notes, learn music theory, chord progression and CAGED Now my playing is smooth and I'm on the beat so it's time to learn the scales and not only the solo
Answer: One thing is to take a simple tune in a major key, and sticking initially to one key, try to play it all over the neck, using the shapes and positions you say you've learned.
Then play it in different keys, all over the neck again. Not from the dots - which will only be in one key, but using your fretboard knowledge.
Another is to use 1,3,5 (and maybe 7), to play arpeggios up and down. But here, you can elongate them by starting in a low position, and moving, perhaps a couple of times, to the next set of notes - and back again.
EDIT: an introduction to modes. Try starting each scale pattern on different notes, and go up ato one or two octaves above that before returning. By starting on the second note, you're playing a Dorian mode, third note gives Phrygian, etc.
That should keep you busy for a good few months! Good luck!
Answer: Beside scales what have you been playing for 3 years? You should try to have a mix of drills, memorizing pieces, sight reading... and IMO improvisation. All of which can be geared to the beginner level. The reason for the question has to do with application of scale studies...

What I need to do with the major scale?

In most real music full or multi octave scales are not used. The typical thing is for a portion of a scale to be used.
Also, in real music you won't find scale passages starting and ending with the fingering given for scale drills.
When you work on scale drills you should be thinking about finger groupings on the strings and the various ways your hand moves in and out of positions. The point isn't so much to literally learn the scale (as I said before you won't find a lot of music of just full scales) but the point is about learning good fingering and position.
If your scale drills are feeling good, start to play pieces with prominent scalar passages. If the music includes fingerings, compare groupings and position changes to scale drills. For example, you might see a five note scalar passage - starting on the tonic - but it may or may not have the same fingering as the start of a scale drill based on what comes before and after the passage.
You can also try simple improvisation. Instead of playing up and down the whole scale as in the typical drill, play portions of the scale into important harmonic notes. Hold the harmonic notes with a longer rhythm as "targets" or "goal" notes. So, for example, you could play down the scale, from the dominant, three times, targeting in turn the tonic, then leading tone, then back to the tonic - DO TI DO. (It will outline the basic harmony I V I.) You can play flexibly with rhythm to get your target notes hitting on downbeats. Something like that is a way to make a basic musical statement from a simple scale. But, if improv interests you, find a method book appropriate to the style you like.
Also, depending on how you have been practicing you can up the level of your drills. If you have only been playing up and down the scale, and additional musical elements. Firstly, play metrically (some scale patterns don't really fit barline/meter) and count time aloud. Play scales with various meters. Alternate ascending/descending the scale. "Rotate" the starting note. If you have only been playing from tonic to tonic, play the scale starting on each tone of the scale. If you play the scale only as a straight, step-wise motion, play it in broken third, fourths, etc. You can also play the scale in thirds by skipping every other tone, like 1 3 5 7 2 4 6 8. There are lots of ways like that to vary a simple scale drill. And, in fact, a lot of those linear variations become the building blocks of melody/improv.
Comment: Ok, so in these 3.5 years I learned songs and solos by ear or tabs, learn and improve my techniques (right hand, timing, finger picking, little flamenco techniques etc) for studio recording, learn guitar neck notes, learn music theory, chord progression and CAGED Now my playing is smooth and I'm on the beat so it's time to learn the scales and not only the solo
Answer: Here's a video that gives you something to do with the major scale in all 12 keys.
Comment: Great, but if and when link-rot sets in, this will be ineffective.
Comment: No, sorry. It's just that previous posts with only videos have been commented on similarly.
Comment: @Tim I suppose it's true, but out of of all possible external destinations, YouTube videos should be lasting much more than average. Perhaps in a few more years, with costs of storage going down, and transfer speeds going up, StackExchange will be able to host its own videos too, but until then I think YouTube is not the worst solution. Do you have other ideas or alternatives in mind?
Comment: @MMazzon - I've personally found that YouTube suffers link rot at an incredible rate. On average, I'd say a third of the YouTube videos I link to become unviewable 3 years later.


Get string of specific function name in C++

Question: In my C++ project I want to refer to a specific set of functions with strings.
Basically I want to announce certain abilities of a class to a string-array.
Like this:
<code>class Dog{
    public:
        doBark(){}
        doPoop(){}
        doLick(){}
        doWalk(){}
        doRun(){}
        otherFunction(){}
        getAbilities(){}
}
</code>
And getActions() should return a string array (or vector) with the function names starting with "do".
In case any one wonders why:
In a framework I use I can only use a certain set of types such as strings.
My objects should tell the framework what they can do, so that tasks can be planned accord to their ability. Later, strings should be mapped back to functions, about which I already found useful answers on here.
Now my question: Is this even possible? If yes, how?
Comment: _"Now my question: Is this even possible?"_ No it isn't. C++ doesn't support runtime reflection so far.
Comment: It's not possible automatically ala reflection, but you can use function pointers and strings to simulate it to some extent. You can also create some macros to add a bit of magic to the whole thing. It's still not as good as reflection unfortunately.
Comment: pretty sure this can't be done at run-time unless perhaps debugging symbols are used. what you could do (or what I would do I should say) is have a tertiary class called something like `class ActionGetter { virtual string getActions() = 0; }` (of course using proper syntax), inheriting, and overriding the `getActions()` method on a per class basis. If someone knows of an easier way let's hear it.
Comment: Ah, "reflection" was what I was looking for. Remembered using it in Objective-C way back when. Too bad that it is not possible in C++. Have to implementing a workaround based on some of your suggestions.
Comment: This is the kind of thing that _traits_ are used for in C++.
Comment: C++ does have an extension for reflection called RTTI, but as far as I'm aware it doesn't provide support for returning function/method names. Some C++ toolkits do include this capability, such as Qt.
Comment: You can do this programatically using *function objects* and tables like [std::function](http://en.cppreference.com/w/cpp/utility/functional/function) and [std::map](http://en.cppreference.com/w/cpp/container/map).
Answer: Remember that function names as well as variable names are only available at compile time. Once a program is compiled into machine code, these names not available without some serious convolutions to load the debug symbols similar to a source-level debugger.
Comment: @fanton You definitely have a pedantic point. Hopefully my most recent edit will satisfy you ;-)
Comment: Only if you discard symbols, otherwise you can, very well, see function names everywhere if you disassemble the binary.
Comment: While that's true, @fanton, it's not particularly useful for the OP.
Comment: @fanton AFAIK, these symbols are not available to your own program at run time.
Comment: @DavidHoelzer: True, but I didn't even have that intention. My intention was to point out that the answer is not *that* true.
Comment: @Code-Apprentice: I think it depends on the level of craziness you want to do in your program. As a process, you can always read your executable image and extract info from there, but that's far beyond the scope of this question.


Validation of a random forest

Question: I am a complete newbie in this area and I am probably doing something wrong. I am trying to use randomForest in R for a regression and I am using the iris dataset. I want predict the Sepal.Length from the Petal.Width and the Sepal.Length. I want to test it with cross validation and I got confused. Here is my example.
data <- iris
k = 5
n=floor(nrow(iris)/k)
error=rep(NA,k)

for (i in 1:k){
  s1=((i-1)*n+1)
  s2=(n*i)
  sub=s1:s2
  train=iris[-sub,]
  test=iris[sub,]
  model=randomForest(Sepal.Length~Sepal.Width+Petal.Length,data=train,mtry=1,ntree=501,importance=TRUE)
  prediction=predict(model,newdata=test[,-1])
  error[i]= roc.area(test[,1],prediction)
}

Questions

Is the ROC a good choice for a regression model?
How can I get the accuracies for every fold and for the entire model?
Comment: Did you mean "... from the Sepal.Width and the **Petal**.Length**"? Even with that correction, the premise is faulty - there is no dependence between what you have chosen as features and the prediction target.
Comment: @Bobev I know that. This is just an example of data frame. I just cannot understand how to extract results from folds.
Answer:
Is the ROC a good choice for a regression model?

AuROC is not a suitable figure of merit for regression models. A better typical choice would be e.g. mean squared error, in your case sqrt (mean ((test$Sepal.Length - prediction)^2))

How can I get the accuracies for every fold and for the entire model?

Your error[i]= error (test$Sepal.Length, prediction) is one possibility. I usually prefer to store the predicitions rather than the surrogate models' performance as that allows to look at different figures of merit afterwards, allowing better insight.
If you store the error, you need to take into account that in general test sample size can vary a bit across folds and you need to take care to properly average them ($\sqrt a + \sqrt b \neq \sqrt{a + b}$) - which depends on the figure of merit you decided to use.
Comment: Thank you, your response helped me a lot, especially your comment about the storage of error and the variation of test sample size. Thank you.

Validation of a random forest


How to test the effect of experimental condition on a "select all that apply" variable?

Question: People are randomly assigned to participate in multicultural training (treatment) or a control activity. Weeks later, they are given a list of behaviors that could benefit multiple groups: Black Americans, Asian Americans, gays and lesbians, immigrants, and Muslims. They are asked to select all activities in which they would be interested in participating.
What is the best way to analyze the effect of condition on this dependent variable? I can think of a few ways:
1. Run five logistic regression models. Using this approach, I would treat each behavior as a binary variable (1 = yes, want to participate; 0 = no, don't want to participate) on their own. This is straightforward, but the immediate problems are: first, each of these five outcome variables are related to one another, but I treat them as completely separate in this analysis; second, inflated Type I error rate due to multiple comparisons. I could adjust p-values at this point, but I generally find these methods unsatisfying and difficult to choose between one of the many possible approaches. This also doesn't allow the models to "share information" with one another, when they should—because participation for different behaviors are likely to depend on one another.
2. Run a Poisson or negative binomial model. This involves creating a count of how many behaviors the participant would like to partake in, where they can score from 0 (selected none) to 5 (selected all of them). I do not wish to use this approach, because I want to know the granularity of a specific level—not just how many overall they selected. I also do not wish to equate selecting behaviors benefitting Black and Asian Americans (count = 2) with Muslims and immigrants (count = 2, also).
3. Fit a multilevel model. This involves nesting all five variables within an individual. I define a dummy-coded variable at Level 1 (within-person) denoting the target group (e.g., Black, Asian, Muslim, etc.) and another dummy-coded variable at level 2 (between-person) denoting what condition they were in. I define a random slope and intercept within-person. The model looks like:
$Y_{ij} = \beta_{0j} + \beta_{1j}X_{ij} + \epsilon_{ij}$
$\beta_{0j} = \gamma_{00} + \gamma_{01}Z_j + u_{0j}$
$\beta_{1j} = \gamma_{10} + \gamma_{11}Z_j + u_{1j}$
Where $X$ would actually be a 4 dummy-coded variables—I have just left them off for brevity here—and $Z$ represents assignment to condition. As an lme4 formula, this is:
glmer(participate ~ group * condition + (1 + group | id), data, family = binomial)
However, I am not having good luck at getting this model to converge. At about 300 participants and 5 observations per person, I do not believe N is an issue. I'm not sure if there is a particularity about my data that is leading to convergence problems, or if there is a general issue with this model that I am overlooking. I feel as if the model is having a hard time converging on individual estimates for the effect on a ${0, 1}$ outcome for each person (where this might not be as much of an issue if I were using a Gaussian link function with a continuous outcome).
4. Some type of extended chi-square table approach? There is an R package called MCRV, but it seems like this is focused more on examining relationships between multiple "select all that apply" variables, not looking at the experimental effect of one variable on a multiple response categorical variable.
What is the best (with some justification) way to analyze the effect of an experimental condition on a "select all that apply" multiple response categorical variable?
I have seen similar questions asked on CrossValidated, but I have not found the answers to be very helpful (see How to analyse a "Check all that Apply" question, How to test for group differences in a 'select all that apply' question).
Answer: Interesting problem. If I understand this correctly, participants can choose one of the following:
    - A single behaviour;
    - Two behaviours;
    - Three behaviours;
    - Four behaviours;
    - Five behaviours.
If my counting is correct, participants can choose one behaviour in 5 different ways, 2 behaviours in 10 different ways, 3 behaviours in 10 different ways, 4 behaviours in 5 different ways and 5 behaviours in a single way - that means a total of 31 possibilities. It's possible that some of these possibilities are not represented in the data, so you have less than 31 possibilities - even so, that's a lot of possibilities!
If you didn't have so many possibilities, I guess you could have defined your outcome variable as "possibility selected by participant" (e.g., participant # 1 selected behaviours 1 and 2), in which case a multinomial logistic regression might have helped.
So it looks like you might have no option but to collapse information across all these possibilities.
Maybe there is a natural ranking of these behaviours whereby behaviour 5 is the best and behaviour 1 is the worst. Then you could assign ranks to each behaviour (e.g., behaviour 5 receives 5 points and behaviour 1 receives 1 point) and define your outcome variable as the sum of the ranks corresponding to the selected behaviours. Then, in your modelling of this summated rank, you can control for the number of questions selected by the participants by including number of questions as a covariate in your model.
Or maybe you can single out two of the behaviours you think are most important (e.g., behaviours 1 and 2) and then define your outcome variable to have the categories: "behaviour 1 (by itself or in conjunction with any or all of the behaviours 3, 4 or 5 but not in conjunction with behaviour 2)", "behaviour 2 (by itself or in conjunction with any or all of the behaviours 3, 4 or 5 but not in conjunction with behaviour 1)", "behaviours 1 and 2 together (by themselves or in conjunction with any or all of the behaviours 3, 4 or 5), "all other sets of behaviours". Then you have a more maneageable number of mutually exclusive categories which you can model via multinomial regression.
I guess you have to define your outcome variable in a way that reflects your research question while acknowledging the challenges involved in the data. I just wanted to share some ideas in case they might prompt you to think differently about your problem.


How do I modify a core field to use Ajax and add markup?

Question: I am still getting the hang of D8... I have some entity types with various reference fields. I need to ajax in other values from another node type when changing the value of the entity reference select field I have.
Node type form 1:
#####################################
#  _____                            #
# |Title|                           #
#  ___________                      #
# |Description|                     #
#  _______________________________  #
# |Node type 2 select reference |v| #
#                                   #
#####################################

Whenever I select a node from the Node type 2 select reference field I would like to Ajax in a specific view mode of the node as #suffix markup. After selecting a node the resulting form should look like this:
#####################################
#  _____                            #
# |Title|                           #
#  ___________                      #
# |Description|                     #
#  _________________________        #
# |Some node (node id: 2) |v|       #
#                                   #
#  * Node 2 value from field 'a'    #
#  * Node 2 value from field 'b'    #
#                                   #
#####################################

I have attempted using #ajax property in a hook_form_alter on the select field but am not getting it to work due to errors. What is the best approach here?
Comment: Your approach sounds good (there are others, but they'll need more code). If you can edit the question and include the code + errors I'm sure someone will be able to point you in the direction
Answer: After much testing and finding a missing character in one line even I was able to come up with some working code:
<?php
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;

function fsed_entry_form_eform_submission_fsed_entry_submit_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['field_faculty_member']['widget']['#ajax'] = array(
    'event' => 'change',
    'callback' => 'fsed_entry_faculty_member_ajax_callback',
    'wrapper' => 'faculty-member-details-wrapper',
  );
  $form['field_faculty_member']['widget']['#prefix'] = '
';
  $form['field_faculty_member']['widget']['#suffix'] = '
';
}

function fsed_entry_faculty_member_ajax_callback($form, &$form_state) {
  $nid = $form_state->getValue(array('field_faculty_member', 0, 'target_id'));
  if ($nid) {
    $view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
    $storage = \Drupal::entityTypeManager()->getStorage('node');
    $node = $storage->load($nid);
    $build = $view_builder->view($node, 'eform_preview');
    $output = render($build);
  }
  else {
    $output = '';
  }

  $form['field_faculty_member']['widget']['#suffix'] = $output . '
';

  return $form['field_faculty_member']['widget'];
}


Overload sumOf and use both prewritten and my own simultaneously in Kotlin

Question: Suppose I have next class:
data class IntHolder(val x: Int) {
    operator fun plus(other: IntHolder) = IntHolder(x + other.x)
}

And an extension function Iterable<T>.sumOf((T) -> IntHolder):
@OptIn(ExperimentalTypeInference::class)
@OverloadResolutionByLambdaReturnType
inline fun <T> Iterable<T>.sumOf(f: (T) -> IntHolder) = fold(IntHolder(0)) { acc, i -> acc + f(i) }

How can I use both Iterable<T>.sumOf((T) -> Int) (which is from kotlin.collections) and my own Iterable<T>.sumOf((T) -> IntHolder) simultaneously?
The next code (all together) doesn't compile:
import kotlin.experimental.ExperimentalTypeInference

data class IntHolder(val x: Int) {
    operator fun plus(other: IntHolder) = IntHolder(x + other.x)
}

@OptIn(ExperimentalTypeInference::class)
@OverloadResolutionByLambdaReturnType
inline fun <T> Iterable<T>.sumOf(f: (T) -> IntHolder) = fold(IntHolder(0)) { acc, i -> acc + f(i) }

fun main() {
    val range = 1..5
    val a = range.sumOf { it * 2 }  //here is an error
    val b = range.sumOf { IntHolder(it * 2) }
}

It says

C:\my\kotlin\src\Test.kt:13:27
Kotlin: Type mismatch: inferred type is Int but IntHolder was expected

I thought the compiler will understand which version of sumOf I want to use, because lambdas returning type differs from ones from kotlin.collections.
If it's impossible to achieve what I want, please explain the reasons, I don't get it. I was absolutely sure that it might be fixed just by one more import, but I failed at it.
Comment: Maybe it's because the standard `sumOf` doesn't have `@OverloadResolutionByLambdaReturnType` according to https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/sum-of.html? Though I don't know why it works at all in this case.
Comment: It does, I found this annotation in `kotlin.collections.sumOf` sources and copied it into my example, but it didn't help.
Comment: Ah, just not shown then.
Answer: Use an import alias!
import kotlin.collections.sumOf as classicTasteSumOf

and refer to it with that function name instead. (You can do alt+enter on the function name and do it automatically too)
Comment: Oh, you mean you want the compiler to see you're passing lambda that returns an ``IntHolder``, so it automatically resolves to the ``IntHolder`` version of ``sumOf``? Yeah honestly I'm not sure why it doesn't - you might want to edit your question so it's more about overload resolution, and see if some of the language experts know anything. The spec is here: https://kotlinlang.org/spec/overload-resolution.html and it explains the process of resolving them, but it's beyond me I'm afraid!
Comment: Well, it's a simple workaround, right, but maybe it's possible without renaming? I mean, It would be nicer to use `sumOf` everywhere, without thinking of which version I really need here.
Comment: That's exaclty what I want. Probably I should create a new question instead of modifying this one because it changes current question a little. Thanks for the reply!
Answer: The easiest way to achieve this is to copy the sumof Int->Int to your code
import kotlin.experimental.ExperimentalTypeInference

data class IntHolder(val x: Int) {
    operator fun plus(other: IntHolder) = IntHolder(x + other.x)
}

@OptIn(ExperimentalTypeInference::class)
@OverloadResolutionByLambdaReturnType
inline fun <T> Iterable<T>.sumOf(f: (T) -> IntHolder) = fold(IntHolder(0)) { acc, i -> acc + f(i) }

inline fun <T> Iterable<T>.sumOf(selector: (T) -> Int): Int {
    var sum: Int = 0.toInt()
    for (element in this) {
        sum += selector(element)
    }
    return sum
}

fun main() {
    val range = 1..5
    val a = range.sumOf { it * 2 }  //here is an error
    val b = range.sumOf { IntHolder(it * 2) }
}

or to use an import alias
Comment: As you might know, there is a bunch of overloaded versions of sumOf, one for each built-in data type, and I don't really want to copy-paste them. It's good as a workaround, but not as a solution I'm looking for.


How do I allow only the owner of a an item to do something with it?

Question: Could anyone explain to me how to do it? I've been trying for a while without managing to do it. I am just trying to restrict permissions so that not anyone with the right link can edit/delete a particular object
models.py:

class Items(models.Model):

    author = models.ForeignKey(
        'auth.User', on_delete=models.CASCADE, null=True)
    name = models.CharField(max_length=256)
    description = RichTextField(blank=True, null=True)
    url = models.URLField(null=True, blank=True)
    image = models.ImageField(null=True, blank=True)

    class Meta:

        ordering = ['name']

    def __str__(self):
        return self.name

and
views.py

class SiteList(ListView):
    model = Items

class SiteUpdate(LoginRequiredMixin, UpdateView):
    model = Items
    form_class = SiteUpdateForm
    success_url = reverse_lazy('portfolio:sitelist')

class SiteDelete(DeleteView):
    model = Items
    success_url = reverse_lazy('portfolio:sitelist')

Answer: You can implement a get_object() (see the inheritance hierarchy) that enforces this.
class MustBeAuthorGetObjectMixin:
    def get_object(self):
        obj = super().get_object()
        if obj.author != self.request.user:
            raise PermissionDenied("...")
        return obj

# ...

class SiteUpdate(MustBeAuthorGetObjectMixin, LoginRequiredMixin, UpdateView):
   # ....

This way, when UpdateView (well, BaseUpdateView) calls self.get_object(), it'll get your version which has the permission check.


Calculate the height of the cone from the frustum's bottom and top radius and frustum height.

Question: Given the following diagram of a cone frustum, with the top radius of 5cm, the bottom radius of 9cm and the height of the frustum being
8cm, what is the height of the original cone? Don't use a method that involves using rise/run or gradient calculations in any way shape or form.
I have tried to attempt this many times, but I am extremely lost still - and don't understand it. I have tried to do some scuffed calculation using squaring and fractions like this:
(OH is Original Cone Height)
$$
OH \equiv \frac{h + 8}{9} + \frac{h}{5}
$$
Which then must mean:
$$
OH \equiv \frac{h^2+8}{4}
$$
Which somehow gets me 18, which my teacher says is the full cone height.
How did I do this, and does this work for everything? If not, what is a good equation that matches the rule set of the question asked.
Thanks,
Henry.
Diagram of Frustum Image
Answer:
The figure above summarizes the situation.  We have two similar triangles, the big one with height $h$ and base $9$, and the small one with height $(h-8)$ and base $5$.
Therefore, by equal ratios of similar triangles corresponding sides, we have
$ \dfrac{h}{h-8} = \dfrac{9}{5} $
From which
$ 5 h = 9 h - 72 $, so that $h = \dfrac{72}{4} = 18 $
Comment: Do you mind elaborating on where you got the very first fraction from? And how did I get what I got… sorry, I am Sophomore level in HS so I don't understand that much.
Comment: @Psuedodoro Check my updated solution.
Comment: Thanks so much, this clears it all up for me!

Calculate the height of the cone from the frustum’s bottom and top radius and frustum height.


Handlebar get request object

Question:
Request object is populated in servlet.
req.setAttribute("Files", fileMap);

In jsp, I could iterate it by below code:
<c:forEach items="${Files}" var="file">
    <option value="${file.key}">${file.value}</option>
</c:forEach>

How could I iterate it inside Handlebar template?
Answer: You can iterate over a list using the built-in each helper. Inside the block, you can use this to reference the element being iterated over.
Try this
<select>
  {{#each Files}}
    <option value={{@key}}>{{this}}</option>
  {{/each}}
</select>

Comment: @NabarunDey answer updated. hope it will solve your problem.

Handlebar get request object


Showing a branch which i not even there in Github

Question: The repo have only one branch(i.e, main) is also the default one but while opening the files it is showing a branch name 'b3c52f83e0'.
What's the issue?
Answer: It would be not the name of a branch, but a SHA1 of a commit.
Check your GitHub project commits history and see if that commit does exist.
You cal also check that locally by cloning the same repository, and using  git log.


If a sequence converges to an irrational number, prove that different sets of the sequences are not bounded.

Question: Sorry for the oddly worded title. The original was too long, so I had to try and shorten it as best as I could.
Here is the question:
Let $a∈(0, 1)$ be an irrational number and suppose there exists a sequence
$r_n = \frac {p_n} {q_n}$ with
$p_n$, $q_n ∈  \Bbb N$ and $\lim_{n\to \infty} r_n = a$.
Show that both $\{p_n : n ∈ N \}$ and $\{q_n : n ∈ N \}$ are not bounded
Suppose $a∉\Bbb Q, a∈(0, 1),$ and sequence $r_n = \frac {p_n} {q_n} \to a$, with $p_n, q_n∈ \Bbb N$. Show that both $\{p_n:n∈\Bbb N\}, \{q_n:n∈\Bbb N\}$ are not bounded.
I'm pretty confused by the question. I'm not sure where to begin. Any help would be much appreciated.
Answer: Suppose $\{p_n\}$ is bounded.
If $\{q_n\}$ is also bounded, then the set $\{\frac{p_n}{q_m} \mid n,m \in \Bbb N\} \subset \Bbb Q$ is finite, thus it cannot have an irrational limit point.
So $\{q_n\}$ must be unbounded. But then, there exists a subsequence $q_{n_k} \to \infty$. Thus $\frac{p_{n_k}}{q_{n_k}}\to 0$, which contradicts $a \in (0,1)$.
If you suppose first that $\{q_n\}$ is bounded, you'll get the same contradictions with $\frac{q_n}{p_n} \to \frac{1}{a}$.
Comment: I'm confused about the end. If q_n is bounded and p_n is not, wouldn't the limit go to infinity? @Nitrogen
Comment: @eulersnumber Yes, of course.  But that's also a contradiction since no converging sequence can have a subsequence with limit $\infty$.
Comment: Rad. Thanks! I guess I am confused about how if {q_n} is bounded that that implies q/p --> 1/a.


in c++ I have 2 struct and wants to pass to the same function

Question: I would like to ask if is it possible doing the following in c++:
I have this 2 struct
struct RegistroPyF {
    int Fecha=0;
    int ups=0;

};
struct BuySigPyF {
    int columna=0;
    int fecha=0;

};

An I would like to pass it to a function.
void CreaTabla(struct ,const char *base, string accion){};

And calling like:
CreaTabla(RegistroPyF ,const char *base, string accion);

or
CreaTabla(BuySigPyF ,const char *base, string accion);

How could I define a structure in a function so when I call it I can use either of the struct?
Comment: Overloading would allow you to get the two calling notations; you just need to define two different functions that take the different structs as the first argument. That said, I have no idea what you are asking with _"How could I define a structure in a function so when I call it I can use either of the struct?"_. Could you clarify? Why would you be defining the structure in the function?
Comment: You need to be more specific on your function declaration.  There can be an unlimited quantity of `struct`, each one different.  Try something like `void CreaTabla(const RegistroPyF&, const std::string& base, const std::string accion);`
Comment: Since the members are in different orders, I would move the common code out of `CreaTabla` into a `CreaTabla_helper` and then have two overloads of `CreaTabla` to handle the struct specific code.
Comment: How would you know, in the function, which structure was passed?
Comment: I think this question needs to detail _the problem being solved_.  There are many ways to allow a function to take varying parameter types.  Which approach to use depends on _what you are trying to do_.  If the question is really "if it is possible", the answer is Yes.
Comment: Hi, thanks for the answers.
Comment: to be more precise. I have several structs (just put two for example) with different types. The idea is to use one function to cread and manage a table that has the types of the struct as columns. So I wanted to use just one function to perform the task but give me the liberty to use whichever struct need.
Answer: You could accept both:
void createTable(RegistroPyF *p1, BuySigPyF *p2, const char *base, string accion) {
}

And then call either like so:
RegistroPyF  registro;
BuySigPyF buy;

createTable(&registro, nullptr, "foo", "bar");
createTable(nullptr, &buy, "foo", "bar");

You could also use a void * and figure out what type it is, but I consider that dangerous.


symplectisation of a manifold

Question: I have a contact form $\alpha$ on a manifold $M$.
I have to show that the $2$-form $d(e^tp^*\alpha)$ is symplectic where $e^t:\mathbb{R}\times M\rightarrow \mathbb{R}:(tx)\mapsto e^t$ and $p:\mathbb{R}\times M\rightarrow M$.
Any hints to get me started?
closed is obvious but for degenerate less. The problem for me is that the calculations mix the two different views of 2-forms and that I can't seem to unify them. I.e. forms as maps from vector fields to maps and forms as sections of $\Lambda^rT^*M$.
Answer: Hint: $T(\Bbb R\times M)=\Bbb R \partial t \times \Bbb RR \times \ker \alpha$, where $R$ is a reeb vector field and let $\omega = e^t dt\wedge\alpha + e^t d\alpha$. Show that every vector $v$ which is purely in one of these factors, there exists a vector $v'$ with $\omega(v,v') \ne 0$.
Answer: I will suppose that $M$ is $2n-1$ dimensional.
Another approach would be to write $\omega = e^t dt \wedge \alpha + e^t d\alpha$ and then expand $\omega^n$. Recall that $\alpha$ is a contact form if and only if $\alpha \wedge (d\alpha)^{n-1}$ is a volume form.
When you expand $\omega^n$, you will find useful that $(dt \wedge \alpha)^2=0$.

symplectisation of a manifold


MySQL - listing multiple properties

Question: I have two tables in my database: AppropriateFor and AquariumModel, shown below. They share three keys - AquariumType, Salinity, and Volume. I am attempting to find all aquarium models that are considered appropriate for more than one species. I'm struck trying to correctly count the primary tuple in AppropriateFor and then join it with the AquariumModel table.
The AppropriateFor table has four columns: speciesName, aquariumType, salinity, volume:
RED-BELLIED PACU                AGGRESSIVE  FRESHWATER  300
GOLDEN MORAY EEL            AGGRESSIVE  MARINE      25000
NURSE SHARK                 AGGRESSIVE  MARINE      25000
COMMON TOADFISH             COMMUNITY   BRACKISH    150
DRAGON GOBY                 COMMUNITY   BRACKISH        150
BRONZE CORYDORAS            COMMUNITY   FRESHWATER  250
COMMON DISCUS               COMMUNITY   FRESHWATER  250
SPOTTED RAPHAEL             COMMUNITY   FRESHWATER  250
UPSIDE-DOWN CATFISH         COMMUNITY   FRESHWATER  250
BLUESPOTTED ANGELFISH       COMMUNITY   MARINE      50000
CHALK BASS                  COMMUNITY   MARINE      50000
FLAME ANGELFISH             COMMUNITY   MARINE      50000
ORIENTAL SWEETLIPS          COMMUNITY   MARINE      50000
ROUND STINGRAY              COMMUNITY   MARINE      50000
ROYAL ANGELFISH             COMMUNITY   MARINE      50000
TEIRA BATFISH               COMMUNITY   MARINE      50000
BARTLETTS ANTHIAS           REEF        MARINE      75000
BELLUS ANGELFISH            REEF        MARINE      75000
CHALK BASS                  REEF        MARINE      75000
COPPERBANDED BUTTERFLYFISH  REEF        MARINE      75000
MANDARINFISH                    REEF        MARINE      75000
COMMON TOADFISH             SPECIES     BRACKISH    100
GREEN SPOTTED PUFFER        SPECIES     BRACKISH    100
REEDFISH                    SPECIES     BRACKISH        100
ELECTRIC EEL                    SPECIES     FRESHWATER  500
ORNATE BICHIR               SPECIES     FRESHWATER  500
REEDFISH                    SPECIES     FRESHWATER  500
BRAZILIAN SEAHORSE          SPECIES     MARINE      10000

AquariumModel has four columns as well: aquariumType, salinity, volume, price:
AGGRESSIVE  BRACKISH    125    200
AGGRESSIVE  FRESHWATER  300    500
AGGRESSIVE  MARINE      25000  4500
COMMUNITY   BRACKISH    150    250
COMMUNITY   FRESHWATER  250    400
COMMUNITY   MARINE      50000  7000
REEF        MARINE      75000  10000
SPECIES     BRACKISH    100    150
SPECIES     FRESHWATER  500    800
SPECIES     MARINE      10000  3000

Comment: OP, I know my answer has already been accepted, but I added an SQL Fiddle for you as well as a comment on your database design.
Answer: I think you can start by joining the two tables together on the values that you need, which would start like this:
SELECT *
FROM aquariummodel am
JOIN appropriatefor af ON am.aquariumtype = af.aquariumtype AND am.salinity = af.salinity AND am.volume = af.volume;

Then, you want to group by all the values in aquarium type, and use the condition that the count is greater than 1. So I would then change the query to this:
SELECT am.*, COUNT(*) AS numFishAppropriateFor
FROM aquariummodel am
JOIN appropriatefor af ON am.aquariumtype = af.aquariumtype AND am.salinity = af.salinity AND am.volume = af.volume
GROUP BY am.aquariumtype, am.salinity, am.volume
HAVING COUNT(*) > 1;

EDIT
Here is an SQL Fiddle to demonstrate that it works.
If I may, I would like to comment on the design of your database.
In the appropriate for table, you have several columns that are repeated from the aquariummodel table. I would add a primary key to your aquariummodel table (like an auto_increment id) and use that id in the appropriate for table. That way, aquariummodel would have 5 columns, but appropriatefor could be cut down to two columns: speciesname and aquariummodel_id. Just a suggestion though.
Comment: Working on SQL Fiddle to test now. Just need time to input data.

MySQL - listing multiple properties


std::getline throwing when it hits eof

Question: std::getline throws exception when it gets an eof.
this is how I am doing.
std::ifstream stream;
stream.exceptions(std::ifstream::failbit|std::ifstream::badbit);
try{
  stream.open(_file.c_str(), std::ios_base::in);
}catch(std::ifstream::failure e){
  std::cout << "Failed to open file " << _file.c_str() << " for reading" << std::endl;
}
while(!stream.eof()){
  std::string buffer = "";
  std::getline(stream, buffer);
  //process buffer
  //I do also need to maintain state while parsing
}

In the above code getline is throwing exception as it gets eof
How to handle this situation ?
EDIT
std::string buffer = "";
while(std::getline(stream, buffer)){
    //also causes getline to hit eof and throw
}

Comment: You are asking for an exception. After hitting `eof`, the stream is in a `bad` state.
Comment: [Why is iostream::eof inside a loop condition considered wrong?](http://stackoverflow.com/q/5605125/500104)
Comment: Side note: the structure of the loop is incorrect as you need to check `eof()` immediately after the `std::getline()`.
Comment: 'How to handle this situation'. That depends on what you want to do, you haven't explained yourself very well. Do you want to not have an exception? Do you want to catch the exception, and if you want to catch it what do you want to happen next? Please explain what you are trying to do.
Answer: You activate the exception handling of your stream at the very beginning of your code:
stream.exceptions(std::ifstream::failbit|std::ifstream::badbit);

Now if the extraction of formatted data such as floating-point values, integers or strings will fail, it will set the failbit:
eofbit    indicates that an input operation reached the end of an
          input sequence;
failbit   indicates that an input operation failed to read the expected
          characters, or that an output operation failed to generate the
          desired characters.
While getline(stream,buffer) will indeed set the eofbit if it reaches the end of a file, it will also set the failbit, since the desired characters (a line) couldn't be extracted.
Either wrap another try-catch-block around your loop or disable the failbit exception.
Example:
#include <iostream>
#include <fstream>

int main(){
  std::ifstream stream("so.cc");
  stream.exceptions(std::ifstream::failbit|std::ifstream::badbit);
  std::string str;

  try{
    while(std::getline(stream, str));
  }catch(std::ifstream::failure e){
    std::cerr << "Exception happened: " << e.what() << "\n"
      << "Error bits are: "
      << "\nfailbit: " << stream.fail()
      << "\neofbit: " << stream.eof()
      << "\nbadbit: " << stream.bad() << std::endl;
  }
  return 0;
}

Result:
Exception happened: basic_ios::clear
Error bits are:
failbit: 1
eofbit: 1
badbit: 0
Note that both eofbit and failbit are set.
See also:

std::ios_base::iostate
Table 124 in § 188.8.131.52.5 (see above)
Comment: If you use `getline(std::istream,std::string)`, then the only reason for it to fail to extract the string will be an EOF. I suggest you to actually disable throwing an exception on `std::ifstream::failbit`. Of course you can use a silent catch block. There are many ways to handle such things, choose the one that suits you best.
Comment: So should I place a silent catch block around `getline` ?
Comment: I want the `getline` read the stream into buffer as long as it doesn't fetch `eof. once it fails due to `eof` I want the control to come below `getline` because I've states of previous lines kept previous iterations.
Answer: As you said, calling getline when the stream is currently positioned on the blank line at the end of the file will set both eofbit (because it reaches the end of file) and failbit (because nothing could be extracted, not even the line delimiter).
So, if you have set the stream to throw exceptions when failbit is set, you get an exception thrown when reading that blank line.
To prevent that, you can peek for the next character on the stream before calling getline:
std::string buffer = "";
while(stream.peek() != EOF && std::getline(stream, buffer)){
    //do something with the buffer
}

Comment: Did not have luck with this approach; I still get an exception after the peek.

std::getline throwing when it hits eof