What does the compound time require to be?

Question: I am trying to study music theory which would help me learn various aspects of music, so I started with basics and then time signature. It states that for a music to be in compound time each beat is divided to three notes but the diagram(in the book that I'm following) shows:

how are the notes first divided to three but in the second they're again divided in two. Is this some kind of an error?
Answer: The first level is "How many beats in a bar"
The second level is "Do they subdivide into twos or threes?"  This is the simple/compound question.
There are further levels!
Your book is not being very helpful in writing every note as a crotchet (quarter note).
Answer: Let's forget about the graphic and just go over what the diffrences between simple and compound time signatures which lies in how the grouping of each is done.
In simple time, you just have one grouping of notes per measuer like in 2/4 you have a group of 2 quater notes per measuer, 3/8 you have a group of 3 eighth  notes per measuer,  2/2 you have a group of 2 half notes per measuer, ect.
In compound time, you have two levels of grouping. One level of grouping is to add another beat grouping, typically grouping in 3, to give the time signature more of a simple feel  like the ones above and the other is grouping the remaining groups.
For example in 12/8, we group the 12 eigth notes into groups of 3 which we have 4 of total. We then look at the group of 3 eigth notes as a dotted quarter note and now we can break the measure up into a quadruple meter feel, but there is still the underlying groping of the eigth notes which is why we call them compound time signatures which is because we are using multiple groupings.
The diagram you came across is very confusing in nature because it approaches it from an odd angle at just looking at subdivisions in isolation which isn't the clearest  way to demonstrate that. Try looking at Music thoery.net's lesson and see if that clears it up for you.
Comment: @LaurencePayne what's confusing about it? That's exactly what is going on in compond time signatures and even the link provided explains it in almost the exact same way. There's a reason why the tempo marks in 6/8 are set a dotted quater note as that is where we break up the measure in that meter, but the subgroup of 3 eighth notes is still observed inside that grouping.
Comment: I have rarely seen a more confused and unhelpful answer!  I guess that deserves some sort of a prize?


If two modules both defined the same menu path in 'hook_menu', which one Drupal will choose?

Question: For example, "moduleone" defines the path 'admin/hello', which output print_moduleone_stuff().
/**
 * Implements hook_menu()
 */
function moduleone_menu() {
  $items['admin/hello'] = array(
    'title' => 'Module One Hello World',
    'page callback' => print_moduleone_stuff,
  );
  return $items;
}

"moduletwo" defines the path 'admin/hello', which output print_moduletwo_stuff().
/**
 * Implements hook_menu()
 */
function moduletwo_menu() {
  $items['admin/hello'] = array(
    'title' => 'Module Two Hello World',
    'page callback' => print_moduletwo_stuff,
  );
  return $items;
}

Both modules defined 'admin/hello' path for different result. With these two module enabled, how does Drupal select one than another? How does Drupal solve the conflict?
Answer: The function invoking hook_menu() is menu_router_build(), called by menu_rebuild(). It contains the following code.
  foreach (module_implements('menu') as $module) {
    $router_items = call_user_func($module . '_menu');
    if (isset($router_items) && is_array($router_items)) {
      foreach (array_keys($router_items) as $path) {
        $router_items[$path]['module'] = $module;
      }
      $callbacks = array_merge($callbacks, $router_items);
    }
  }
  // Alter the menu as defined in modules, keys are like user/%user.
  drupal_alter('menu', $callbacks);

If there are two modules defining the same route, the last module in the array returned by module_implements() will override the value defined from the other modules.
The second parameter required by module_implements() is defined as:

$sort By default, modules are ordered by weight and filename, settings this option to TRUE, module list will be ordered by module name.

Since menu_router_build() doesn't pass the second parameter to menu_implements(), the function is using the default value for that parameter. This means the list of modules are ordered by their weight and filename; when two modules have the same weight, the first module that appears in the list is the one that alphabetically comes first.
Furthermore, any module implementing hook_module_implements_alter() can alter the order the hooks are invoked.
For this reason, you should not assume to know in which order the hooks are invoked.
If the purpose of the code is altering the route implemented by another module, for example because a route should be removed when a second module is installed and enabled, the code should use hook_menu_alter(). If you are trying to understand which module would "win" in the case of route conflicts, I would rather avoid such route conflict, and define a route that is not already defined from another module.
If then you are implementing hook_menu_alter(), and you want to be sure your module is executed last, to be the module that effectively overrides a route, you should implement hook_module_implements_alter() too.
function mymodule_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'menu_alter') {
    // Move mymodule_menu_alter() to the end of the list. module_implements()
    // iterates through $implementations with a foreach loop which PHP iterates
    // in the order that the items were added, so to move an item to the end of
    // the array, we remove it and then add it.
    $group = $implementations['mymodule'];
    unset($implementations['mymodule']);
    $implementations['mymodule'] = $group;
  }
}

Comment: so clear and helpful, thanks. also thanks for mentioning the usage hook_menu_alter() in this case.
Comment: what if two modules define same path in hook_menu_alter()?  same rules applied?
Comment: `hook_menu_alter()` is not used to define new menus, but to alter the existing ones. If two modules alter the same menu, the alteration that survives is the one from the module that is executed for last.
Comment: Great answer, thank you
Answer: Whichever module has a lower weight value in the system table will be called first, so the module with the higher weight value will 'win' in this case.
If the weights are the same for two (or more) modules I believe there is no specific ordering done other than the ordering that comes directly from the MySQL table (I could be wrong about that though).
As the return results from the invoke of hook_menu are just put into a single array of menu items there will never be a 'conflict' as such, the results from later calls to hook_menu will simply override those from the earlier calls.
Comment: According to _Pro Drupal Development_, modules with equal weight are called in alphabetical order by their system name.
Comment: What reported by that book is correct: The list of modules implementing a hook is generally sorted by weight and alphabetically; it would not be sorted if `module_implements()` gets `FALSE` as second parameter, but functions like `module_invoke_all()` calls it with just a parameter.
Comment: My previous comment is not completely exact. What I report in my answer is correct.


Qual a linguagem utilizada para programar um sistema operacional?

Question: Qual a linguagem utilizada na programação de um SO?
Comment: Muito Ampla a pergunta. Quer saber apenas do Windows ou de alguma distribuição do Linux também?
Comment: Os principais amigo
Comment: O do MSX é feito grande parte diretamente no código de máquina mesmo, outras partes em assembly.
Answer: Essencialmente qualquer uma que desejar. De uma certa forma é possível escrever um sistema operacional não convencional até com JS, embora seja uma linguagem péssima para isso e haverá fortes limitações. Já há OSes escritos em Lua (aqui e aqui).
Alguns foram escritos em C#: (Singularity, COSMOS, SharpOS, Midori). Outros em Java. Enfim, qualquer linguagem pode ser usada para escrever um OS. Eu poderia sair listando OSes em praticamente cada uma das linguagens mainstream e até mesmo em outras de nicho. Isso pode ser lido aqui.
Linguagens de programação possuem a capacidade de executar qualquer tarefa. Suas implementações podem limitar um pouco o que elas podem acessar no hardware onde vão rodar.
Claro que algumas linguagens são mais adequadas. Por isso C é muito usada para isso. C++ também vem sendo usada com sucesso cada vez mais. Assembly dominava esse tipo de desenvolvimento por muito tempo e ainda há casos assim.
O Windows é essencialmente escrito em C (não vou postar aqui por motivos óbvios, mas a internet "disponibiliza" os fontes de uma versão antiga dele). Muitas APIs e serviços extras são escritos ou adaptados para C++. Claro que possui algumas pequenas partes em Assembly, é difícil que não exista pelo menos um pequeno trecho de um OS que não seja. Softwares agregados podem eventualmente ser escritos em outras linguagens, mas duvido que possam ser considerados partes do OS.
A implementação da linguagem pode ser mais importante para definir se dá para escrever um OS do que a linguagem especificada.
Leitura complementar:

O que caracteriza uma linguagem de programação?
O que é linguagem de programação, IDE e compilador?

Coloquei no GitHub para referência futura.
Comment: Porque seria pirataria.
Comment: Muito obrigado por compartilhar seu conhecimento comigo e com todos do StackOverflow, tirou todas as dúvidas possíveis.
Comment: "não vou postar aqui por motivos óbvios". Poderia explicar?
Answer: No caso do Windows é  C, C++, C# e algumas coisas em assembly segundo a própria microsoft. Linux é só pegar o código da distribuição na internet e olhar. A maioria utiliza muito C, C++ e assembly pra coisas que precisam ser muito otimizadas.
Answer: Atualmente os sistemas operacionais "de produção" são escritos em C.
Comment: Todos eles? tem certeza? O que seria "de produção"?
Comment: Logo ? How soon is soon ? :) Pra mim esse "logo" vai ser algumas dezenas de anos ainda....
Comment: Windows, Linux, UNIXes em geral (incluindo BSDs)....mainframes IBM possuem sistemas operacionais escritos em assembly, mas de modo geral acho que estão em regime de manutenção, não de evolução...deve haver sistemas real-time/embarcados escritos em assembly....os sistemas "de produção" que considero são uma questão de opinião, claro, por isso as aspas, mas na prática, atualmente escrever um sistema operacional em outra linguagem que não C é algo um tanto exótico
Comment: Tá explicado, mas cada vez se usa menos C e mais outras linguagens para escrever SOs, logo C talvez seja considerada exótica para isso :)
Comment: Como grande parte do SOs novos já são escritos em outras linguagens, de uma certa forma já está acontecendo
Answer: A linguagem C foi desenvolvida para criar sistemas operacionais de modo a facilitar o o processo do programador ( para nao ter que ficar  usando assembly). Hoje em dia ainda é usado "C"
Comment: Quanto as outras ainda não sei mas essa publicação pode ser considerada de  baixa qualidade, é um comentário que não responde a pergunta feita na página. Está equivocado, C é uma linguagem de multipropósito e foi concebido em 1972, por Dennis Ritchie e Ken Thompson, com o intuito de criar ferramentas para o sistema operacional UNIX. Só para constar o UNIX foi desenvolvido em 1970 escrito em assembly, somente em 1973 saiu a primeira versão, System4, escrita em C.
Comment: porque apenas minhas resposta esta ganhando "-" . Exijo um feed Back... minha reputação esta caindo e atrapalhando minha interação
Comment: @AugustoVasques igual você disse "Foi criada em 1972 por Dennis Ritchie para ser usada no desenvolvimento sistema operacional Unix"  Não disse que sempre foi utilizado C mas que a criação do C teve como objetivo a criação de SOs


$A = \mathbb{R}$ , and $a\mathrel{p} b$ if and only if $\sin a = \sin b$

Question: My question is: For the relation $p$ described below, determine if $p$ is reflexive, symmetric,
transitive, anti-symmetric. In each case, if $p$ is an equivalence relation, describe the equivalence classes.
$p$ = $\mathbb{R}$, and $a\mathrel{p} b$ if and only if $\sin a$ = $\sin b$
Okay so now we know that $p$ is symmetric, reflexive and transitive, we know that it is an equivalence relation. Although how would I describe the equivalence classes?
Answer: Hints:
reflexive, $a p a$ since $\sin a=\sin a$.
symmetric, If $a p b$, then  $\sin a=\sin b$, and hence  $\sin b=\sin a$, which shows that $b p a$
.
transitive, If $apb$ and $bpc$, then  $\sin a=\sin b$ and  $\sin b=\sin c$, and hence  $\sin a=\sin c$.
So $apc$.

$[a]=\{b\in \Bbb R: \sin a=\sin b\}$.
Comment: OP:  and the equivalence classes are?
Comment: Thank you for your answer Paul, I have a whole bunch of these questions but now I realise they are quite simple. Also Sammy Black is correct.. How would I go about describing the equivalence classes?
Comment: Is it the case of since sin a = sin b \iff sin a - sin b = 0
Comment: It is: $[a]=\{b\in \Bbb R: \sin a=\sin b\}$.


What is the magnitude of a dual number? I'm not finding information on this.

Question: I'm investigating dual quaternions and am having to learn a lot of stuff myself because I'm finding very few resources on the mathematical background.
I know that the magnitude of a dual quaternion is a dual number.  This makes sense because it is a dual number with real quaternions jammed into its real components.  Alternately, it is a quaternion with dual numbers jammed into its real components.  Both approaches yield the same form.
Question: But what is magnitude of a dual number?  Does that question even make sense?
I know that the magnitude of a complex number is the root of sum of the squares of the real numbers.  Ditto for a real quaternion.  But the dual number operator epsilon (I'll abbreviate it as simply 'e') is not like the irrational unit numbers.  Square any of the irrational unit numbers and you get -1.  Square e and you get 0.  This makes the dual number completely useless as a rotor, but it still has use as a multi-part number.  I'm wondering if nature of this dual operator also makes it unsuitable to calculate its magnitude with the Pythagorean Theorem.
Again, the magnitude of a dual quaternion is a dual number, and it doesn't make sense to me to calculate the magnitude again just to get a pure real number, so I've postulated that the magnitude of a dual number is simply itself, like saying that the magnitude of the real number 5 is simply 5.  The magnitude of 1189 is 1189.  The magnitude of 35 + 14e is 35 + 14e.  But I don't know how to prove this or if it is even right.
Help?
Comment: That's the convention.  Look up any of the works of V. Majernik on the subject.  For instance [this one](http://przyrbwn.icm.edu.pl/APP/PDF/86/a086z3p01.pdf) on complex, split-complex, and dual numbers or [this one](http://przyrbwn.icm.edu.pl/APP/PDF/87/a087z6p02.pdf) on dual quaternions.
Comment: Its just the absolute value of the real part.  For example $\|-35 + 14\epsilon\| = |-35|=35$.
Comment: @Bye_World why is this the right notion, out of all the possibilities one could think of? Actually, that doesn't seem to be right at all.
Comment: It's chosen to satisfy the identity $z\bar z = \|z\|^2$ -- the same formula that the complex numbers and split-complex numbers satisfy.  So $\|-35 +14\epsilon\|^2=(-35+14\epsilon)(-35-14\epsilon) = (-35)^2-(14)^2\epsilon^2 = (-35)^2$.
Comment: OK, I agree with this.
Comment: @Bye_World Thanks for the explanation.  That makes sense.  I'll have to update some of my ideas and notes that I was writing for myself, but this makes sense.
Comment: @Bye_World Follow-up question: Where did you find the definition for magnitude of a multiple-component number?  It makes sense to me, but I'd like a reference if you can provide one.

I looked at the papers that you linked but couldn't find the words 'magnitude' or 'norm' in them.
Comment: @JohnCox I don't seem to have the book anymore, but there's a nice book on this subject called *Hypercomplex Numbers* by I.L. Kantor & A.S. Solodovnikov.  I'm relativitely sure it'll have that definition.  However, look again at that first link I gave.  On the second page Majernik defines this as the "absolute value" of a "two-component number system" (including dual numbers).  He means the same thing you're calling the magnitude and I usually call the modulus.
Answer: The modulus/ norm/ magnitude of a dual number $z=a+b\varepsilon$ is just the absolute value of the real part $|a|$.
Some background:  Up to isomorphism, there are exactly $3$ unital $2$-dimensional algebras over $\Bbb R$.  They are the complex numbers, split-complex numbers (AKA hyperbolic numbers), and dual numbers.  All of them are defined to have the same formulae for conjugation and modulus.  For any member of one of these algebras $z=a+b\omega$, where $\omega$ is the "imaginary" unit of the given algebra, the conjugate is defined as $\overline z = a-b\omega$ and the modulus is defined by $\|z\|^2 = z\overline z = \overline z z$.
We can see that this is a good definition, because the norm will always give us a member of $\Bbb R$: $\|z\| = \sqrt{z\overline z} = \sqrt{(a+b\omega)(a-b\omega)} = \sqrt{a^2-b^2\omega^2}$, where $\omega^2 \in \Bbb R$.
In the case of the dual numbers, $\varepsilon$ is defined by $\varepsilon \ne 0$ and $\varepsilon^2 = 0$.  Then for $z=a+b\varepsilon$, we have $\|z\| = \sqrt{a^2-b^2\varepsilon^2} = \sqrt{a^2}  = |a|$.
NOTE: You might also be interested to know that each of these algebras has a well-defined exponential form as well: $z=a+b\omega = \pm \|z\|e^{\operatorname{Arg}(z)\omega}$, where $\operatorname{Arg}(z)$ is akin to an angle -- in fact in the complex numbers it IS the angle.  The norm of the dual number $re^{\theta\varepsilon}$ is just $|r|$.
In fact, the  exponential form of the dual numbers is particularly easy.  We define the exponential of a number by the infinite series $$e^x = \sum_{i=0}^\infty \frac {x^i}{i!}$$
In the case of dual numbers we have $e^{\theta\varepsilon} = 1 + \theta\varepsilon + \frac {(\theta\varepsilon)^2}2 + \frac {(\theta\varepsilon)^3}6+\cdots$.  Notice that all of the terms which include a power of $\varepsilon$ greater than $1$ are $0$.  Therefore this infinite series has only $2$ non-zero terms: $e^{\theta\varepsilon} = 1 + \theta\varepsilon$.  Therefore the exponential form of the dual number $z=a+b\varepsilon$ is just $$z=ae^{(b/ a)\varepsilon}$$
The cavaet in this representation is clear, however: $\operatorname{Arg}(z)=\theta$ does not exist for pure imaginary numbers in the dual number plane.
Comment: I am not sure that we want to call this modulus a norm.  Indeed, a norm requires `norm z = 0  ==>  z = 0`.  The modulus described here does not seem to respect this condition.  What we have here is a seminorm, which may assign 0 to non-zero vectors.
Comment: Note that if you choose this norm, the induced topology does not distinguish $a + b_1 \varepsilon$ and $a + b_2\varepsilon$ (and thus is non-Hausdorff); which means that the limit of the exponential series (taken under that topology) is not unique. The limit is well-defined if you use the product topology, but this isn't compatible with the norm $\|a + b\varepsilon\| = \|a\|$.


The map $\frac1{1-z}$

Question: I want to find the image of the unit circle under the map $\frac1{1-z}$. I first rewrote this as
$$
\frac{1+z}{1-z^2}
$$
But on the unit circle, $z^2 = 1$. So I get $\infty$ for the image of all points on the unit circle as the result. But I thought linear fractional always map circles to lines or circles. Can anyone point out what I did wrong?
EDIT: It turns out that I was confusing $z^2$ with $\bar{z}$, so not all points on the unit circle satisfy $z^2 = 1$. I should let $z = x + iy$ and plug that into the map instead.
Comment: Not many points on the unit circle satisfy $z^2=1$.  You're confusing $z^2$ and $z\bar z$.
Comment: It's not true that on the unit circle $z^2 = 1$. You forgot something here.
Comment: Oh! I see. Let me try something else.
Answer: The easiest way to find the images of circles and lines (generlized cirlces) under linear fractional transformations (or Möbius transformations) is to simply look at three points on the preimage. Three points on the unit circle is 1, $i$ and -1. Now let
$$f(z) = \frac{1}{1-z}$$
and observe that
$$f(1) = \infty, \quad f(i) = \frac{1+i}{2}, \quad f(-1)=\frac{1}{2}.$$
This shows that the image of the unit circle under $f$ is the straight line through $\frac{1}{2}(1+i)$ and $\frac{1}{2}$, i.e. $\{ z \in \mathbb{C} \, | \, \Re(z) = \frac{1}{2} \}$.
Comment: I see! This is indeed a lot simpler than I thought. Thanks!
Comment: So how do you explain that $\infty$ has real part $1/2$?
Comment: To say that $\infty$ has real part 1/2 would be a bit tabloid. The fact is that $\infty$ understood as a point in the extended complex plane can have any real part. This has a rigorous and interesting interpretation in light of stereographic projection onto the Riemann-sphere. However, I think that an in depth discussion of this is beside the question.
Comment: Different textbooks and instructors do this differently, bur if we consider $f$ as a map of the extended complex plane and want to explicitly state that $\infty$ is in the image, we could write it as $\{ z \in \mathbb{C} \, | \, \Re(z) = 1/2 \} \cup \{ \infty \}$.
Answer: Let $w=\frac1{1-z}$. Then, $z=1-\frac1w$ and, with unit circle $|z|=1$
$$|z|^2=(1-\frac1w)(1-\frac1{\bar w})=1\implies w+\bar{w}=1
\implies Re(w)=\frac12$$
which is the vertical line $x=\frac12$ in the complex plane.
Answer: There are sort of three things going on here:  $1) z\mapsto-z,2)z\mapsto z+1$ and $3)z\mapsto \dfrac1z$.  The first is reflection about the origin, the second translation, and the third inversion.
But personally I prefer to use the method of checking what happens to $3$ points, since generalized circles get sent to generalized circles by Mobius transformations.

The map $\frac1{1-z}$


Problemas conversão/formatação de data

Question: Estou com problemas para formatar uma data para útil, eu preciso formatar uma data que esta Tue Nov 22 00:00:00 BRST 2017 (exemplo) para data no formato dd/MM/yyyy.
Eu andei vendo alguns links, como: Como converter uma string em data ou date? porém não esta dando certo, acredito não estar sabendo usá - los.
        Date data = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(data);

        //eu ultilizo o calendar em alguns calculos, depois eu seto ele no meu pojo.
        //porém ele vem nesse formato, exemplo: Tue Nov 22 00:00:00 BRST 2017
        //quero converter em dd/MM/yyyy
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        meuPojo.setVencimento(sdf.parse(calendar.getTime())); // minha tentativa de converter, porém da erro de: "incompatible types: Date cannot be converted to String"

        //exemplo de como é o meu método setVencimento

public void setVencimento(Date data){
            this.data = data;
        }

Comment: Se o `setVencimento` recebe um `Date` é só passar `calendar.getTime()` pois isso já é um `Date` não há necessidade de fazer parse. Não pode fazer parse de um `Date` que é o que está a tentar fazer
Comment: Um detalhe, quando você faz `new Date()`, está criando um `Date` correspondente à data/hora atual. E ao chamar `Calendar.getInstance()`, está criando um `Calendar` correspondente à data/hora atual. Então criar o `Date` e depois passar para `Calendar` com `setTime` é redundante e desnecessário (só faria sentido se o `Date` não fosse correspondente à data/hora atual).
Answer: Se o método espera um tipo util.Date, pra que fazer conversão? Passe o Date direto pelo método getTime() da classe Calendar, pois ela já retorna um tipo util.Date e não precisa nem criar esse tanto de código:
meuPojo.setVencimento(calendar.getTime());

Se der problemar de tipos incompativeis, cheque os imports se por acaso não está utilizando a classe sql.Date ou invés de util.Date.

Ainda sim, recomendo que aprenda sobre a nova API de datas do java, pois ela é bem mais fácil de lidar e é mais precisa.
Comment: @Java o problema não está no `set` mas no sitio onde você escreve/mostra a data. É nesse local que tem de aplicar a formatação. @Articuno Bem interessante essa recomendação de API de datas, que eu pessoalmente não conhecia.
Comment: não posso passar new Date(), preciso das datas que estão dentro do calendar, ele recebe datas de acordo com algumas condições, por isso tenho que formatar em baixo.
Comment: @Java você não mencionou isso nem no código e nem na pergunta.
Comment: eu escrevi ali em cima, nos comentários do codigo
Comment: @Java então passe gettime direto, o retorno já é um Date.
Comment: mais ai ele me retorna aquela data Tue Nov 22 00:00:00 BRST 2017, ai queria formatar ela em dd/MM/yyyy
Comment: @Java você disse que o método recebe um tipo Date, ele não é formatavel dessa forma. Pra formatar como quiser, precisa converter para string. Da uma lida  [nesta resposta](https://pt.stackoverflow.com/a/234357/28595) para entender melhor.
Comment: é que seria mais fácil guardar ela formata ali, o duro de converter pra string, é que ai o setVencimento não vai aceitar ela.
Comment: @Java veja a classe DateHelper que o Victor fez em resposta a um problema que tive [neste post](https://pt.stackoverflow.com/a/122302/28595), provavelmente ela irá resolver seu problema.

Problemas conversão/formatação de data


Selecionar opção de uma lista - via Jquery

Question: conseguem me ajudar?
Estou tentando preencher um formulário via web, mas estou com dificuldades com combobox.
Consigo abrir as opções do combox, mas não consigo selecionar a opção que preciso 'VA - SUSTENTAVEL'.

Está é a opção que preciso selecionar:
VA - SUSTENTAVEL

Alguma dica?
Answer: Assumindo que você precisa pegar o valor que o usuário seleciona na combobox
Eu trocaria as tags html para select, adicionaria um id (por exemplo: id="meuId") e aninharia as opções com a tag option, que possue a propriedade value.
Então, com jquery, faria:
var valor = $(#meuId).val();
Comment: Olá, Pedro.
Obrigado pela resposta. No caso, estou preenchendo um formulario em uma plataforma, não um outro usuário. Estou utilizando as funções para alimentar os elementos solicitados.
Answer: Depois de quase uma semana quebrando a cabeça, achei a resposta!
$("span:contains('VA - SUSTENTAVEL')").click()

Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Sharepoint. How to access objects in RenderingTemplate

Question: I'm working on rendering templates (Sharepoint 2010), overrided standart new/edit/display forms with my own, but I can't get objects in code-beghind from inside RenderingTemplate class.
for e.g:
<SharePoint:RenderingTemplate ID="ParentItemsListView" runat="server">
<Template>

<asp:Label ID="label1" runat="server" />

<SharePoint:FieldLabel runat="server" ID="TitleDescriptionField"  ControlMode="Edit" FieldName="Title" />

</Template>

I need to custom FieldLabel object.
I hope someone could help me. Thanks.
Answer: You should be able to get it like this:
FieldLabel fieldLabelControl= ParentItemsListView.FindControl("TitleDescriptionField") as FieldLabel;
if(fieldLabelControl != null)
{
  //Do something with it
}


How to make a list item width as body width instead of container width

Question: Hi i am trying to set the width of list item to browsers width, when i set width to 100% then it is taking parent's width, but i want it to take whole browser width as that list item width.
i have used following code for the child item of list item div
      .submenu {
       position: absolute;
        left: 0;
        right: 0;
       background: #ddf0f9;
        border-bottom: 5px solid #2ea0cb;
        z-index: -1;
           white-space: nowrap;
           padding: 0;
          }

it doesn't worked, it is taking parent element width as it's width.
similar to mashable.com submenu
Comment: What browser support do you need
Comment: Please add some code or jsfiddle please.
Comment: set position absolute to the ul. be sure the container doesn't have a relative position.
Answer: Use the following:
.classname{
    margin-left:0;
    margin-right:0;
    width:100%
}

Answer: mashable.com set position: absolute; left: 0; right: 0; to the list item, and does not set a position for any of its parents. Since a absolute positioned element positions itself based on its first positioned parent, the list item will have the width of the highest parent (the body).
If you don't need positioning for any of the list item's parents then you can use that method.


Analyze multiple csv files in a folder and write ONLY the results to a single csv file using pandas

Question: I can read and analyze a single csv file and add new columns to the same data frame. However, I cannot do that for multiple files in a folder and save ONLY the results to a single csv file.
I have tried like the following for a single csv file
df1 = pd.read_csv('file.csv')
df1['Number of rows'] = (len(df1))
df1['Number of unique data'] = df1['column1'].nunique()
df1['Number of A type in Column2'] = df1['column2'].value_counts()['A']
df1.to_csv('df1_results.csv' , index = False)

But, I need the result like the following image in a csv file for multiple files in a folder:Need result like this
Answer: You can iterate over the different csv files in your input folder, process the corresponding data and append the output dataframes to a list of dataframes:
import pandas as pd
import os
list_of_dataframes = []
path = "path to your csv files"
list_of_files = os.listdir(path)

for file in list_of_files:
    if file.endswith('.csv'):
        df1 = pd.read_csv(file)
        df1['Number of rows'] = (len(df1))
        df1['Number of unique data'] = df1['column1'].nunique()
        df1['Number of A type in Column2'] = df1['column2'].value_counts()['A']
        list_of_dataframes.append(df1)

The only thing left to do is concatenate the list of dataframes into a single dataframe that you can then output to csv:
df = pd.concat(list_of_dataframes)
df.to_csv('df_results.csv' , index = False)

Comment: Thanks for the answer Sheldon! If I specify the folder with multiple csv files as 'list_of_files' in your code then it gives 'IsADirectoryError: [Errno 21] Is a directory: '

Also, if i use 'df1 = pd.read_csv('file.csv')' then I am reading a single file not multiple files one by one. Thanks again. Sorry for the naive question
Comment: You may use `os.listdir()` to list all csv file in your folder. I edited my answer to show you how to proceed.


text overlay image views

Question: I want to show images on my website. website example
When I hover over the images, the page title shows up. But when you move with your cursor over the text it won't link to my colorbox popup.
How can I solve this problem. I've been looking for a long time.
I've used the rewrite results to get the title on hover.
Comment: this is a css/js issue but basically since the z index of your text is above your image, it as you see covers over that part of the image (and link) and therefore doesn't acknowledge the click.  what you'll have to do is either use js and look into bubbling and capturing of events or to use rewrite to make this span clickable as well with the same code as the underlying image.
Comment: Will have to do it with rewrite because i want to use as less js as possible.
First I have my Title field and then Image field. I excluded my title field  and put this rewrite in image field.

[field_image]
[title]

i have to add an  ?
Comment: For the info, I use the field slideshow module in views.
Comment: Please add the extra information to the question. The users who votes to close a question don't look for comments, whose purpose is not making a question clearer.
Answer: There are 2 solutions:

use title as the text and it will automatically redirects you to the content page when you click on it.
in your views add the path field to your fields,

apply it and now check the exclude from display checkbox in its setting. go to Rewrite Results and set these settings:

click ok and move the path field at the top of the fields.

Now click on the field that displays your text on the image and set these settings:

Now that field will be a link to your content.
Comment: I got this working but I want to link the title to open my colorbox popup not the node
Comment: pointer-events:none did the trick!
Comment: @user2301868 if it is not important to yuo to use colorbox, you can use tinybox (http://sandbox.scriptiny.com/tinybox2/) it does the same thing. then use the `title` href as the url.

text overlay image views


backup servers for domain

Question: I have domain example.com and I have site hosted on two servers serverip1 and serverip2
I want serpverip1 be the default server and if anything goes wrong then example.com should direct all requests to serverip2 (like I want serverip2 to be my backup server)
any suggestion ?
Answer: This cannot be done with DNS. If you're thinking that you've heard something like this being done, you might be confusing Round Robin DNS with some form of redundancy or failover. Round robin DNS will distribute a different IP address to a DNS client requesting name resolution.
To do anything like this with DNS, from a theoretical standpoint, you'd need to switch your example.com domain A records from the failed node, to point to the standby node. You'd want your TTL values on the A record to be very low so that most DNS client won't have an old, stale record. However this is assuming that DNS servers across the globe that cache your record will always honor TTL values, which is not the case.
To make your two servers be able to handle a failure event, you will need a hardware load balancer in front of the two servers to intelligently determine when one of the two web servers is non responsive and then have all traffic forwarded to the secondary one. The DNS A record will point to the load balancer, and the load balancer will then distribute traffic in the manner that you desire to the servers behind it.
Comment: And if you are concerned with making things redundant you probably want a PAIR of load balancers in case one of those dies too!
Comment: ...and then a pair of drops to each load balancer. And a pair of geo-diverse datacenters. And a pair of alternate universes...
Comment: Yep.  And redundant power, generaters, routers, switches, etc.  Remember murphys law tells you the item you didnt make redundant will probably fail first! Just keep adding everything in pairs until you go 'aw @#$% it, if that fails I'm just gonna give up'

backup servers for domain


How to understand the definition of weak convergence of stochastic processes

Question: I have some problems with the definition of $\textit{weak convergence of stochastic processes}$. To ask my question, we start with two well-known definitions corresponding to measures and random variables.

$\textbf{Definition 1 (weak convergence of measures).}$ Suppose $\left(\mu_n\right)_{n =1}^{\infty}$ is a sequence of probability measures. Then we say that $\mu_n$ converges weakly (or in distribution) to a probability measure $\mu$ and write $\mu_n \xrightarrow{\mathcal{D}} \mu$, if
  $$  \forall \, \varphi \in \mathcal{C}_b(\mathbb{R}) \colon \int_{\Omega} \varphi \, \text{d} \mu_n \xrightarrow{n \to \infty} \int_{\Omega}\varphi \, \text{d} \mu, $$
  where $\mathcal{C}_b(\mathbb{R})$ denotes the set of continuous and bounded functions.

$\textbf{Definition 2 (weak convergence of random variables).}$ Suppose $\left( \Omega, \mathcal{F}, \mathbb{P}\right)$ is a probability space and $\left(f_n\right)_{n =1}^{\infty}$ is a sequence of random variables. Then we say that $f_n$ converges weakly (or in distribution) to a random variable $f$ and write $f_n \xrightarrow{\mathcal{D}} f$, if
  $$  \forall \, \varphi \in \mathcal{C}_b(\mathbb{R}) \colon \ \mathbb{E} \varphi(f_n)\xrightarrow{n \to \infty} \mathbb{E} \varphi(f) \Longleftrightarrow \int_{\Omega} \varphi(f_n(\omega)) \, \text{d} \mathbb{P}(\omega) \xrightarrow{n \to \infty} \int_{\Omega} \varphi(f(\omega)) \, \text{d} \mathbb{P}(\omega) \\
\Longleftrightarrow \int_{\Omega} \varphi \, \text{d} \mathbb{P}_{f_n} \xrightarrow{n \to \infty} \int_{\Omega}\varphi \, \text{d} \mathbb{P}_f.$$

These two definitions were clear to me. The following definition is the one I am asking about.

$\textbf{Definition 3 (weak convergence of stochastic processes).}$ Suppose $f$ and $\left(f_n\right)_{n \in \mathbb{N}}$ are random variables with values in $\mathcal{C}([0,\infty))$. Then we say that the stochastic processes $\left(f_n\right)_{n \in \mathbb{N}}$ converge to the stochastic process $f$, if the corresponding laws converge weakly in the topological space $\mathbb{S}$ consiting of $\mathcal{C}([0,\infty))$ equipped with the topology of uniform convergence on comapct subsets of $\mathcal{C}([0,\infty))$. That is, if $\varphi(f_n) \xrightarrow{\mathcal{D}} \varphi(f)$ whenever $\varphi \colon \mathcal{C}([0,\infty)) \rightarrow \mathbb{R}$ Borel measurable.

Now my question is, how can I understand Definition $3$ in the sense of Definition $2$? Can I just replace $\varphi \in \mathcal{C}_b(\mathbb{R})$ by $\varphi \in \mathcal{C}([0,\infty))$? What is meant with "equipped with the topology of uniform convergence on comapct subsets of $\mathcal{C}([0,\infty))$"?
Comment: The point is that Definition 2 makes sense if you replace $\mathbb{R}$ by any other topological space, such as $C([0,\infty))$ with the mentioned topology (do you understand what this topology is?).  So you should replace $C_b(\mathbb{R})$ with $C_b(C([0,\infty)))$.
Answer: I think this is easier to understand in a somewhat broader context. You have a sequence of stochastic processes $f_n$. We think of this in three equivalent ways. We have sets $\Omega,T,A$, with $T$ the time set and $A$ the set of values of the process. We can think of each $f_n$ with any of the signatures:

$\Omega \times T \to A$ (a function of the randomization and time, symmetrically)
$T \to (\Omega \to A)$ (a time-parametrized family of random variables)
$\Omega \to (T \to A)$ (a random function of time).

In discussing weak convergence, we think in terms of the third signature. Specifically, we first give (a restriction of) the space of functions $T \to A$ some notion of convergence, through some topology. For continuous functions on a compact interval, this is naturally given by the metric of uniform convergence. For continuous functions on an unbounded domain, the metric of uniform convergence no longer makes sense, so we extend it with the topology of uniform convergence on compact subsets. That is, a sequence of continuous functions $f_n$ on $X$ converges in the topology of uniform convergence on compact subsets if the restriction of $f_n$ to $K$ converges uniformly for each compact $K \subset X $.
With this topology, we get the corresponding Borel $\sigma$-algebra. Then we say $f_n$ converges weakly to $f$ if for each Borel measurable $\varphi : (T \to A) \to \mathbb{R}$, $\varphi(f_n) \to \varphi(f)$ in the sense of distribution. So really, definition 3 is the natural extension of definition 2, we just have a different space and topology on the codomain of the functions.
Comment: Did you mean $\mathbb{E} \varphi(f_n)\xrightarrow{n \to \infty} \mathbb{E} \varphi(f)$ with $\varphi(f_n)\rightarrow  \varphi(f)$?
Comment: @user214418 I edited.


Uninstall module for which an update is pending?

Question: I have a module for which an update is pending (drush updatedb). Unfortunately the update fails, blocking other updates of course (since it seems impossible to update selectively).
Is it safe to I pm-uninstall the module? Will this automatically delete the pending update? Or do I risk ending up in an even worse limbo?
[ As noted in the comments, taking a database dump and then restoring if anything goes wrong is an option; I'm still curious if there is a general rule about uninstalling while db updates are pending) ]
(BTW the module is service_links)
Comment: So lots of struggling going on here :) @Chapabu I didn't take that as being rude; it had a smiley which in my world means it's to be taken nicely! Dan, you should have a test environment set up (and don't talk to me about resources, any developer in the world ***should*** have a disposable dev copy of their project :P) That's what you would use to answer the question yourself, in a matter of seconds. To the _principle_...As soon as you uninstall the module, it's inactive in the system table, and its install file will _not_ be queried for update functions when the time comes. Hope that helps
Comment: What happens when you try it? Do you get errors? I'm struggling to understand the motivation for asking this, surely trying it yourself would have been far quicker than asking here?
Comment: Because I might get in an even worse state if the uninstall fails, or if it seemingly succeeds but then completely blocks future updatedb's? I'm struggling to understand the motivation for asking a question with such an obvious answer :)
Comment: @dan3 I'm struggling to work out why you would post something so rude to someone trying to help. I'd suggest taking a database dump, and then running the uninstall. If it does anything funky, you can just restore the database.
Comment: My comment was an exact mirror of the one I replied to, wasn't it? I could do the dump, thanks -- however I'm still curious about the general principle (if there is a general principle)
Comment: @Clive, if you want me to accept your answer, you might want to make it an answer :)
Comment: Go with Greg's answer, looks like I over-simplified things ;)
Answer: Slight correction to Clive's comment above: as soon as you disable the module, it is inactive in the system tables. When you uninstall it, all of its data is erased from the database. The fact that a module has pending updates won't affect the operation of disabling or uninstalling it, but beware of re-enabling a module that has been disabled for a period of time.  For way too much information on this subject, see: https://drupal.org/node/1199946
Comment: So I guess once you disable you might as well uninstall; which is what I was planning to do anyway


Does temporarily quitting singing lessons affect your voice

Question: I have been taking singing lessons for 9 months, but I will have to stop for about 3 to 4 months because I will be moving to another state for some reasons. Will this cause my voice to get worse, and if so, how can I prevent this from happening and improve my singing during this time?
Is it common for singers to stop taking voice lessons for a while or permanently and still having good singing voice and making good songs?  I'm not talking about full-time professional singers like Ariana Grande, Beyonce, or Adele. I'm referring to the good independent singers who have a good voice and make good songs as a hobby or interest yet are still good at it.
Comment: Yeah it's not the lessons, it's the practice that's important.
Comment: As  long as you keep on singing in between times, to keep the voice going, it should be no problem.. If you, for any reason, don't sing at all between, then, yes, there will be degradation. Why wouldn't there be?
Comment: Occasionally you voice will even get better if you take a break, as it will have time to rest and regenerate from potential stress. If you stop taking lessons for some time the only thing that would really happen is you having less progress, unless you tend to do harmful things while singing on your own.
Comment: Singing uses many muscles: diaphragm, chest, throat, and mouth — and while everyday life uses most of them, it won't exercise them in the same way that singing does. So going for some time without singing is likely to cause some of them to lose tone. The effects could include loss of fine control, reduction in range, loss of support, etc. But of course none of that is permanent: it'll come back when you start practising again (and probably much quicker, now you know what to do).
Answer: It depends on your teacher. If your current teacher is bad, then it could actually be good to stop taking lessons!
Beyond that, it depends on a lot of different factors.
Beginner singers usually have lots of bad vocal habits (straining to hit high notes, poor breath management). Good teachers help beginners to fix these bad habits. Beginners will often revert back to their bad habits if they stop taking lessons.
Advanced singers may have mastered the fundamentals enough that they won't benefit as much from regular singing lessons: they can detect and fix singing issues on their own.
In terms of trying to improve your singing without lessons: just keep practicing your singing, and don't push through pain. The biggest risk is that your technique is bad, and you don't have a teacher to correct it. If your voice doesn't feel good, then take a break.
You can also seek out alternative sources of feedback besides lessons. Example: post a video of your singing online and ask for feedback
There are thousands of "good, independent singers", and they have a wide variety of approaches to getting singing lessons. There are lots of good singers who take weekly lessons, as well as other good singers who never take lessons.


Proper ukulele strumming technique

Question: I've browsed the internet and found a few different techniques mentioned. Generally, they involve either the index finger, thumb, or multiple fingers.
Are all these techniques correct and just used in different contexts? As a beginner, is there one I should prefer?
Comment: What actually makes a technique *correct*..?
Comment: In some cases, you can make efficiency arguments, like one chord fingering is easier than another. For strumming techniques, I guess it'd be more like what sound people expect from a ukulele. But I could imagine someone using just their pinky or a guitar pick. Not sure if that's incorrect or weird.
Comment: It makes it *different*. And in some cases, *better*, not particularly incorrect or weird, so why don't players develop their own ways. Most of us did with handwriting, for instance...
Answer: Different strumming techniques make different sounds. When I was first beginning on the uke, I used my thumb to strum while I was still figuring out how to make the chords. I  soon switched to my index finger (nail pointed down) and found this a little easier to play while making a bigger sound. I still use my thumb occasionally when I want a mellower sound.
There are many other strumming techniques, and they all sound different. As you progress on the uke, try working on some other strums and see what sounds you can make. The song I am working on now uses four different strums over the course of the song.
Answer: Those are all used.  I actually either use my middle finger or a felt plectrum (which gives more sound).  Basically, you have to experiment and find out which one works best for you.
Comment: Thumb is softer sounding  than the fingers (as the latter use fingernails to strike the strings).

Proper ukulele strumming technique


1912 Steinway B

Question: I purchased a rebuilt 1912 Steinway B four months ago. It has been tuned three times since I got it. Each time, it seems like after playing 20-30 minutes the intervals start to migrate. Perhaps it is overtones or beats but it's enough to be distracting to me. Two technicians have said the soundboard and bridges were well done. I think the action has older parts but for the life of me I cannot figure out why this piano doesn't stay in tune better or have a better tone. Any thoughts?
Comment: Do you know if the piano has been restrung shortly before? If so the string might need a few tunings to settle.
Comment: This is one of the times location would be helpful - both of OP *and* the piano itself: in the sun, by a heater, in an unheated room, etc?
Comment: Perhaps you could arrange with a technician to tune it, then stay for 30 minutes while you (or the technician) plays.
Comment: How long ago was the piano rebuilt?
Comment: Can we get you to auctually ask a question in the title of this question?
Comment: We typically don't have discussion on this website. This is not a forum. Can we ask you to ask an actual question which can be answered in an definitive manner?
Comment: Hi Neil, my apologies for not posing a question in the heading. I'm new to this page. The seller (a very large and well-known entity) told me the piano was rebuilt by someone else within the past 10-20 years. However, the parts have been indentified as being from the 1980s. The strings are not new. The pin block and soundboard are new. Does this clarify the situation?
Answer: Older pianos will eventually develop problems with keeping their tuning, because the holes the tuning pins are in get worn. This needs to be dealt with using thicker tuning pins and/or bushing out the holes.
Comment: The piano is recently rebuilt.
Comment: @phoog - yes, I got that. That doesn't exclude the possibility that it was rebuilt incompetently.  But I agree, new strings stretching out is (hopefully) the more likely cause.
Answer: After only 4 months and 3 tunings, it'd be back to the shop - I guess that's where it came from. Rebuilds should mean good as new (almost). So there ought to be some sort of guarantee for more than 4 months, but be quick!
Lazy's suggestion about new strings could be a good reason.
Comment: Good answer, I'll just add that in my experience the tuner puts the piano through its paces at the end of the appointment, just as a matter of course.  Also a good tuner will check location and humidity.  And when the first tuning failed they should have sent their most experienced person to see what's going on.
Comment: The strings are not new…..they are from when the piano was restrung after a new board was put in….probably 20+ years ago. The piano is in my apartment in New York City, away from the windows and radiator. In fact, I turned the radiator off.

1912 Steinway B


O em e o rem usam as tags html ou body como referência?

Question: Lendo sobre, vi locais dizendo que as medidas Em e Rem utilizam a tag html como referência outros dizendo que é a tag body, mas qual realmente é a tag que é utilizada como referência?
Answer: O rem toma por base o html, se o documento for um HTML
De acordo com o W3C:

rem unit: Equal to the computed value of font-size on the root element.

Significando:

unidade rem: Igual o valor computado do tamanho da fonte do elemento raiz.

E, de acordo com a MDN:

rem: This unit represents the font-size of the root element (e.g. the font-size of the  element).

Ou seja,

rem: Esta unidade representa o tamanho da fonte do elemento raiz (por exemplo, o tamanho da fonte do elemento )

Para entender o motivo do HTML ser mencionado no "por exemplo", temos que lembrar que o CSS pode ser usado com outros tipos de documento.
No caso específico de um documento HTML, a raíz é justamente o , que por sua vez contém o  e o , e todos os demais ítens. Sendo assím, a "raiz do documento" é sinônimo para o  em documentos HTML, portanto o rem toma por base o tamanho da fonte do .
O em toma por base o valor herdado pela fonte do elemento
Ainda no link da MDN acima, temos:

em: This unit represents the calculated font-size of the element. If used on the font-size property itself, it represents the inherited font-size of the element.

Ou seja,

em: Esta unidade representa o tamanho calculado da fonte do elemento. Se usado no próprio tamanho da fonte, é tomado por base seu tamanho herdado.

Simplificando, o que acontece com o em basicamente é o seguinte:
Se você especifica um tamanho de fonte como sendo 2em, ela vai ter o dobro do tamanho que teria normalmente, se não especificasse nada. Um exemplo de uso do em é esse (mas não se limite a isto, as possibilidades são muito mais que essas):

.reais span {font-size:.6em}
.tamanho1 {font-size:13px}
.tamanho2 {font-size:20px}
.tamanho3 {font-size:30px}

R$29,90

R$29,90

R$29,90

Note que neste caso, usamos um em só para definir a fonte menor do R$ e dos centavos. O em será sempre de .6 da fonte principal, sem que precisemos nos preocupar com o tamanho da linha.
Por outro lado, se você especifica a medida de um elemento com em, esta medida será relativa à fonte do próprio elemento. Veja o em aplicado no tamanho de um ícone, por exemplo:

.icon {
  background:url(https://i.stack.imgur.com/NNhpF.png) no-repeat 0 0;
  background-size:1em 1em;
  padding-left:1.5em;
  line-height:1em;
  margin-bottom:5px;
}

.tamanho1 {font-size:13px}
.tamanho2 {font-size:20px}
.tamanho3 {font-size:30px}

Ícone ajustado

Ícone ajustado

Ícone ajustado

Note que neste caso com uma definição, o ícone se ajusta para o tamanho da linha, acompanhando a fonte. Por usarmos em em suas medidas, quem determina o tamanho do ícone é a fonte.
Veja também:

Por que é recomendado utilizar a unidade "em" ao invés de "px" para fontes?
Comment: O certo mesmo é entender cada uma e usar onde for melhor. Uma coisa é certa: não faz sentido usar rem pra tudo, nem em pra tudo, nem px pra tudo. Você pode "misturar" sem problemas, desde que com a finalidade certa. Um exemplo: aquele caso do preço que eu pus acima, o ideal é porcentagem ou em, nao é vantagem usar rem nem px lá. Por outro lado, um cabeçalho principal pode ser baseado em rem, afinal, é pra acompanhar a página toda. Mas não tem uma regra geral, o fundamental é você entender pra que cada um serve. Qual é melhor, só depende do objetivo que aquele elemento terá no seu design.
Comment: Achei uma das minhas dúvidas, você acha que seria bom eu utilizar as medidas em ou rem além das fontes, como outras tag...a `div` é um exemplo, o tamanho de uma imagem etc...


Bernoulli distribution

Question:
Definition 3.3.1 (Bernoulli distribution). An r.v. X is said to have the Bernoulli distribution with parameter p if P(X = 1) = p and
P(X = 0) = 1 − p, where 0 < p < 1. We write this as X ~ Bern(p). The
symbol ~ is read "is distributed as". Any r.v. whose possible values
are 0 and 1 has a Bern(p) distribution, with p the probability of the
r.v. equaling 1. This number p in Bern(p) is called the parameter of
the distribution; it determines which specific Bernoulli distribution
we have. Thus there is not just one Bernoulli distribution, but rather
a family of Bernoulli distributions, indexed by p. For example, if X ~
Bern(1/3), it would be correct but incomplete to say "X is Bernoulli";
to fully specify the distribution of X, we should both say its name
(Bernoulli) and its parameter value (1/3), which is the point of the
notation X ~ Bern(1/3). Any event has a Bernoulli r.v. that is
naturally associated with it, equal to 1 if the event happens and 0
otherwise. This is called the indicator random variable of the event;
we will see that such r.v.s are extremely useful.
Definition 3.3.2 (Indicator random variable). The indicator random variable of an event A is the r.v. which equals 1 if A occurs and 0
otherwise. We will denote the indicator r.v. of A by IA or I(A). Note
that IA ~ Bern(p) with p = P(A).

These are the definitions in Introduction to Probability book, however, as been stated in the Definition of Bernoulli distribution that 0 < p < 1 so that means it exclude 1 and 0 but in the Indicator random variable definition it states that when some event A occur P(A) = 1 and P(A) = p ( the small p here is the parameter) which leads us that p = 1 which contradicts what I understand from the first definition that 0 < p < 1 , I think it suppose to be p is bigger or equal to 0 and less or equal to 1, correct me if I said something wrong and explain to me what exactly I am missing?
Answer: The first definition describes the Bernoulli random variable $X$ that follows the Bernoulli distribution. It has the following probability mass function
$$ f_X(x) = \begin{cases} p & \text{if }x=1, \\[6pt]
1-p & \text {if }x=0.\end{cases} $$
The second quote says that you can use Bernoulli distribution for random variables defined in terms of indicator random variable. In such a case, $IA$ is equal to $1$ if $A$ occurs and $0$ otherwise. The Bernoulli probability mass function is
$$ f_{IA}(Ia) = \begin{cases} p & \text{if }Ia=1, \\[6pt]
1-p & \text {if }Ia=0.\end{cases} $$
$P(IA=1) = p$ saying it differently.
The quotes do not say that the probabilities could be $1$ or $0$. In fact, probability equal to $1$ would mean that the random variable is constant, so it's degenerate, it wouldn't follow Bernoulli distribution because there would be only one (not two) event possible for it.

Bernoulli distribution


Eigenvelues of $f_A:V\to V, X\to AXA.$

Question: Let $V$ be a vector space on $\mathbb C$ made by $2\times 2$ complex matrix.
And for $M\in V,$ define $f_M : V\to V$ by $X\mapsto MXM.$
Let $A$ be a $2\times 2$ real and symmetric matrix that has two eigenvalues $\lambda, \mu \ (\lambda \neq \mu)$.
Then, calculate the eigenvalues of $f_A$.

Since $A$ has two eigenvalues $\lambda, \mu$, there exist $u,v\in \mathbb{C^2}$ s.t. $Au=\lambda u, Av=\mu v.$
And in order to calculate the eigenvalues of $f_A$, I have to consider $f_A(X)=\nu X.$
I tried letting $A=\begin{pmatrix} a & b \\ b & c \end{pmatrix}, X=\begin{pmatrix} x & y \\ z & w \end{pmatrix}$ and calculating $AXA=\nu X$, but this is too complicated so that I couldn't.
Thank you for your help.
Comment: Can you see why you only need to consider $A=\begin{pmatrix}\lambda\\&\mu\end{pmatrix}$.
Comment: @user10354138 I can't see… .  Why ?
Answer: We can write $A = UDU^T$, where $U$ is an orthogonal matrix and $D = \begin{pmatrix} \lambda & 0 \\ 0 & \mu\end{pmatrix}$.
Note that:
$$
f_A(X) = UDU^TXUDU^T = Uf_D(U^TXU)U^T.
$$
If we denote by $\sigma_U$ the linear map on $V$ given by $Y\mapsto UYU^T$ we have
$$
f_A = \sigma_U \circ f_D \circ \sigma_U^{-1}.
$$
This shows $f_A$ and $f_D$ are similar operators on $V$ and hence they have the same eigenvalues.
Now consider usual the basis $\{E_{i,j}\}$ for $V$, where $E_{i,j}$ is the $2\times 2$ matrix with $1$ in the $(i,j)^{\text{th}}$ component and zero elsewhere. A bit of algebra gives
\begin{align}
f_D(E_{1,1}) & = \lambda^2 E_{1,1} \\
f_D(E_{1,2}) & = \lambda\mu E_{1,2} \\
f_D(E_{2,1}) & = \lambda\mu E_{2,1} \\
f_D(E_{2,2}) & = \mu^2 E_{2,2}.
\end{align}
So there are three eigenvalues: $\lambda^2$, $\mu^2$, and $\lambda\mu$. Interestingly enough, note that
\begin{align}
\det(f_A) & = \det(A)^3 \\
\text{Tr}(f_A) & = \text{Tr}(A)^2 - \det(A).
\end{align}
Comment: $A$ is a real symmetric matrix, so by the spectral theorem we can decompose it as $A = UDU^T$. The "philosophy" here is that $A$ and $D$ are, up to an orthogonal change of coordinates, the same. So if we can answer the question for $D$ we'll also have an answer for $A$. Finding the eigenvalues of $f_D$ is straightforward.
Comment: This is a elegant solution, but how did you come up with that idea ? @Pirate_Prentice
Comment: Thank you for explaining.

Eigenvelues of $f_A:V\to V, X\to AXA.$


Second derivative test inconclusive

Question: I have the function $f(x,y) = x^2y(4-x-y)$ and $T = \{(x,y) | x\ge 0, y \ge 0, x+y \le 6\}$. With the second derivative test I have found that $(2, 1)$ is a relative maximum.
By calculating the first derivatives you will see that $x=0$ and $y \in [0, 6]$ are critical points (correct me if I am wrong). So by using those numbers, the second derivative test is inconclusive.
My questions are: What can I do if the second derivative test is inconclusive? Does this function have a relative minimum?
Answer: The Weiertrass theorem states that, if $f:X\to \Bbb{R}$ is a continuous function and $X$ is a compact set, then there exists $x_1, x_2 \in X$ such that $$f(x_1)\leq f(x) \leq f(x_2) \; \forall x\in X.$$ We say that $x_1$ and $x_2$ are absolute minimum and maximum points. Note that every absolute minimum (maximum) point is a relative minimum (maximum) point. So, here, you have the existence of such point. To find it, you have to look at the bound of your $T$ (if there is no minimum points in $int(T)$, then they are in $\partial T$).
Answer: You may use the second derivative only on the interior of $T$. Since $T$ is compact $f$ must have global extreme values.
Calculate the extrema in the interior of $T$, that is $x,y>0$ and $x+y<6$, first.  You'll get only one candidate, namely $(2,1)$. The Hessian will reveal that this is a maximum with value $f(2,1)=4$.
Now consider the boundary.  Since $T$ is compact we expect extrema on its boundary.  So if $xy=0$ we have $f(x,y)=0$. If $y=6-x$ we're looking for the extreme values of $x^2(6-x)(-2)$.  Candidates are $x=0$ (see above) and $x=4$.  Show that we have a minimum in $x=4$ (hence $y=2$) with value $-64$.
So $f$ attaines its global maximum in $(2,1)$ and its global minimum in $(4,2)$.

Second derivative test inconclusive


how to install mssql 2008 r2 from iso

Question: I'm trying to install ms sql from iso. I've installed virtual clonedrive which mounts the iso as drive however i'm getting the following error.
E:\Resoourse\1033\setup.rll is either not designed to run on Windows or it contains and error. Try installing the program again using the original installation media or contact your system administrator
what is the best method to install ms sql from iso.
Answer: I would suggest you run a hash on the ISO image and make sure is not corrupted. Extracting the contents is fruitless if you have some corrupt data as is only going to waste your time.
I would suggest you use HashTab to generate the HASH for your ISO and compare that to the Microsoft download page.
SHA1 sums for TechNet/MSDN Media:

18105DB70F0F0B23418F5005A6CE4B25317C6D03 (en_sql_server_2008_r2_enterprise_x86_x64_ia64_dvd_520517.iso)
09CF52A4209CA96FF480537BB86786F79AE0E8A3 (en_sql_server_2008_r2_standard_x86_x64_ia64_dvd_521546.iso)

Hope this helps
Answer: You didn't mention if you had a dvd drive or not, but if you do then burn the iso file to a dvd using isoburn or the like and try installing it again.
Answer: Or use 7-Zip to extract the ISO, and install from the folder it extracts to.
http://7-zip.org/
Answer: I ran into this same issue.  The issue is the Windows machine was not up-to-date on all the updates.  First the computer did not have Internet access and that had to be resolved.  Once I got Internet Access I spent 1 hour downloading Windows Updates.
After the Updates were all installed.  Everything worked.

how to install mssql 2008 r2 from iso


Is least squares means (lsmeans) statistical nonsense?

Question: I recently came accross this quote from Brian Ripley, who seems to be well-regarded as a statistician.

"Some of us feel that type III sum of squares and so-called ls-means are statistical nonsense
which should have been left in SAS"
Brian Ripley
S-News (May 1999)
http://www.math.yorku.ca/Who/Faculty/Monette/pub/stmp/1332.html

However I haven't read any justification for this, apart from what seems to be a dislike for SAS.
Why did (or does) Ripley and others feel that lsmeans is nonsense ?  It seems to be very popular these days. Was this a controversial viewpoint at the time, or has the consensus thinking on this matter changed over the years ?
Comment: Sometimes they are appropriate and sometimes not. The choice should be made based on understanding what they are, not on whether they remind you of SAS. By the way, they were not originated by SAS, as many believe.
Comment: See ["What are LS means useful for?"](https://stats.stackexchange.com/questions/332167). Personally I find LS means quite nonsensical. See also the comment thread under the answer there.
Comment: Also see [Exegeses on Linear Models](https://www.stats.ox.ac.uk/pub/MASS3/Exegeses.pdf) by WN Venables sections 5.1 and 5.2. Venables also seems to dislike the idea.
Comment: But Venables & Ripley does not seem to really explain why ... (but I will reread that exegesis).
Comment: @kjetilbhalvorsen I wonder if the book by Venables and Ripley has any insight ? Sadly I don't have a copy :(
Comment: @kjetilbhalvorsen, regarding *Venables & Ripley does not seem to really explain why*: One could reasonably be expected to accept a technique that serves a sensible purpose. The problem with LS means is, there does not seem to be any obvious sensible purpose for it. As such, the burden of explanation should be on those who invented LS means, not on those who criticize purposeless techniques.
Comment: @You might be right, I don't know (will try to find out what this is about). But part of it must be the want of having one big computer output containing everything (sensible when SAS was created in the 60's), and another want of having sensible anova output for unbalanced designs, automatically. Venables says, basically, all sensible comparisons are comparisons of two models, (full and reduced) so just compute both and compare, (But part of this is guessing)
Comment: I think design bears strongly on this issue. LS/EM means make more sense when you have a survey sample. In that case the weights can reasonably be estimated. For a designed experiment, weights are more more subjective.
Answer: The short answer is that LS means (or more modernly, estimated marginal means) are incredibly useful with experimental data. With observational data, not so much. A long-winded explanation follows.
The underlying ideas are very old (and predate SAS by at least 50 years). Look at a standard experimental design textbook -- pretty much any of them. Such a book has initial chapters on one-way CRDs, focusing especially on balanced designs. Then they move on to factorial designs, and it is a 2-way factorial I will discuss the most. For that, we randomize experimental units to combinations of the levels of two factors $A$ and $B$, and consider analyzing a model of the form
$$ Y_{ijk} = \mu_{ij} + E_{ijk}, \quad i=1,2,...,a;\quad j=1,2,...,b;\quad k=1,2,...,n_{ij} $$
where $Y_{ijk}$ is the $k$th observation at the $i$th level of $A$, $j$th level of $B$, the $\mu_{ij}$ are the cell means, and $E_{ijk}$ are random errors, typically assumed to be iid normal. Emphasis is usually placed on balanced experiments, where the $n_{ij}$ are all equal.
We proceed to talk about partitioning the total sum of squares into components attributable to marginal effects of $A$, marginal effects of $B$, perhaps interaction effects, and residual error.
If the interactions are not strong, we are attracted to an additive model whereby $\mu_{ij} = \mu + \alpha_i + \beta_j$; in that case, interpretation is simpler because the effects of $A$ and $B$ can be considered independently. Evaluating these effects can be expressed in terms of the marginal means for $A$, $\mu_{i.}=\mu+\alpha_i$, and for $B$, $\mu_{.j}=\mu+\beta_j$; and perhaps pairwise comparisons thereof. In a balanced design, these marginal means may be estimated as the marginal means of the data: $\bar Y_{i..}$ and $\bar Y_{.j.}$.
Balanced experiments lie in very foundational places in statistics, including the writings of Fisher, Youden, Snedecor, Cochran, Cox, Box, and Tukey. But what if it isn't a balanced experiment? For example, a few observations were lost (completely at random). In very old design texts, what was suggested in some cases was the "method of unweighted means", whereby we use the values of $\bar Y_{ij.}$ and construct an analysis of those cell means as if they were data from a balanced experiment with $\tilde n$ observations per cell (where, typically, $\tilde n$ is the harmonic mean of the cell sample sizes). This is far preferable to just computing marginal means of the data, because some cells receive more weight than others, which can produce Simpson's-paradox-like effects.
"Least-square means" are essentially a model-based version of unweighted means. They were developed by Walter Harvey in a technical report in 1960 and finally published as
Walter R. Harvey (1982), "Least-Squares Analysis of Discrete Data,"
Journal of Animal Science, 54(5), 1067–1071, https://doi.org/10.2527/jas1982.5451067x. They were indeed implemented in SAS in an add-on procedure called PROC HARVEY, not long after the first (1972) edition of SAS was released, and then later implemented as part of the new PROC GLM released in SAS75. You may also want to take a look at a 2014 retrospective by Weijie Cai.
Again, LS means are essentially the same idea as unweighted means, which is a very, very old idea. In LS means, we fit a model to the data and use it (in the two-way factorial case) to predict the $\mu_{ij}$; then our marginal means are estimated as equally-weighted marginal averages of these predictions, just as in unweighted-means analysis. But these LS means are linear functions of the model predictions, and hence of the regression coefficients; so they can be estimated from the model with no need for ad hoc quantities like $\tilde n$. The idea extends to other experimental designs, such as Latin squares, split-plots, etc., and even to covariance models (where typically we make predictions at the mean of each covariate). You can also generalize these ideas to experimental data analyzed with other types of models, including generalized linear models, ordinal models and multinomial models, zero-inflated models, etc. And the ideas can be applied to Bayesian models fitted via MCMC methods, simply by computing the relevant quantities from the posterior predictions.
Is this useful? Definitely yes, when the model is additive and/or the interaction effects are small. They mimic the types of analyses proposed for balanced experiments by the giants among our forebears. If, on the other hand, we do have sizeable interaction effects, then (as our forebears recommend) we simply should not even consider estimating marginal means. (In a multi-factor experiment, it may still be reasonable to construct some marginal means where we are averaging only over negligible interaction effects).
In the situation where you have data sampled from a population, then LS means or EMMs may very well be entirely inappropriate. They certainly don't estimate the marginal means of your population because the equal weighting is not appropriate. The emmeans package provides various alternative weighting schemes, and some may be suited for a particular purpose; or not.
What about type III sums of squares? What I would say is that you need to consider whether they are appropriate for an individual situation. SAS defines these in terms of estimable functions, and a given set of estimable functions corresponds to a family of contrasts that can usually be expressed as contrasts among LS means. If that family of contrasts is of interest, then the associated type III test is fine; and if not, it's not fine. And again, this has to do with the appropriateness of the LS means being considered. I personally shy away from type III tests, but that is because I don't use omnibus tests for anything but model selection.
An additional reference is Searle, Speed, and Milliken (1980), "Population marginal means in the linear model: An alternative to least squares means", The American Statistician 34(4), 216-221, doi:10.1080/00031305.1980.10483031, where they critique Harvey's method and propose the term "estimated marginal means." They also discuss instances where there are empty cells. In that part, I personally think they do it all wrong, but it depends of course on what you are trying to accomplish (if the cells are empty because those factor combinations actually cannot happen, then what they do is more defensible). In general, empty cells can be terribly problematic, and the emmeans package deals with them in terms of assessing estimability of the specified quantities.
I would also say that there is a definite anti-SAS attitude among some members of the R community (and S and S-Plus before R). This is unfortunate, because SAS is carefully developed under the direction of many top professional statisticians. It is well documented and its code is solid and reliable for what it does. There are definite reasons I prefer R to SAS myself, not the least of which is that SAS cannot quite escape some very old ruts. But I would like to encourage users to adopt a less tribal attitude about statistical software.
Comment: (+1) This is an excellent answer. Thank you. I will award it a bounty when eligible.
Comment: Misinderstsnd, I guess. I never said to use them only with balanced data -- that would be crazy
Comment: I feel like disagree or misunderstand. You seem to advocate computing EMMeans (only) for balanced designes. But, for all I know, if a (cross-factorial) design is balanced and there's no covariates then, in ANOVA/linear model, Est Marg Means are always = Obs Marg Means, for each factor. At least that's what I see in SPSS which, for its General linear models, uses the "modified definition by Searle, Speed, and Milliken (1980)", - I think, though not for sure, this is what SAS does.
Comment: (cont.) I've found that Est. Marg. Means <> Obs. Marg. Means only either under covariate present or design is unbalanced (hence, factor effects correlate).


O Git Bash não está conseguindo abrir uma conexão com o meu agente de autenticação

Question: Estou tentando configurar o meu github no windows pelo git bash com a ajuda desse blog: http://gabsferreira.com/instalando-o-git-e-configurando-github/, mas o git bash não consegue uma conexão com o meu agente de autenticação.
Eu faço como pedido na parte "2- Agora, precisamos adicionar a chave que criamos ao ssh-agent. Primeiro, vamos ativa-lo:" e aparece:
Logo em seguida faço o que é pedido na parte "Em seguida, vamos adicionar a chave que geramos ao ssh-agent:" e aparece:
Sou muito iniciante no git bash e estou perdida. Uma mãozinha?
Answer: Ola,
no proprio post achei um problema parecido com o seu e a reposta da pessoa foi:

exec ssh-agent bash, executa isso e depois refaz o ssh-add ~/.ssh/id_rsa.

Pode ser que ajude.
Comment: Muito obrigada, não tinha visto mesmo!


Get all children of a term

Question: I  have the following tree structure, I want to get all child terms. I implemented taxonomy_get_children('tid') drupal api function.
1.Gloves
 1.1 Seamless
   1.1.1 Kevlar
    184.108.40.206 Shell
    126.96.36.199 Dots
    220.127.116.11 Coated
 1.2 mechanics
 1.3 cut and sewn
2.Apparels
 2.1 Coveralls
 2.2 Aprons
 2.3 Trousers

When I clicked on Apparels I successsfully get all child terms using but when I clicked on Gloves, it provides me only top level child terms ('seamless', 'mechanics','cut and sewn'), not the deep levels.
Answer: Use taxonomy_get_tree instead, it takes vocabulary ID as the first param, and the term ID under which to generate the tree - this should give you all children of a term.
More info here.

Get all children of a term


Filetree is not refreshing after switching branches - cloud9

Question: In cloud9 IDE, I am doing simple rails app in master branch. I decided to experiment a little, so I created new branch like this:
git checkout -b experiment-branch

Then I created some controllers, models etc. but experiment fails and I do not committed it. However I dont't want to delete this branch, so I tried to go back to master:
git checkout master

and code (controllers, models etc) from the previous experiment was still there in filetree, ApplicationController etc.
I tried git reset --soft <desired-previous-commit-hash> but it not worked.
I assume the second command should return me the state of my app from before creating the branch experiment-branch. Am I right or I do something wrong?
Answer: If you have not tracked the new files you add in the experiment-branch - these are still lying around as untracked files.
Untracked files are not removed when you change branches.
You would need to clean them to remove the untracked files. use git clean -n (dry-run) to identify all the files that are untracked.
Then you could git clean -f to clean all the file shown in the dry-run. Or you could use the interactive mode git clean -I
To revert changes from tracked files, use git checkout .
Refer this post for more details.
Comment: Thank you for answer but that's not what I mean. I have used `git clean -n` & `-f` and all files 100% related to `exp.branch` has gone but code from this branch in files like `application_controller.rb` is still there. What I wanted is to get back to state of the app just before creating this exp.branch like it never happened (with leaving this branch just for review)


Call Tornado WebSocketHandler from Requesthandler

Question: I am using Tornado Webserver and want to internally call a WebSocketHandler from a RequestHandler.
It is not possible to use the redirect /redirectHandler functionality, because the WebSocketHandler class to call ("IndexHandlerDynamic1" in the example below) will be created with a classFactory.
Using the definition of Requesthandler (here) my example looks like:
class IndexHandlerDynamic1(tornado.web.WebSocketHandler):
    def initialize(self):
        print "Forwarded to Websocket"
    def open(self):
        print "WebSocket opened"
class IndexHandlerDistributor(tornado.web.RequestHandler):
    def get(self, channelId):
        IndexHandlerDynamic1(self.application, self.request)

If I request the related url he jumps into IndexHandlerDistributor and IndexHandlerDynamic1.initialize() is called.
But on Clientside the Browser console outputs the following error:
Error during WebSocket handshake: Unexpected response code: 200

Obviously the socket connection is not opened correctly, what's my mistake ?
EDIT:
Thanks to Ben for his help!
Sadly I still have trouble to route the user to a dynamically created class named like a url parameter. I hope you can understand my problem by having a look on my example:
app = tornado.web.Application(
        [(r"/", IndexHandler)] +
        [(r"/channel/(?P<channelId>[^\/]+)?", ClassFactory(channelId))]
        )

How to use channelId as a parameter for my call of ClassFactory as Requesthandler?
Or is there maybe another way to dynamically change the routing of my application while the application is running? If so, i could use this way to solve my initial task.
Answer: The problem is that you're attaching two RequestHandlers to the same request.  I'm not sure that dynamically creating handler classes is a great idea, but if you want to do it just pass your factory function (which is not itself a RequestHandler) to the url routing table.  The routing table doesn't necessarily need a RequestHandler subclass, it just needs an object which can be called with (app, request) and return a RequestHandler instance.
Comment: Thanks for your usefull suggestion! I updated my question, maybe you can give me a hint how to solve it.
Comment: The parsed components of the url are not made available until the RequestHandler._execute method is called, so you won't be able to use them when constructing the handler instance.  You can access the raw url via attributes of the request object and parse it yourself in the factory.
Comment: Great! Thanks for your help. Extracting the parameters from the raw url via attributes solved it.


MIDINetworkConnection EXC_BAD_ACCESS error

Question: I am working on an app that controls daw software. Occasionally I am getting EXC_BAD_ACCESS errors. I believe it is related to the MIDINetworkConnection, even though the project is ARC enabled. It appears to be trying to access the number of connections, but going to the wrong memory address. Can anyone spot the problem?
<code>- (NSString*) describeConnections {

    NSMutableArray* connections = [NSMutableArray arrayWithCapacity:[[[MIDINetworkSession     defaultSession] connections] count]];
    for (MIDINetworkConnection* connection in [[MIDINetworkSession defaultSession] connections]) {
        [connections addObject:[[connection host] name]];
    }
    if ([connections count] > 0) {
        return [connections componentsJoinedByString:@", "];
    }
    else{
        return @"(Not connected)";

    }

}
</code>
The breakpoint error stops on
<code> NSMutableArray* connections = [NSMutableArray arrayWithCapacity:[[[MIDINetworkSession     defaultSession] connections] count]];
</code>
with the message: Thread 1: EXC_BAD_ACCESS(code=1, address=0x2033b00c)
In the debugger I'm seeing connections = (NSMutableArray*)0x839ab1e0 which doesn't match the above error.  Could this be the cause of the problem?
This the thread stacktrace:
<code>* thread #1: tid = 0x9f2b0, 0x01da9e15 libobjc.A.dylib`objc_retain + 21, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x5302f2fb)
frame #0: 0x01da9e15 libobjc.A.dylib`objc_retain + 21
* frame #1: 0x0000d14b Fader`-[MIDIController describeConnections](self=0x7c3c35b0, _cmd=0x00083ee3) + 683 at MIDIController.m:149
frame #2: 0x00049073 Fader`-[MainViewController internalReloadConnections:](self=0x7d0f6000, _cmd=0x000849f0, sender=0x7d0f6000) + 115 at MainViewController.m:1087
frame #3: 0x000494e0 Fader`-[MainViewController updateDisplay](self=0x7d0f6000, _cmd=0x000847c9) + 272 at MainViewController.m:1143
frame #4: 0x014e2119 Foundation`__NSFireTimer + 97
frame #5: 0x020bf8d6 CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 22
frame #6: 0x020bf25d CoreFoundation`__CFRunLoopDoTimer + 1309
frame #7: 0x0207e6ba CoreFoundation`__CFRunLoopRun + 2090
frame #8: 0x0207dbcb CoreFoundation`CFRunLoopRunSpecific + 443
frame #9: 0x0207d9fb CoreFoundation`CFRunLoopRunInMode + 123
frame #10: 0x038d324f GraphicsServices`GSEventRunModal + 192
frame #11: 0x038d308c GraphicsServices`GSEventRun + 104
frame #12: 0x002b58b6 UIKit`UIApplicationMain + 1526
frame #13: 0x0000b06c Fader`main(argc=1, argv=0xbfff63f0) + 76 at main.m:14
frame #14: 0x02a6bac9 libdyld.dylib`start + 1
</code>
Comment: Any message in the debug console when you hit the breakpoint?  (Or if you turn off the breakpoint?)
Comment: No message just (lldb)  in the console
Comment: Type 'bt' at the (lldb) prompt to get a stack trace.  It might have clues.
Answer: perhaps the [[MIDINetworkSession defaultSession] connections] collection is being altered while you are enumerating it? (a midi connection is made/drops out)
it is not wise to fast enumerate a mutable collection, especially one that you do not own. I suggest copying it into an NSArray at the start and enumerating that instead
ie
<code>    - (NSString*) describeConnections {

       // NSArray *tempConnections = [NSArray arrayWithArray: [[MIDINetworkSession defaultSession] connections] ];
      //edit. replaced with line below, we are working with a set, not an array, see comments below..
        NSArray *tempConnections = [[[MIDINetworkSession defaultSession] connections]allItems];

        NSMutableArray* connections = [NSMutableArray arrayWithCapacity:[tempConnections count]];
        for (MIDINetworkConnection* connection in tempConnections) {
            [connections addObject:[[connection host] name]];
        }
        if ([connections count] > 0) {
            return [connections componentsJoinedByString:@", "];
        }
        else{
            return @"(Not connected)";

        }

    }
</code>
Comment: Hi @Jef thanks so much for the reply! You are probably correct about this, makes sense. When I try to use the code example you provided, I get the warning " Incompatible pointer types sending 'NSSet *' to parameter of type 'NSArray *'  Any idea why?
Comment: perhaps [[MIDINetworkSession defaultSession] connections] is a NSSet or NSMutableSet where I had assumed it was an array. try changing the first line to NSArray *tempConnections = [[[MIDINetworkSession defaultSession] connections]allItems];


Calculating the probability of guessing 3 card draws out of 6

Question: My friend guessed the correct card drawn from a full deck of 52, 3 times out of 6 guesses (card not replaced each time).
I'm trying to work out the probability. My thinking is that if you guessed right the first 3 out of 6 times it would be:
1/52 (correct) * 1/51 (correct) * 1/50 (correct) * 48/49 (wrong) * 47/48 (wrong) * 46/47 (wrong)
But then there are 20 different ways to choose 3 from 6 so I multiply the outcome by 20. Does that give me the approximate answer?

In case I'm not being clear:
There are 52 cards and a guess is made and a card drawn.
Now there are 51 cards and a different guess is made and a card is drawn.
This happens 6 times and out of those 6 times, the correct guess is made 3 times. What are the chances of that?
Comment: The answer will depend on whether your friend sees the actual cards for the early guesses before making the later guesses (as a toy example, suppose the deck only has six cards: if your friend sees the first five cards before making the sixth guess then the sixth guess should always be correct)
Answer: In your example the first three guesses are right and the last three are wrong. But if the first three guesses were wrong and the last three were right, then you'd get a (slightly) different answer because the probabilities are all a bit different from each other. So you can't just multiply by 20 and get the correct answer (although it won't be horribly wrong for your particular question).
Instead you need to compute the probability of each of the 20 possibilities and add them up. The answer I get is
\begin{equation}
\frac{151999}{977208960} \approx 1.55544 \times 10^{-4} .
\end{equation}
This is about as likely as guessing 12 or 13 coin flips in a row.
Additional detail
Here is some additional detail on how I thought about the problem. Let
\begin{equation}
y = (y_1,\ldots,y_6) \in \{0,1\}^6
\end{equation}
be a collection of independent Bernoulli variables:
\begin{equation}
p(y) = \prod_{i=1}^6 \textsf{Bernoulli}(y_i|\theta_i) ,
\end{equation}
where $p(y_i=1|\theta_i) = \theta_i$ and
\begin{equation}
\theta_i = \frac{1}{53-i} .
\end{equation}
There are $2^6 = 64$ points in the probability space. Evaluate $p(y)$ at each of the points for which $\sum_{i=1}^6 y_i = 3$ and add the results up.
Answer: Hypergeometric distribution. The probability of drawing all three of three specified cards in six draws without replacement is a hypergeometric probability:
$$\frac{{3\choose 3}{49\choose 3}}{{52\choose 6}}.$$
This can be evaluated in R using the hypergeometric PDF
function dhyper as follows:
dhyper(3, 3,49, 6)
[1] 0.0009049774

choose(3,3)*choose(49,3)/choose(52,6)
[1] 0.0009049774

Simulation using sampling without replacement.
This probability is a little too small to simulate gracefully,
but a million iterations give a reasonable approximation by simulation.
set.seed(2022)
deck = 1:52
Three.of.6 = replicate(10^6, sum( sort(sample(deck, 6))[1:3]==1:3 )==3)
mean(Three.of.6)
[1] 0.000891       # aprx 0.0009
2*sd(Three.of.6)/1000
[1] 5.967267e-05   # aprx 95% margin of simulation error.

The logical vector Three.of.6 has a million TRUEs and FALSEso, its mean is the proportion of its TRUEs.
Thus the simulation gives $0.00089 \pm 0.00006,$ which
includes $0.0009.$
Note: I do not completely understand your attempted solution,
but there is more than one way in which to choose the three
required cards. Also, I think you may be mixing ordered
and unordered outcomes.
In the hypergeometric formula,
numerator and denominator both count unordered outcomes. By contrast, my simulation keeps track
of order.
Among the pages linked as 'Related' in
the margin of this question, you may find the two
on "poker" to be useful.
Comment: One thing I don't understand about the answer: in the denominator you have (52 C 6). If I said that there were 12 guesses instead of 6 guesses, presumably I would change the denominator to (52 C 12) which gives me a much SMALLER probability. But surely having 12 tries (rather than 6) makes the probability of getting 3 right larger?
Comment: *No cards were "specified"* in this problem.  That makes it difficult to see how your method finds the relevant probability.  Could you show us why your method ought to work?  I am suspicious of this solution, too, because it looks like if we were told the subject guessed three cards correctly during six successive draws of a *six* card deck, your formula would be $\binom{3}{3}\binom{3}{3}/\binom{6}{6}=1,$ essentially asserting it's certain anyone would guess all six cards correctly!
Comment: My interpretation was that the lucky friend 'specified' the three cards when (s)he made the predictions. Without loss of generality, my simulation assumes the specified values to have been $1,2,3.$
Comment: This conflicts with the description in the question following "In case I'm not being clear."


Formatting Time, Amount In Javascript

Question: My data is returned in this way. I need to return all the values in a list ensuring the time format and fare amount corrected as I explained. I want to remove the comma in fare, and AM & PM in departure and arrival. Many thanks in advance. As there are about 3 flightCodes and all together 18 fares.
The returned response.
[ { flightCode: 'SHA735',
    departure: '01:30 PM',
    arrival: '01:55 PM',
    fareCode: 'T Class',
    fare: '4,000',
    baggage: '20' },
  { flightCode: 'SHA735',
    departure: '01:30 PM',
    arrival: '01:55 PM',
    fareCode: 'B Class',
    fare: '5,900',
    baggage: '20' },
  { flightCode: 'SHA735',
    departure: '01:30 PM',
    arrival: '01:55 PM',
    fareCode: 'I Class',
    fare: '6,600',
    baggage: '20' },
  { flightCode: 'SHA735',
    departure: '01:30 PM',
    arrival: '01:55 PM',
    fareCode: 'H Class',
    fare: '7,500',
    baggage: '20' },
  { flightCode: 'SHA735',
    departure: '01:30 PM',
    arrival: '01:55 PM',
    fareCode: 'H Class',
    fare: '7,500',
    baggage: '20' } ]

Expected Result:
[ { flightCode: 'SHA735',
    departure: '01:30',
    arrival: '01:55',
    fareCode: 'T Class',
    fare: '4000',
    baggage: '20' },
  { flightCode: 'SHA735',
    departure: '01:30',
    arrival: '01:55',
    fareCode: 'S Class',
    fare: '5000',
    baggage: '20' },
  { flightCode: 'SHA735',
    departure: '01:30',
    arrival: '01:55',
    fareCode: 'E Class',
    fare: '5300',
    baggage: '20' },
  { flightCode: 'SHA735',
    departure: '01:30',
    arrival: '01:55',
    fareCode: 'B Class',
    fare: '5900',
    baggage: '20' }
]

My Javascript code is below.
 const $ = cheerio.load(html);
        const format = {
             klasses: new Array(),
        }
        const result = [];

        const flights = $('.flight-result > .tbody').find('.no-of-flights').toArray();

        flights.forEach(function(flight, _id) {

            result[_id] = Object.assign({},format);
            const flightCode = $(flight).find('p.font-reg.redcolor').contents().filter(function(){
                return this.type === 'text';
            }).text().trim();
            const times = $(flight).find('p.font-reg.redcolor').find('small').html().match(/\d\d:\d\d [AP]M/g);
            const flightClassContainer = $(flight).find('.flightclasscontainer').toArray();

            flightClassContainer.forEach((flightClass, __id) => {
                result[_id].klasses[__id]   = {

                    flightCode:$(flight).find('p.font-reg.redcolor').contents().filter(function () {
                        return this.type === 'text';
                    }).text().trim(),
                    departure: times[0],
                    arrival: times[1],
                    fareCode: $(flightClass).find('.class').text(),
                    fare: $(flightClass).find('.price').text(),
                    baggage: '20'
                 }
            })
        });

        let items = [].concat(...result.map(o => o.klasses));
         console.log(items);
        return items;

Comment: Jai Nepal, see the answer and let me know if that is what you expect
Answer: Use split(' ')[0] to remove the time parameter AM/PM and replace(',','') to replace the comma in fare.

var flights = [ { flightCode: 'SHA735',
    departure: '01:30 PM',
    arrival: '01:55 PM',
    fareCode: 'T Class',
    fare: '4,000',
    baggage: '20' },
  { flightCode: 'SHA735',
    departure: '01:30 PM',
    arrival: '01:55 PM',
    fareCode: 'B Class',
    fare: '5,900',
    baggage: '20' },
  { flightCode: 'SHA735',
    departure: '01:30 PM',
    arrival: '01:55 PM',
    fareCode: 'I Class',
    fare: '6,600',
    baggage: '20' },
  { flightCode: 'SHA735',
    departure: '01:30 PM',
    arrival: '01:55 PM',
    fareCode: 'H Class',
    fare: '7,500',
    baggage: '20' },
  { flightCode: 'SHA735',
    departure: '01:30 PM',
    arrival: '01:55 PM',
    fareCode: 'H Class',
    fare: '7,500',
    baggage: '20' } ];

flights.map((flight) => {
  flight.departure = flight.departure.split(' ')[0];
  flight.arrival = flight.arrival.split(' ')[0];
  flight.fare = flight.fare.replace(',','');
});
console.log(flights);
Comment: flight.fare.replace is not a function.
Comment: @AshokBhattarai Did you check the snippet. It is not giving that error.
Comment: Sorry error in my code. I have changed the comma earlier. Thanks Its working.
Comment: @AshokBhattarai you can accept the answer if it was helpful to you
Comment: As all the data is returned using this code, the returned data is not completely pushed into my db table. How can I acheive this. Previously for another airline this is done like this.     items.push({
      `flightCode,
      departure,
      arrival,
      fare,
      fareCode,
      baggage,
    });
  });

  return items;` and all the data was pushed into db table.

Formatting Time, Amount In Javascript


How to setup static IP with gateway IP out of the subnet using systemd-networkd?

Question: Basically what i want to do is:
~$ ip addr add 220.127.116.11/32 dev eth0
~$ ip route add 220.127.116.11 dev eth0
~$ ip route add default via 184.108.40.206

what i tried is:
/etc/systemd/network/wired.network
[Match]
Name=eth0

[Network]
Address=22.214.171.124/32
Gateway=126.96.36.199

when i tried ip route there is no output. What have i done wrong and what is the correct way to do this ?
Comment: The solution to this question works for me. http://serverfault.com/questions/667319/systemd-networkd-and-direct-routes. However i cant understand it.
Comment: In theory, that isn't possible, but it has been done in practice. The idea of a gateway is that it is the network address in your network to where traffic destined for a different network gets sent. if the gateway address is in a different network, your address should not know how to get to the gateway address because it is on a different network. Basically, to get to a different network, you use the gateway, but the gateway is on a different network, so you must use the gateway to get to itself.
Comment: @Shankar this works because a Point to Point network literally only has _one_ place to send packets to. So it just sends them to the other end of the link and crosses its fingers that the receiver knows how to deal with it. This has been done on some networks I've read about that run /31 or /32 _everywhere_ on ethernet links, essentially eliminating L2. But it also usually involves running a routing daemon on each node. The exception is Point-to-point protocols like, uuh, PPP (which stands for Point to Point Protocol). It's very common on DSL connections.
Answer: Gateway=184.108.40.206 try with GatewayOnLink= in route section it should work.
https://www.freedesktop.org/software/systemd/man/systemd.network.html#GatewayOnlink=
Answer: I had a similar issue, where I needed to setup systemd-networkd with a gateway on a completely different subnet (because of the addresses the ISP gave me).
The answer by user29005 pointed me towards the solution.
Here's how I got it working in Arch Linux.
/etc/systemd/network/20-wired.network:
[Match]
Name=ens18

[Network]
Address=184.108.40.206
DNS=XX.XX.XX.XX

[Route]
Gateway=188.8.131.52
GatewayOnLink=true

The GatewayOnLink=true line solves the 'unreachable next-hop' error.
Hope that helps,
D