Validar usuários usando Modal Bootstrap

Question: Estou validando o acesso de usuários usando o método tradicional:

Gostaria que essa mensagem aparecesse em um Modal Bootstrap. Tentei o código abaixo, porém aparece o fundo do modal (preto) e fecha rapidamente, não mantém o modal aberto:
HTML
<form method="post" id="login-form">

         Login:
         <input required="required" type="text" name="LoginAcesso" id="usuario" placeholder="Matrícula" class="form-control" />

         Senha:
         <input required="required" type="password" name="SenhaAcesso" id="password" placeholder="Senha" class="form-control" />

         <button type="submit" name="submit" id="botao" class="btn btn-primary">Acessar</button>

</form>

MODAL

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

Login e senha inválidos

Tente novamente.

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

JQUERY

VALIDAR.PHP
<?php
    echo 1; // Teste
 ?>

Comment: Descreva "Não funcionou", por favor. No jQuery não deveria existir um `.val()` quando você define o valor de `login` e `senha`?
Comment: E no PHP, quais são os valores que chegam?
Comment: Quando dou um alert('login') ou alert('senha'), não chegam os valores, mesmo os campos preenchidos.
Comment: Mas `alert` dentro do arquivo PHP não será executado, pois o código não é executado pelo navegador. No PHP faça `var_dump($_POST)` e no jQuery, adicione `console.log(data)` em `success`.
Comment: na verdade o alert está dentro do jquery, após a linha var senha = $('#password');
Comment: Então deveria aparecer no mínimo um `[object Object]` no alerta.
Comment: Consegui um pequeno progresso no código. Estou pegando agora o valor. Com isso reformulei a minha dúvida e atualizei o código.
Comment: em var login = $('#username').val(); está usando username e no form usando id="usuario", não vai retornar o valor
Comment: Olá Leo. O problema é que o Modal não abre. Sobre o valor informado, obrigado pela observação. Fiz o ajuste.
Answer: Depois de muito pesquisar, uma pergunta aqui e outra ali, consegui resolver. Segue abaixo para quem quiser usar o Modal Bootstrap como solução para a tradicional mensagem de Usuário ou login inválidos.
HTML/Modal
<form method="post" id="login-form">

 Login:
 <input required="required" type="text" name="LoginAcesso" id="username" placeholder="Matrícula" class="form-control" />

 Senha:
 <input required="required" type="password" name="SenhaAcesso" id="password" placeholder="Senha" class="form-control" />
 <button type="button" id="show_password" name="show_password" class="fa fa-eye-slash" aria-hidden="true"></button>

 <button type="submit" name="submit" class="btn btn-primary">Acessar</button>

</form>

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

 Login e senha inválidos

Dados inválidos. Por favor, verifique suas credenciais e tente novamente!

        <button type="button" class="btn btn-danger" data-dismiss="modal">Fechar</button>

JQUERY
$(document).ready(function(){
   $('#login-form').submit(function() {
     data = $('#login-form').serialize();

     $.post("validar.php",{
            d: data,
     },
      function (d) {
        //console.log(d);
       if(d == 1){
           $('#myModal').modal('show');
        }else{
          var redirecionar = "pagina-de-acesso.php";
         $(window.document.location).attr('href',redirecionar);
        }
      });
      return false;
    });
});

Página validar.php
$sql = mysqli_query($conexao,"Query");
if(mysqli_num_rows($sql) == 0){
          echo 1;
       }else{
          echo 0;
}

Validar usuários usando Modal Bootstrap


How is SockJS selecting the protocol?

Question: I will first start with what I am aware of, as it may be useful for the rest.
It is clear that you can instantiate SockJS with a subset of protocols:
<code>sockJsProtocols = ["xhr-streaming", "xhr-polling", ....];
socket.cliente = new SockJS(url, null, {transports: sockJsProtocols}));
</code>
I also found out that when SockJS is calling the /info endpoint, server is returning websockets true or false (depending on server compatibility).
I am also aware of the nice table here with 3 columns: websockets, streaming and polling.
But I have 2 questions:
1) How is SockJS deciding for polling, streaming or websockets? It can't be on browser compatibility, since I see in our logs lots of XHRStreaming sessions with recent browsers. How is that this is not documented anywhere?
2) Why does SockJS need to be calling /info every time? the compatibility of the server will be the same always.
Answer: Ok, I had to read the sourcecode of SockJS client to understand how it works. Now I do. This answer is valid, at least for SockJS 1.3.
SockJS is calculating the RTT (Round-Trip-Time) of the /info call. Then it takes this time and calculates an RTO (Retransmittion Timeout). If the RTT is less than 100ms, then it simply adds 300ms to it, otherwise, it multiplies it by 4.
The RTO is then multiplied by the number of roundtrips of each protocol, which apparently for websockets equals 2.
This is then used as a timeout starting when we open the websocket connection, until we receive the OPENED frame (Stomp CONNECTED frame). When this is timing out, SockJS is simply closing the protocol socket and trying with the next one. If there are no protocols left, it is going to retry all over again.
The whole logic sounds very data based and speculative, based on some experiments done by the team. Why 300ms? why roundtrip of websocket is 2?. And what is more surprising is that one can't really override this value in either client or server side (Server could override this value with the response in the /info call)
This effectively means, that if your Stomp server is too slow creating a queue, clients will be lost in negotiation.
Lets assume your client is not far distant from servers, then it most probably gonna fallback into the < 100ms RTT. Therefore, the client has to receive the CONNECTED frame in between 700-800ms.
I can't find another way to work around this, other than slowing down with a filter the processing of the /info call by a certain amount calculated empirically from measuring an average of our lag to our broker relay.

How is SockJS selecting the protocol?


Como funciona a parte do Front-end com OAuth 2.0?

Question: Eu fiz toda a parte necessária do back-end pra usar o OAuth e a api já retorna o access_token e o refresh_token, minha dúvida é, o que é necessário fazer no front-end (se possível com exemplos).
Toda requisição primeiro vou ter que verificar se o token não expirou, caso sim, gerar um novo token?
Answer: Dependendo da maneira que você for utilizar não é necessário ficar autenticando sempre que ele expira. A 2 meses atrás eu implementei a API do Gmail(Gsuite) no meu site. Depois do processo de autenticação me foi gerado um arquivo que salva as informações para que eu não precise ficar renovando a mesma.
Caso você vá utilizar varias contas de acesso, acredito que seja necessário armazenar um arquivo para cada usuário. No meu caso eu apenas utilizo uma ,que é a minha conta "bussines" do Gmail.
Tive essa mesma duvida e mandei um ticket para o Google, segue a resposta(ela pode ser aplicada no seu caso pois Oauth):

O token de acesso do Gmail tem sim uma validade de 3600 segundos, ou uma hora, e deve ser atualizado sempre que o token expira. Para que o usuário não tenha que ficar autenticando a aplicação a cada hora, tu podes implementar o que é chamado de Server-side Authorization que utiliza as informações salvas do usuário para renovar o token de acesso e com isso não interromper o funcionalmento da aplicação.


How to normalize a vector in python?

Question: I'm trying to calculate the scalar product and the normalized vector of temp_a and E in python.
I'm using this c++ example:
vector temp_a = a;
vector_normalize(&temp_a);
vector E;
vector_normalize(&E);

float LSM303DLH::vector_dot(const vector *a,const vector *b)
{
  return (a->x * b->x) + (a->y * b->y) + (a->z * b->z);
}

void LSM303DLH::vector_normalize(vector *a)
{
  float mag = sqrt(vector_dot(a,a));
  a->x /= mag;
  a->y /= mag;
  a->z /= mag;
}

This is what I've got so far in python:
vector_a = [321,321,321]
vector_e = [123,123,123]

#calculating the scalar product between two vectors
vector_dot_a = numpy.dot(vector_a, vector_a)
vector_dot_e = numpy.dot(vector_e, vector_e)

#normalizing the vectors
scalar_a = math.sqrt(vector_dot_a)
vector_a[0] /= scalar_a
vector_a[1] /= scalar_a
vector_a[2] /= scalar_a

scalar_e = math.sqrt(vector_dot_e)
vector_e[0] /= scalar_e
vector_e[1] /= scalar_e
vector_e[2] /= scalar_e

For the normalization can I just use this instead?
numpy.linalg.norm(vector_a)
numpy.linalg.norm(vector_e)

-+-+-+-+Edit 1-+-+-+-+
This is my result:
def readMagneticHeading(x_offset_min_m, y_offset_min_m, z_offset_min_m, x_offset_max_m, y_offset_max_m, z_offset_max_m):

  #shift and scale the calibrated min/max magnetic data
  x_heading_m = (x_data_m - x_offset_min_m) / (x_offset_max_m - x_offset_min_m) * 2 - 1.0;
  y_heading_m = (y_data_m - y_offset_min_m) / (y_offset_max_m - y_offset_min_m) * 2 - 1.0;
  z_heading_m = (z_data_m - z_offset_min_m) / (z_offset_max_m - z_offset_min_m) * 2 - 1.0;

  vector_from = [0,-1,0] #from vector
  vector_a = readAccelerations() #accelerations vector
  vector_e = [0,0,0] #east vector
  vector_n = [0,0,0] #north vector
  vector_m = readMagnetics() #magnetics vector

  #vector_a dot vector_a, the scalar dot product between two vectors
  scalar_dot_a = numpy.dot(vector_a, vector_a)
  #get the vector norm
  vector_norm__a = numpy.linalg.norm(scalar_dot_a)
  vector_a /= vector_norm__a

  #create the cross product of the east vector
  vector_e = numpy.cross(vector_m, vector_a)

  #vector_e dot vector_e, the scalar dot product between two vectors
  scalar_dot_e = numpy.dot(vector_e, vector_e)
  #get the vector norm
  vector_norm__e = numpy.linalg.norm(scalar_dot_e)
  vector_e /= vector_norm__e

  #create the cross product of the north vector
  vector_n = numpy.cross(vector_a, vector_e)

  vector_dot_e_from = numpy.dot(vector_e,vector_from)
  vector_dot_n_from = numpy.dot(vector_n,vector_from)

  #calculate the heading
  heading_m = round(math.atan2(vector_dot_e_from, vector_dot_n_from) * 180 / math.pi)

  if (heading_m < 0):
    heading_m += 360

  return heading_m

compared to the c++ version:
// Returns the number of degrees from the -Y axis that it
// is pointing.
int LSM303DLH::heading(void)
{
return heading((vector){0,-1,0});
}

// Returns the number of degrees from the From vector projected into
// the horizontal plane is away from north.
//
// Description of heading algorithm:
// Shift and scale the magnetic reading based on calibration data to
// to find the North vector. Use the acceleration readings to
// determine the Down vector. The cross product of North and Down
// vectors is East. The vectors East and North form a basis for the
// horizontal plane. The From vector is projected into the horizontal
// plane and the angle between the projected vector and north is
// returned.
int LSM303DLH::heading(vector from)
{
    // shift and scale
    m.x = (m.x - m_min.x) / (m_max.x - m_min.x) * 2 - 1.0;
    m.y = (m.y - m_min.y) / (m_max.y - m_min.y) * 2 - 1.0;
    m.z = (m.z - m_min.z) / (m_max.z - m_min.z) * 2 - 1.0;

    vector temp_a = a;
    // normalize
    vector_normalize(&temp_a);
    //vector_normalize(&m);

    // compute E and N
    vector E;
    vector N;
    vector_cross(&m, &temp_a, &E);
    vector_normalize(&E);
    vector_cross(&temp_a, &E, &N);

    // compute heading
    int heading = round(atan2(vector_dot(&E, &from), vector_dot(&N, &from)) * 180 / M_PI);
    if (heading < 0) heading += 360;
return heading;
}

void LSM303DLH::vector_cross(const vector *a,const vector *b, vector *out)
{
  out->x = a->y*b->z - a->z*b->y;
  out->y = a->z*b->x - a->x*b->z;
  out->z = a->x*b->y - a->y*b->x;
}

float LSM303DLH::vector_dot(const vector *a,const vector *b)
{
  return a->x*b->x+a->y*b->y+a->z*b->z;
}

void LSM303DLH::vector_normalize(vector *a)
{
  float mag = sqrt(vector_dot(a,a));
  a->x /= mag;
  a->y /= mag;
  a->z /= mag;
}

are there any differences left regarding the logic?
Comment: You can simply do `vector_a /= scalar_a` and `vector_e /= scalar_e`, no need to explicitly modify every item. And `np.linalg.norm(a)` is equivalent to `np.sqrt(a.dot(a))`, you'd still need the division.
Comment: You can also get the same result with less lines of code and you don't care about the dimension of the vector:

`scalar_a = math.sqrt(reduce(lambda a,b: a+b, map(lambda x: x**2, vector_a)))
vector_a = map(lambda x: x/scalar_a, vector_a)`
Answer: Yes, you can use numpy.linalg.norm.  It gives the same results as your code.
Also note you could do your division in vectorized form, like so:
vector_a /= scalar_a

That's much faster than the three separate ones you had, and arguably clearer too.
Comment: The exact code of `norm` can be checked [here](https://github.com/numpy/numpy/blob/v1.8.1/numpy/linalg/linalg.py#L2056), it should be equivalent (but slower) to calling `dot` and `sqrt`.
Comment: What confuses me is that the c++ function vector_normalize calls vector_dot and using its results in the calculation.
Using numpy.linalg.norm would not actualle use the numpy.dot, right?
This is the point why I think the results might be different...
Comment: I was hoping somebody would also write about detecting "zero vectors" - can the norm be too small to divide by?

How to normalize a vector in python?


How to install php-xml and php-mbstring on PHP 5.4.9-4?

Question: I have added the PHP5 to UBUNTU 12.04
sudo add-apt-repository ppa:ondrej/php5 -y

and installed the PHP5
php5 php5-common php5-mysql php5-xmlrpc php5-cgi php5-curl php5-gd php5-cli php5-fpm php-apc php-pear php5-dev php5-imap php5-mcrypt

However I can't find two packages
php-xml and php-mbstring

Any idea how they are called now?
Many Thanks,
Answer: You should check the package description for PHP from that repo.
Package: libapache2-mod-php5
Source: php5
....
 Description: ...
 The following extensions are built in: bcmath bz2 calendar Core ctype date
 dba dom ereg exif fileinfo filter ftp gettext hash iconv json libxml
 mbstring mhash openssl pcre Phar posix Reflection session shmop SimpleXML
 soap sockets SPL standard sysvmsg sysvsem sysvshm tokenizer wddx xml
 xmlreader xmlwriter zip zlib.

Note that mbstring and xml are built in according to the description.
Comment: The link 'package description' is broken.
Comment: And I can verify through actual software setup that the libapache2-mod-php5 library does provide a functional php-xml package for the system. PHP is just really bad about their package/dependency naming.
Comment: Still suffering from _linkrot_


If I use node_save() to create a new node, do I need to manually escape user input?

Question: I am writing a custom module for Drupal 6 that programmatically creates a node using node_save().
The various custom node fields come from user input - is it necessary to manually escape these fields, or will node_save() take care of that for me?
Answer: If by escaping you mean using check_plain() or similar functions, then no; escaping is done when outputting something, not when saving it in the database, or in Drupal persistent variables.
Imagine what would happen if you call check_plain() on a node containing "&"; that character would be escaped to "&" that it would be converted in &amp; when Drupal would show the node content. The result is that "&" would be shown as "&" and that is not what it would be expected.
In Writing secure code, you can read the following text:

Use check functions on output to prevent cross site scripting attacks
No piece of user-submitted content should ever be placed as-is into HTML.

Use check_plain() or theme('placeholder') for plain text.
Use check_markup() or filter_xss() for markup containing text.
Use the t() function with "@" or "%" placeholders to construct safe, translatable strings.

See how to handle text in a secure fashion for more details.

As you see, the page about writing secure code doesn't say to escape the text being saved, but only text being output, when the text has been entered from users, in a way or in another. An example of text entered from a user is the username or the signature associated to user accounts, the node title, or the node body.
About SQL injection, you just need to use placeholders in you queries; Drupal database functions escapes the content of the placeholders, which would not be possible if you write a query like the following one, for example:
$query = db_query("SELECT * FROM {node} WHERE title = '$title'");

The "Writing secure code" reports:

Use the database layer correctly. For example, never concatenate data directly into SQL queries, like this:
<?php
 db_query('SELECT foo FROM {table} t WHERE t.name = '. $_GET['user']);
?>

Instead, use proper argument substitution with db_query:
<?php
 db_query("SELECT foo FROM {table} t WHERE t.name = '%s' ", $_GET['user']);
?>

If you have to accommodate a variable number of arguments in your SQL, create an array of placeholders. Don't do this:
<?php
 db_query("SELECT t.s FROM {table} t WHERE t.field IN (%s)", $from_user);
?>

Instead, do this:
<?php
 $placeholders = implode(',', array_fill(0, count($from_user), "%d"));
 db_query("SELECT t.s FROM {table} t WHERE t.field IN ($placeholders)", $from_user);
?>

Comment: `node_save()` doesn't need to escape the values because its code has been written following the points on how to write secure code. It's the database API that takes care of any security issues for SQL injection, and other problems; `node_save()` doesn't need to do anything extra.
Comment: Sorry, I should have specified - I was talking about SQL injection. I will strip html tags when outputting it too.
Comment: @John McCollum Yet, it's not about escaping the input of the user before saving it. The database API takes care of escaping the values, but the saved values are still what the user entered.
Comment: The page on writing secure code doesn't, but the next page in the series does: http://drupal.org/node/101495 (handling user input with care)
Comment: That's the thing. I understand that using placeholders within db_query removes the risk, but I'm not using db_query - I'm using node_save(). Thanks for your answer, by the way :)
Answer: I quickly glanced through node_save and there is no escaping done on the $node object before drupal_write_record, drupal_write_record does no escaping either so even if I've overlooked something your best bet is to escape. Better safe than sorry!


secure sqlserver 2008 database by AD group

Question: Is it possible to restrict access to a SQLServer 2008 database to users of a given AD group, without having to create accounts for each user?
If so, how do I do it?
Users will be authenticating with SQLS with Windows Authentication using their respective accounts.
Thanks
Answer: Sure you can!
Just go to the Security\Logins->New Login... as specify your group in the "Login name" text box:

And them make sure to assing this group to an appropriate database user and role:
Comment: I don't know what SQSL is and I'm assuming in your question that you mean you want to grant access to a specific database based on AD group membership, and if so, Regent's answer is correct. I've used this method many times. When members of the group access the database with their AD accounts they'll be granted access by virtue of their membership in the group.
Comment: doesnt this mean i have to authenticate with SQSL as this single login though? Users will be authenticating with their own AD accounts
Comment: yeah it does work, didnt realise it was this simple. cheers all
Comment: I meant SQLS (sql server), was a typo


Angular JS index of selected TD

Question:

    {{car.Type}}
    {{car.Name}}
    {{car.Year}}

Can I get a car's index: a number which represents a place in cars array?
Currently, it is not in right order, because of orderBy filter.
Answer: Do the sorting in a controller. Then place the sorted items into a cars array. Then do

  {{$index}}
  {{car.Type}}
  {{car.Name}}
  {{car.Year}}

Answer: You could just call indexOf() with your car object to get its original index

    {{car.Type}}
    {{car.Name}}
    {{car.Year}}

Angular JS index of selected TD


In general, how do I maintain a slide whistle?

Question: I asked about lubrication. Now I'm wondering how in general I should maintain my slide whistle.
This is my first non-percussion instrument. Maintaining a percussion instrument amounts to hitting it and listening if it sounds right. How do I maintain a slide whistle?
Comment: You didn't have to tune the drums, replace the heads, smooth the bearing edges, lubricate the nuts, clean the shell, etc.?
Comment: @Todd Wilcox Lubricate the nuts?
Comment: I'm not sure what percussion instruments you've used so far, but for some there's a lot more involved.
Comment: @ToddWilcox I mostly had things like drums and xylophones. Nothing like a piano.
Comment: I'm not sure whether it needs swabbing after playing, to dry it out on the inside.
Answer: As you have already covered off lubrication, the only real issue is cleaning, and most of this comes down to keeping the interior dry, and wiping down the exterior.
From Eagle Music:

After each use, clean out the bore of your whistle and remove any moisture or dirt that has settled there. This can be done with what is called a flute/whistle  mop which is made from lint free wadding held in position by thin wire that is wrapped around it and also forms a shaft and handle.

Wiping down the mouthpiece with a baby wipe and then drying it after every use is also recommended.
Comment: The problem with a slide whistle is that the bottom hole is not normally accessible, as it is closed by the plug of the plunger or slide (I'm hot sure what's the right word in English). If it's possible to disassemble the slide, then this advice applies *ipsis verbis*, other wise only partially (clean up the mouth piece as best as possible).
Comment: And take the slide all the way down, invert the whistle and swab what you can...
Answer: I confirm, a little cleaning and lubrication will maintain the slide whistle.


As I move through an object, i need to increase 1 digit as I create a url

Question: Sorry but I cant think of how to word the question. This is what I am trying to do. I have an xml file that contains
<Image1>pic1.jpg</Image1>
<Image2>pic2.jpg</Image2>
<Image3>pic3.jpg</Image3>
<ImageCount>3</ImageCount>

I am creating a url to show the pic. As I click "next" to view the next image I need to create the next url. I know it would be something like this but I cant wrap my head around it this morning.
if (onImageCount <= totalImageCount) {

        //here we are on the second image request. we need to create a string to pass the "nextimageurl". this string points to which "Image1,2,3," xml tag to pull up next

        nextImageURL = [NSString stringWithFormat:@"http://www.pictureshostedhere.com/%@",selectedVehicle.Image[onImageCount]];
        imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:nextImageURL]];
        carImage = [[UIImageView alloc] initWithFrame:CGRectMake(46,8,228,171)];
        carImage.image = [UIImage imageWithData:imageData];
        [scrollView addSubview:carImage];
        //[self.view sendSubviewToBack:carImage];
        [carImage release];

Any help would be great!
Comment: i dont think it would be a for loop. i already have the object created. now I just need to look at each string within that object, only as the user clicks "next image".
Comment: It looks like you need to increase onImageCount. UserClick->delegateEvent->increase onImageCount->calls the above method.
Comment: i increase the image count just about the if statement (in my project, not shown here sorry should have added that).
Answer: Something like this perhaps...
onImageCount++;
if (onImageCount <= totalImageCount) {
        nextImageURL = [NSString stringWithFormat:@"http://www.pictureshostedhere.com/%@",[self nextImageFromXML:onImageCount]];
       // Other stuff...
}

then, somewhere in your code:
-(NSStrng*)nextImageFromXML:(NSUInteger)count
{
   // Somewhere you've already parsed the XML into an Array
   return [xmlArray objectAtIndex:count];
}

The shortcut would be just...
 nextImageURL = [NSString stringWithFormat:@"http://www.pictureshostedhere.com/%@",[xmlArray objectAtIndex:onImageCount]]; // Where xmlArray returns the appropriate string

Comment: this would work, but the array is full of car objects. so your setup would return a car, instead of the cars image urls. Does that make sense? Inside the car object I have a bunch of strings. Price, make, model, pic1, pic2, etc....
Comment: OK, so once you grab the car object, increment a counter in car object for the next picture. To be honest, we can't read your mind, we can only go off of what you've posted. I believe there's a better way to do this though.
Comment: I agree jordan, sorry about the half ass question :) I am actually working on a solution that was based off of your answer. I am almost there I believe. Ill keep you posted. thanks for the input.


was the first inversion of triads usual before Renaissance? where there any rules about doubling or not doubling root tone?

Question: We have the music of Palestrina, Gallus, Lassus, Cavalieri, Lechner and others. Most chords are in root position. But some are not. In which period the first inversion of triads came up? Was it right after the organum with the first third chords? what rules were used in 4-part practice? who was the first that established some rules about this question?
Comment: sorry, we call (in german) *sixth chords* those chords with the third as bass tone, that means the first inversion. I didn't mean the sixth ajouté
Comment: Oh, okay. So like (C♯-E-A), right? I get it now. Man, someone VTCed already? I hope they come back and see the edits. Good question!
Comment: You mean major 6th chords, like (A-C♯-E-F♯), right? And you're asking when they started to get used in music? (Just clarifying)
Comment: Are you placing _Fauxbourdon_ harmony in Renaissance rather than Middle Ages?
Comment: Good idea: I think it is placed in both epochs: *Fauxbourdon, (French), English false bass, also called faburden, musical texture prevalent during the late Middle Ages and early Renaissance, produced by three voices proceeding primarily in parallel motion in intervals corresponding to the first inversion of the triad.*
So it doesn't matter: I would even mean all music before the well-tempered pitch, so if you find rules of early Baroque it will be interesting too.
Answer: That's a great question that's often insufficiently covered in music history classes. Franco of Cologne's textbook Ars cantus mensurabilis in the 1200's declared the major and minor 6ths (at least in 2-part counterpoint) to be dissonances, an even more restrictive category than the 3rds, which were considered "imperfect consonances." This indeed matches French practice at his time: while 3rds and root-position triads were rather freely used (although cadences had to end on an octave or fifth), the 6th and the 6/3 and 6/4 chords are usually kept on weak beats and used as passing tones, etc.
The English were rather freer than this, and often used parallel 6ths in 2-part writing (the Oxford Book of Carols has some early examples) as well as faburden/fauxbourdon, a 3-part style with parallel 6/3 chords ending on an 8/5. In the next two centuries these English practices began making their way through Europe. By Dufay's time (mid-1400s), the 6th was universally heard and taught as an imperfect consonance, and the Lydian faburden cadence Em/G - F5 (to borrow rock notation!) was commonplace. When this cadence is used in a 4-part piece (e.g. Machaut's Messe de Notre Dame), one upper voice is doubled, in spite of the resulting parallel octaves and fifths! This practice declined in the 1400s.
Interestingly, during this time, while the 6th and 6/3 chord was getting more freely used, the 4th above the bass, appearing notably in the 6/4 chord, was increasingly heard as a dissonant tone in need of resolution to the 3rd. So in Palestrina and his contemporaries (excepting the dilettantish Henry VIII!) when a 6/4 chord occurs, the 4th will always be prepared as a suspension, or the chord will arise from passing or neighboring tones, etc. Or, once or twice, he'll lean on the dissonance as a special effect (usually with words like "O cruel death" or "We have acted unjustly" - see Jeppesen's The Style of Palestrina and the Dissonance for more on particular rules). The doubling of the 6/4 chord is limited by the treatment of the dissonance: if the 4th is a suspension, it cannot be doubled without creating parallel octaves, because it must resolve down. Doubling in 6/3 chords in the Renaissance is an incidental by-product of melodic motion; the doubling is not governed by rules, except that chromatic leading tones (e.g. C# in D Dorian) are at this time never doubled.
This is the story of these chords in educated, mostly vocal music. However, the 16th-century Spanish guitar had a reentrant tuning, like the modern ukulele; the extant texts make clear that street musicians played chords on it without regard to which note was on the bottom, which must have driven learned listeners nuts!
Comment: very detailed and competent answer!
Comment: sorry for accepting your answer so late, I wanted to give a chance for other answers but yours was so perfect that in almost includes all ;)


Why does math.pow throw OverflowError when x**y does not?

Question: Per the documentation, the math.pow function operates as:
def pow(x, y):
    """
    pow(x, y)

    Return x**y (x to the power of y).
    """
    pass

I decided to mess around with large numbers, but I receive an error when I run this:
import math
calc = math.pow(1000, 103)
print(calc)

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    print(math.pow(1000, 103))
OverflowError: math range error

However, the follow does not error:
calc = 1000 ** 103
print(calc)
>> (very large number)

If math.pow is suppose to function as x**y, why does it throw an OverflowError whereas explicitly doing x**y does not?
Comment: Try small integers for arguments; you'll see that `pow` returns an `int` while `math.pow` returns a `float`. The two are not entirely identical.
Comment: Could it be that you are using too big of numbers for the variables?
Answer: math.pow uses floating point which is limited to something about 1e308. If you require a function, use just pow or operator.pow (note those are not the same thing).
operator.pow is exactly the operation from x ** y while pow is a three-argument function to calculate x ** y % z where z can be omitted.
Answer: math.pow uses C complied code and the limit of float in 1.2E-38 to 3.4E+38 in C. Whenever, the result exceeds 3.4E+38, it throws OverflowError.


Is it possible to generate a random complex $n \times p$ matrix $M$, that satisfies $M M^\dagger = \mathbb{1} $?

Question: As stated in the title, I'm interested in generating isometric complex matrices of a given $n \times p$ size. Such a matrix $M$ fulfills the following condition $ M M^\dagger = \mathbb{1} $.
Is there some way to generate such matrices efficiently?
Comment: What kind of distribution to you want the random matrix to have?  Element values uniformly distributed within a certain range?
Answer: $ M M^\dagger = I$ is equivalent to $M$'s rows being any $p$ rows of a unitary matrix (with $p \ge n$), which is further equivalent to the rows of $M$ forming any $p$ elements of a size $n$ orthonormal basis of $\mathbb{C}^n$.
Therefore, you can use the following procedure to generate your random matrix:

Generate a random unit-length complex vector of size $n$. (This can be done by generating any random vector, then dividing by its length.) Let's call this $v_1$.
Using $v_1$, generate $v_2, \dots, v_n$ using complex Gram-Schmidt orthogonalization. This will create a right-handed system of orthonormal vectors.
Finally, choose any $p \le n$ vectors from $v_1, \dots, v_n$ and use them as the rows of your matrix.

Note: If $p < n$, you can still use the same method, simply transpose the matrix at the end.
Comment: Note that $MM^\dagger$ means that the **rows** (not the columns) of $M$ are orthonormal. Note also that the QR method does not *uniformly* produce unitary matrices, as is [noted in this paper](https://arxiv.org/pdf/math-ph/0609050.pdf).
Comment: Well, I gave it a try. This is what I came up with on the fly. I'll correct the columns <-> rows dilemma though.
Answer: This paper gives a method of producing a (uniformly) random matrix $p \times p$ matrix $A$ satisfying $AA^\dagger = I$. Extracting the first $n$ rows gives you a (uniformly random) matrix satisfying $MM^\dagger = I$.
Adapting the Python script given in the paper, we could run the following:
<code>from scipy import *
from linalg import qr
p = 5
n = 3
z = (randn(n,n) + 1j*randn(n,n))/sqrt(2)
q,r = qr(z)
d = diagonal(r)
ph = d/absolute(d)
q = q@ph@q
M = q[:n]
</code>


Perform Find and Insert in eclipse

Question: Instead of find and replace i want to perform a find and insert in eclipse.
Eg: I want to insert a line say "@myAnnotation" before each line starting with "public static final String".
How I can do this?
Thanks
Answer: This can be done using the find and replace tool. For this to work, you should check the Regular Expressions check box. After that, you can search for public static final String and then replace with @myAnnotation\Rpublic static final String (where \R indicates the new line).
Answer: You could do:
1) edit -> Find/Replace
2) fill Find field with: "public static final String"
3) fill Replace with: "@myAnnotation \R public static final String"
4) Check regular expression checkbox.
This should do the work.

Perform Find and Insert in eclipse


How can I delete all field collection revisions?

Question: I want to delete all field collection revisions of a specific field.
I found deleteRevision for this job, but I don't know how to use it. (I couldn't find any example of it.)
Anybody know how can I delete all field collection revisions of a specific field?
Comment: check this https://drupal.org/project/revision_deletion and https://drupal.org/project/node_revision_delete
Comment: also this http://fivepaths.com/drupal-revision-removal-and-database-cleanup-by-brute-force
Comment: @Bala tnx for your attention, but my problem is about field collection revision
Answer: Since you want to purge revisions on a field in a field collection and not an entire content type, your best bet is going to be doing this directly in phpMyAdmin. I don't know of any modules that enable you to delete revisions for a particular field but not the whole content type.
I would locate the field in question and run DELETE from field_revision_field_yourfieldname.
Of course you should back up things before you run a delete query.
The data for nodes and node revisions are store in two different tables. The data for the node page is stored in field_data_yourfieldname. The data for the revision is stored in field_revision_field_yourfieldname.
To illustrate this concept for you, I set up a fresh install of drupal (7.28) on my local machine and connected it to a new empty database.
I set up a content type called field collection demo and I added two field collections.

Since I'm not sure what your configuration entails, the fields I used may or may not be similar to your fields.
Then I created two sample nodes and edited both of them several times with revision tracking turned on. I mostly used lipsum text but for the last revision I typed meaningful text to help you see what's happening in the database.
Here you see that I have created the two nodes:

Here you can see the lipsum text in the original post.

Here you can see that I've created multiple revisions of the node.

And here you can see the meaningful revised text that is the most recent revision.

The next picture shows you how this data is stored in the database in the field_revision_field_yourfieldname table.

You can manually delete one row from the table using the red "X" in phpMyAdmin. Look, for instance, at the last row in this table.
After I click the red "X" for that row, it is deleted.

You can see that now the revision that began with r2 is gone from the field_revision_field_my_fifth_field table.
This removes the revision from the node's revision page. Notice in this picture, the field labeled "My fifth field" is missing.

But this does not affect the node's public view, because that data is stored in the field_data_my_fifth_field table not in the field_revision_field_my_fifth_field_table.

Therefore, I can safely delete all the revisions from the field_revision_field_my_fifth_field_table with the delete query (as I've done on my demo site) and still view the node with no problems:

All the revisions from the field "My fifth field" are gone on the revisions tab but the view tab remains unchanged.
If you wanted to delete all the revisions for all the fields that comprise a node collection, you would simply run the delete query for each of the field_revision_field_yourfieldname tables in the database.
Comment: Do you sure , if I delete all revision, the field collection show value or they will be empty ?
Comment: Well, it depends on what you mean by "will they be empty?" The data for nodes and node revisions are store in two different tables. The data for the node page is stored in field_data_yourfieldname. The data for the revision is stored in field_revision_field_yourfieldname. I'll revise my answer above with screenshots to illustrate.
Comment: Did the revised answer above give you what you needed to delete the field collection revisions?
Comment: I think doing this will remove data from fields in display as well as from edit form of node. This is what happens in my case.


Can I think of convergence as an independent mathematical object?

Question: Recently I studied convergence of sequence of real numbers in an introductory analysis course.

Can I think of convergence as an independent mathematical object just as we think of numbers and functions as mathematical objects?
If I can think of convergence as an independent object does there exist a larger class of objects to which convergence belongs, just like polynomials belong to the larger class of algebraic expressions?
Comment: It's hard. Functions and numbers can be boiled down to a particular set, thus allowing us to think of them as objects. Convergence, on the other hand, is a property of objects. However, you might be able to talk about the collection of convergent sequences/functions/what have you.
Comment: In a certain sense, point-set topology can be considered the study of convergence, in the sense that everything that can be said in point-set topology can be recast into the language of convergence. However it cannot all be recast into the language of convergence of *sequences*; this level of generality requires you to consider convergence of so-called *nets*.
Answer: The answer to (1) is probably hard to come by, as @AndrewWray comments. Convergence is a property of some objects (for example, sequences of numbers).
The answer to (2) is "yes" in an appropriate sense. Topology is the branch of mathematics that deals with things like convergence in a more abstract way. A topological space is an object in which you can think about the convergence of a sequence. So topological spaces may be the larger class of objects that you are trying to imagine.
Answer: Convergence is more like a concept rather than an object.
One can think about convergence of other objects. One cannot manipulate convergence as one usually does with mathematical objects.


Can we use metatheory of set theory for proof statements in set theory?

Question: I wanna know if is possible or have examples of theorems in set theory, for example $\beta$, that have a demonstration of forme
$Cons(ZFC)\Rightarrow \beta$
but $\beta$ is independent of axioms of $ZFC$.
Comment: I was thinking in sentences in language of sets, β in this case talk about sets, Con(ZFC) talk about sentences
Answer: Yes, it is possible.  You can add $Con(ZFC)$ as an assumption.  If you then derive $\beta$ you have proven within $ZFC$ that $Con(ZFC)\implies \beta$.  If you can then prove that $\beta$ is not provable from $ZFC$ you are there.
A trivial example is to take $\beta = Con(ZFC)$.  Then ordinary logic proves $Con(ZFC) \implies \beta$ even without $ZFC$.
Comment: @mihaild "of course can't disprove" No. it is a logical possibility that ZFC can disprove Con(ZFC). Of course it will do so if it is inconsistent, but it is even a possibility that it does so while still being consistent. ZFC could consistent, but wrong about some arithmetic statements.
Comment: @AndersonBot Statements about sentences, suitably translated, are statements about sets. I.e. Con(ZFC) can be expressed in the language of set theory.
Comment: @mihaild yes, that's exactly what I mean. (It even sounds more plausible to me that way.) Actually slightly stronger: ZFC has no models with standard $\omega.$
Comment: Con(ZFC) is not independent of ZFC (or at least the statement that it is is of higher consistency strength than ZFC itself).
Comment: Statement is independent of theory iff theory can't neither prove nor disprove it. $ZFC$ can't prove (and of course can'd disprove) $Con(ZFC)$.
Comment: I was thinking in sentences in language of sets, β in this case talk about sets, Con(ZFC) talk about sentences, but I understand your point
Comment: @spaceisdarkgreen you mean ZFC is consistent, but has only non-standard models?


Snare drum volume vs. chorus

Question: A choir is rehearsing a piece of mine for voices (approx. 30 people, SATB), piano, violin, and snare drum.  In a fast/loud section, the snare drum overpowers the chorus.  It's probably too late to change the snare drum part itself, but are there any things we can try to help improve the balance?
Would a particular set of sticks help, or would something heavy placed on the head help?  I've seen jazz drummers put their wallet on the snare for this reason.  Could something be put inside the drum to deaden it?
The drummer is a skilled performer, so I don't think it's a feature of a young player simply playing too loud.
Comment: Does it seem to be the snap of the snare wires or the ring of the heads (or both) that's creating the issue?  Does the drummer have different choices of instruments to offer (e.g. metal vs. wood, different head types)?
Comment: If you're using amplification, and if you have it, you can of course but the drumset inside a plastic "cage" and mic as needed. This is ultimately the best way to control balance. But to get a good sound you'll need lots of mics (kick, snare, hi-hat, one above the whole set esp for ride), the cage is heavy and expensive, and you'll need good mixing.
Comment: @AndyBonner - no kit, only snare! So encapsulating suddenly becomes easier.
Comment: No cages, no drumset (snare only)
Answer: Volume suggestions…
Stick types, in volume order...
Heavy sticks 2B
Light sticks 7A
Wood whacks/rods
Thinner rods
Brushes
If the drum is too ringy, you can either tune it out, stick a piece of paper tissue over one edge using sticky tape [top/bottom skin or both], or in extremis put a tea towel over it.
After that, it's technique. I know drummers that are a lot louder on 7As than others with 2Bs, because of how they whip into the skin rather than swing at it from a distance.
In case you've not seen them before…
Wood whacks

Rods
Comment: I've seen the whacks/rods sold in the US as "hot rods" and "cool rods" respectively.  Moon Gels (not sure of generic term) will also kill ring and bring volume down somewhat.
Comment: I guess 'rods' are also known as 'rutes'?
Comment: @Theodore - I've seen such ring-killer devices, but tbh if the ring is out of the park, the tuning is wrong. Fix that first.
Comment: @Tetsujin Yes, if it's your drum to tune.  If you're dealing with "someone else's ring", it's probably an easier sell to affix a damper device than to have at it with a tuning key.
Comment: If I'm MD/engineer & the drummer can't tune his kit… I carry a key in my mic case :P

Snare drum volume vs. chorus


Add office365 Sharepoint library to OneDrive Sync

Question: I'm working on automating the OneDrive setup for new computers, and I'm new to this kind of thing.
I need to automate the Sharepoint shared library setup on the user computer. This way the user has all the shared librairy  in the Windows file explorer. This Sharepoint is provided with our Office365 account.
I read the Microsoft documentation and build the URL with the necessary data needed as explained in the part "Auto-configure SharePoint site synchronization".
But there is a problem in my powershell script that I don't understand.
When I run the powershell command Start-Process "odopen://sync/?siteId[...]", the OneDrive window opens and I have to set up the account. But at the end of the process, the only thing synchronised with OneDrive is the user's personal (business) OneDrive, and not the shared librairy.
The folder created by OneDrive is : C:\Users%username\OneDrive -
And the one I want to have is : C:\Users%username<tenant name><Shared Librairy>
It's like OneDrive doesn't care about all the parameters passed in the URL.
FYI, I run this script in a fresh Windows 10 VM.
Thanks for your help
Answer: So, we must URL encode paramters like below :
Add-Type -AssemblyName System.Web
$WebURL = [System.Web.HttpUtility]::UrlEncode("https://plop.sharepoint.com")
$SiteID = [System.Web.HttpUtility]::UrlEncode("{xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
$WebID = [System.Web.HttpUtility]::UrlEncode("{xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}")
$ListID = [System.Web.HttpUtility]::UrlEncode("{xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}")
$WebTitle = [System.Web.HttpUtility]::UrlEncode("PLOP")
$ListTitle = [System.Web.HttpUtility]::UrlEncode("Folder")
$UserName = [System.Web.HttpUtility]::UrlEncode("firstname.lastname@example.com")

Write-Output "Configure OneDrive"
$odopen = "odopen://sync/?onPrem=0&webTemplate=68&libraryType=4&siteId=" + $SiteID + "&webId=" + $WebID + "&webUrl=" + $webURL + "&listId=" + $ListID + "&userEmail=" + $UserName + "&webTitle=" + $WebTitle + "&listTitle=" + $ListTitle

Start-Process $odopen

That's all...


Is this enough to prove linear independence?

Question: Given the vector space $({\mathbb{R}}^{\mathbb{R}},+,\cdot)$, with ${\mathbb{R}}^{\mathbb{R}}$ defined as the set of all functions $f: \mathbb{R} \rightarrow \mathbb{R}$, we are asked to prove that $f_1(x) = e^x$ and $f_2(x) = e^{-x}$ are linearly independent.
We recall that $f_1(x)$ and $f_2(x)$ are linearly independent if, and only if, $\forall a_1,a_2 \in \mathbb{R}$ $\big(a_1f_1(x) + a_2f_2(x) = 0 \big) \Rightarrow \big( a_1 = a_2 =0 \big).$
Is it enough to do the following?
Proof:
Consider the case $x=0$, then clearly we have that $a_1 = -a_2$. Then consider the more general case. We have:
$$a_1e^x - a_2e^{-x} = 0 \iff a_1e^x - a_1e^{-x} = 0$$ from our equality obtained above. This implies that
$$a_1(e^x-e^{-x}) = 0,$$ which subsequently implies that either  $a_1 = 0$ or $e^x = e^{-x}$.
Thus for all $x$, $a_1 = 0$, and from our earlier equality $a_1=-a_2=0$, which implies $f_1,f_2$ are linearly independent.
In the lecture notes I am referring to, the latter part of the argument wasn't done for general $x$, but rather it was done in particular for $x=1$, and the same conclusion was reached. I am struggling to see how this tells you anything about the functions for all $x$, but perhaps I am just being dense.
As an additional question, the lecture notes also discuss using derivatives to prove linear independence of functions, but this has not been justified anywhere in the notes thus far. Why is this a reasonable thing to do?
Comment: So long as there is one value of $x$ for which the linear combination is not zero, the linear combination of the two functions is not identically zero, whence the functions are linearly independent. To put it the other way, for the two functions to be linearly dependent, there must exist coefficients that work for every value of $x$.
Answer: This is basically correct, but I would start by supposing the hypothesis: "Suppose $a_1, a_2 \in \mathbb{R}$ so that $a_1e^x + a_2 e^{-x} = 0$ for all $x$."
Then, you come to the conclusion that $$a_1(e^x - e^{-x}) = 0.$$ But remember the definition of $0$ in the space of real-valued functions: it is actually the function that maps every $x \in \mathbb{R}$ to $0$.  To prove two functions are equal is to prove they are equal on every input.  So there is really a hidden quantifier in this statement.   You have found that
$$a_1(e^x - e^{-x}) = 0 \text{ for all $x$.
}$$
Thus either $a_1 = 0$, or else $e^x = e^{-x}$ for all $x$. You need to show that the latter is not possible.  This might be regarded as obvious, but in general, to disprove a universally quantified statement (a "for all x" statement) you need to furnish a counterexample.  Thus, you need to prove there exists an $x$ so that $e^x \neq e^{-x}$.  Choosing $x=1$, for example, does the job.
I can't really answer your second question without knowing what the course is.  But if it is not a course in calculus/analysis, where you go to the trouble of defining derivatives, it is not unreasonable to assume that all this work has been done and that the basic facts of calculus are known.
Comment: @Benjamin I can't help without details about how the derivative is being used in that particular case.  It is just one of the tools available to you.
Comment: This answered my question thank you. But RE the derivative question: I don't understand why the derivative tells us anything about the linear independence of the original function.


How do I combine 2 Select Queries

Question: SELECT * FROM user_pokemon_db WHERE user_id = '".$id."'

SELECT path FROM pokemons WHERE pk_id = '".$pkmn_id."'

I know I have to use JOIN, but I am not getting it right!
How can I do that??
Comment: It's quite hard to tell without having an idea of your database schema... Indeed you will probably have to use JOIN somewehre...
Comment: So what _have_ you tried so far and what was wrong with those tries?
Comment: Perhaps you should start at the beginning. http://www.w3schools.com/sql/default.asp?PHPSESSID=300ae3404d5fa2612f238abeebb8869c
Answer: If you expect both queries to return the same structure, you could use UNION.
http://www.w3schools.com/sql/sql_union.asp
SELECT * FROM user_pokemon_db WHERE user_id = '".$id."'
UNION
SELECT path FROM pokemons WHERE pk_id = '".$pkmn_id."'

Comment: That would expect both queries to return the same result structure. That most likely is _not_ the case!
Answer: The following query will return the path for every row in user_pokemon_db table.
SELECT p.path, upd.*
FROM user_pokemon_db upd, pokemons p
WHERE upd.user_id = '".$id."'
AND p.pk_id = '".$pkmn_id."'

Comment: This style would help me further :)

How do I combine 2 Select Queries


Audio Conferencing Solutions

Question: I need to re-evaluate our phone conferencing vendor / package.  Not having managed this particular service in the past, would anybody care to share what kind of companies/offerings are out there that you've encountered?
Throwing out some points of interest to get started, feel free to add/change/disregard...

Do you host your own phone conferencing solution?

Number of users
Platform

Do you outsource?

Vendor
Terms (not rates, I realize these vary, but are charges by the minute, bundled, per account, etc.)
Limitations, features

(I've intentionally kept this separate from video conferencing)
Comment: Hi, I looked at your profile and couldn't see a country/continent - it might help to know where you are as in general telephony options vary around the world and it might help us to respond better to your question.
Comment: Makes sense to me!
Answer: We once did it ourselves with Asterisk. We're small, so eventually we decided to go with Trixbox. They have a very sucky billing department, but their support is good (sometimes very slow do) and it just works.
As far as terms go, you pay for the licenses and support, since it's a whole PBX, not just a conferencing solution.
You can use either land lines or a VoIP account, so as far as cost goes it depends on that. They have a very nifty feature where if two companies have Trixbox installed, calls between them get routed over the Internet, and they're completely free (bandwidth issues aside).
Answer: Hosting internally
Pros: More control over costs and technology
Cons: Increased cost for line usage to the PSTN.
Outsourcing:
Pros: Can Scale on demand, less management, more features (ie transcription)
Cons: Pay per swallow.
I've used:
Freeconference.com if all you need is audio. Max size 150!
Hey Otto has a certain cool factor to it, but it's $.09 per minute.
gotomeeting.com audio quality is shotty sometimes, but nice if you have a presentation.
Voted +1 for Asterisk. Huge fan of our Switchvox.
Comment: I shied away from freeconference when it looked like you can end up waiting if you try to start a conference at a busy time?
Answer: Telephony is black magic to many in our world!  And it is getting worse rather than better as VoIP and SIP start to merge voice onto our networks.
The biggest issue in rolling your own phone conferencing is getting sufficient connectivity to the system.  A 16 user conference call requires 16 phone lines (or 16 channels on a PRI or equivalent).  Those costs add up fast for a small business, and there are powerful economies of scale available.  I would be surprised if a small company without lots of phone connectivity could do it cost effectively.
Assuming you have sufficient telephone connections, there are lots of options available for doing your own conferencing.  Most phone systems have conference hosting options, some are expensive and some are cheap.  For instance, NBX Software has an interesting solution that uses SIP/VoIP and runs on Windows; with it and a telephone gateway you are going!
Comment: This confirms my thinking re: rolling your own.  I suspect all I'll need to prove along these lines is why it'll cost too much to be worthwhile.  Now to find some reputable service providers to compare against our current partner.
Comment: The monthly minutes is the key number, along with the cost of a PRI in your neighborhood and the cost of the conference bridge.  A *complete* WAG is that $1000/month on conferences smaller than 20 people is the LEAST that could justify rolling your own.
Answer: If you're considering rolling your own, the best open source telephony engine is Asterisk.
Choose an ITSP with a good reputation and attractive rates, and configure as many conferences as you like with no telco hassles. Many ITSPs offer declining-balance options, so you truly only pay for what you use, and typical rates are about 1/3 of what you're paying now.
For those that like a safety net, Digium (the creator and sponsor of Asterisk) offers subscriptions that include professional, round-the-clock tech support.
Don't want to mess with Asterisk directly? Check out Switchvox, Digium's business-ready PBX based on Asterisk. Its web interface makes administering a PBX simple. And it does conferencing, too.
As a long-time Asterisk user and Digium employee, I'm a bit biased. Doesn't mean I'm wrong -- try it and see.
Answer: We're using AccuConference and they have been great - our bills are half what they used to be (in large part due to their auto-disconnect if after 15 minutes if there is only one party on the line).  We do 3,000+ minutes/month & are on a volume plan with a good rate - they bill per minute/per caller.  Probably haven't had more than 10-15 parties on a call, so I don't know their limit.
The coolest thing for me has been the ability to generate as many conference codes as needed - I created one for each member of the sales staff - which eliminated all of the "Using conference line between 3:00 and 4:00" emails in addition to giving some accounting of who is using it.  There are other features like conference recording which can be useful.  It looks like they may be rolling out a web/video conferencing solution but I haven't gotten there yet.
Comment: Thank you!  I'll check them out.  I love having options.
Answer: We're currently using a provider with a $.06/min US rate on domestic conference calls with a fairly large limit on call-ins (150, I believe) - international @ .08/min.  It seems like a reasonable rate to me, and I can't find anything lower outside of free services (at which point you give up guaranteed scheduling - not something I would think we should use with customers or prospects).
However, there are some who think I should be able to find something cheaper/better.  Looks like there's not a whole lot of interest or new information in this area?

Audio Conferencing Solutions


What's the probability that Abe will win?

Question: Abe and Bill are playing a fun game. Each of them roll a dice every turn. Abe succeeds if he rolls either a 1 or 2. Bill succeeds is he rolls either a 3, 4, or 5.
If they both succeed on a turn, then they tie the game. If exactly 1 player succeeds on a turn, then the succeeding player wins. If neither player succeeds on a turn, another turn occurs.
What's the probability that Abe will win? I originally thought that the answer was $\frac{2}{5}$, but I realized that the players could tie as well.
Comment: Does Bill succeed if Abe rolls a $3$, $4$, or $5$? Or do they need to roll "their" number?
Comment: They both need to roll one of their numbers on their own dice. Good point.
Comment: A non-mathematical comment: *dice* is plural, the singular being *die*.
Answer: Out of 36 (6x6) combinations of die rolls:
Abe will win in 6 of them:
(Abe rolls 1 or 2) AND (Bill rolls 1 or 2 or 6)
Bill will win in 12 of them:
(Abe rolls 3 or 4 or 5 or 6) AND (Bill rolls 3 or 4 or 5)
The remaining lead to another roll, so they became irrelevant as only one of the 18 situation above finishes up the game.
Out of 18 possible, and equally likely, game ends, Abe wins 6 times, thus:
P{Abe wins} = 6/18 = 1/3
Answer: Let $p$ be the probability that Abe eventually wins the game. This can happen in three  ways:
(i) (Immediately) Abe succeeds and Bill fails.
(ii) Abe succeeds, and Bill does. Then they are tied. Given this, Abe's probability of ultimately winning is $p$.
(iii) Abe and Bill both fail. Then we are in a situation similar to (ii).
So
$$p=\frac{2}{6}\cdot\frac{3}{6}+\left(\frac{2}{6}\cdot\frac{3}{6}\right)p+\left(\frac{4}{6}\cdot\frac{3}{6}\right)p.$$
Solve. We get $p=\dfrac{1}{3}$.


If $\lim A_n$ exists, then $P(\lim A_n) = \lim P(A_n)$

Question: Given a sequence $\{A_n\}$ of events with $\lim A_n = A$, I would like to show that $P(\lim A_n) = \lim P(A_n)$.
$\lim A_n = A$ implies that $\limsup A_n = A$. Thus $\bigcap \bigcup_{k=n}^{\infty}A_k=A$
Let $B_n=\bigcup_{k=n}^{\infty}A_k$ for every $n$. Then $B_n$ is non increasing.
We have:
$P(\lim A_n) = P(A) = P(\bigcap \bigcup_{k=n}^{\infty}A_k)=P(\bigcap B_n) = \lim P(B_n)$ since $B_n$ non-increasing.
Thus $P(\lim A_n) = \lim P(\bigcup_{k=n}^{\infty}A_k))$.
How do I go from here to $\lim P(A_n)$?
Any hep would be greatly appreciated.
Comment: I think you want subscript $k$ (not $n$) in your $\bigcap\bigcup$ expressions
Comment: What means $\lim_{n\rightarrow \infty} A_n = A$?
Comment: $A_n \subseteq \cup_{k=n}^{\infty}A_n$, so $P(A_n) \leq P(\cup_{k=n}^{\infty}A_n)$. Combined with what you have already, this gives you $\limsup P(A_n) \leq P(\lim A_n)$. For the opposite inequality, presumably you also need to use that $\liminf A_n = A$. It would suffice to show that $P(\lim A_n) \leq \liminf P(A_n)$.
Answer: Since $\bigcap_{k\geq n} A_k$ is an increasing sequence of events, $P(\limsup_n A_n) = \lim_n P(\bigcap_{k\geq n} A_k)$.
Since $\bigcup_{k\geq n} A_k$ is a decreasing sequence of events, $P(\liminf_n A_n) = \lim_n P(\bigcup_{k\geq n} A_k)$.
Since $\lim_n A_n = \liminf_n A_n = \limsup_n A_n$, $P(\lim_n A_n) = P(\liminf_n A_n) = P(\limsup_n A_n)$.
But for all $n$, $P(\bigcap_{k\geq n} A_k)\leq P(A_n)\leq P(\bigcup_{k\geq n} A_k)$, so by squeezing, $P(A_n)$ converges to $P(\lim_n A_n)$.
Comment: Sounds like a wheel reinvention. Why not just use Fatou's Lemma? I posted an answer.
Comment: I further edited my answer to address comment of Gabriel Romon.
Answer: TL;DR The other answers seem to reinvent the wheel. Just use Fatou's Lemma
$$P(\liminf A_n) \le \liminf P(A_n) \le \limsup P(A_n) \le P(\limsup A_n)$$

Note to justify: I really mean that I expect that at this point that the student knows the inequalities above collectively known Fatou's Lemma (and reverse Fatou's Lemma and the regular $\limsup$ and $\liminf$ of real numbers in calculus). Maybe the student also knows integration version of Fatou's Lemma in measure theory, but I don't expect the student to know Fatou's Lemma in this sense (and thus of course in the expectation sense. Consequently further, I don't expect the student to use or even know $E[1_A]=P(A)$).

Edit: For further justification, see below.

Actually, what we first have to prove is that $\lim P(A_n)$ exists, i.e. $\liminf P(A_n) = \limsup P(A_n)$ and then we define this common value as $\lim P(A_n)$. Then

Fatou's lemma says

$$P(\liminf A_n) \le \liminf P(A_n) \le \limsup P(A_n) \le P(\limsup A_n)$$

Now, saying '$\lim A_n$ exists' means '$\liminf A_n = \limsup A_n$' and then we define this common value as $\lim A_n$.

Then

$$P(\lim A_n) \le \liminf P(A_n) \le \limsup P(A_n) \le P(\lim A_n)$$

Hence, $\liminf P(A_n)  = \limsup P(A_n)$, i.e. $\lim P(A_n)$ exists

Finally, $P(\lim A_n) = \liminf P(A_n)  = \limsup P(A_n) =: \lim P(A_n)$

Edit: For the Note above and the comment of Gabriel Romon:
See for yourself that in David Williams' Probability with Martingales, you can prove Fatou's Lemma without any knowledge of measure-theoretic (Lebesgue) integration.
Comment: I did not downvote. You're assuming the prior knowledge of the inequalities $P(\liminf A_n) \le \liminf P(A_n)$ and $\limsup P(A_n) \le P(\limsup A_n)$ (as statements or corollaries of Fatou's Lemma). However Fatou's Lemma is usually stated as $\int \liminf f_n d\mu \leq \liminf \int f_n d\mu$ for nonnegative measurable functions. A bit of work is required to show that $\liminf 1_{A_n}  = 1_{\liminf A_n}$.
Comment: No, I even upvoted it.
Comment: @GabrielRomon I actually address this in the 'Note'. Here's the order of the Fatou's Lemma versions I learned: 1 - the measurable function thingy you said, 2 - the probability of events thingy I said, 3 - the (conditional) expectation version --> Here, we do not quite see how (2) follows from (1), but we do see how (2) follows from (3).
Comment: @GabrielRomon Nevertheless, we learn events before random variables. So we just take for granted that (1) and (2) are somehow related before we learn (3). However, you don't need to take (2) for granted. You can still prove (2) without using (1), (3), integration, expectations and measure theory and stuff. I don't believe this is unconventional. See David Williams' Probability with Martingales. The Fatou's Lemmas I state are in Chapter 2 (the '(2)'), but the Fatou's Lemmas you state are in Chapter 5 (the '(1)'). Later the probabilistic version is in Chapter 6 (the '(3)').
Comment: @GabrielRomon Anyhoo thanks!
Comment: @GabrielRomon so actually do you disagree with anything in my answer?
Comment: @GabrielRomon right thanks XD
Answer: A very useful way of thinking about this is to verify that $A=lim A_n$ exists iff $I_A=\lim I_{A_n}$ at every point. If you know DCT then  you get $P(A)=\lim P(A_n)$ immediately.
Comment: Sounds like a wheel reinvention or unnecessary use of the machinery of limits of random variables. Why not just use Fatou's Lemma? I posted an answer.
Comment: I further edited my answer to address comment of Gabriel Romon.


Using the ARI to validate clusters

Question: To validate the results of a clustering solution, I am using the ARI to quantify the agreement with a reference classification method.
Something which I do not quite understand is the concept of a "correct" or "true" clustering nature of a dataset, and as such if comparison with "Distribution" is appropriate for evaluating the clustering solutions.
Answer: What is your aim of clustering? It all depends on what you want to know. If your aim is to reproduce the given classification, the ARI will tell you how well you do that. However I wonder why then would you want to cluster these data if you know the true clusters already?
What you do here gives some sensible validation information for your clustering if, although you want to learn something new and therefore your aim is not simply to reproduce the given classification, you can argue that from your aim of clustering it can be expected to be positively related to that classification. Although this doesn't necessarily mean that the clustering with 0.2898 is necessarily better than the one with 0.2387. Both are somewhat but not very strongly related to the given classification, the one with $K=4$ a bit better, but there may be other criteria you may also want to look at.
However, if your aim of clustering is unrelated to the given classification, these values don't tell you anything useful.
Clustering relies crucially on what kind of clusters the user wants to find, what clusters are supposed to mean in terms of subject matter and background information etc. One shouldn't think about clustering as a fully automatic formal procedure.
You may want to read this, particularly Sec. 2 regarding the idea of "true" clusters:
 https://arxiv.org/abs/1503.02059
Comment: Can't say much about this, because "I am told" basically means that somebody else has decided this and I have no idea on what basis.
Comment: The ARI says that the $K=4$ solution is more similar to the given classification. To what extent that means that it's better is another matter, see my answer. It may play some role...

Using the ARI to validate clusters


What is the generalization of Gauss's Theorem to a manifold?

Question: In a (pseudo-)Riemannian manifold with constant basis vectors, one certainly has that the integral of the divergence of a tensor field $T$ over a submanifold $\Omega$ is equal to the integral over the boundary $\partial\Omega$ of the inner product of $T$ with the outward-directed unit normal vector. To be more explicit, in component form in Minkowski space,
$$ \int\limits_\Omega \partial_\mu {{T^\alpha}_\beta}^\mu \ \mathrm{d}x^0 \wedge \mathrm{d}x^1 \wedge \mathrm{d}x^2 \wedge \mathrm{d}x^3 = \int\limits_{\partial\Omega} {{T^\alpha}_\beta}^\mu \varepsilon_{\mu|\alpha\beta\gamma|} \ \mathrm{d}x^\alpha \wedge \mathrm{d}x^\beta \wedge \mathrm{d}x^\gamma, $$
where I'm using the convention in Misner, Thorne, & Wheeler that $|\alpha\beta\gamma|$ runs over all indices such that $0 \leq \alpha < \beta < \gamma \leq 3$, and $\epsilon$ is the Levi-Civita symbol/tensor (there being no difference in the lowered-index form in Minkowski space).
The problem is, the proof given in that book only makes sense in Cartesian coordinates. What if I have some arbitrary coordinates in a curved manifold? Is there an analogous equation relating
$$ \int\limits_\Omega \nabla_\mu {{T^\alpha}_\beta}^\mu \sqrt{|g|} \ \mathrm{d}^4x \leftrightarrow \int\limits_{\partial\Omega} {{T^\alpha}_\beta}^\mu n_\mu \sqrt{|\gamma|} \ \mathrm{d}^3x? $$
(Here $\nabla$ is the covariant derivative compatible with the metric, $g$ is the determinant of the metric, and $\gamma$ is the determinant of the induced metric on the surface.)
Wald1 shows in an appendix that
$$ \int\limits_\Omega \nabla_\mu v^\mu = \int\limits_{\partial\Omega} v^\mu n_\mu, $$
where I've followed his lead and suppressed the volume elements. This would seem to indicate that I can follow a naive "partial to covariant" prescription to make my first equation turn into my second. But does this work for arbitrary tensors? I worry because rank $(1,0)$ tensors can have fortuitous cancellations, such as how $\nabla_\mu v^\mu = \partial_\mu (\sqrt{|g|} v^\mu) / \sqrt{|g|}$ holds without extra connection terms.

1 Yes, another physics book. It occurs to me that I don't own any pure math differential geometry books.
Comment: I friend of mine (whom I passed your question) tells me that the answer to your question is on p. 147 & 148 of "Geometrical methods
of mathematical physics" by Bernard Schutz. Regards
Answer: Your statement for general tensors is not true, I think. Assume that $T^{\alpha \mu}_{\beta} = S^{\alpha}_{\beta} v^{\mu}$, where $\nabla S$ is not identically zero. Then, dropping indices, $\nabla T = (\nabla S)v+ S\nabla v$. The second term of the right-hand side, $S\nabla v$, after being integrated, gives the right-hand side of your hypothesized formula, by Gauss's theorem. But then you also need to integrate the first term, $(\nabla S)v$, and there is no reason to expect this to always be 0.


How can I test whether two logistic regression coefficients are identical in mixed models?

Question: Similar to question here.
3 variables (1 continuous (X) and 2 categorical (A & B)) predict 1 dichotomous variable in generalized linear mixed models.
Both variables A and B are dichotomous and are coded with 0 (reference category) and 1. Criterion is coded with 0 & 1.
After
library(lmerTest)
glmer(Y ~ X*A*B + (0+X|G) + (1|G), data=dat, family = "binomial", verbose = T, control = glmerControl(optimizer = "bobyqa"))

we have the following results:
Random effects:
 Groups    Name                        Variance  Std.Dev.
 G         (Intercept)                 0.1458298 0.38188
 G          X                          0.21727   0.46612
Number of obs: 26260, groups:  G, 230
Fixed effects:
                                   Estimate Std. Error z value Pr(>|z|)
(Intercept)                         1.47384    0.04094  35.997  < 2e-16 ***
X                                  -0.03252    0.01612  -2.017  0.04370 *
A2                                 -0.46066    0.04853  -9.492  < 2e-16 ***
B2                                 -0.61576    0.04811 -12.799  < 2e-16 ***
X:A2                                0.07502    0.01810   4.144 3.41e-05 ***
X:B2                                0.08031    0.01945   4.129 3.64e-05 ***
A2:B2                               0.62260    0.06653   9.358  < 2e-16 ***
X:A2:B2                            -0.06789    0.02367  -2.868  0.00413 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Now, the slopes for different conditions are:
    A1      A2
B1  X       X+X:A2
B2  X+X:B2  X+X:A2+X:B2+X:A2:B2

How can I test the following hypothesis
X+X:B2 = X+X:A2 + X:B2 + X:A2:B2 which equals to
0 = X:A2 + X:A2:B2 and finally
X:A2 = -X:A2:B2
For logistic one-level models we use Wald's test as described in here.
library(aod)
R <- cbind(0,0,0,0,0,0,1,1)
wald.test(b = coef(model), Sigma = vcov(model), L = R)

Can we use the identical approach for mixed models?
Comment: $R$ vector should be $(0, 0, 0,0,0,0, 1, 1)$ if you want to test whether fixed effect 7th and 8th covariate - counting the intercept - together are 0, as implied when you say 0 = X:A2 + X:A2:B2.
Comment: I suppose you fit the model in R judging by the output. What is the fit command?
Comment: Added the code in the OP
Comment: Yes, you are right!
Answer: You can use the GLMMadaptive package in which the anova() method has an argument called L that is a user-defined contrast matrix. For more info check here.
The relevant code would be something like:
library(GLMMadaptive)
fm <- mixed_model(Y ~ X * A * B, random = ~ X || G, data = dat,
                  family = binomial())
R <- cbind(0,0,0,0,0,0,1,1)
anova(fm, L = R)

Comment: Thank you but using GLMMadaptive is not an option for me now. Is there something similar to Wald's test for logit models?
Comment: You can check the **aod** package that has the `wald.test()` function.
Comment: BTW, the model you posted above can be fitted with **GLMMadaptive**.
Answer: I am not overly familiar with mixed models (read I cannot tell you whether this is a correct statistical approach) but based on reading here mixed models on SSC I think you may be looking for something like this:
set.seed(1)
#### SIMULATE ####
n <- 1000
K <- 4
A <- as.numeric( runif(n)<0.5 )
B <- as.numeric( runif(n)<0.3 )
X <- rnorm(n) + runif(n)
random_effect_index <- sample(1:K,10,replace=TRUE)
random_effect <- rnorm(K,sd=0.3)[random_effect_index]

# Fixed effect parameters
beta_0 <- 0
beta_X <- 0.5
beta_B <- 1
beta_A <- 1.3

beta_XA <- 0.5
beta_XB <- 1.3
beta_AB <- -0.5

beta_XAB <- -1

# probabilities

interaction_effects <- (beta_XA*X*A) + (beta_XB*X*B) + (beta_AB*A*B) + (beta_XAB*X*A*B)

exp_z <- exp(beta_0 + beta_X * X + beta_A * A + beta_B * B + interaction_effects + random_effect)
p <- exp_z / (1 + exp_z)
hist(p)

# dependent
Y <- as.numeric( runif(n) < p )
mydata <- data.frame(Y=Y,X=X,A=A,B=B,G=random_effect_index)
head(mydata)

#### FIT MODEL ####
library(lme4)
gmm <- glmer(Y ~ X*A*B + (0+X|G) + (1|G), data=mydata, family = "binomial", verbose = T, control = glmerControl(optimizer = "bobyqa"))
summary(gmm)

# Likelihood Ratio Test using Linear Hypothesis Command
library(car)
LH <- linearHypothesis(gmm,c("X:A + X:A:B=0") )
LH

Answer: If you have two predictors in a regression model and want to test whether or not they have equivalent effects, i.e. that $\beta_1 = \beta_2$ in
$$ Y = \beta_0 + \beta_1 X_1 + \beta_2 X_2 + \varepsilon$$
Then form a new predictor, $Z = X_1 + X_2$, and compare the model with $X_1, X_2$ as predictors to the one using only $Z$. If the larger model is not significantly better you don't have evidence that the coefficients are different.
I described this in terms of continuous predictors, and for linear regression, but you can imagine an analogous approach for categorical variables and for GLMs like logistic regression.


Is inline summation index has different functionality, such as $\sum_{x,y} f(X,Y)$?

Question: I find different papers use summation with a different style than other summation in the same paper. This thing repeats in more than one paper. Therefore I believe this is summation do different work than normal one.
 <- from the paper 1
2<-from the paper 2
What does this summation call?
What does it do?
Paper use this kind of summation:

Jeffrey–divergence eq, https://www.researchgate.net/publication/3703241_Non-parametric_similarity_measures_for_unsupervised_texturesegmentation_and_image_retrieval
9+ 10 eq, http://www.sciencedirect.com/science/article/pii/S0924271616304324
Comment: I still looking for answers
Answer: Those ambiguous context dependent expressions could be open to different interpretation.
$\sum_k$: This is just a summarized standard sum of some index $k$ over some discrete domain $K$. One has to derive from the context which is that domain (perhaps the histogram samples in this case?)
$\sum_{ij}c_{ij}$: This is the same case, but the sum is double. Again this is context dependent. One could think on independent domains for $i$ and $j$, or even coupled $i,j$ pairs to be included on the sum. I was unable to check this second paper.
$\sum_XP_{XY}$: In this case, the context reads for a marginal discrete distribution. Again, omiting the domain of the random variable $X$ creates an ambiguity. Which in this case is increased by the ambiguity of making no difference between the random variable name $X$, the values it can take, and the values considered for the sum. Sometimes, we can assume too much.
Edit:
From the context, the expressions:
$$
P_{XY}=\frac1{\sum_{ij}c_{ij}}JH\\
P_{X}=\sum_{Y}P_{XY}\\
P_{Y}=\sum_{X}P_{XY}
$$
are equivalent to:
$$
P_{XY}(ij)=\frac1{\sum_{i'=1}^m\sum_{j'=1}^nc_{i'j'}}c_{ij}\\
P_{X}(i)=\sum_{j=1}^nP_{XY}(ij)\\
P_{Y}(j)=\sum_{i=1}^nP_{XY}(ij)
$$
From the paper $c_{ij}$ are the elements of the matrix $JH$, hence $P_{XY}$ is just normalizing the histogram matrix $JH$ in order to be interpreted as a joint distribution.
And from here, $P_X$ and $P_Y$ are vectors, obtaining by summing one of the indexes of the previously obtained matrix, which can be interpreted as the marginal distributions of $X$ and $Y$.
Comment: I think you did not get my question. My question is the inline summation of these papers just like normal summation or not?  if same.. why the authors use inline style while using normal with other summation in the same paper.
Comment: the 2nd paper http://www.geosimulation.cn/Papers/isprs_image_registration.pdf
Comment: I can understand from your ans there is no difference between write index under sigma or inline text. thanks for your update
Comment: Check the edit. These are the proper replacement for the overloaded notation. I hope this is clearer now.
Answer: Your first example seems to be the one that's worrying you. The "$ij$" is written to the lower right of the $\sum$ symbol. I think this is what you mean by "in-line" positioning.
The positioning of the $ij$ doesn't mean anything. It doesn't matter whether the $ij$ is to the right of the $\sum$ symbol or below it. The meaning of the summation is the same in both cases.


generalized eigenspaces for many operators III

Question: Let $\phi_1, \cdots, \phi_n$ be commutative linear operators on a vector space $V.\,\,$ Then we have $$V=\oplus V_{(a_i)}, \text{ where } V_{(a_i)} = \{x\in V \mid \exists p \,\,\text{ such that }\,\, (\phi_i-a_i)^px=0, \forall i\}.$$
When we decompose $V$ with respect to $\phi_1$, we have
$$
V=\oplus V_i, \text{ where } V_i = \{ x\in V \mid \exists p, a_i \,\,\text{ such that }\,\, (\phi_1-a_i)^px=0\}.
$$
What is the relation of these two decomposition? Thank you.
Comment: Your notation is prone to confusion, using $a_i$ for several different things.
Answer: Let $\lambda_1,\ldots,\lambda_k$ be the distinct eigenvalues of $\phi_1$; if the characteristic polynomial of $\phi_1$ splits (something you seem to be assuming implicitly), then we have
$$V = V_{\lambda_1}\oplus V_{\lambda_2}\oplus\cdots\oplus V_{\lambda_k}$$
where
$$V_{\lambda_j} = \{x\in V\mid \text{there exists }p\text{ such that }(\phi_1-\lambda_jI)^px = 0\}.$$
But even if we don't have that, letting $V_{\lambda_j}$ be as above, we still get the obvious inclusions:
Let $(a_1,\ldots,a_n)$ be a tuple corresponding to a nonzero $V_{(a_1,\ldots,a_n)}$ from the first decomposition. Then each $a_i$ must be an eigenvalue of $\phi_i$. In particular, $a_1 = \lambda_j$ for some $j$, $1\leq j\leq k$. Then
$$V_{(a_1,\ldots,a_n)} = V_{(\lambda_j,a_2,\ldots,a_n)} \subseteq V_{\lambda_j}.$$
In general, if we let
$$V_{j,\mu} = \{x\in V\mid \text{there exists }p\text{ such that }(\phi_j-\mu I)^px=0\},$$
then
$$V_{(a_1,\ldots,a_n)}\subseteq V_{1,a_1}\cap V_{2,a_2}\cap\cdots\cap V_{n,a_n}.$$
This inclusion holds in general, whether or not the characteristic polynomials of the $\phi_i$ split.
Comment: thanks. In your argument, it seems that $(\phi_1-a_1)^{p_1}x=0$ implies $(\phi_1-\lambda_j)^{p_2}x=0$. But here $p_1$ may be different from $p_2$.
Comment: @user9791: I don't understand your comment. I make no assumptions whatsoever about the value of the exponent. If $a_1=\lambda_j$ (that is, if $a_1$ is an eigenvalue of $\phi_1$), and $x\in V_{(a_1,\ldots,a_n)}$, then in particular there exists a value of $p\gt 0$ such that $(\phi_1-a_1 I)^px = (\phi_1-\lambda_j I)^px = 0$, hence $x\in V_{\lambda_j}$. I don't understand what you are wondering about. Note that $p$ is not unique in any case, since if $p$ works, then so does any $p'\gt p$.


how to send an email from within the app

Question: I'm trying to send an email with data from text field and image and it doesn't work, please advise. Here is my code:
<code>     - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(buttonIndex==1)
{

    Cocktails*c=[[Cocktails alloc]init];

    _arrTextField=[NSArray  arrayWithObjects:_txtName,_txtIngredients,_txtPreper,_txtServe,_txtFrom ,nil];

    NSLog(@"send email");

    if ([MFMailComposeViewController canSendMail])
    {
    NSMutableArray*recipients=[[NSMutableArray alloc]init];

    [recipients addObject:@"firstname.lastname@example.com"];
    MFMailComposeViewController *controller= [[MFMailComposeViewController alloc]init];
    controller.mailComposeDelegate= self;
    [controller addAttachmentData:_imgDrink mimeType:@"image/png" fileName:@"Myimage"];
    [controller setSubject:@"my cocktail"];
    [controller setMessageBody: _arrTextField isHTML:NO];
    [controller setToRecipients:recipients];
    }
    else
    {
        UIAlertView* alert=[[UIAlertView alloc]initWithTitle:@"Alert" message:@"Your devise is not set up for Email" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:Nil, nil];

        [alert show];
       //  [alert release];
    }
</code>
Answer: You never present the mail controller. It needs to be presented like any other modal view controller.
Answer: Here that should help:
<code>-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    switch (result)
    {
        case MFMailComposeResultCancelled:
            NSLog(@"Mail cancelled: you cancelled the operation and no email message was queued.");
            break;
        case MFMailComposeResultSaved:
            NSLog(@"Mail saved: you saved the email message in the drafts folder.");
            break;
        case MFMailComposeResultSent:
            NSLog(@"Mail send: the email message is queued in the outbox. It is ready to send.");
            break;
        case MFMailComposeResultFailed:
            NSLog(@"Mail failed: the email message was not saved or queued, possibly due to an error.");
            break;
        default:
            NSLog(@"Mail not sent.");
            break;
    }

    // Remove the mail view
    [self dismissModalViewControllerAnimated:YES];
}

-(IBAction)sendCode:(id)sender {
    if ([MFMailComposeViewController canSendMail])
    {
        MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];

        mailer.mailComposeDelegate = self;

        [mailer setSubject:@"Your subject"];

        NSArray *toRecipients = [NSArray arrayWithObjects:@"firstname.lastname@example.com", nil];
        [mailer setToRecipients:toRecipients];

UIImage *myImage = [UIImage imageNamed:@"MyImage.png"];
            NSData *imageData = UIImagePNGRepresentation(myImage);
            [mailer addAttachmentData:imageData mimeType:@"image/png" fileName:@"myimag

e"];

        NSString *emailBody =
        @"your body";

        [mailer setMessageBody:emailBody isHTML:NO];

        [mailer setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
        [self presentModalViewController:mailer animated:YES];

    }
    else {
        {
            UIAlertView *alert2 = [[UIAlertView alloc] initWithTitle:@"Error"
                                                             message:@"Your device doesnt support that action."
                                                            delegate:nil
                                                   cancelButtonTitle:@"Okay"
                                                   otherButtonTitles:nil];

            [alert2 show];

        }
    }
}
</code>
and in the .h file add:
<code>#import <UIKit/UIKit.h>
#import <MessageUI/MessageUI.h>

@interface Controller : UIViewController <MFMailComposeViewControllerDelegate> {

}

-(IBAction)send:(id)sender;

@end
</code>
Comment: That should be your solution!
Comment: thanks, but i don't want to see the email screen, i want it to be sent automatically
Comment: ohh okay my fault I will look up for it
Comment: there is an explanation here: http://www.theappcodeblog.com/2011/04/08/iphone-email-app-tutorial-part-1-send-an-email-from-within-the-app/
but it does't work for me
Answer: You cant send automaticaly email because apple wont let you do this kind of things without user knowledge. You must present presentModalView!


Why is my template suggestion not called (the return)?

Question: I have seen many questions like this ones and I have tried all the solutions...
Here is my setup:
1-I have a custom entity with the id defined as follow:
 * @ContentEntityType(
 *   id = "bank_operation",
 *   label = @Translation("Bank Operation"),

2- My hook_theme():
function bank_operation_theme() {
  return [
    'bank_operation' => [
      'render element' => 'elements',
     ],
  ];
}

3- My hook_theme_suggestions_HOOK()
function bank_operation_theme_suggestions_bank_operation(array $variables) {
  $suggestions = [];
  $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');
  $suggestions[] = 'bank_operation__' . $sanitized_view_mode;
  return $suggestions;
}

4- My Route to display the entity with a "receipt" view mode
entity.bank_operation.receipt:
  path: '/bank_operation/receipt/{bank_operation}'
  defaults:
    _entity_view: bank_operation.receipt
    _title: 'Receipt'
  requirements:
    _entity_access: 'bank_operation.view'

5-My twig files:
modules/custom/bank_operation/templates/bank-operation.html.twig
modules/custom/bank_operation/templates/bank-operation--receipt.html.twig

Result: Everything works fine :
-receipt view mode is used
-suggestions seems to be correctly added:

Except that bank-operation--receipt.html.twig is not called
I have tried all combinations of file name/suggestions/base hook name/... without any success
I have added all the possible twig file name in my templates folder (with or without dash)
I have the feeling that the problem is coming from the fact that the ID of my entity have an underscore in its name...
Comment: Additional template suggestions are picked up from the active theme, not from a module.
Comment: To pick it up from the module see https://drupal.stackexchange.com/a/298906/47547
Comment: You saved my day!!! many thanks!!!
Comment: Does this answer your question? [Use custom content entity theme suggestions in own module?](https://drupal.stackexchange.com/questions/298844/use-custom-content-entity-theme-suggestions-in-own-module)
Answer: For anyone else landing here, a lesson I learned the hard way, and not obvious from the docs.
The beginning of the suggestion seemingly MUST match the 'THEME HOOK' plus two underscores. e.g. for the theme hook 'slick'
This should work
function THEMENAME_theme_suggestions_slick_alter(array &$suggestions, array $variables, $hook) {
$settings    = $element['#settings'];
if (!empty($settings['field_name'])) {
$suggestions[] = 'slick__' . strtr($settings['field_name'], '-', '_');
}

However
$suggestions[] = 'slicktheme__' . strtr($settings['field_name'], '-', '_');

Will not work because "slicktheme" is not the theme hook. Additionally be sure that underscores, not hyphens, are added to $suggestions array using the strtr function or it will probably not work.
Comment: Note that you can do this, which is the way to ensure the lesson you learned isn't run into: `$suggestions[] = '$variables['#theme_hook_original'] . strtr($settings['field_name'], '-', '_');`


In IntelliJ, how to use a surround Live template without use $SELECTION$ in the template body?

Question: I didn't found the way to use the $SELECTION$ variable without use it in the template.
I can modify SELECTION in another variable and use this variable in the template. But if I don't use the $SELECTION$ in the template, the template is not available in the "Surround With" menu.
Is there a way to use a Live template which can take in parameter the user SELECTION without display it in the template ?
The goal is to store and apply a dozen of regex/replace.
Thanks
Answer: It's seems to be a bug of my current IntelliJ Idea version. I use the version 2019.2.
WebStorm Live Template $SELECTION$ Regular Expression


Case insensitive exiqgrep?

Question: My mail queue is currently full of bounce messages for the same domain, but in mixed case.
I tried using exiqgrep to filter these mails from my queue, but it seems that the command is case sensitive. Is there any way to perform a case insensitive search?
Answer: As the other gentleman pointed out, the exiqgrep program is just a perl script.  It takes the raw value passed to the -r function (recipient) and uses it in a pattern match.  The pattern match is a simple $rcpt =~ /$opt{r}/ perl test, the default match, since it's not specified, is case sensitive.
As with all things perl, TIMTOWTDI (There Is More Than One Way To Do It).  Since the function above does not strip or sanitize the value passed to -r, you can simply embed an ignore case modifier in the regex.  See perldoc perlre for more details about how the (?MODIFIERS:...) sequence works.
Here is an example where I show that a mixed case search doesn't find the domain I'm looking for, but by using an inline flag modifier as part of the search term, it finds it.
OVZ-CentOS58[root@ivwm51 ~]# exiqgrep -r 'email@example.com'
26h  4.0K 1VGRud-0001sm-P1 <> *** frozen ***
      email@example.com

OVZ-CentOS58[root@ivwm51 ~]# exiqgrep -r 'email@example.com'
OVZ-CentOS58[root@ivwm51 ~]# exiqgrep -r '(?i:firstname.lastname@example.com)'
26h  4.0K 1VGRud-0001sm-P1 <> *** frozen ***
      firstname.lastname@example.com

Your search will be similar, something like:
(?i:@thedomainyouseek.com)

Comment: This is the right, and quite elegant, answer.
Comment: Thanks, great solution! @dawud thanks for your answer as well. I did not realize it was plain Perl that could be edited.
Comment: Update: based on the discussion in this question and on the Exim mailing list, the exiqgrep search has been changed to case-insensitive mode. This new operation will be a part of the forthcoming exim 4.82 release.
Answer: The manpage does not show such option, but the exiqgrep utility is a perl script whose source you can modify to fit your needs:

114 sub selection() {
115   foreach my $msg (keys(%id)) {
116     if ($opt{f}) {
117       # Match sender address
118       next unless ($id{$msg}{from} =~ /$opt{f}/); # here
119     }
120     if ($opt{r}) {
121       # Match any recipient address
122       my $match = 0;
123       foreach my $rcpt (@{$id{$msg}{rcpt}}) {
124         $match++ if ($rcpt =~ /$opt{r}/); # or here
125       }
126       next unless ($match);
127     }
128     if ($opt{s}) {
129       # Match against the size string.
130       next unless ($id{$msg}{size} =~ /$opt{s}/);
131     }
132     if ($opt{y}) {
133       # Match younger than
134       next unless ($id{$msg}{ages}  $opt{o});
139     }
140     if ($opt{z}) {
141       # Exclude non frozen
142       next unless ($id{$msg}{frozen});
143     }
144     if ($opt{x}) {
145       # Exclude frozen
146       next if ($id{$msg}{frozen});
147     }
148     # Here's what we do to select the record.
149     # Should only get this far if the message passed all of
150     # the active tests.
151     $id{$msg}{d} = 1;
152     # Increment match counter.
153     $mcount++;
154   }
155 }

Case insensitive exiqgrep?


Migration Fails in Qemu with error `Unknown ramblock "mem1", cannot accept migration`, while it exists on the source

Question: I'm trying to migrate a VM in QEMU, after I hotplug memory to my VM I cannot migrate it and I face with Unknown ramblock "mem1", cannot accept migration while this name is ok and it really exists on the source of migration. The Parameters on the source and destination are:
Source:
-name mig-test3.compute,debug-threads=on
-machine q35,accel=kvm,dump-guest-core=off
-cpu host
-smp cores=1,maxcpus=64
-m slots=32,maxmem=262144M,size=2048M
-mem-path /dev/hugepages
-monitor none
-pidfile /opt/feynman/qemu/compute/mig-test3/pid
-chardev socket,server,nowait,id=manager-socket,path=/opt/feynman/qemu/compute/mig-test3/manager.sock
-mon manager-socket,id=manager-monitor,mode=control
-chardev socket,id=mertics-socket,path=/opt/feynman/qemu/compute/mig-test3/metrics.sock,server,nowait
-mon mertics-socket,id=metrics-monitor,mode=control
-chardev socket,server,nowait,id=snapshot-socket,path=/opt/feynman/qemu/compute/mig-test3/snapshot.sock
-mon snapshot-socket,id=snapshot-monitor,mode=control
-chardev socket,id=ops-qmp-socket,path=/opt/feynman/qemu/compute/mig-test3/ops-qmp.sock,server,nowait
-mon ops-qmp-socket,id=ops-qmp-monitor,mode=control
-chardev socket,path=/opt/feynman/qemu/compute/mig-test3/ops-rl.sock,server,nowait,id=ops-rl-socket
-mon ops-rl-socket,id=ops-rl-monitor,mode=readline -vnc :234
-chardev socket,id=qemu-guest-agent,path=/opt/feynman/qemu/compute/mig-test3/guest-agent.sock,server,nowait
-device virtio-serial
-device virtserialport,name=org.qemu.guest_agent.0,chardev=qemu-guest-agent
-device pcie-root-port,slot=4,chassis=0,addr=4.0,id=disk-reserved-pcie.0,multifunction=on
-device pcie-root-port,id=disk-reserved-pcie.1,slot=4,chassis=1,addr=4.1
-device pcie-root-port,chassis=2,addr=4.2,id=disk-reserved-pcie.2,slot=4
-device pcie-root-port,slot=4,chassis=3,addr=4.3,id=disk-reserved-pcie.3
-device pcie-root-port,slot=4,chassis=4,addr=4.4,id=disk-reserved-pcie.4
-device pcie-root-port,slot=4,chassis=5,addr=4.5,id=disk-reserved-pcie.5
-device pcie-root-port,slot=4,chassis=6,addr=4.6,id=disk-reserved-pcie.6
-device pcie-root-port,slot=4,chassis=7,addr=4.7,id=disk-reserved-pcie.7
-drive format=qcow2,throttling.iops-read=390,cache=none,stats-intervals.0=30,if=none,throttling.iops-write=160,node-name=ld-R8FGNRBTAP1B1EKRKGBEMV91R0,throttling.bps-read-max=9437185,throttling.iops-write-max-length=30,throttling.bps-write-max-length=30,throttling.iops-write-max=320,throttling.bps-read=4608000,file=/opt/feynman/disks/compute/os-2aa293e149614b849f9b0311c39f3706/initial.qcow2,throttling.iops-read-max=780,throttling.bps-write=4608000,throttling.bps-read-max-length=30,aio=native,throttling.iops-read-max-length=30,throttling.bps-write-max=9437185,index=0,id=virtio0
-device virtio-blk-pci,serial=R8FGNRBTAP1B1EKRKGBE,drive=virtio0
-drive media=cdrom,node-name=cloud-init,index=1,file=/opt/feynman/qemu/compute/mig-test3/cloudinit-429550438.iso,if=ide
-boot order=c
-smbios type=1
-netdev id=ln-0600063325cd,ifname=ln-0600063325cd,script=no,downscript=no,vhost=on,vnet_hdr=on,queues=2,type=tap
-device virtio-net-pci,mac=06:00:06:33:25:cd,mq=on,vectors=6,netdev=ln-0600063325cd

Destination:
-name mig-test3.compute,debug-threads=on
-machine q35,accel=kvm,dump-guest-core=off
-cpu host
-smp cores=1,maxcpus=64
-m maxmem=262144M,size=2048M,slots=32
-mem-path /dev/hugepages
-monitor none
-pidfile /opt/feynman/qemu/compute/mig-test3/pid
-chardev socket,server,id=manager-socket,nowait,path=/opt/feynman/qemu/compute/mig-test3/manager.sock
-mon manager-socket,id=manager-monitor,mode=control
-chardev socket,id=mertics-socket,nowait,path=/opt/feynman/qemu/compute/mig-test3/metrics.sock,server
-mon mertics-socket,id=metrics-monitor,mode=control
-chardev socket,nowait,path=/opt/feynman/qemu/compute/mig-test3/snapshot.sock,server,id=snapshot-socket
-mon snapshot-socket,id=snapshot-monitor,mode=control
-chardev socket,id=ops-qmp-socket,nowait,path=/opt/feynman/qemu/compute/mig-test3/ops-qmp.sock,server
-mon ops-qmp-socket,id=ops-qmp-monitor,mode=control
-chardev socket,nowait,path=/opt/feynman/qemu/compute/mig-test3/ops-rl.sock,server,id=ops-rl-socket
-mon ops-rl-socket,id=ops-rl-monitor,mode=readline
-vnc :623
-chardev socket,id=qemu-guest-agent,nowait,path=/opt/feynman/qemu/compute/mig-test3/guest-agent.sock,server
-device virtio-serial
-device virtserialport,chardev=qemu-guest-agent,name=org.qemu.guest_agent.0
-device pcie-root-port,multifunction=on,slot=4,addr=4.0,chassis=0,id=disk-reserved-pcie.0
-device pcie-root-port,id=disk-reserved-pcie.1,slot=4,addr=4.1,chassis=1
-device pcie-root-port,addr=4.2,chassis=2,id=disk-reserved-pcie.2,slot=4
-device pcie-root-port,addr=4.3,chassis=3,id=disk-reserved-pcie.3,slot=4
-device pcie-root-port,addr=4.4,chassis=4,id=disk-reserved-pcie.4,slot=4
-device pcie-root-port,addr=4.5,chassis=5,id=disk-reserved-pcie.5,slot=4
-device pcie-root-port,addr=4.6,chassis=6,id=disk-reserved-pcie.6,slot=4
-device pcie-root-port,id=disk-reserved-pcie.7,slot=4,addr=4.7,chassis=7
-drive throttling.iops-read=390,file=/opt/feynman/disks/compute/os-2aa293e149614b849f9b0311c39f3706/initial.qcow2,throttling.bps-write-max-length=30,throttling.bps-read-max-length=30,throttling.bps-write=4608000,throttling.bps-write-max=9437185,throttling.iops-write=160,cache=none,node-name=ld-R8FGNRBTAP1B1EKRKGBEMV91R0,if=none,index=0,stats-intervals.0=30,throttling.bps-read=4608000,throttling.iops-read-max-length=30,throttling.iops-write-max-length=30,aio=native,format=qcow2,throttling.iops-read-max=780,throttling.iops-write-max=320,id=virtio0,throttling.bps-read-max=9437185
-device virtio-blk-pci,drive=virtio0,serial=R8FGNRBTAP1B1EKRKGBE
-drive file=/opt/feynman/qemu/compute/mig-test3/cloudinit-429550438.iso,if=ide,index=1,media=cdrom,node-name=cloud-init
-boot order=c
-smbios type=1
-netdev queues=2,script=no,type=tap,vhost=on,vnet_hdr=on,downscript=no,id=ln-0600063325cd,ifname=ln-0600063325cd
-device virtio-net-pci,mq=on,netdev=ln-0600063325cd,vectors=6,mac=06:00:06:33:25:cd
-device host-x86_64-cpu,node-id=0,core-id=0,thread-id=0,id=cpu1,socket-id=1
-object memory-backend-file,mem-path=/dev/hugepages,share=off,discard-data=on,id=mem1,size=2147483648
-device pc-dimm,id=pcdimm1,memdev=mem1
-incoming tcp:172.19.36.133:586a

I hotplugged 1 CPU and 2 GB of rams. It works on Qemu 5.0.0 and Ubuntu 20.04. I Have this issue on QEMU 2.11.1 on Ubuntu 18.04 and I have issues with upgrading.
Answer: I think that might have been an old screwup fixed by upstream commit fa0cb34d2210cc749b9a70db99bb41c56ad20831  where some memory objects got named /object/name rather than just 'name'
Comment: I tried id=/object/mem1 but it does not accept it. Because it has '/' character which is invalid for this parameter. But it is a possiblity.


Poset and Mobius function

Question: Suppose that $P = (X,\leq)$ is a poset such that for $x,y \in X, x \neq y$, we have that either $|[x,y]| = 0$ or $|[x,y]| = 2$ or $|[x,y]| = 6$.  I asked to compute the Möbius function for this poset.  I originally thought it to be $\mu(x,y) = 1, x = y$, $\mu(x,y) = -1, y = x + 1$, and $\mu(x,y) = 0$ otherwise.  I have been debating with a classmates who believes it is $\mu(x,y) = 1, x = y$, $\mu(x,y) = -1, y = x + 1$, $\mu(x,y) = 3, y = x + 5$ and $\mu(x,y) = 0$ otherwise.  Looking for some help on truly understanding this problem.
Answer: I'm afraid your classmate is (mostly) right.
You either forgot to mention that the elements of the poset are numbers, or you abused notation in adding integers to them. I'll solve the problem as stated without assuming that the elements of the poset are numbers.
If $|[x,y]|=0$, then $x\nleq y$ and $\mu(x,y)=0$.
If $|[x,y]|=1$, then $x=y$ and $\mu(x,y)=1$.
If $|[x,y]|=2$, then the interval consists only of $x$ and $y$, and $\mu(x,y)=-1$.
If $|[x,y]|=6$, then there are $4$ elements between $x$ and $y$. Let one of them be $a$. Then $|[x,a]|=2$, since the cases $0$ and $1$ can be excluded and $|[x,a]|=6$ would imply that there are further elements in $[x,y]$. Then by Hall's theorem (see How to calculate the mobius function of a Poset using Hall's theorem), since $[x,y]$ contains $C_0=0$ chains of length $0$, $C_1=1$ chain of length $1$ and $C_2=4$ chains of length $2$, in this case we have $\mu(x,y)=0-1+4=3$.

Poset and Mobius function