Scale, Heptatonic Scale, Diatonic Scale, Major Scale

Question: A scale with 7 notes, in an octave, is called a Heptatonic Scales.
Heptatonic scales are further divided based on tone and semitones arrangements.
If a Heptatonic scale have five tones and two semitones, where the two semitones are separated from each other by either two or three tones, then it's called Diatonic Scale or Diatonic Heptatonic Scale.
Diatonic Scales are further divided based on more specific tones and semitones arrangements. If the arrangement between five tones and two semitones is TTSTTTS then the Diatonic scale is called a Major Diatonic scale.
Did I get it right so far?
Answer: Yes you are correct, I'll just put it in simpler terms.
The major scale is both diatonic and heptatonic.
Heptatonic just means that there are 7 notes per octave in the scale.
The diatonic scales just a name for the specific name for scales that contain a specific whole step, half step pattern TTSTTTS in some way, shape, or form.
All the 7 natural modes of the major scale are diatonic because they are all based off the same whole step. half step pattern:

Major/Ionian    TTSTTTS
Dorian          TSTTTST
Phrygian        STTTSTT
Lydian          TTTSTTS
Mixolydian      TTSTTST
Minor/Aeolian   TSTTSTT
Locrian         STTSTTT
Comment: @iamcreasy: The seven modes include the major scale / ionian mode. In total there are seven modes, simply because there are seven different notes in a diatonic scale.
Comment: In the last line, '7 natural modes of major scale...', is it correct? I thought Diatonic scale has 7 modes, and major scale is a one of the modes.
Comment: A scale is recognizable by its mode.

Google defines a mode as "a way or manner in which something occurs or is experienced, expressed, or done."

This means a scale's mode refers to the way the notes move forward—its unique scale step pattern.

So while a diatonic scale indeed has seven possible modes, the major scale (i.e., Ionian mode) has but one.
Answer: As already mentioned in Dom's answer, everything you wrote is correct. I'd just like to add a few things concerning the term diatonic.
As you said, one meaning of "diatonic scale" is a scale with five whole tones and two half tones where the two half tones are maximally separated, i.e. at least by two whole tones. This includes the major scale and all its modes, and, consequently, also the natural minor scale.
However, this definition would exclude the melodic minor scale, which also has five whole tones and two half tones, but the two half tones are separated by only one whole tone. Also the harmonic minor scale would be non-diatonic according to this definition, because it has one augmented second. So there is also a more inclusive usage of the term diatonic scale, which includes these two other forms of the minor scale as diatonic. Since it seems that there's no generally accepted definition of diatonic scale (either including or excluding the melodic and harmonic minor scales), this is a source of confusion.
One nice property of diatonic scales, in the narrow, exclusive definition, is the fact that they can be generated by stacking perfect fifths on top of each other. E.g., if you take the sequence of perfect fifths F-C-G-D-A-E-B you get all notes of the C major scale. If you take F as the root, you get F lydian. This property of the lydian scale, that it can be generated by stacking six perfect fifths on top of each other, was the main motivation for viewing the lydian scale as the fundamental scale in George Russell's Lydian Chromatic Concept.
Comment: Interesting last para. Surely the same reasoning could be used for any mode, as taking C as mother, D Dorian has the same notes. As has E Phrygian, etc., all made from stacked 5ths?
Comment: @Tim: If you stack six perfect fifths on top of each other you always get the lydian scale with the lowest note as the root. If you want another mode, you need to find the relative lydian scale and start stacking with the root of that lydian scale. E.g., if you want the notes of A dorian, you need to find the lydian scale with the same notes, which is C lydian, and then you can start stacking six perfect fifths starting from C to get the notes of A dorian.
Comment: Thanks for that. What I don't get now is which is the lowest note. There's F,C,G,D,A,E and B in order, so is F, as the first, deemed to be the lowest?
Comment: @Tim: Yes, F up to C is a perfect fifth. Down to the next lower C would be a perfect fourth.
Comment: It would be nice to put that "you get the lydian scale **if you take the lowest note (F) as the root**" into the answer, because without that the argument of _"This property of the **lydian** scale, that it can be generated by stacking six perfect fifths"_, following the "get the notes from the fifths" part is indeed confusing, especially because the paragraph starts with _"One nice property of **diatonic** scales ... is the fact that they can be generated by stacking perfect fifths"_. (At least it did confuse me, too, exactly the same way as @Tim. :) ) The answer is otherwise great (+1ed).


Find line orthogonal to another line passing through point p in R³

Question: So in R³, given a line $G$ in parameter form and a point Q, how do I compute the line passing through Q that is orthogonal to $G$?
In order for two vectors to be orthogonal, the dot product has to be zero. Also, for a point to be located on a line, inserting the point into the line equation must result in equality, right? Not quite sure how to use this for the task.
A hint to get me on the right track would suffice
Answer: Let $G: \mathbf{a}+\alpha \mathbf{b}$ and let $\mathbf{q}$ be the vector from the origin to the point $Q$. Then determine the point on $G$ which is closest to $Q$ by minimizing the distance:
$$d=(\mathbf{q}-\mathbf{a}-\alpha\mathbf{b})^T(\mathbf{q}-\mathbf{a}-\alpha\mathbf{b})$$
This gives you a quadratic equation in $\alpha$ which can be easily minimized by taking the derivative w.r.t. $\alpha$ and setting it to zero. The result is
$$\alpha_0=\frac{ \mathbf{b}^T(\mathbf{q}-\mathbf{a})}{ \mathbf{b}^T\mathbf{b} }$$
So we have a point on $G$ and on the desired line $H$:
$$\mathbf{c}=\mathbf{a}+\alpha_0\mathbf{b}$$
Then the line $H$ can be parametrized by
$$H: \mathbf{c}+\beta(\mathbf{q}-\mathbf{c})$$
Comment: sorry, but the $^T$ puzzles me a bit. Besides that, good answer, will try it asap
Comment: the $^T$ just means transpose, i.e. $\mathbf{x}^T\mathbf{y}$ simply is the dot product of vectors $\mathbf{x}$ and $\mathbf{y}$ (at least in my weird notation).
Comment: That's really weird, but thanks :D
Comment: Well, it's basically matrix notation, i.e. row vector times column vector will give you a scalar, which is the dot product between the two vectors.
Answer: For $P \in G$, compute $\vec{PQ}$ (which depends on the parameter $\lambda$). Then $\vec{PQ} \cdot \vec{G}=0$ (where $\vec{G}$ is the direction of $G$) is a linear equation in $\lambda$.
If $G=\{\lambda (g_x, g_y, g_z) + (p_x, p_y, p_z)\}$ and $Q=(q_x, q_y,q_z)$, then $\vec PQ=(\lambda g_x + p_x -q_x, \lambda g_y + p_y -q_y, \lambda g_z+ p_z -q_z)$ and $\vec PQ \perp G$ iff $g_x(\lambda g_x + p_x -q_x)+g_y(\lambda g_y + p_y -q_y+ g_z(\lambda g_z+ p_z -q_z)$.
That is, iff $\lambda (g_x^2 + g_y^2 + g_z^2) = g_x(p_x-q_x)+g_y(p_y-q_y)+g_z(p_z-q_z)$.


Onclick apontar para função com $_SERVER

Question: Devido a uma necessidade obscura do sistema, ao clicar em um botão, preciso saber o IP que acionou o mesmo para direcionar a página correta. Com $_SERVER['REMOTE_ADDR'] tenho essa informação. Mas como poderia passar isso para um JS ? Mais ou menos dessa forma:
document.getElementById('LIMPAR').onclick = function() {
      if ($_SERVER['REMOTE_ADDR'] == 'XXX') {
         location.href = '1';
      } ELSE {
         location.href = '2';
      }
}

Testando a lógica acima, não tive sucesso. Alguma sugestão?
Comment: Talvez no atributo onclick do botão limpar, chamar uma função para fazer esse redirecionamento, passando como parametro o $_SERVER['REMOTE_ADDR'] vindo direto do PHP na hora de montar o HTML.
Answer: Você está tentando acessar uma variável do contexto do PHP, server, no lado cliente, javascript.
Tente algo assim:
document.getElementById('LIMPAR').onclick = function() {
  var ip = '<?php echo $_SERVER['REMOTE_ADDR']; ?>';
  if (ip == 'XXX') {
    location.href = '1';
  } ELSE {
    location.href = '2';
  }
}

Comment: Exato, dessa forma de certo. Obrigado.


Verificação de extensão do arquivo e mudar o seu diretório

Question: Estou com problema em um script python que verifica se existem arquivos com alguma extensão específica no diretório e move todo o diretório para um outro destino
Isto é um teste para automatizar o processo de mover um diretório para outro lugar dependendo de sua extensão, mas eu só consigo realizar isso se todos os arquivos possuírem a mesma extensão, caso contrário, mesmo que exista somente um arquivo com a extensão desejada ele não realiza a mudança de diretório.
Conteúdo do diretório 'testar_mover_diretorio':
arquivo_texto.txt
arquivo_python.py
import os, shutil

def verificar_dir(diretorio, extensao, destino):
    if (os.path.exists(diretorio) == True):
        for pasta, subpastas, arquivos in os.walk(diretorio):
            for arquivo in arquivos:
                extensao_arquivo = arquivo.endswith(extensao)
                if (extensao_arquivo == True):
                    result = ('Existem arquivos com a extensão {} na pasta').format(extensao)
                    if (os.path.exists(destino) == True):
                        shutil.move(diretorio, destino)
                    else:
                        result = 'O diretório de destino não existe'
                else:
                    result = ('Não existem arquivos com a extensão {} na pasta').format(extensao)
        return print(result)

    else:
        print('Este diretório não existe')

diretorio = input('Qual é o diretório que você deseja verificar? ')
extensao = input('Qual é a extensão que você procura? ')
destino = input('Qual será o destino deste diretório? ')
print('')

verificar_dir(diretorio, extensao, destino)

Exemplo: Eu tenho uma pasta 'teste_mover_diretorio' na área de trabalho com arquivos '.txt' e '.py' e quero mover ela para o diretorio 'Projetos', mas o script não realiza a mudança mesmo havendo um arquivo '.py' dentro da pasta.
Comment: esse script tem alguns problemas, mas o código como está vai fazer a udança quando achar o _primeiro_ arquivo com a extensão desejada. (eu nem sei se ele não quebra imediatamente após isso). Definitivamente esse código acima não vai fazer a ação "somente se todos os arquivos tiverem a extensão desejada". Ou o código está diferente do que você roda aí, ou a pergunta não está clara.
Answer: Para versões iguais ou superiores a 3.4 da linguagem utilize o pacote pathlib para gerenciar diretórios e arquivos. A API dele é mais direta e simples que a fornecida pelo pacote os.

Para abrir um diretório, use foo = pathlib.Path('./foo');
Para buscar arquivos com determinada extensão, use foo.glob('*.py');
Se retornar pelo menos um arquivo, renomeie o diretório;

Em código ficaria algo como:
from pathlib import Path

foo = Path('foo')

for _ in foo.glob('*.py'):
    foo.rename('bar')
    break
else:
    print('Nenhum arquivo .py encontrado')

Assim, se você possuir o diretório:
/foo
    main.py

Ao rodar o programa terá
/bar
    main.py

Mas cuidado com as condições de corrida se houverem múltiplos processos manipulando o mesmo diretório de forma paralela.
Comment: Muito obrigado! Não conhecia esta API, pesquisarei mais sobre ela e suas funcionalidades. O código fica bem mais amigável e simples


Adicionar +1 min ao cronômetro regressivo - Com timer já finalizado ou em andamento

Question: Cada vez que eu clicar em um botão, quero adicionar +1 min ao timer.
<Button
    onPress={this.somarUmMinuto}
    title="Somar 1 minuto"
    color="#007FFF"
    accessibilityLabel="Somar 1 minuto"
/>

Código utilizado para definir a contagem regressiva:
iniciarCronometro() {
    var intervalId = setInterval(this.somarUmSegundo, 1000);
    this.setState({
      intervalId: intervalId,
    });
}

somarUmSegundo() {
    let segundos = this.state.contadorSegundo;
    let minutos = this.state.contadorMinuto;

    minutos == 1 || segundos > 0;
    if (segundos == 0) {
      segundos = 59;
      minutos = minutos - 1;
    } else {
      segundos = segundos - 1;
    }

    this.setState({
      contadorSegundo: segundos,
      contadorMinuto: minutos,
    });
}

Preciso incrementar o evento para adicionar +1 min ao timer, seja com ele já finalizado ou ainda em andamento na contagem.
Cronometro regressivo tem duração de 1 minuto.
Comment: Veja se esse código ajuda: http://jsfiddle.net/alnitak/aBWce/
Comment: Você  já separou os minutos e segundos (contadorMinuto e contadorSegundo), não entendi qual é realmente o problema. Não é só ir no contadorMinuto e incrementar?
Comment: @JrD tentei fazer o incremento direto no contador minuto, mas da erro. Utilizei ´code´ let somar = (this.contadorMinuto +1);
Comment: @PhilipeSaid O seu contadorMinutos está no estado da aplicação, então pra acessá-lo vc precisa usar o this.state. No lugar desse código que vc apresentou tente let somar = this.state.contadorMinuto + 1
Comment: @JrD Continua dando o erro ( undefined is not an object ( evaluating'this.state.contadorMinuto') ).
Comment: @PhilipeSaid Provavelmente vc está perdendo o contexto... faça o bind do seu método para poder acessar o state através do this. Seu onPress ficaria assim onPress={this.somarUmMinuto.bind(this)}
Comment: @JrD O erro não acontece mais. Porém, não executa o incremento do valor.
Comment: @PhilipeSaid Atualize seu código aí por favor para ver o que acontece, esses comentários já estão ficando muito extensos
Answer: Primeiramente é preciso fazer um bind no onPress do botão para que seja possível acessar o estado da aplicação, seria dessa forma:
onPress={this.somarUmMinuto.bind(this)}

Depois é preciso criar a função para esse incremento:
somarUmMinuto(){
    this.setState({
        contadorMinuto: this.state.contadorMinuto + 1,
    });
}

Comment: Minha função estava completamente errada. Obrigado


Xamarin.Auth Android Native UI not working

Question: I am using Xamarin.Auth to authenticate to my identity provider with implicit flow on Android. I can't get the native ui (chrome custom tabs) to work with Xamarin.Auth as I get the following error:

UNHANDLED EXCEPTION: 06-30 11:40:48.903 I/MonoDroid( 7670):
  System.MissingMethodException: Method
  'Android.Support.CustomTabs.CustomTabsIntent.LaunchUrl' not found.
  06-30 11:40:48.903 I/MonoDroid( 7670):   at
  Android.App.Activity.n_OnCreate_Landroid_os_Bundle_ (System.IntPtr
  jnienv, System.IntPtr native__this, System.IntPtr
  native_savedInstanceState) [0x0000f] in
  <93e2413825534efca8b597098003b511>:0  06-30 11:40:48.903 I/MonoDroid(
  7670):   at (wrapper dynamic-method)
  System.Object:ce197f13-7701-4b2e-840f-19029a77ef6c
  (intptr,intptr,intptr) 06-30 11:40:48.913 W/art     ( 7670): JNI
  RegisterNativeMethods: attempt to register 0 native methods for
  android.runtime.JavaProxyThrowable 06-30 11:40:48.918 D/HockeyApp(
  7670): Writing unhandled exception to:
  /data/user/0/com.mycompany.myapp/files/9a7dae18-3c5a-4e97-b7cb-4a3f1581c690.stacktrace

My authenticator is set up like this:
<code>var authenticator = new OAuth2Authenticator(
    AuthSettings.ClientId,
    AuthSettings.Scope,
    new Uri(AuthSettings.AuthorizeUrl),
    new Uri(AuthSettings.RedirectUrl),
    null,
    true);
</code>
I am not using linking either.
Any ideas?
Answer: After a quick google search I came accross an issue thread on a github page for the 'SharePlugin' for Xamarin, fortunately James Montemagno is in their helping out. The issue listed is similar to yours so for reference purposes it can be found Here.
It appears to have been a fairly common issue with this method 'Android.Support.CustomTabs.CustomTabsIntent::LaunchUrl'. In that thread they obviously mention that:

Release Mode => Linker option => None , Every thing works.

So that's worth double checking, to make sure that's what you're doing. (I realise you've mentioned you've had a look at the linked assemblies, but always worth a double check).
There is also some conversation on the GitHub repository for Xamarin.Auth iteself, a particular issue found Here talks about the versions of both Xamarin Auth and Xamarin Forms, needing to match in a certain way, I would suggest updating xamarin.forms to it's latest version, and trying again, perhaps even downgrading Xamarin.Auth.

It worked with 1.5.0-alpha-03. Tried with 1.5.0-alpha-09 but it
  failed.
Comment: I have tried the linker option, and have tried different versions. Still no dice. It seems the issue is active on github, so I will probably follow that.


Problems placing analog synth on window shelf above radiator?

Question: I have recently purchased an analog synthesizer (the DSI OB-6 Desktop). Unfortunately, the only place I can place it is on a window shelf which has a water-heated radiator below it.
I have read that musical equipment should be placed away from radiators (this has previously been covered here and here) as they may cause detuning. I'm not sure if there can be other problems, like something affecting the wood or material of the instrument.
My understanding is that the detuning primarily comes from temperature changes, not heat per se.
I am therefore wondering if I'm ill-advised to place the synth at this location? Is it alright as long as the radiator is always on, or should I turn it off (at the detriment of getting a chillier room during winter)?
Furthermore, I'm also concerned that the proximity to the window will further lead to more extreme temperature changes as the temperature variability during winter can be several tens of celsius. Although thermodynamics even out temperatures in a room, I find that it can sometimes be somewhat cooler by a window.
Comment: Windows, even double glazed ones, can attract moisture, and if it's South facing, will also make the equipment get rather hot on Summer days. Where is the property?
Comment: That is an expensive and high quality instrument. If it were mine, I would happily move furniture around to make sure I had a better place to put it. In front of a window above a radiator sounds like the worst possible place. Except perhaps in a shower.
Comment: Yes, because of all the things that can happen near a window that can be bad for musical instruments. Temperature, moisture, sunlight - and that's assuming the window is never opened.
Comment: @ToddWilcox Because of moisture and/or temperature swings from the window? The radiator can be turned off if needed.
Comment: Possible duplicate of [Do instruments get out of tune when you place them near a radiator?](https://music.stackexchange.com/questions/13995/do-instruments-get-out-of-tune-when-you-place-them-near-a-radiator)
Comment: You have picked the worst possible place to put a musical instrument, acoustic or electric.  No good can come from that choice.  You say it is the only place.  I'd rearrange the room so that the instrument has a place where it is not near direct heat, sunlight, and/or moisture.
Comment: @ggcg Just to be fair, I haven't even placed it on that location yet. It's still in its box, and asked this question first. Will rearrange the room later this week. :)
Comment: That's fine, it's still a bad choice.  Glad to hear you are rearranging the room.
Answer: Whatever you do, do not put it next to a window or a radiator. Move furniture and stuff to make room for it. Also, don't put it in the basement, if you have one.
Explanations as requested:
The radiator emits heat. The window provides moisture. The heat bends the wood, and the moisture alters the wood shape. Obviously, the synth will not stay in tune.
I don't suggest the basement, because if isn't finished (and even if it is), due to wildly varying temperatures and humidity, the wood will alter shape.
This condition exists with all instruments (especially ones containing or made of wood, such as a piano or violin). If you need to put it somewhere which has highly varying temperatures and/or humidity levels, I suggest you get a humidity controller.
Comment: I agree - although some finished basements are quite safe for musical instruments. It depends on the basement, in my experience.


How to delay and queue commands for execution at a later time?

Question: My site receives numerous uploads and I can't afford to waste cycles and time processing them on the spot (e.g., trimming, optimizing, resizing, etc.). What technologies exist to delay and queue these non-essential commands for execution at a later time? Upon execution I would also like to use cpulimit to allocate a certain % and also limit memory usage.
Running Ubuntu 10.04 LTS
Comment: I edited your question to make it less like a shopping question and less subjective, both of which are off-topic.
Answer: Well, I'm not sure what the "best" is. You'll need to decide that for yourself.
You need some sort of message queue. There are many of these around: MSMQ, Gearman, RabbitMQ, Amazon SQS, etc.
Myself? I use RabbitMQ for communication between disparate parts of our application, and to queue up actions that should not be performed synchronously. It takes a bit of time to wrap your head around the difference between exchanges and queues, and to figure out how best to arrange things for your environment, but after that, it's a piece of cake to use.
Comment: Thanks. Reading about RabbitMQ now. I take it you run it in tandem with cron, which check to see if there are any messages queued and then executed them if there are?
Comment: For delayed processing, yes you could do it that way, yes. Or, you have an RMQ consumer that is always bound and "listening" to the queue for messages. When a message is placed in the queue, it can act immediately.
Comment: OK. You put me on the right path. I zeroed in on Redis + Resque, especially since I already use Redis as a memcache respacement. Thanks.


how to go from character to usable expression in R from a list?

Question: I have a data.table df with various columns x1,x2,x3,etc... (no actual pattern in the name though) and I want to generically pass in a "config" for a variable amount of columns to do something. For example, produce a list of column plots. What I envision is saying something like this:
col.plot.list <- list(list(col='x2', seg=c(0,6)), list(col='z17', seg=NULL))

then being able to pass that to a function that will return a list of plots for the columns interpreting elements of each sublist to configure the plot in different ways. In this example, something like this:
gen.plots <- function(col.plot.list) {
    lapply(col.plost.list, function(x) {
        ggplot(df, aes(cumsum(x$col)) #plus geoms & optionally leverage x$seg if not NULL
    }
}

What I'm wondering though is how to turn the string corresponding to the column name back to a usable expression that I can pass to things like df$x$col or aes(y=x$col) etc.. does something for that exist? Or is there a different type I should use to save in the original list to start with which could help? I wouldn't want to save the full column vector as that wouldn't then allow me to do data.table operations in an lapply.
Comment: You are probably referring to `get()`. See `?get`
Comment: get seems to be working too in some of my examples, thanks for the reminder on that one.
Answer: Your question is not very clear, but maybe this example is useful. Basically, you need to use aes_, which can handle quoted expressions.
library(data.table)
library(ggplot2)
df <- data.table(x2 = 1:2, z17 = 3:4, y = 1:2)

col.plot.list <- list(list(col='x2', seg=c(0,6)), list(col='z17', seg=NULL))

gen.plots <- function(col.plot.list) {
  lapply(col.plot.list, function(x) {
    col <- x$seg
    xval <- as.name(x$col)
    ggplot(df, aes_(x = bquote(cumsum(.(xval))),
                   y = quote(y),
                   color = if (is.null(col)) NULL else quote(col))) +
      geom_point()
  })
}

gen.plots(col.plot.list)[[1]]
gen.plots(col.plot.list)[[2]]

If you just want to subset a data.table (or data.frame) this is a FAQ and you need to study help("[") and the data.table vignettes: df[[col.plot.list[[1]]$col]]
Comment: very interesting, im unfamiliar with `as.name` and what type that would be and `bquote`. I'll read up on those two. [apparenlty `name` is a class, did not know that]


cortar string de nucleotideos de DNA

Question: Alguem poderia me ajudar nessa questao:
Tenho uma sequencia de nucleotídeos (letras: A,T,C,G), preciso retirar parte dessa sequencia e deixar somente nove nucleotídeos começando por ATG e terminando por TAA... exemplo
AATG ATGCGTTAA AGTCAT

Preciso somente da sequencia do meio...
Answer: Solução é iterar sobre cada nucleotídeo da sequência de DNA, pegar o nucleotídeo + os dois seguintes e checar se essa tríade é "ATG". Caso positivo, repetimos o meso processo até encontrarmos o TAA:
dna = "AATGATGCGTTAAAGTCAT"
result = ""
for index in range(len(dna)):
    start = dna[index:index+3]
    if start == 'ATG':
        sliced_dna = dna[index:]
        for subindex in range(len(sliced_dna)):
            end = sliced_dna[subindex:subindex+3]
            if end == 'TAA':
                result = sliced_dna[:subindex+3]
print(result)  # ATGCGTTAA

Note que a operação para encontrar o início e o fim da sequência é basicamente a mesma - poderíamos simplificar este código definindo funções ao invés de for loops dentro de for loops, mas o funcionamento é o mesmo.
Da forma como escrevi, o programa procura pela última sequência "TAA", se quiser parar na primeira será necessário usar break para acabar com os loops precocemente.
Comment: muito obrigada!! Deu certo e eu entendi!!
Answer: Poderá fazer:
todosOsNucleotideos = "AATG ATGCGTTAA AGTCAT"
apenasATGCGTTAA = todosOsNucleotideos[5:14]

Comment: estou no Python, desculpa nao ter citado antes!!Pode me ajuda tbm?
Comment: Ajustei a resposta, depois adiciona esta informação na sua pergunta.
Comment: nao deu certo ainda !!
Comment: Ops, my bad, acertei.

cortar string de nucleotideos de DNA


How to get the checkboxes dynamically in android?

Question: In my project I need to display questions and its options. Here the options are at max 20 with multiple answers. The options are not fixed for each question. That means for each question the options may be 2 or 3 or 6 or 18 or 2o. Since the question contains multiple answers I need to create checkboxes to display options dynamically. Based on the number of options for the question we need to display the checkboxes. How can I do that? Please help me regarding this.
Thanks in Advance
Answer: You can create an empty LinearLayout and call its addView() function
to add the checkboxes dynamically in your code.
For example,
CheckBox[] cbs = new CheckBox[20]; // Number varies..
for(int i=0; i<20; i++){
    cbs[i]  = new CheckBox(this);
    ll.addView(cb);
    cbs.setText("Test");
 }

Look at this turorial Android, Part III: Dynamic Layouts
EDIT:
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);

 CheckBox[] cbs = new CheckBox[20];
for(x=1; x<numberofoptions; x++)
 {
   cbs[x] = new CheckBox(getContext());
   ll.addView(cbs[x]);
  }

Comment: Hi thanks for the code. I have tried like rl =(RelativeLayout)findViewById(R.id.rlt_layout);  CheckBox[] cbs = new CheckBox[20];  for(x=1; x<numberofoptions; x++){
  cbs[x]  = new CheckBox(getContext());
rl.addView(cbs[x]);  } but it is displaying only 1 checkbox..plz help me where i am going wrong
Comment: Hi thanks for the response...I tried like that but it is not displaying the checkboxes still....where i am going wrong?
Comment: Welcome anytime.. Happy coding.. :-)
Comment: Hi I need to get the id's of those dynamically displayed checkboxes. I  tried but chk.getId() is not working. Please help me regarding this.
Comment: Just set ID of check box at time of creation checkbox in loop. like, cbs[x].setId(x); and the you can get ID with cbs[x].getId()..


PHP: Substituição de caracteres dentro de uma string a parti de uma determinada posição

Question: Estou precisando de uma forma em PHP de substituir partes de strings a partir de uma posição dada, por exemplo:
String: aaaaaaaaaa
Substituir a partir do 3º caracter por "-"
Resultado: aaa-------
ou
String: aaaaaaaaaa
Substituir até o 7º caracter por "-"
Resultado: -------aaa
ou
String: aaaaaaaaaa
Substituir ou a parti de qualquer posição até qual quer outra
Resultado: aa------aa
Resultodo: ---aaa----
Answer: ideone
<code>$str = "aaaaaaaaaa";
$carater="-";
$apartir=3;
$ate=7;
$ambos="ambos";
$entre="entre";
$compr=strlen($str);

if ($apartir==3){
 $nome=substr($str, $compr-$apartir, $compr);
 $right = str_pad($nome, $compr, $carater, STR_PAD_RIGHT);
}

if ($ate==7){
  $nome=substr($str, $compr-$apartir, $compr);
  $left = str_pad($nome, $compr, $carater, STR_PAD_LEFT);
}

if($ambos=="ambos"){
    $nome=substr($str, $ate, $compr);
    $both = str_pad($nome, $compr, $carater, STR_PAD_BOTH);
}

    echo $right;
    echo "\n";
    echo $left;
    echo "\n";
    echo $both;
    echo "\n";

$quant=2;

$parts = str_split($str, $quant);
$inicio = $fim = $parts[0];

$aux=substr($str,$quant*2,$compr);

$compl=str_replace("a",$carater,$aux);

$meio=$inicio.$compl.$fim;
echo $meio;
</code>
Referencias:
strlen
substr
str_pad
str_split
Comment: Leo muito grato, era exatamente o que eu precisava. Foi de grande auxílio.


Acessar galeria de fotos pra fazer uploads de fotos pelo inappbrowser

Question: Pessoal tenho um app de noticias, fiz uma parceria com um site de classificados e coloquei um botão no app que direciona pro classificados usando o inappbrowser, no entanto quando o usuário do app esta dentro do site mais precisamente na aba de colocar um produto, ele precisa postar uma foto do produto, o problema que quando o usuário clica no botão imagem não acontece nada, não abre a janela pra escolher a foto... testando com o navegador nativo do do android sem usar o app, funciona normalmente o botão imagem do site da ate a opção de tirar foto, ja usando o app, nao acontece nada... eu acredito que seja permissão mas nao sei como resolver... eu estou usando o dreanweaver para escrever os codigos (jquery-mobile) e depois compilo com o phonegap build CLI 6.3.0, uso os plugin inappbrowser pra navega no site e whitelist plugin pra liberar os acessos Http. alguem pode me dar uma luz... agradeço desde já.
Answer: Consegui resolver. é só usar o codigo pra abrir o navegador nativo do dispositivo, ao inves de usar o webview.


Access denied for admin user after new drupal 6 install

Question: I just installed Drupal 6 (Don't ask why) from a fresh install (Version 6.29). I followed the install steps, created an admin user, set the correct time zone, etc.
But when I login and attempt to proceed to the admin panel, I get Access denied
You are not authorized to access this page. I have read about this issue many other places, and have attempted many solutions, but none seem to work for me.
I noticed that there is nothing in the sessions table of my MySQL database for this drupal install (but there is data in other tables). I think that this has something to do with it, but ti could be that there is info in the table, but it is immediately removed due to a session/cookie issue.
I have repeatedly removed all my browser cookies each time I have tried a solution. I have tried many solutions on drupal.org, many of which have been also referenced on other sites, but none have worked.
OS: Mac OSX 10.9 (Mavericks)
Web Server: Apache/2.2.24 (Unix) PHP/5.4.17 mod_ssl/2.2.24 OpenSSL/0.9.8y DAV/2 Server at XX.XX.XXX.XXX Port 80
Not using SSL for this drupal install.
Answer: It may be that your cookie domain is not set correctly, this is a known cause of Access Denied errors when logging in, and it might be worth removing cookie domain info from settings.php and see if that works, and go from there.
Answer: Running Drupal 6 on PHP 5.4 is unreliable at best. PHP 5.2 is recommended, 5.3 could work, but you would probably run into issues with contributed modules.
That said, you could try what has been outlined here, basically:

Create a temporary session.
Clear all caches.
Updated php.ini with correct timezone info (and reload Apache settings).

Cheers,
Comment: None of that helped. When i created a temporary session with drush and used the link it generated, I got a access denied message after I got redirected to `/?q=user/1/edit`. Since I can't login to clear the cache, I used drush to clear all the caches on my site. This did not help either. My php.ini has the correct timezone. None of these things seemed to help :(
Comment: Sorry to hear it didn't work. My other suggestion would be to check the error logs and try to figure out and solve the root cause. You should also be able to install 5.2 alongside 5.4, but it might just be easier spin up a VirtualBox instance or upload the site to a server running 5.2.
Answer: It is probable an issue with a cookie.
If you are using chrome
(1) go to : chrome://settings/cookies.
(2) paste the link of your website to the search bar.
(3) delete the session cookie.
(4) Try access your site again..


Color scheme for histogram and curve comparisions?

Question: I'm making a comparison between the model I build and the data (empirical distribution), using various plots, like this:

Histogram and probability densiti function (PDF)
CDF
CDF at different axis (Weibull Axis)

The bule color is the data (empirical distribution), the black and red curve is the model.
The problem is that, what color scheme should I chose?
I mean, in the 1st plot, I use black to represent model, but in 2nd, and 3rd plot, I use red instead, because it contrasts better with blue dots. I'm afraid this inconsistancy would result in confusion, because there are only 2 type of data (Model vs. Empirical), yet I used 3 colors:
UPDATE:
After changing the black to red
Comment: If there is only the slightest chance of your results getting printed, I would ensure the colors also work when the print is in grayscale. In such cases, a very, very light gray for the data distribution, a thicker line in medium gray for the model, and black dots (or other symbols) usually do the trick for me.
Comment: I agree with your consistency argument, and would probably change the black curve in the leftmost plot to red (I think changing the red to black in the other plots would make them harder to read).  Otherwise I think these look pretty good.
Comment: @MatthewDrury Yes, I tried changing the red to black. It's just hard to read. I'll update with your suggestion.
Answer:
I agree with your consistency argument, and would probably change the
  black curve in the leftmost plot to red (I think changing the red to
  black in the other plots would make them harder to read). Otherwise I
  think these look pretty good.
Comment: I've copied this comment by @MatthewDrury as a community wiki answer because the comment is, more or less, an answer to this question. We have a dramatic gap between answers and questions. At least part of the problem is that some questions are answered in comments: if comments which answered the question were answers instead, we would have fewer unanswered questions.


Guitar : Difficulty in chords shifting

Question: I have started learning guitar basics,since last couple of months. I am facing huge difficulty in shifting chords.
I have started playing simple open chords like C,Am,Em,Gm. I am practicing for these four chords. I am facing huge difficulty while shifting. It is sometimes very depressing and at the same time frustrating when I cannot play it correct.
I have tried practicing with metronome and go slow, but still I cannot shift easily from one chord to another.
Any tips will be really helpful.
Thanks
Comment: I think it was a good couple years before I was switching chords cleanly in almost all cases. It takes time, but the upside is that's all it takes. You don't have to learn any complicated math or physics or foreign languages to learn guitar, all you have to do is practice.
Comment: @Sidd Make sure you are using the correct hand position for the type of guitar you are using [Steel String vs. Nylon String Technique](https://www.jayskyler-guitarlessons-sanfrancisco.com/guitar-lessons-sf/the-two-ways-to-play-guitar.html)
Comment: Gm is not a simple open chord.  Are you sure you don't mean G?
Answer: *Try to think hard about where your fingers have to move from/to. With C - Am, for example, two fingers (4th and 2nd strings) don't need to move off their frets.
*Try to move a pair of fingers together, as in Em - Am,keeping them touching each other as they move across between strings. When you learn E, then A, you leave your index finger on the 3rd string (for E), but also don't take it away for A. You'll find some chords which often move between each other, like E/A, and E/B7, found in many many songs. Leave fingers in place if you can, as pivots for your other fingers.
*Learn to 'hammer on' chords, so that all your fingers arrive at the same time.
*Gm is not one of the chords I'd be teaching a beginner. Apart from not being easy to play a proper version, the other chords found in a song with Gm are not beginners chords, either.
*Don't lift your fingers far above the fingerboard when changing chords.
*If you're looking at the fingerboard while finding chords, it'll put  guitar at a bad angle for your wrist and hand. Don't! Use a mirror, or try to feel your way.
Answer: I feel your frustration!  But it is a normal part of learning to play guitar.
One reason so many aspiring new guitarist, give up before they ever get to a point where they feel a sense of reward and accomplishment, is that learning guitar involves overcoming several difficult challenges thrown at you all at once in the very beginning.
First you have the pain of tender fingers pressing on steel strings.  Then you are using muscles in your hand and fingers that ordinary daily living activities have not helped you to develop the strength required for playing guitar.  And, as expressed in your question, you must train your brain to tell your fingers and hands to contort in very unnatural and strange positions to play chords.
My best advice is to abandoned any idea of instant gratification and commit to the idea that learning guitar is a slow process in the beginning.  It gets exponentially easier to improve your skills after you get past the huge hurdles you encounter in the beginning.
Think of where you presently are in your journey as merely preparation and training.  You are getting in shape to learn to play by developing some basic skills and building finger strength and callouses and coordination. Progress will be very slow in the beginning but if you persevere, you will reach a point where progress comes at a far more rapid pace.
Now to your specific challenge.  Before working on transitions between chords, you must first train your brain to tell your fingers to form the proper shape for each of the two chords.  Start one at a time.  Learn to properly form and play a particular chord (say a C chord for example).  Practice forming the chord and releasing your hand and forming the chord again and releasing.  Do this over and over until you can go from an open hand position to a C chord without hesitation.  Do this before you even think about transitioning from a C chord to something else.
Next step is to learn the next chord (Em for example).  Practice forming an Em chord and opening your hand and forming the chord again - until you can play it without hesitation.
Once you are able to form a C chord from an open hand without much hesitation and can do the same with the Em chord, then you can begin to practice the transition between the two chords.  To do this, start on one chord, then play the second chord and repeat this process.  Start slowly and you will build speed over time.  Don't use a metronome in the beginning, it will only add to your frustration.  Once you can quickly and easily transition between the two chords, you can begin to practice using a metronome to further ingrain your transition and develop some rhythm at the same time.
It would be very helpful to have a teacher or experienced guitarist, help you with the proper fingering and hand position for every chord you endeavor to learn.  Efficiently forming a chord involves more than just putting your fingers on the right strings at the right frets.  Each chord requires a different hand position and sometimes arm position.  Some chords have you tilting your hand one direction - others the opposite.  Some chords have your thumb in the center of the back of the neck, while others may be much easier to play if your thumb is at the top of the neck.
Keep your goals and expectations realistic.  It may be helpful to set a goal of learning the I - IV and V chord of a particular key and then learning to transition between those three.  In the key of C that would be I = C  IV = F and V = G.  Once you learn the basic I - IV and V chords and develop the ability to transition between them, you will be able to play literally thousands of songs.
If you accomplish that one small goal, you will develop the passion and desire to continue your journey, which will provide opportunities to continue to learn and improve for the rest of your life.  And it gets more enjoyable as you go.
Don't give up!  What you are experiencing is normal and something that all of us (who have learned to play guitar) went through in the beginning.  It takes slow and deliberate practice to get over the huge wall at the start.  It gets much easier after you get over that initial wall.  Good luck!
Comment: I gave up learning guitar a bunch of times. Eventually I'd discovered every possible way to play it wrong... and then finally, I picked it up one more time, and I could play it just fine!
Comment: @Rockin Cowboy Thanks for all the motivation and tips.. I will surely not give up and try to stick with it.
Answer: I have started learning guitar basics,since last couple of months. I am facing huge difficulty in shifting chords.
Welcome to the guitar.
Any tips will be really helpful.
Welcome to the guitar.  That's really all there is to it.  Chord shapes take mental effort and motor coordination for you right now and there is nothing that will help other than repetition.
Just be sure to stop whenever it hurts.  This kind of stumbling conscious effort and non-fluid movement is quite more strain on hand and fingers than well-mastered "effortless" playing.  Also it makes more sense to practice good playing than bad playing, so you should quite prefer slow reasonably well-executed play over fast and interrupted sloppy one.  Picking up speed later on works better than reducing a sizable quota of errors.
Comment: A great phrase I saw on this very SE is "practice makes permanent, NOT perfect",
Comment: Agree with both of you here, lots of **quality** practice. Listen hard to the end of one chord and the start of the next - look for a smooth transition without finger noise on the strings, or stray notes ringing out.  Lots of practice on chords also helps develop your "ear" for tuning, your hand strength, your arm position and general rhythm.  It isn't time wasted.
Answer: As with many questions asked here, the answer is practice; lots of practice.
The simplest way to practice is to play songs -- sing or whistle if you like; you don't need to sing well if you're practising in private.
By playing actual songs, you learn functional sets of chords that work together, and the way your left hand can shift from one of these to another.
Make sure you learn to do this in lots of keys; either by picking songs in a variety of keys, or by transposing. A good early target is to be able to play the "three chord trick" (root, fourth, fifth -- for example a 12 bar blues) in E, G, A, C and D.
When you learn barre chords, notice how you can translate the E/A/B three chord trick you already know into any key by playing the corresponding barred shapes at any position up the neck. You can sometimes substitute these shapes for other inversions, for an easier chord shift.
Answer: I've been playing the guitar for 3-4 years now; I remember the same difficulty with chords: I still can't hit the open G major perfectly sometimes... You need to get used to the shapes of the chords, and practice is the only way. Then you will have difficulties with power chords. The same: practice, play a lot of these chords, and you will feel the improvement in weeks-months. Then come some exotic chords: this is my current level. The solution: practice.
Answer: Partly, it just takes time to learn the shapes, such that you think "E minor" and your fingers "just go" to that shape. It might take a long time, but you'll get there with practice. Just keep doing it while you're watching TV etc. A couple of months isn't that long to have been learning.
Also, it's good to make sure you are getting your wrist and elbow position correct for each chord. It's not just about moving your fingers.
When it comes to getting smooth transitions between the chords - partly that comes as your fingers get faster with time, but also you learn to cheat such that if you have a difficult transition, you play e.g. just the root note for a beat while you adjust the rest of your fingers. To be honest, if you can get into the "cheating" mindset, you'll do well at the guitar!

Guitar : Difficulty in chords shifting


Can't access Apache in my CentOS Virtualbox

Question: I'm setting up a VirtualBox with CentOS so I can test out all my code, etc. on a Linux box instead of the Windows I use for development.
I just got the SSH working (I SSH to localhost:2222 and it port forwards it to the virtualbox port 22).
It's using NAT because for some reason it refuses to start with a bridged adapter.
I'm trying to do the same thing with Apache, to get a web server up and running.
I've portforwarded port 8888 on localhost to port 80 in my CentOS Virtualbox, but I can't seem to access anything with localhost:8888 in my browser?
Apache is also definitely running:

ps -e | grep httpd
2108  ?      00:00:00 httpd
2110  ?      00:00:00 httpd
2111  ?      00:00:00 httpd
2112  ?      00:00:00 httpd
2113  ?      00:00:00 httpd
2114  ?      00:00:00 httpd
2115  ?      00:00:00 httpd
2116  ?      00:00:00 httpd
2117  ?      00:00:00 httpd

Iptables:

# Generated by iptables-save v1.4.7 on Fri Jan 27 18:26:36 2012
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [32:2278]
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
-I INPUT -p tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT
-I OUTPUT -p tcp --sport 80 -m state --state ESTABLISHED -j ACCEPT
-I INPUT -p tcp --dport 443 -m state --state NEW,ESTABLISHED -j ACCEPT
-I OUTPUT -p tcp --sport 443 -m state --state ESTABLISHED -j ACCEPT
COMMIT
# Completed on Fri Jan 27 18:26:36 2012

I've also stopped iptables, so that's not interfering.
I tried to telnet into port 80 from my CentOS Virtualmachine to see if it'd work, and
Neither 127.0.0.1 or [vm ip] works for telneting to port 80. It gets to connecting to [ip] and then says connection closed by foreign host. For the listen lines in my httpd.conf, it says listen 0.0.0.0:80
Output of netstat -tlnp | grep http

netstat -tlnp | grep http
tcp        0      0 0.0.0.0:80                       0.0.0.0:*                        LISTEN      2032/httpd
tcp        0      0 :::443                      :::*                        LISTEN      2032/httpd

When I nmap localhost, I get

[root@CentOS conf]# nmap localhost

Starting Nmap 5.21 ( http://nmap.org ) at 2012-01-28 00:58 WST
Nmap scan report for localhost (127.0.0.1)
Host is up (0.0000090s latency).
Hostname localhost resolves to 3 IPs. Only scanned 127.0.0.1
Not shown: 993 closed ports
PORT    STATE SERVICE
22/tcp  open  ssh
23/tcp  open  telnet
25/tcp  open  smtp
80/tcp  open  http
111/tcp open  rpcbind
443/tcp open  https
631/tcp open  ipp
Comment: Are you absolutely sure that 18.104.22.168 is the correct IP?  That list of ports is extremely different.
Comment: Looks like you are binding to ipv6 only and not ipv4 - you may need to explicitly specify the use of ipv4 with Listen 0.0.0.0:80 ([Apache docs](http://httpd.apache.org/docs/2.0/bind.html)). (Also check that localhost maps to 127.0.0.1 and not just to ::1 in /etc/hosts - but that is unlikely).
Comment: @ShaneMadden definitely sure it's the right IP
Comment: Hosts: `127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
10.0.2.15 localhost
`
Comment: @ShaneMadden So I somehow fixed the IP issue, nmaping the IP address is now the same as nmaping localhost. However, it's still not working. I also can't ssh into the IP address directly (10.0.2.15:22) so I assume it's the same issue that's messing things up
Comment: Wgeting also works perfectly, whether it's localhost/index.html, 127.0.0.1/index.html or 10.0.2.15/index.html. I'd assume it's a port forwarding issue if the SSH didn't work perfectly
Comment: @cyberx86 Done. Everything works from the local machine now, just not my windows host?
Answer: You have copy pasted the iptables rules? If yes then there is an error in it:
 _I OUTPUT -p tcp --sport 80 -m state --state ESTABLISHED -j ACCEPT

the underscore insted of hyphen.
Comment: Should have said, I've fixed that, editing the post now :)
Answer: First you have to make sure that apache is listening on the ethernet interface (the one from the VM) or on all addresses. For this run:
sudo netstat -tlnp|grep http

If it is not listening to external interface (as opposed to loopback one), then you have to change the Listen directive in apache configuration and restart apache (not reload).
Comment: I've edited the OP with the output, I'm not entirely sure what it means?
Answer: In virtualbox, try changing the network settings to Bridge Adapter instead of NAT and select the appropriate interface you want to use (wired or wireless). Fire up CentOS and then re-check your ethernet address (run ifconfig).
From there check if you can now access apache using the new ethernet address.
With regard to ssh on centos, you have to make sure to edit sshd_config and uncomment the following:
Port 22
PermitRootLogin No

Also create another user aside from root and then add that user in sshd_config:
AllowUsers username


Get row element form row.clicked event

Question: I'm using Table from Bootstrap Vue, and I'm trying to display row details when clicking on a row.
I used row-clicked event as the doc said, but I don't find any row details with a toggleDetails method.
So I don't even know how to open it and where toggleDetails come from.
There is a way to open this details row with row.clicked event ?
Or should I use another method to do this ?
Do you have some clues ?
EDIT
There is some code to illustrate a bit more my problem, there is my table with the details row.

  <template
    slot="message"
    slot-scope="row"
  >
    {{ row.item.message }}
  </template>
  <template
    slot="row-details"
    slot-scope="row"
  >
    {{ row.item.message }}
  </template>

You can see the row.clicked event I use on the table, and then my methods where I'm trying to open the row details. It's a simple method with some console.log
methods: {
  test(item, index, event) {
    console.log(item, index, event);
  },
},

Comment: Show more code so we can better understand the issue.
Comment: @skribe I have added some code to illustrate.
Comment: untagging D because it doesn't seem to have anything to do with the D programming language...
Comment: Yes nice catch, this was a fail tag.
Answer: All you have to do is to place somewhere in your "base" row (probably in a row cell called actions) a button that calls the toggleDetails function for this specific row.
The code for this button and the details row should be like this:
<template slot="actions" slot-scope="row">

        {{ row.detailsShowing ? 'Hide' : 'Show' }} Details

</template>
<template slot="row-details" slot-scope="row">

</template>

You can find more examples and explanations in the documentation
If you want to show the row details by clicking anywhere in the row, firstly you should add a _showDetails variable to each item object:
items: [
    { foo: true, bar: 40, _showDetails: false },
    ...
    { foo: true, bar: 100, _showDetails: false }
]

Then you just have to add the proper functionality for the row-clicked event:

And in your component methods:
methods: {
    onRowClicked (item, index, event) {
        item._showDetails = !item._showDetails;
    }
}

Comment: Yes I know I can trigger the details opening with a button as you write. But I trying to open this row details when I click anywhere on a row.
Comment: Please make sure to add the "_showDetails" variable on each item object when created, else beware the Vue reactivity caveats https://vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats
Comment: Yes that is what I did, this is working well, thanks
Comment: What version of BV is this solution for? It's not working for me with v2.2.
Comment: I edited my post to also answer your specific problem.
Comment: Ahhh ok I see what I need to do, I will try it, thanks
Comment: If you're using an ajax call to fetch the data, you need to do something like this, assuming `data` contains the response data:
`setRowData: function (data) {data.forEach(e => e._showDetails = false); this.items = data; }`
Comment: this is working well, thanks.

Get row element form row.clicked event


Add default value to existing field

Question: I have tried to add default value to an existing field using hook_form_alter() but it does not work.
Below is the html of the fields
<fieldset class="js-form-item js-form-type-textfield form-type-textfield js-form-item-order-fieldscheckout-field-my-fieldname-0-value form-item-order-fieldscheckout-field-my-fieldname-0-value form-group" style="display: block;">
  field Label
  <input class="js-text-full text-full form-control" data-drupal-selector="edit-order-fieldscheckout-field-my-fieldname-0-value" type="text" id="edit-order-fieldscheckout-field-my-fieldname-0-value" name="order_fields:checkout[field_my_fieldname][0][value]" value="" size="60" maxlength="9" placeholder="">
</fieldset>

Below is the code that I tried to set default value in the field
function module_name_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'commerce_checkout_flow_multistep_default') {
    $form['field_my_fieldname'][LANGUAGE_NONE][0]['value']['#type'] = 'hidden';
    $form['field_my_fieldname']['widget'][0]['value']['#value'] = 1;
    // Tried to add class attribute but not working
    $form['field_my_fieldname']['#attributes']['class'][] = '123456789';
  }
}

Answer: I could make your code work like this:
function module_name_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'commerce_checkout_flow_multistep_default') {
    $form['field_my_fieldname']['widget'][0]['value']['#type'] = 'hidden';
    $form['field_my_fieldname']['widget'][0]['value']['#value'] = 1;
    $form['field_my_fieldname']['widget'][0]['value']['#attributes']['class'][] = '123456789';
  }
}

Note that LANGUAGE_NONE is Drupal 7 specific and won't work in Drupal 8 and newer.

Add default value to existing field


Admin approval notification based on role choose by user on registration form?

Question: I need to set admin approval for a particular role. I am using auto assign module to provide user to choose role on registration form.
authenticated users: Do not need admin approval
<code>$form_state['values']['status'] = 1;

$form["account"]["status"]["#default_value"] = FALSE;
</code>
Try to use above line on validate function but not getting any success.
Answer: I have created a module for this, which addresses my question. It can be found at Select registration roles. Some more details about it (from its project page):

The Select Registration Roles module adds a role field on the user registration form. Admin can configure roles to be displayed on the
  registration form as, and can set roles which require admin approval.

Here is a screenprint of it also:
Comment: nice! Please check my edit of your answer (now that it is a full project). If you don't like the edit, just perform a rollback, ok?
Comment: Thank you @Pierre.Vriens. Yes you are right. Now it is a full project. Thank you edit the answer.


Changing the size of status message in MS CRM Workflows

Question: We are having some workflows crash due to a workflow status message being too large. The messages are set when we stop workflow with status cancelled and then we set the status message.
Is there a way to increase the size of this field?
Comment: If the sole purpose of what you are trying to do is to log more meaningful messages from your workflows, create a custom entity and write messages.
Answer: I don't believe that can be customised. You are probably better off using a shorter message.
Answer: My solution was to create a plugin that takes in the message and limits it to 2000 adding ... on the end.


If $f$ is not primitive, then it is not irreducible?

Question: This is the beginning of a proof from Algebra, Chapter $0$ by Aluffi.

I am not sure why this statement is true. If $f$ is not primitive, then the gcd of its coefficients is not $1$. But what if the content of $f$ is a unit. Then we can factor $f$ but it would still be irreducible. What am I missing?
Comment: Presumably when it begins with the hypothesis that $f\in R[x]$ is irreducible, it means irreducible in $R[x]$. Note GCD in a UFD is only defined up to units, so the content being a unit and the content being $1$ are essentially the same thing. In order for the content to not be $1$ mod units, it would have to be a non-unit.
Answer: This is mainly echoing the comment above, but I think what you're missing is the definition of primitive. The definition of primitive is not that the content is $1$, it's that the content is a unit.


how can i use json explict function ? to pull the data fom different sites

Question: can i use json explicit function i,e{http://www.example.org/?json=get_recent_posts} to pull the data from other popular sites like Forbes etc..?
Answer: Websites must provide the JSON for you to access, via some sort of built in webservice. There is no way to automatically convert HTML content to JSON in a meaningful way. You can search or request that a site provide a JSON webservice, or try to parse the HTML (or RSS if provided) yourself.


Contact for per node in Drupal 8?

Question: This was quite easy on Drupal 7. You could just use Webform. In Drupal 8, I'm not so sure.
I have nodes of type "Business". I want a form to appear on this page, that when filled in, it must send an email to the business. The "Business" content type has a field on it called "Business Contact Email Address". This is where the mail must go...
I was thinking of:

Finding a way to do it using the inherent Drupal 8 contact forms... any clues as to how?
Creating a new content type called "Node Contact Form" that references a node and then use Rules to mail the field on the referenced node.

Is there an easy way to do this?
Answer: Not without code, but its fairly easy.
You could add a reference field to contact forms to your node type, and "view" the contact form. contact_storage provides a view builder that will display the form then. That doesn't work for your additional mail requirement, however.
To be able to do that, you need custom code to display the form, something like this in hook_node_view(). field_node_reference is an entity reference field that points back to the node. that will allow you to easily see for which node it was submitted and also use it later on to change the recipient:
  $message = \Drupal::entityManager()->getStorage('contact_message')
    ->create(array(
      'contact_form' => 'YOUR_FORM_ID',
      'field_node_reference' => $node,
      // You can generate a default subject or even hide it completely
      // and always use this value.
      'subject' => t('Contact about "@title".', ['@title' => $node->label()]),
    ));
  $form = \Drupal::getContainer()->get('entity.form_builder')->getForm($message);
  $build['yourmodule_contact_form'] = array(
    '#type' => 'details',
    '#open' => TRUE,
    '#title' => t('Contact the business'),
  );
  $build['yourmodule_contact_form']['form'] = $form;

yourmodule_contact_form can be defined as an extra field (hook_entity_extra_field_info), then you can conditionally display it using if ($component = $display->getComponent('yourmodule_contact_form')) { and you can configure the place and if it should be displayed per view mode.
The final piece is then to override the mail recipient of the sent mail using a hook_mail_alter():
function yourmodule_mail_alter(&$message) {
  if (!empty($message['params']['contact_form']) && !empty($message['params']['contact_message'])) {
    /** @var \Drupal\contact\Entity\ContactForm $contact_form */
    $contact_form = $message['params']['contact_form'];
    /** @var \Drupal\contact\Entity\Message $contact_message */
    $contact_message = $message['params']['contact_message'];

    if ($contact_form->id() == 'YOUR_FORM_ID' && $contact_message->hasField('field_node_reference')) {
      /** @var \Drupal\node\NodeInterface $node */
      $node = $contact_message->field_node_reference->entity;
      if ($node && $email = $node->field_email->value) {
        $message['to'] = $email;
      }
    }
  }

This could possibly be built in a generic way but it would require configuration for the mail and reference fields.

Contact for per node in Drupal 8?


Show that $x^5+x+1=0$ has a solution in $\mathbb{R}$

Question: My work:
Let $f:\mathbb{R}\rightarrow \mathbb{R}$ be defined by$f(x)=x^5+x+1$
I calculated $f(-2)=-33$ and $f(1)=3$, then $0\in [f(-2),f(1)]$
So by Intermediate value theorem, and knowing that $\mathbb{R}$ is connected, $\exists c\in \mathbb{R}$ such that $f(c)=0$
Therefore the equation given admits a solution.
Correct ?
And also how could I prove that this solution is unique ?
Comment: the derivative is always positive, so the function is strictly increasing everywhere.
Comment: Your solution is basically correct, but $\;\Bbb R\;$ being connected (even path connected) has nothing to do here and you may want to write that polynomials are continuous functions. About uniqueness of the solution read the above comment.
Comment: @PedroAlvarès Details may depend on how your specific formulation of the IVT reads. Typical formulations start "Let $f\colon [a,b]\to\Bbb R$ be continuous ..." and while the reason for the theorem to work is the connectedness of $[a,b]$, it is not specifically mentioned as premise (it's just that intervals *are* connected anyway)
Comment: Oh thanks , but  to apply intermediate value theorem shouldn't the domain of the function be connected ?
Answer: Yes, your work appears to be correct.  To prove this solution is unique, note that
$$f\left(x\right) = x^5 + x + 1$$
means that
$$f'\left(x\right) = 5x^4 + 1$$
which is always $\ge 1$ as $x^4 \ge 0$ for all real $x$.  Thus, $f$ is a strictly increasing function.
You could also graph the function to see this.
Answer: For fun:
Assume there is an other zero, i.e.
$x_0,x_1$, where $x_1 >x_0$.
MVT.
$\dfrac{f(x_1)-f(x_0)}{x_1-x_0}=0=f'(a)$, where $a \in (x_0,x_1).$
But $f'(x)=5x^4+1 >0$, contradiction.


ERGM with larger log-likelihood but worse fit than reference model?

Question: I'm using the R package statnet to fit some ERGMs to the Faux Dixon High simulated network data provided with the package. The first model I fit is almost identical to the model used to generate the simulated data, and is shown below:
model.fdh <- ergm(fdh ~ edges
                  + mutual
                  + absdiff("grade")
                  + nodefactor("race")
                  + nodefactor("grade")
                  + nodefactor("sex")
                  + nodematch("race", diff = TRUE, levels=c("B","O","W"))
                  + nodematch("grade", diff = TRUE)
                  + nodematch("sex", diff = FALSE)
                  + idegree(0:1)
                  + odegree(0:1)
                  + gwesp(0.1,fixed=T),
                  constraints = ~bd(maxout=10),
                  control =
                    control.ergm(MCMLE.steplength = 1, MCMC.burnin = 100000, MCMC.interval =
                                   10000, MCMC.samplesize = 2500, MCMLE.maxit = 100), verbose=T)

Unsurprisingly, since this model is almost exactly like the one used to generate the simulated data in the first place, the model fits the data extremely well. Below are some diagnostic plots.

In addition, the log-likelihood of model is 0.2368874, and AIC = -11801 and BIC = -11557.
Next, I tried fitting a more complicated model to the data, shown below:
model.fdh2 <- ergm(fdh ~ edges
               + mutual
               + absdiff("grade")
               + nodefactor("race")
               + nodefactor("grade")
               + nodefactor("sex")
               + nodematch("race", diff = TRUE, levels=c("B","O","W"))
               + nodematch("grade", diff = TRUE)
               + nodematch("sex", diff = FALSE)
               + gwidegree(0.1, fixed=F)
               + gwodegree(0.1, fixed=F)
               + istar(2)
               + ostar(2)
               + gwesp(0.1,fixed=F)
               + transitive,
               constraints = ~bd(maxout=10),
               control =
                 control.ergm(MCMLE.steplength = 1, MCMC.burnin = 100000, MCMC.interval =
                                10000, MCMC.samplesize = 2500, MCMLE.maxit = 100), verbose=T)

Based on diagnostic plots, this model appears to fit the data less precisely.

Obviously I'm not showing diagnostic plots for all of the statistics that statnet returns, but all of them more or less look like this: the simulated graphs tend to overstate the statistics in this second model. However, this second model has a higher log-likelihood than the previous one at 1.120519, with AIC= -11781 and BIC = -11501. Does this make sense? Is it possible to have an ERGM with a higher log-likelihood but an apparent worse level of fit to the data?
Answer: Yes, it's possible.
The smaller log-likelihood (so as AIC, BIC) score, the better fit of model.
You can imagine log-likelihood as residuals.
The fewer residuals between predict value and true value , the explanation of model is better.


Resampling data by week

Question: I have a time series dataset of 100 users looking at 365 days of transactions. The dataframe is currently set up like the following:
      date    2018-04-01 2018-04-02 2018-04-03 2018-04-04  2018-04-05 ...
userid
   1              0          0             0        0          13.40
   2            12.32        0             0        0           3.60
   3            11.32        0           14.22      0            0
   4              0          0             0        0           9.87
   5              0          0           19.52      0            0
  ...

I want to resample this to 52 weeks, taking the sums of the transactions every 7 days. How would I do this?
Answer: You can use weekofyear:
df.groupby(df.columns.weekofyear, axis=1).sum()

Output:
date       13     14
userid
1        0.00  13.40
2       12.32   3.60
3       11.32  14.22
4        0.00   9.87
5        0.00  19.52

You can also groupby every seven days:
(df.groupby(np.repeat(np.arange(df.shape[1]), 7)[:df.shape[1]],
            axis=1)
   .sum()
)

Answer: For this there is a method DataFrame.resample:
#df.columns=pd.to_datetime(df.columns)
df_resamp=df.resample('W',axis=1).sum()
print(df_resamp)

        2018-04-01  2018-04-08
userid
1             0.00       14.50
2            12.32        5.60
3            11.32       17.22
4             0.00       12.87
5             0.00       21.52

Resampling data by week


When a node is created, automatically update data in a corresponding node

Question: Background (simplified)
We're collecting data for a study in which participants come in on several occasions to have health measures taken. We have two custom node types: Participant stores background data about a person, and Visit stores information from a single visit (e.g., their blood pressure that day). Each Visit is related to one Participant via a field created by the Node References module.
On each visit, a participant might qualify for a one-time reward. Visit nodes have a reward_visit field indicating whether the participant earned a reward on this visit, and Participant nodes have a reward_ever field indicating whether the participant has ever received a reward.
Question
I'd like to set up the following behavior: If a Visit node is created where reward_visit was set to Yes, also set reward_ever to Yes in the corresponding Participant node.
Is there a way to make this happen automatically, using Node References or some other relations module? I could custom-code it using hook_node_insert() or something, but I'd like to know if there's already an accepted way.
Answer: UPDATE:
The answer to this question is "Rules". I hadn't learned about them at the time. With a rule, you can choose to trigger on saving or updating new content and use conditions to limit it to the content type in question. For the action, choose "set a data value" and the relation between the two nodes should allow you to select the relevant field on the node you just created as the source, and the relevant field on the related node as the value to set.
Original answer:
I ended up writing a small custom module that implements hook_node_insert and hook_node_alter for visit nodes. It gets the nid of the related participant from the submission, gets it using node_load(), changes the relevant values, and saves it using node_save(). I still suspect there's a less kludgy solution, but this seems to work perfectly well.


Converter horas "hh:mm:ss" para minutos no formato int

Question: Tenho a seguinte função que calcula as horas 01:00, retorna 60 minutos.
 mas a coluna do sql armazena no formato time(0) 01:00:00,
O que da erro na minha função, não sei incrementar o código para calcular os segundos, e me retornar os 60 minutos inteiros.
CREATE FUNCTION [dbo].[FN_CONVHORA] (@Horas varchar(10))
RETURNS int
BEGIN
DECLARE @iMinutos INTEGER
Select @iMinutos =
  (Convert(int, SubString(Convert(VarChar(10), @Horas), 1,
  CharIndex(':', Convert(VarChar(10), @Horas)) - 1)) * 60) + (Convert(int, SubString(Convert(VarChar(10), @Horas),
  CharIndex(':', Convert(VarChar(10), @Horas)) + 1,
  Len(Convert(VarChar(10), @Horas)) -  CharIndex(':', Convert(VarChar(10), @Horas)))))
 RETURN @iMinutos
END
GO

Answer: Assumindo que você está utilizando um tipo data para armazenar seus dados, você nem precisa de uma função para isso, basta usar o DATEDIFF
SELECT DATEDIFF(second, 0, '20:10:10') AS diferenca_em_segundos

Exemplo no SQL Fiddle
Sintaxe do DATEDIFF
DATEDIFF ( datepart , startdate , enddate )

datepart - parte da data a ser retornada, no seu caso second.
startdate - a data inicial. Como você quer contar os segundos somente da hora, considere como zero.
enddate - a data final do intervalo. No seu caso a hora desejada.
Comment: Valeu pela resposta, programo em sql e c# a 2 anos, apenas para uso próprio, e tem função que vejo e nem imagino para que serve, mas é exatamente isso que eu preciso.  Isso será um programa tipo o velho  e bom controle dos pais do Windows, que hoje virou uma bos..... quero bloquear meus filhos em determinados dias e horários, mas apenas os programas que eu acho que eles não devem se envolver demais.
Answer: Substitua sua função por essa chamada para retornar as horas em minutos:
SELECT CAST(LTRIM(DATEDIFF(MINUTE, 0, '01:03:00')) AS INT)

Caso tenha a intensão de pegar a informação diretamente de uma tabela, você pode fazer da seguinte forma:
SELECT CAST(LTRIM(DATEDIFF(MINUTE, 0, NomeDaColuna)) AS INT) FROM NomeTabela

Você pode adaptar sua função com essa instrução de código também:
CREATE FUNCTION FN_CONVHORA(@Horas VARCHAR(10))
RETURNS INT
BEGIN
    RETURN (SELECT CAST(LTRIM(DATEDIFF(MINUTE, 0,convert(varchar(10), @Horas, 108))) AS INT))
END

Boa sorte!


Ansible: list all variables required for a playbook

Question: Given a playbook
<code>---
- hosts:
  some_host_group
  roles:
  - foo
  - bar
</code>
I'd like to get the list of all variables that the playbook needs to be defined. Something like:
<code># playbook-requires myplaybook.yml
</code>
For more elaborate (or just numerous) playbooks this might come handy. Before starting to write such utility, I'd like to make sure I'm not re-inventing the wheel.
A quick googling shows a lot of solutions for the opposite task (listing all defined variables). That's not what I'm looking for.
So, is anyone aware of such utility being available?
Comment: I doubt that it is possible. Look at something like this: `{{ myvar2 if myvar1 is defined else myvar3 }}`. What vars are required in this case?
Comment: @Konstantin: (myvar2 and myvar1) or myvar3. I agree, it might get ugly, but browsing through the code containing some elaborate constructs won't be any prettier. In particular when you've got a set of playbooks and have to configure everything from scratch.
Answer: There is no tool like that, and I'm sure you need a complete Ansible-Yaml and Jinja-Parser. Maybe ansible-lint is a good starting point.
Because there could be vars used in the playbooks and roles and also in dependencies of that roles. Also roles will have templates and that could use vars. And then it is unlikely possible to have "constructed" var-keys in dictionaries or lists, which you can only see, when you completely run the script. There is a playbook dryrun - maybe it is possible to start there by examining all errors - but if it contains an if else condition only one block is interpreted.


Does every $k$ algebra necessarily have a basis closed under multiplication?

Question: Let $A$ be a $k-$algebra with $k$ field. Suppose $A$ is finite dimensional over $k$.
$\textbf{Q:}$ Is it possible to find a basis $B$ of $A$ over $k$ s.t. the basis set is closed under multiplication in general? It seems this is true in finite quiver path algebra quotient by admissible ideals or finite group algebra over field $k$. If not, what is the counter example?
Comment: A non-interesting example: $xy=0$ for all $x,y\in A$.
Answer: No, the existence of such a basis is an extremely strong condition.  For instance, notice that for any $x\in B$, the powers of $x$ must be eventually periodic, since they are all elements of the finite set $B$.  In particular, if $A$ is a field extension of $k$, this implies every element of $B$ is a root of unity, and so $A$ must be spanned by the roots of unity it contains.  So for instance, if $k=\mathbb{Q}$ and $A=\mathbb{Q}(\sqrt{2})$, this is not possible since the only roots of unity in $A$ are $\pm 1$.
Answer: This is not always possible, for example $\mathbb{C}$ has no multiplication-closed basis over $\mathbb{R}$. The main theorem of this interesting AMM note provides many more examples.


error while starting jboss 7.1

Question: Unable to set property fileName on class org.jboss.logmanager.handlers.FileHandler: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.jboss.logmanager.PropertyConfigurator.configureProperties(PropertyConfigurator.java:187)
    at org.jboss.logmanager.PropertyConfigurator.configureHandler(PropertyConfigurator.java:312)
    at org.jboss.logmanager.PropertyConfigurator.configure(PropertyConfigurator.java:128)
    at org.jboss.logmanager.PropertyConfigurator.configure(PropertyConfigurator.java:86)
    at org.jboss.logmanager.LogManager.readConfiguration(LogManager.java:246)
    at org.jboss.logmanager.LogManager.readConfiguration(LogManager.java:231)
    at java.util.logging.LogManager$3.run(LogManager.java:399)
    at java.util.logging.LogManager$3.run(LogManager.java:396)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.util.logging.LogManager.readPrimordialConfiguration(LogManager.java:396)
    at java.util.logging.LogManager.access$800(LogManager.java:145)
    at java.util.logging.LogManager$2.run(LogManager.java:345)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.util.logging.LogManager.ensureLogManagerInitialized(LogManager.java:338)
    at java.util.logging.LogManager.getLogManager(LogManager.java:378)
    at org.jboss.modules.Main.main(Main.java:275)
Caused by: java.io.FileNotFoundException: C:\Program Files\jboss-as-7.1.1.Final\standalone\log\boot.log (Le chemin d'accès spécifié est introuvable)
    at java.io.FileOutputStream.open0(Native Method)
    at java.io.FileOutputStream.open(FileOutputStream.java:270)
    at java.io.FileOutputStream.(FileOutputStream.java:213)
    at org.jboss.logmanager.handlers.FileHandler.setFile(FileHandler.java:152)
    at org.jboss.logmanager.handlers.FileHandler.setFileName(FileHandler.java:183)
    ... 20 more
20:48:27,119 INFOS [org.jboss.modules] JBoss Modules version 1.1.1.GA
java.lang.IllegalStateException: JBAS018704: Could not create server data directory: C:\Program Files\jboss-as-7.1.1.Final\standalone\data
    at org.jboss.as.server.ServerEnvironment.(ServerEnvironment.java:388)
    at org.jboss.as.server.Main.determineEnvironment(Main.java:242)
    at org.jboss.as.server.Main.main(Main.java:83)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.jboss.modules.Module.run(Module.java:260)
    at org.jboss.modules.Main.main(Main.java:291)
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=256m; support was removed in 8.0
Comment: JBoss AS 7.1 will not start successfully with Java 1.8.  [here](https://developer.jboss.org/thread/223739?start=0&tstart=0)  the forum thread of the issue.

If you really need to use Java 1.8 consider using WildFly
Answer: JBoss AS 7.1 will not start successfully with Java 1.8. here  the forum thread of the issue. If you really need to use Java 1.8 consider using WildFly
And  by pasting the new WildFly's directory  in the C:/

error while starting jboss 7.1


How to run the localhost url for post in Jax rs

Question: I am trying to run the localhost url for POST in jax -rs but every time I am trying to run the localhost I am not getting any results. For GET it is perfectly working.
@Path("playlists")

    public class PlaylistResource implements PlaylistApi {

        @Override
        @POST
        @Consumes(MediaType.APPLICATION_JSON)
        @Produces(MediaType.APPLICATION_JSON)
        public Response createPlaylist(PlaylistRequest request)
    }

I tried:
localhost:9999/playlists/
Comment: How do you POST your request? Do you get any errors?
Comment: no i am not getting any errors the page loads without showing anything.
Comment: If you just load the page on a browser, it will make a GET request. You will need a more active client to make a POST request, and it will need to send JSON content for your method, too.
Answer: If you want do a post request,you must use Postman or some other tools like that,if you only type into the address into a browser,it will be a get request always.
Comment: Is there any eclipse plugin with which I can get the result. Thanks
Comment: I dont use eclipse, you can try postman,it is a free software and easy to learn,if you develop complex web applications more than get request,it is a best choice


Eigenvalues of Invertible Matrix

Question: Suppose I have two square matrices $A, B$ with the same size $n\times n,$ and $AB = I = BA.$ What conclusions could we draw for the eigenvalues and eigenvectors of matrix $A?$
I only know that $A$ is an invertible matrix, and it has non-zero eigenvalues. I don't think $A$ can have $n$ distinct eigenvalues to say that it is diagonalizable.
Comment: Consider the matrix $A = \begin{bmatrix} 1 & 1 \\ 0 & 1 \end{bmatrix}$ which is certainly invertible but is not diagonalizable. All we know from invertibility is the eigenvalues are non-zero.
Answer: Suppose $A$ is an invertible square matrix and $B$ is its inverse.
Eigenvalues of $B$ are inverse to those of $A$ (and vice versa) and $A,B$ share eigenvectors corresponding to the pairs of inverse eigenvalues $(\lambda,\lambda^{-1}).$
To prove it,
let $\lambda\neq 0$ be an eigenvalue of $A$ and $u$ a right eigenvector corresponding to $\lambda.$ This writes
$$u=(BA)u=B(Au)=B(\lambda u)=\lambda Bu.$$ Therefore $$Bu={\lambda}^{-1}u.$$
Similarly, if $v$ is a left eigenvector corresponding to the eigenvalue $\lambda$ of $A,$ then $v$ is also a left eigenvector of $B$ corresponding to $\lambda^{-1}.$
This proves also that inverse matrices have equal algebraic multiplicity and equal geometric multiplicity.
EDIT
Left (or "row") eigenvectors corresponding to the eigenvalue $\mu$ satisfy the relation $$v^TA=\mu v^T.$$  Let us prove that the eigenvalues corresponding to the left or right eigenvectors are the same. (So, the name "eigenvalue" without specifying the side is legitimate.)
For, realize that $A$ and its transpose $A^T$ share eigenvalues because they have the same charasteristic polynomial.
Let $(\lambda,u)$ be an eigenpair of $A.$
$$\begin{aligned}Au=\lambda u \iff &(Au)^T=(\lambda u)^T\\ \iff & u^T A^T=\lambda u^T \end{aligned}$$
Therefore, there exists a row vector $v^T$ such that  $$v^T A=\lambda v^T.$$
The rest of the proof can be completed analogously.
Comment: Thank you for a nice explanation. Could you elaborate the left/right parts of the eigenvector?
Comment: @Jack Edited. Is it what you're interested in?
Comment: Yes, it is clear for me now! Thank you.

Eigenvalues of Invertible Matrix


When will the SMT-LIB standard be extended to include optimization?

Question: After working with νZ, an extension within the SMT solver Z3 to make use of objective functions, I was surprised to find that the used optimization primitives are not part of the SMT-LIB2 syntax. These primitives are:
<code>(maximize t) - instruct the solver to maximize t.
(minimize t) - instruct the solver to minimize t.
(assert-soft F :weight n) - assert soft constraint F, optionally with weight n.
</code>
This extension was introduced in 2014. The latest version of the SMT-LIB standard, version 2.6, still doesn't seem to introduce any kind of syntax to support objective functions. Is this really the case? If so, is there any work being done to introduce such a standard?
Answer: I'm not aware of any work to standardize Max-SAT (i.e., optimization) in SMTLib. Your best bet is to ask at the SMTLib mailing list (https://groups.google.com/g/smt-lib), to call for attention to this matter.


Failover Cluster Manager showing wrong interface for node

Question: I have a 2 node 2012 R2 Hyper-V setup that i am trying to configure Hyper-V HA. The network setup for both nodes are as follows:
Total: (8 x Ports):
4 x Adapters - (Teamed:Production/VM external access) @ 3 x 1Gbps and 1 x 10Gbps
Teaming Mode: Switch Independent
Load balancing mode: Dynamic
Stanby adapter: None (All adapters active)
Network: 192.168.100.x
2 x Adapters - iSCSI (MPIO) @ 10Gbps
Network: 192.168.115.x
1 x Adapters - Cluster (Managment,VM Migration and replication) @ 10Gbps
Network: 192.168.100.x
1 x Adapters - Phone Network @ 1Gbps
Network: 192.168.104.x
The problem is that the failover and cluster manager (FCM) is selecting the Production network for one node and the cluster for the other. I want the cluster network to be dedicated for managing the hyper-v, migrations and replication.
I have configured the adapter order on the nodes as follows:
vEthernet (vSwitch_Production)
Team_Production
NIC1 - Production
NIC2 - Production
NIC3 - Production
NIC4 - Production
NIC5 - Cluster
NIC6 - iSCSI
NIC7 - iSCSI
NIC8 - Phone
Can anyone please comment as to if this network setup will work with Hyper-V HA and, how I can ensure the correct adapters are selected by FCM?
Answer: Launch FCM, specify a required cluster and go Networks. Then select the network you want to modify settings for and click Properties. This way you can allow or forbid cluster/client communication on certain networks. You can also manually configure live migration channels over there.
More recommendations on how to isolate network traffic on Hyper-V cluster can be found here: https://technet.microsoft.com/en-us/library/dn550728(v=ws.11).aspx
As for your projected network design, it looks reasonable to me. But still refer to this article to learn more about different approaches to networking setup on Failover Cluster with Hyper-V: http://www.dell.com/support/article/us/en/19/SLN268062/EN
Comment: Try to segregate your production and cluster networks by using different subnets. AFAIK Failover Clustering can recognize only one IP address per subnet, so it ignores all of the rest. This is a good practise, especially if you want to have that networks dedicated to specific traffic type.
Comment: Thanks for the reply, this issue is not isolating the traffic type its the fact that FCM is detecting the wrong adapter in the network section.
Comment: I did consider breaking the IP scopes to differnt subnets however does anyone know how FCM choose which IP per subnet. This is the key point of my question, if I could get the answer to that I could be up and running.


Using COALESCE to avoid dynamic SQL?

Question: I would like to use following sql to avoid constructing sql dynamically:
SELECT CommentID, Comment,
FROM Comments
--if Author id is not null then filter upon author id otherwise get all comments (ignore author id)
WHERE AuthorID LIKE COALESCE(@AuthorId, '%')
   --if comment type is present filter upon it, otherwise get all comments (ignore comment type condition)
   AND CommentType LIKE COALESCE(@CommentType, '%')

I want to know is that safe way to approach this problem?
EDIT:
Here is final code that satisfy my need to ignore search parameter if is null and applied it if is present:
SELECT CommentID, Comment,
FROM Comments
--if @AuthorId is not null then filter upon @AuthorId otherwise get all comments (ignore author id)
WHERE AuthorID = COALESCE(@AuthorId, AuthorID)
    --if @CommentType is present filter upon it, otherwise get all comments (ignore comment type condition)
    AND CommentType = COALESCE(@CommentType, CommentType)

Answer: If AuthorId or CommentType are nullable, this will not work. Instead you should use an OR:
SELECT CommentID, Comment,
FROM Comments
WHERE ( @AuthorId Is Null Or AuthorId = @AuthorId )
    And ( @CommentType Is Null Or CommentType Like @CommentType )

Btw, if AuthorId and CommentType are not nullable, then you can use Coalesce like so:
SELECT CommentID, Comment,
FROM Comments
WHERE AuthorId = Coalesce(@AuthorId, AuthorId)
    And CommentType = Coalesce(@CommentType, CommentType )

The catch is that this is an exact match as opposed to a wildcard match like you had with LIKE.
Comment: No field in Comments table is nullable, I beleive that I'm safe with proposed code?
Comment: @krul - If no field on which you are filtering is nullable, then you can use Coalesce but it will result in an exact match. If you need a wildcard match, then you need to use the first approach I provided.
Comment: @krul - You can of course mix and match. Use Coalesce for exact match columns and use the `@Foo Is Null Or Foo Like @Foo` construct for those where you want a wildcard match.
Comment: Thanks, that clarifies issue, due to explaining in-proper use of wild card in my code I will grant you answered check.
Comment: Would you say that your code is more performant than the COALESCE option that Krul posed in his question?
Comment: @wcm - I would guess that my solution would be faster in that it does not actually have to perform the LIKE comparison when the parameter is null. However, if there are lots of AND statements, it can start to be a problem (in either solution). If that happens, then an alternate solution such as free-text should be sought.
Answer: Looks good to me but in this particular case you can ISNULL instead of COALESCE.
Just thought that I would point out that I don't think you will return any values if the AuthorID or CommentType is null.
Comment: ISNULL and COALESCE effectively do the same thing except that COALESCE can handle more than two parameters. In addition, I would recommend against ISNULL since COALESCE is the ANSI standard.
Comment: thanks for fast response, I'll wait to see if there are some more opinions and approve your answer ...
Comment: OK, to conclude, since no field is nullable in my comments table I can assume that code will safely include condition if condition is not null or ignore condition if condition is null?
Comment: Did not know that about COALESCE :)  I'll start using that more myself.  I have recently started doing a lot more Oracle stuff.

Using COALESCE to avoid dynamic SQL?


Can an eligible receiver play at an ineligible position?

Question: I was reading through an older question here and I was wondering if a player whose number lies in the eligible receiver range can line up as an interior offensive lineman?
Also, if they can line up there (I'm thinking in case of some injury) are they automatically still eligible receivers without any additional declaration?
Answer: Yes, an eligible receiver-by-number may play in an ineligible position, similarly to how an ineligible player-by-number may line up in an eligible position.  In both cases, they must report to the referee, who will then report it over the intercom or simply directly to the defensive huddle (though, usually over the intercom), and will do so each down the player remains in the game (and the player must report each down).  Rule 5-3-1 states this:

ARTICLE 1. REPORTING CHANGE OF POSITION. An offensive player wearing the number of an ineligible pass receiver
  (50–79 and 90–99) is permitted to line up in the position of an eligible pass receiver (1–49 and 80–89), and an offensive player
  wearing the number of an eligible pass receiver is permitted to line up in the position of an ineligible pass receiver, provided
  that he immediately reports the change in his eligibility status to the Referee, who will inform the defensive team.
He must participate in such eligible or ineligible position as long as he is continuously in the game, but prior to each play he
  must again report his status to the Referee, who will inform the defensive team. The game clock shall not be stopped, and the
  ball shall not be put in play until the Referee takes his normal position.

The New England Patriots played with this extensively during the AFC Championships last year (2014-15).  As such, a rule change was made for the 2015 NFL championship season by way of a note on the preceding rule (5-3-1):

Note: An offensive player wearing the number of an eligible pass receiver who reports as ineligible must line up within the
  normal five-player core formed by ineligible players. The player cannot be more than two players removed from the middle
  player of a seven-player line.

This is because the Patriots would have lines where, for example, two players with eligible numbers were located on the line, one of which where the "tackle" normally is (2 players left of the center), and one in the normal "tight end" position (3 players right of center), but the "tight end" is ineligible and the "tackle" is eligible.  That was legal at the time, but no longer is.