É possivel implementar um método de "Recycle Bin" em SAMBA?

Question: É possivel implementar um método de "Recycle Bin" em SAMBA?
Ou seja, quando um utilizador eliminar um ficheiro numa partilha SAMBA, é possivel enviá-lo para a "Lixeira", em vez de o eliminar definitivamente?
Se sim, que tipo de pacotes e configurações são necessárias implementar para que este método seja implementado?
Answer: Para se proceder à implementação de um "Caixote do lixo" em SAMBA, precisamos de pelo menos um pacote, uma dependência para a funcionalidade em questão:
vfs_recycle — Samba VFS recycle bin

O vfs_recycle intercepta os pedidos de eliminação para ficheiros e move os ficheiros afetados para um repositório temporário ao invés de os eliminar de forma permanente. Isto dá o mesmo efeito que a Lixeira em computadores Windows.

Passo-a-passo
Para lidar com a questão de forma programática, podemos recorrer a um script em bash que vai passo a passo lidar com as verificações a serem feitas e no final adicionar ao ficheiro de configuração do SAMBA a entrada(s) necessária(s) para incluirmos nas diretorias a funcionalidade "Caixote do lixo":

Especificar o nome do pacote correto para a distribuição de Linux em uso, no exemplo usamos samba-vfs, mas por exemplo, em distribuições Ubuntu +14.04 o nome é samba-vfs-modules. Este pacote é uma dependência que permite implementar a referida funcionalidade "caixote do lixo";
Especificar o caminho para o ficheiro de configuração do SAMBA smb.conf, normalmente situado em /etc/samba/smb.conf;
Verificamos se o pacote está instalado, caso não, vamos executar um comando para o instalar. De notar que a forma como procedemos à verificação bem como o comando para instalar um pacote pode variar consoante a distribuição de Linux;
Preparamos as linhas de configuração a adicionar ao ficheiro smb.conf, onde deveremos especificar:
[NomeUnico]
    path = /caminho/para/pasta/com/dados
    # Ativar caixote do lixo
    vfs object = recycle                        # objeto VFS, neste caso "recycle"
    recycle:repository = /minhaPasta/recycle/%U # caminho interno (*)
    recycle:keeptree = Yes                      # preservar estrutura de diretorias ?
    recycle:versions = Yes                      # preservar versões dos ficheiros ?

(*) Caminho interno dentro do caixote do lixo para que cada utilizador não veja os seus ficheiros misturados com os dos outros utilizadores.
Por último, é preciso reiniciar o SAMBA. Aqui também podem existir divergências dado o comando correto poder variar consoante a distribuição de Linux.

Exemplo
#!/bin/bash

# Nome da dependência
PACKAGE_NAME="samba-vfs"

# Caminho para ficheiro de configuração do SAMBA
SAMBA_CFG_FILE="/etc/samba/smb.conf"

# Verificar se o pacote está instalado
PKG_OK=$(dpkg-query -W --showformat='${Status}\n' $PACKAGE_NAME|grep "install ok installed")
echo "A verificar se o pacote: $PACKAGE_NAME está instalado"

# Caso não tenha sido, instalar
if [ "" == "$PKG_OK" ]; then
  echo "Não está instalado, vamos instalar."
  sudo apt-get --force-yes --yes install $PACKAGE_NAME
fi

# Enviar texto para o fim desse ficheiro
echo "A adicionar ás configurações do SAMBA a entrada para: Partilhados"
sudo cat >> $SAMBA_CFG_FILE << EOL
[Partilhas]
    path = /zuul/Partilhas
    # Ativar caixote do lixo
    vfs object = recycle
    recycle:repository = /zuul/recycle/%U
    recycle:keeptree = Yes
    recycle:versions = Yes
EOL

# Reiniciar SAMBA
echo "Feito, a reiniciar SAMBA"
sudo service smbd restart

Notas:
Analisar atentamente o código antes de o executar, sob pena de danificar o sistema.
Este guia não dispensa a leitura da documentação oficial para o vfs_recycle.
Para o script poder ser executado, o mesmo deverá estar com permissões de execução.


Integral inequality for continuous function

Question: How do I show the following inequality?
Let $\Omega = (0,1) \subset R^1$
Let $u(x) \in C^1(\overline \Omega)$ with the property that $\int^b_au(x)dx=0$
Then, there exists a constant $C>0$ such that $||u(x)||_{L^2(\Omega)} \leq C||u'(x)||_{L^2(\Omega)}$
I was able to write  $\int^b_a|u(x)|dx \leq ||u'(x)||_{L^2(\Omega)}||1||_{L^2(\Omega)} = ||u'(x)||_{L^2(\Omega)}(1-0)^{1/2} = ||u'(x)||_{L^2(\Omega)}$ by using Cauchy-Schwarz inequality, but I could not proceed any further.
I think that I somehow have to use the mean value theorem for integrals to relate $\int^b_a|u(x)|dx$ with $\int^b_a|u(x)|dx$.
Comment: The best constant $C = \frac{1}{\pi^2}$, known as Wirtinger Inequality, see [here](http://math.stackexchange.com/a/934112/129017) for a weaker bound.
Answer: An easy proof: Take $v=u^2$ so that $v'=2uu'$. Therefore the fundamental theorem of calculus gives
$$
u^2(x)\leq \int_0^1 2|u(t)||u'(t)|dt\leq 2 \| u\|_{L^2}\| u'\|_{L^2}.
$$
Integrating over $x$ we get the result with $C=2$.


How to import into Xray Test execution results exported from IntelliJ

Question: Is there any way to import Test Execution result into Xray exported from IntelliJ?
Answer: Do you have the DICOM file? Basically you just need to save the headers on it with the new information.
Comment: Sorry, I do not know what is DICOM file? I have the test result exported from intelliJ and i want to import it into Xray as a test execution result.


How to not reference dependencies of Microsoft.NETCore.App for .NET Core console apps?

Question: I have a brand-new .NET Core app. By default, .NET Core apps reference the Microsoft.NETCore.App NuGet package; I want to uninstall certain packages referenced by that, namely System.Collections.Immutable, so that I can't use the types in them from my app.
How do I do this when the Microsoft.NETCore.App reference is implicitly included? The packages installed by default aren't even mentioned in the .csproj file now, so how am I supposed to remove them?
Below is the contents of my .csproj file:
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>

</Project>

Comment: Is the goal to exclude the assembly? or just to enforce no code uses it? last one would be a good use case for a roslyn analyzer..
Comment: Maybe someone will come through with how to do this, but I doubt it. So it might be better to describe the outcome you are going for and someone might be able to help you get there in a different way. e.g. Are you just looking to restrict other developers in using that particular namespace?
Comment: in 2.0, `Microsoft.NETCore.App` won't have any dependencies but a buch of dlls..
Comment: There is no reason to do that. If you don't want to use .NET Core, just target .NET Framework instead of .NET Core or cross compile to both
Comment: @MartinUllrich: I just got here trying to actually exclude the assembly so I can ship a privately compiled version with a bugfix.
Answer: NuGet supports flags on PackageReference that let you control which assets are installed from a dependency. You can exclude parts of System.Collections.Immutable like this:
<ItemGroup>
  <PackageReference Include="System.Collections.Immutable" Version="1.3.0" ExcludeAssets="Compile" />
</ItemGroup>

See https://learn.microsoft.com/en-us/nuget/consume-packages/package-references-in-project-files#controlling-dependency-assets/ for more details.


Custom entity, entity_save() leads to PDO Exception?

Question: I have built a custom entity called 'person'.
In a module called 'beautify' I use a hook.
Inside this hook I want to create an instance of this object with bundle 'person'. (entity: 'person', bundle: 'person')
In my bundle person I have different fields created by the fields UI. One of these fields is called 'field_person_copy'. The colums of this table called 'fields_data_fields_person_copy' are created by the drupal system:
entity_type, bundle, deleted, entity_id, revision_id, language, delta, field_copy_person_value.
The field is required.
I want to use the drupal system to create new persons, not a db_inject.
  function beautify_contact_person($message){
  // dpm($message);
  $e = entity_create ('person', array(
    $entity->name = $message['params']['last_name'],
    $entity->field_person_copy['und'][0]['value'] = 'NO',
    ));
  //dpm($e,'Instanziiert eine entity');
  entity_save('person', $e);

(Testing with entity->save let the system say that this method is undefined.)
This leads to the following error message:
  PDOException: SQLSTATE[23000]: Integrity constraint violation:
  1048 Column 'entity_id' cannot be null: INSERT INTO {field_data_field_person_copy}
  (entity_type, entity_id, revision_id, bundle, delta, language, field_person_copy_value)
  VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2,
 :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5,
 :db_insert_placeholder_6); Array ( [:db_insert_placeholder_0] =>
 person[:db_insert_placeholder_1] => [:db_insert_placeholder_2] => [:db_insert_placeholder_3]
 => person [:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => und
[:db_insert_placeholder_6] => NO ) in  field_sql_storage_field_storage_write()
(Line 451 von /home/duke/sites/mia-casa/modules/field/modules/field_sql_storage/field_sql_storage.module).

which means that the system doesn't generate the entity_id and fuels it in the function.
So is that a bug of the entity_api or from me? (I hope the latter) ;)
In my custom_module to build the entity, I only overwrote the function "buildContent" in the class EntityApiController, so create, save and update is not influenced by me.
Thx in advance,
maen
Comment: There's no `$entity` variable declared in your code, where does that come from? And why are you assigning to properties of `$entity` in array keys??
Comment: Your code doesn't match the code you've linked to, in any way. I genuinely don't mean this to sound rude: how well do you know PHP? There seems to be a knowledge-gap here. While what you have is _technically_ valid syntax, I can all but guarantee you it's not doing what you think it is
Comment: I don't need to I believe: if you look at http://drupalcontrib.org/api/drupal/contributions!commerce_shipping!commerce_shipping.module/function/commerce_shipping_line_item_new/7 the line_item
Comment: Also: The error says that drupal uses the correct table! So the field is recognized in my mind!!!???
Comment: ??? Don't need to what? A quick search on google will find you the correct way to create an entity. BTW, you are also not giving it a bundle type.
Comment: http://drupal.stackexchange.com/questions/29744/create-entity-programmatically-in-drupal
Comment: http://drupal.stackexchange.com/questions/7271/how-do-i-programmatically-create-an-entity-with-its-fields
Comment: nope, this leads to the eck module, I wrote mine manually. This is not the same!
Comment: https://www.drupal.org/node/1377614. I could keep posting links for days, but I think I'll stop at this one.
Comment: @2pha: Your last answer depends on the module eck. Your forelast answer on eck, a form and the proposition to use "model entities". Your 3rd last answer I tried long before but it is not being saved in the db.
Comment: It depends on entity api, not ECK. But I have to agree with Clive on this one.
Answer: The problem is centred around this bit of code:
$e = entity_create ('person', array(
  $entity->name = $message['params']['last_name'],
  $entity->field_person_copy['und'][0]['value'] = 'NO',
));

It's sort-of-technically-valid PHP (though you don't have a variable named $entity in scope), but certainly isn't doing what you expect. It's almost like you're trying to apply a feature from another language (like object initialisers from C# maybe).
I'm guessing somewhat, but I imagine what you're trying to do is:
$e = entity_create ('person', array(
  'BUNDLE_KEY' => 'BUNDLE_NAME',
  'name' => $message['params']['last_name'],
));

$e->field_person_copy[LANGUAGE_NONE][0]['value'] = 'NO';

entity_save('person', $e);

Or maybe
$e = entity_create ('person', array(
  'BUNDLE_KEY' => 'BUNDLE_NAME',
));

$e->name = $message['params']['last_name'];
$e->field_person_copy[LANGUAGE_NONE][0]['value'] = 'NO';

entity_save('person', $e);

Where BUNDLE_KEY and BUNDLE_NAME are whatever you have set up for your entity type.
Answer: Thx for your input! All of you, because your criticism helped me a lot!
I could solve it like this:
function beautify_contact_person($message){
$e = entity_create ('person', array(
    'name' => $message['params']['last_name'],
    'prename' => $message['params']['name'],
    'customer' => 0,
    'type' => 'person',
    'field_person_copy' => array(
        LANGUAGE_NONE => array(
            0 => array(
                'value' => 'NO',
            )
        )
    ),
    'field_person_tel_privat' => array(
        LANGUAGE_NONE => array(
            0 => array(
                'value' => $message['params']['phone'],
            )
        )
    ),... `
 )->save();
}

It was the 'type' that irritates me ...


Is 2 measures sufficient for a fugue subject?

Question: I know what a fugue is. I also have been reading up on the form of the fugue and how to write in counterpoint. I wrote a canon and I have written a sonatina using sonata form. So theoretically a fugue shouldn't be all that much harder to write, especially with the free counterpoint that makes up the majority of the fugue.
But I am having trouble starting the fugue. Here is what I have thought out so far:
Key: C minor
Basic harmony of the subject
Starting voice: Soprano
Instrument: Piano
Widest interval without arpeggios: Octave
Tempo: Moderato(more specifically, M.M 110)
Time signature: 4/4(at least for now, I might change it later on)
Countersubject?: Yes
Number of voices: 4
Order of entry: SATB
And I have this so far for the subject:
G, F, Eb,  D, Eb, D, C, Bb, C, Rest
1, 2, 3 4, 1,  +,  2,  +,  3,   +, 4
2 measures, that's it. I have heard that if you don't have a long enough subject, you won't have the implied harmony you want in a fugue exposition.
So I looked at diagrams of Bach's fugues to see what the length of the subject is. Turns out, it is usually at least 3 measures long for his WTC fugues. I don't know how long it is for his other fugues though such as the fugue section of Tocatta and Fugue in D minor. But there is only 1 fugue I know of that has a 2 measure long subject. That would be Fugue in C minor WTC book 1, a fugue I am currently leaning along with the prelude(which is full of 16th notes, the prelude is).
Also, I don't know what to do out of 4 possible answers for the subject. Here they are:

Real answer without any harmonic minor

Real answer with harmonic minor

Tonal answer without harmonic minor

Tonal answer with harmonic minor
I know the key will determine whether to use a real or tonal answer but I don't know how it does that. I will listen to more fugues by Bach to try to figure out how he develops his relatively short subject into a full fugue.

But will 2 measures be sufficient for a fugue subject or should I expand my subject to something more like 5 or 7 measures? I mean the longer the subject, the more I can develop the subject and thus the more episodes I can have in a fugue. But too long and you have something more along the lines of a sonata in fugue form.
Comment: "So theoretically a fugue shouldn't be all that much harder to write" - you might want to revise that opinion, after you have tried writing one ;)
Comment: I think the subjects of the fugues in BWV997, BWV998, and BWV1000  (all for the guitar / lute) are all 2 to 3 measures long (but my analytical fugue skills are quite shaky). So it seems 2 is enough for Bach, but, well, he was **Bach**.
Comment: The subjects of Bach's Inventions are often 1 bar long (or even less).
Comment: If a fugue's subject is only just as long as it can be, you won't be able to use it in stretto. (Stretto's not something we expect in an Invention, so the lack of it is no great loss.)
Comment: It depends. The longest fugue subject I know of is in one of Sorabji's Organ Symphonies, and its duration is *more than one minute*. (If doesn't make sense to count bars, because the piece doesn't have a time signature, and the bar lines are irregular and usually 20 or 30 beats apart.)  But the entire fugue lasts more than two hours (and in total has about 6 subjects, and is in up to 8 parts!!) so a one-minute subject isn't ridiculously out of proportion to everything else!
Comment: "... if you don't have a long enough subject" - well, Bach (in the C# minor fugue in the "48") does just fine with a subject four notes long, C# B# E D#.
Comment: I suppose it would be cheating to suggest two measures of  16/8 time :-)
Comment: You could make an argument that the subject of the A major fugue in Book 1 of the "48" is just **one note**. And it's a very short note, followed by a rest that is three times as long as the note!
Comment: Mozart (finale of the "Jupiter" symphony) also wrote a rather impressive fugue with just a 4-note subject: C D F E (in C major). Haydn also used the same subject in a fugue in one of his symphonies (sorry, can't remember which one).
Answer: I think you are overthinking it. Why not experiment??
You already know all the rules to compose a fugue, so, get it done. You can't know for sure if it's too short or not until you try to make a fugue out of it. As you said, Bach himself has fugues with only 2-measure subjects, only 3, and also many more with 4, 5, 6 or whatever. You choose.
About the possible answers, same thing. Try them and decide what you like the most, there is no possible way someone could give a fact-based answer to this question.
All you can do is listen to a bunch of fugues, as you said, and then make all those decisions by yourself. Remember the most important it how it sounds, so try not to make decisions prematurely. (For example, how can you possibly know that M.M 110 sounds better than M.M 100 or 120 if you didn't even compose the song yet??)
So, is a 2-measure subject too short? You can't find out before you try! Real answer or tonal answer? Try both of them and choose what's best! You can compose infinite fugues, if you don't like this one very much, just compose another, you can even use the same subject and good ideas you came up with. Just don't be reluctant to start!

Now, if you would like a little opinion, I personally think it might be too short, but this only means you will have a harder time keeping the breath, because all your voices will be presented really fast (your subject has ~4s), so say you introduce them all in 16-20s, you will have to do something else for the next 90% or the song (or as long as you want, no problem with 1-1,5 minute fugue). And, as you said, it's harder to develop a short subject, so maybe this is meant to be a short fugue. Remember Bach's fugue in C minor's tempo is practically half as fast as yours, so his subject has ~8s, and when he is done introducing all 3 voices, 32s have gone by (you did 4 voices in maybe half the time). Also, his subject has 20 notes and yours has 9, so his is much easier to develop into a 3 minute fugue, despite also being 2 measures long.
Comment: "so say you introduce them all in 16-20s, you will have to do something else for the next 90% or the song " - why is that a problem? Sorry to bring up Bach yet again, but in the D  major fugue from WTC 2 the first 4 notes of the subject occur **about 90 times** in the whole fugue - and it doesn't sound like "boring repetition" either.
Comment: @alephzero No problem, it was just to illustrate that it would be harder with a short subject, but not impossible at all.
Answer: Absolutely. 2 bars is enough for a fugue subject. You might even say it's a 'happy medium' for subject length.
In addition to The Well Tempered Clavier take a look at:

Fischer, Adiadne Musica
Pachelbel, Fugues on the Magnificant

Both have some similarities with The Well Tempered Clavier, they are collections of fugues moving systematically through various keys/modes.
Fischer's set is the smallest of these works with both short overall fugue length and short subjects. Pachelbel's set is sort of in the middle with fugues roughly twice as big as Fischer's, and then the WTC is the grandest.
Fischer's collection includes 20 fugues and I counted 11 where the subject is only 1 bar long. Some are even less than 1 bar and exhibit stretto right at the opening. For example...


Algoritmo recursivo

Question: Estou com um trabalho na faculdade que eu simplesmente não tenho ideia de por onde começar.
Apresentar a funçãao matematica recursiva que define o mdc (maximo divisor comum)
entre dois naturais. Com base nela, fazer:
1. Definir um algoritmo recursivo para computar o mdc e ilustra-lo com pelo menos um
exemplo de computação.
Alguém pode me traduzir este texto? Porque nao sei o que fazer..
Comment: Você sabe como se calcula o mdc?
Comment: Decompondo os dois numeros em multiplicacoes de primos não é? Dai multiplica os numeros primos em comum
Answer: Bem, recursivamente o código fica bem pequeno; lembrando que a recursão deve ter um valor de retorno que a pare caso tal valor seja atingido, senão, a recursão irá continuar a fazer a substituição (lembrando também que, na substituição, algum valor deverá mudar, caso contrário corre o risco de loop infinito.):
Exemplo de Computação (Código Java, por exemplo):
import java.util.Scanner;

public class MDC{

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        int a, b;

        System.out.print("Digite dois inteiros: ");

        a = input.nextInt();
        b = input.nextInt();

        System.out.printf("Máximo divisor comum: %d\n", calcularMdc(a, b));
    }

    static int calcularMdc(int a, int b){

        // Se o novo valor tiver módulo zero,
        // imprime b("a" depois da primeira vez)
        if ( a == 0 )
            return b;

        // Substitui na função, em "a",
        // o valor do resto da divisão de "b" por "a",
        // pois enquanto esse resto não for zero, e também
        // "a" não zerar ele irá continuar o loop.
        // (pois para iteração anteiror, o valor de "a"
        //  será o menor possível, portanto a fração a maior possível)
        return calcularMdc( b % a, a );
    }
}

Para o algoritmo basta traduzir a função calcularMdc em portugol, fluxograma, ou algo do tipo. Acho que é isso que seu professor está querendo. Qualquer coisa leve o código.
É interessante notar, ainda no código, que os valores podem ser inseridos em quaisquer ordem, pois na chamada recursiva há troca de lado dos parâmetros, que vai sempre sendo substituindo, até a condição ser atingida.
Comment: perfeito! Saberia informar como ficaria esse algoritmo com recursão na cauda?
Comment: Já é recursiva em cauda. Não tem necessidade de construir outra função de apoio para eliminar qualquer operação no return. Ela já retorna ela própria.

Algoritmo recursivo


Import and use a Maven managed Java library (CitySDK)

Question: I am trying to build a web application based on the project library CitySDK, but i don't know how to import it properly into my own project.
I have created a Maven Web Application and added the CitySDK library as a Dependency, and then Selected the Project, right-clicked and Selected Build with Dependencies. No errors appeared, and in the image below you can see it appeared as a dependency.
However, whenever i try to use some of the classes specific to it, in my own Web Application(called TourismApplication's TestClass.java), the compiler displays an error, that the package is unknown. Could anyone suggest ideas as to what i have missed? I have followed a few Maven tutorials, but without any effects.

The dependencies are as follows:
Comment: I think you missed a couple of steps in your workflow... you got everything working using Maven, but you're doing something else that results in compiler errors? What exactly are you doing with these files?
Comment: i do not have any compiler errors; i want to use the imported library in my project, but it doesn't identify its objects. The compiler errors appear when i try to use the objects in the imported library.
Comment: Silly question, did you add the appropriate `import` statements?
Comment: i get an error with the import statements; as soon as i write import citysdk.*; i get an error; also, i should usually get an autocomplete for it, which i don't
Comment: What do you see when you expand the dependency for the CitySDK?
Answer: Ok I did some digging and I think I figured out your problem. Their POM file is incorrect based on the structure of project.
First off, I'll paraphrase what I think the steps you took to get it built in your project were, to ensure I followed the same steps to get it working. These are the steps I took:

Cloned/downloaded the sources from the link you placed in the OP
Built the project into a jar file by running the command they said to use: mvn clean package assembly:single
Installed the artifact in your local Maven repo using mvn install
Added a dependency in your project POM

I tried the same thing you did, using the library in a test source file, to no avail. I looked at the .jar file that was built using their instructions and didn't find any .class files archived into it... it was essentially empty.
Turns out, their src folder structure follows Maven standards, but their POM file indicates the sources are down a different chain of directories. If you examine the build log closely, you see "[INFO] No sources to compile"
The POM.xml file they provide specifies the source directory as
<sourceDirectory>src/citysdk/tourism/client</sourceDirectory>

However, the actual files are at
src\main\java\citysdk\tourism\client

After changing the line in the POM file from the above to (similarly for tests):
<sourceDirectory>src/main/java/citysdk/tourism/client</sourceDirectory>
<testSourceDirectory>src/test/java/citysdk/tourism/client/tests</testSourceDirectory>

rebuilt, and installed, it worked when I tried to use it in my project. Hope this helps.
FYI, I used IntelliJ as my IDE, but it should work the same with Eclipse.
Comment: You are awesome!!! I replaced the line in Netbeans, cleaned and built, and it worked!!! Thank you very very very much!


Como chamar uma função dentro dela mesma? Recursividade

Question: Objetivo
Fazer uma recursividade dentro da função SALVARHISTO() para que, seja chamada novamente a função, caso a célula A8 não seja encontrada.
O que eu tentei
Tentei colocar uma condição no final, se a célula A8 não estivesse vazia, a função executava até encontrar a célula A8 vazia. Alguém pode me ajudar?
Código
function SALVARHISTO() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('A7:L7').activate();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Histórico'), true);
  spreadsheet.getRange('7:7').activate();
  spreadsheet.getActiveSheet().insertRowsBefore(spreadsheet.getActiveRange().getRow(), 1);
  spreadsheet.getActiveRange().offset(0, 0, 1, spreadsheet.getActiveRange().getNumColumns()).activate();
  spreadsheet.getRange('A7').activate();
  spreadsheet.getRange('\'Produção mensal\'!A7:L7').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
  spreadsheet.getActiveRangeList().setBackground('#dbe5f1')
  .setBorder(true, true, true, true, true, true, '#000000', SpreadsheetApp.BorderStyle.SOLID)
  .setBorder(false, false, false, false, false, false)
  .setBorder(null, null, true, null, null, null, '#000000', SpreadsheetApp.BorderStyle.SOLID)
  .setBorder(null, null, null, true, null, null, '#000000', SpreadsheetApp.BorderStyle.SOLID);
  spreadsheet.getRange('A7').activate();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Produção mensal'), true);
  spreadsheet.getRange('A6').activate();

  var x = sheet.getRange('A8');
  if( x != " "){
    function SALVARHISTO(){}

  }else{
  return 'Salvo com sucesso.';
  }

};

Comment: Para você executar uma função com recursividade basta você chamá-la novamente dentro da função. **SALVARHISTO()**. Sem a palavra **function** na frente
Comment: Olá Camilla, se você colocar 3 acentos graves (```) antes e depois do seu código, ele vai ficar `monoespaçado` e mais fácil de ler aqui no StackOverflow.
Comment: Não acho que tentar resolver esse problema assim seja uma boa ideia. Você estará executando essa função `SALVARHISTO` muitas vezes por segundo (talvez dezenas, centenas ou milhares). Colocar um `setTimeOut` de 1 segundo já seria algo melhor, mas talvez seja possível fazer uso de *listeners* para isso.
Comment: Isso `function SALVARHISTO(){}` declara uma função e  não executa a função
Comment: Olá @BrunoCunha, acredito que realmente seja este o problema, será q podes adicionar como resposta?
Answer: Olá!
Para você executar uma função com recursividade basta você chamá-la novamente dentro da função SALVARHISTO() sem a palavra function na frente, pois function serve para você declarar uma função.
function SALVARHISTO() {
  // some code
  if( x != " "){
    SALVARHISTO();
  }
}

Answer:
Para você executar uma função com recursividade basta você chamá-la novamente dentro da função SALVARHISTO() sem a palavra function na frente, pois function serve para você declarar uma função.
function SALVARHISTO() {
 // some code
 if( x != " "){
   SALVARHISTO();
 }
}

O Bruno já deu a resposta ali, sempre que você for apenas executar a sua função, você deve invocá-la usando o formato nomeDaFuncao(parametro), sem a palavra reservada function na frente.
Porém eu diria para tomar cuidado com a recursividade dada a simplicidade do seu if.
A chance de acontecer um erro do tipo stack overflow (exceder o limite de chamadas de uma função/método) se você não tiver plena certeza dos possíveis retornos de .getRange() pode ser perigosa.


Reboot ML350 G4 Server in sealed room

Question: I have an old server in a remote location. It has its own power feed which is subject to failure twice a month. The problem with this failure is that it does not simply drop and recover hours later. It drops, recovers for 5 min, drops again, recovers for minutes then might drop again etc. So I don't want to set the server to reboot on AC being restored. I want to wait until I think that the AC is stable.
Many modern BIOS allow one to reboot on mouse, keyboard and (I think) LAN activity.
As I can't access the server location easily , does anyone have first hand experience of what reboot on LAN activity means or am I confused and BIOSs only have the ability to boot from a LAN. If the server can only be set to boot from the LAN and not because of LAN activity is there a way to disable whatever is providing the means for the server to boot from the LAN until I am happy that the AC is stable.
Thanks
Comment: out of curiosity, does the server have iLO configured?
Comment: Not sure. Still have to do learn the ins and out of this machine.
Comment: Is this server not on a UPS?
Comment: No. UPS make lots of beeping noises when they wish to draw attention to their plight. I don't really want to have to modify a UPS to not beep.
Comment: TBH, that sounds a little silly. The only time I could see this being an issue is if the UPS was in a public area where it would bother others. However, you said its remote and locked away...
Comment: And, whats more annoying, a server power cycling over and over, or a beeping UPS?
Comment: Its in an old giant house. The type you see on "Remains of the Day" or "Sense & Sensibility". I am in a different building with a wifi link to routers in the old house. There is an 'elderly' gentlemen who is conviced a plague of rats occupies his wing due to the noises of technology that come from the attic. (Should start on my screen play already and flog the plot to Hollywood)
Answer: This server has iLO management port that can be used, among other things, to control power state of the system. That would be the most appropriate and reliable way to power up the server. Just connect a network cable, configure IP address (can be done from the host OS using HP Proliant Support Pack utilities), and you're good.
However, I can't understand why you're willing to suffer through such power outages, if they can be made a non-issue with an inexpensive UPS unit. A unit that would power you server for half an hour, and have a network management card allowing you to control power from your location, would cost about $500 or so.
Comment: Again if I can find a black ops whisper quiet UPS that dosen't beep while its carring the load then I shall purchase it.
Comment: Sounds like you need a new server location
Comment: Yes. Thinking Marsellies on the French Coast
Comment: I used to have an UPS where the beeping drove me insane (it was in my bedroom).  I took the front casing off, and replaced the beeper with a blue LED.  Quiet.. and Blue.
Answer: The "reboot on LAN activity" is most likely Wake-on-LAN support. You just need to find the right tool for your environment to generate the WOL Magic packet.

Reboot ML350 G4 Server in sealed room


Fitting a glm to a zero inflated positive continuous response

Question: I'm trying to fit R glm's to data sets where the response is zero inflated positive continuous. This is an example data set
df <- structure(list(y=c(0,0,0,0,0,0,0,0,4.09417142857143e-05,0,0,0,0,2.18718787234043e-05,0,0,0,0,0,0,0,0,0,0,0,0,0,4.60192985143918e-05,0,1.16500081901182e-05,0,1.13497040795196e-05,0,2.01959645093946e-05,0,0,2.24704801120448e-05,3.50195529889299e-05,2.26178388643899e-06,0,0,0,0,0,0,1.24748435005701e-05,0,0,0,1.14008923269261e-06,0,0,0,0,0,0,0,1.95445414576182e-05,0,0,0,0,0,0,0,0,1.72293987591653e-05,1.11122316638726e-05,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),behavior = c(0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,3,0,3,0,3,0,3,0,3,0,3,0,3,0,3,0,3,0,6,0,6,0,6,0,6,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,4,0,4,0,4,0,4,0,4,0,4,0,4,0,4),time = c(272,148,132,854,234,340,90,282,840,230,118,620,130,1410,1272,684,6624,1220,250,4556,4500,2254,662,334,336,1364,346,4308,372,7448,1242,9658,926,6706,494,1996,3570,13550,62134,6876,3108,4722,794,2394,21502,21048,5442,2748,920,25596,1954,7896,996,12108,2046,23034,3216,7574,9882,5560,5610,4524,6846,3450,11630,3528,3546,9544,4820,4852,13508,3726,3744,1252,1254,2514,3786,2534,14080,3882,6510,10520,72928,10052)),.Names = c("y","behavior","time"),row.names = c(NA, 84),class = "data.frame")

set behavior to be a factor
df$behavior = as.factor(df$behavior)

The response is df$y, df$behavior and df$time are the fixed effects (categorical and continuous, respectively).
A glimpse at the distribution of the response:

I tried using the R tweedie package with glm2 (and base glm) with this code:
tweedie.fit <- tweedie.profile(y ~ behavior + time, do.plot=TRUE, data = df)
model.fit <- glm2(y ~ behavior + time, family=tweedie(var.power=out$xi.max, link.power=1-out$xi.max), data = df)

which either does not converge (in case of other data sets) or shows poor qq-plot fit:
Is there any hope to reliably fit a glm to such data? If so what am I doing wrong?
I also tried using the R gamlss package with a log normal family where I add .Machine$double.eps to df$y:
df$y <- df$y + .Machine$double.eps
model.fit <- gamlss(y ~ behavior + time, data = df, family = LOGNO())

but it doesn't seem to do much better:

Help would be greatly appreciated.
Answer: The Q-Q plot fit (which compares to normal quantiles) is almost irrelevant. In particular it doesn't tell you that you have a bad model.
While the Tweedie can model data with zeros in it, it tends not to work so well for data that are predominantly zero, and I suspect you probably don't fit the distribution well (it's just that you can't really tell that's the case from the QQ plot)
I'd be inclined to move toward a model that explicitly deals with the zeros, a zero-inflated model or a hurdle model.


Eigenvalues of Symmetric/Hermitian Matrices

Question: I am new to stack exchange so please excuse me as I write in JAX I have a question on linear algebra that goes like this :  If $A$ is an $n\times n$ real symmetric matrix or complex Hermitian matrix, then its eigenvalues are real.
I want to prove this theorem but I hope someone can this proof and correct me if I am wrong : We have that By the Schur's decomposition, $A=QRQ^{*}$ however $A=A^{*}=(QRQ^{*})^{*}=QR^{*}Q^{*}$ where we have that $R$ an upper triangular matrix with eigenvalues of $A$ on its diagonal entries, so $R^{*}$ is a lower triangular matrix thus $A-A^{*}=Q(R-R^{*})Q^{*}=0\implies R-R^{*}=0\implies r_{i,i}=\overline{r_{i,i}}$. Therefore, $R$ is a diagonal matrix and its diagonal entries
are real. I would like to thank whoever checks my proof. Best regards!
Comment: Welcome to MSE!!!
Comment: proof is clear and all good!
Comment: Thank you very much
Answer: Yes, yes, the proof given by our OP Alexandre von Maylen looks fine.  However, it leans heavily on the Schur decomposition which is itself non-trivial. A simple proof may be had by proceeding directly from first principles and definitions, to wit:
We are given
$Ax = \mu x \tag 1$
and
$A^\dagger = A; \tag 2$
we may assume that
$\langle x, x \rangle = 1, \tag 3$
with $\langle \cdot, \cdot \rangle$ the standard  Hermitian inner product on $\Bbb C^n$; thus we have
$\mu = \mu \langle x, x \rangle = \langle x, \mu x \rangle$
$= \langle x, Ax \rangle = \langle A^\dagger x, x \rangle = \langle Ax, x\rangle$
$= \overline{\langle x, Ax \rangle} = \overline{\langle x, \mu x \rangle} = \overline{\mu \langle x, x\rangle}= \bar \mu. \tag 4$
Note that
$\langle x, Ax \rangle = \langle A^\dagger x, x \rangle \tag 5$
is essentially the definition of $A^\dagger$, which coincides with $A^T$ since $A$ is specified to be a real $n \times n$ matrix.


Form desalinhando em resolução alta

Question: Meu form está desalinhando quando o aplicativo roda em monitor com a resolução maior que a minha, o borderstyle está em bsnone e mesmo assim continua desalinhando, eu também setei todas as propriedade anchors pra false.
Answer: Olá,MrHelp.
Eu tenho o problema com resoluções abaixo de 1024, então tive que recorrer a uma re-dimensionamento da tela manualmente.
A tela principal deixo o BorderStyple:=bsSizeable;
Const nTamOriginal = 1280 // resolução da minha tela
var nEsc : Double;
    nInst: ianteger;
if nTamOriginal <> Screen.width then
begin
    nEsc := ( Screen.Width -nTamOriginal ) / nTamOriginal;
    nInt := Round( ( nEsc*100 ) + 100 );
    Self.Width := Round( Self.Width * ( nEsc +1 ) );
    Self.Height:= Round( Self.Height* ( nEsc +1 ) );
    Self.ScaleBy( nInt, 100 );
end;
Self.Top := 0;
Self.Left := 0;

Teste na sua aplicação, a propósito coloque no Create do formulário.

Form desalinhando em resolução alta


DeprecationWarning: distutils Version classes are deprecated while starting odoo15 on local

Question: I installed odoo 15 on my local and installed all the dependances, but when i start my server it shows me a py warning and i am unable to solve this issue, any help will be much appreciated, the warning i am getting in my local is below:

2022-01-11 10:26:54,032 8202 WARNING ? py.warnings:
/home/itachi/Workspace/odoo_15/core/odoo/addons/base/models/ir_actions_report.py:68:
DeprecationWarning: distutils Version classes are deprecated. Use
packaging.version instead.
File "core/odoo-bin", line 8, in
odoo.cli.main()   File "/home/itachi/Workspace/odoo_15/core/odoo/cli/command.py", line 61, in
main
o.run(args)
File "/home/itachi/Workspace/odoo_15/core/odoo/cli/server.py", line 176, in
run
main(args)
File "/home/itachi/Workspace/odoo_15/core/odoo/cli/server.py", line 170, in
main
rc = odoo.service.server.start(preload=preload, stop=stop)
File "/home/itachi/Workspace/odoo_15/core/odoo/service/server.py", line
1286, in start
load_server_wide_modules()
File "/home/itachi/Workspace/odoo_15/core/odoo/service/server.py", line
1196, in load_server_wide_modules
odoo.modules.module.load_openerp_module(m)
File "/home/itachi/Workspace/odoo_15/core/odoo/modules/module.py", line
396, in load_openerp_module
import('odoo.addons.' + module_name)
File "/home/itachi/Workspace/odoo_15/core/odoo/addons/base/init.py",
line 5, in
from . import models   File "/home/itachi/Workspace/odoo_15/core/odoo/addons/base/models/init.py",
line 13, in
from . import ir_actions_report
File "/home/itachi/Workspace/odoo_15/core/odoo/addons/base/models/ir_actions_report.py",
line 68, in
if LooseVersion(version) < LooseVersion('0.12.0'):
2022-01-11 10:26:54,033 8202 WARNING ? py.warnings:
/home/itachi/Workspace/odoo_15/core/odoo/addons/base/models/ir_actions_report.py:73:
DeprecationWarning: distutils Version classes are deprecated. Use
packaging.version instead.   File "core/odoo-bin", line 8, in
odoo.cli.main()
File "/home/itachi/Workspace/odoo_15/core/odoo/cli/command.py", line 61, in
main
o.run(args)
File "/home/itachi/Workspace/odoo_15/core/odoo/cli/server.py", line 176, in
run
main(args)
File "/home/itachi/Workspace/odoo_15/core/odoo/cli/server.py", line 170, in
main
rc = odoo.service.server.start(preload=preload, stop=stop)
File "/home/itachi/Workspace/odoo_15/core/odoo/service/server.py", line
1286, in start
load_server_wide_modules()   File "/home/itachi/Workspace/odoo_15/core/odoo/service/server.py", line
1196, in load_server_wide_modules
odoo.modules.module.load_openerp_module(m)   File "/home/itachi/Workspace/odoo_15/core/odoo/modules/module.py", line
396, in load_openerp_module
import('odoo.addons.' + module_name)   File "/home/itachi/Workspace/odoo_15/core/odoo/addons/base/init.py",
line 5, in
from . import models   File "/home/itachi/Workspace/odoo_15/core/odoo/addons/base/models/init.py",
line 13, in
from . import ir_actions_report   File "/home/itachi/Workspace/odoo_15/core/odoo/addons/base/models/ir_actions_report.py",
line 73, in
if LooseVersion(version) >= LooseVersion('0.12.2'):
2022-01-11 10:26:54,154 8202 WARNING ? odoo.addons.base.models.res_currency: The
num2words python library is not installed, amount-to-text features
won't be fully available.  2022-01-11 10:26:54,181 8202 INFO ?
odoo.service.server: HTTP service (werkzeug) running on
Uchiha-Madara:8069
Answer: This issue has been fixed in this pull request and you need yo update your Odoo to latest version to fix it.


How many of the words contain the text string "mat" somewhere in the word?

Question: This problem consists of three problems.
(i) How many different words can be made by rearrangement of the letters in the word "matematik"?
my answer
$$\frac{n!}{k_m! \cdot k_a! \cdot k_t! \cdot} = \frac{9!}{2!\cdot2!\cdot2!}= \frac{9!}{8} = 9 \cdot 7!$$
(ii) How many of these words starts and ends with "t"?
I just removed the two "t" from the word "matematik", so now I have "maemaik".
My calculations are as follows
$$\frac{n!}{k_m! \cdot k_a!} = \frac{7!}{2! \cdot 2!} = \frac{7!}{4} $$
(iii) How many of the words contain the text string "mat" somewhere in the word?
How should I understand this question?
Understanding 1: How many of the words found in (i) contain one "mat"?
Understanding 2: How many of the words found in (i) contained at least one "mat"?
If assume understanding 2 is the right way to read, my answer is (per intuition)
$$7!-\frac{5!}{2!}$$
I'm not sure how to explain my calculation with words. (Probably because my understanding is not sufficent).
PS 1 The word "matematik" is danish. It means "mathematics".
PS 2 The problem has been translated from Danish into English. The original problem had som ambiguity which has been eliminated.
PS 3 Also, "matematik" is a word. But "amtematik" is not a word. Our professor should have used "text string" in stead of $word$ in the formulation of the problems.
Comment: I highly tend towards understanding 2. For understanding 1, they'd have to mentioned 'once', 'exactly once', or something in that spirit.
Answer: The condition should be understood as "at least one $mat$" – $mat$ only has to appear somewhere and there is no restriction on the count of this substring.
Your answer for this part is correct and may be justified by the inclusion/exclusion principle. $7!$ is the number of permutations of letters when one of the $mat$s is considered a single "letter". We double-count the strings with two $mat$s here, so we subtract $\frac{5!}2$, the number of permutations when both $mat$s are considered "letters".
Answer: I would go by your second guess, that is having at least one "mat" in the string.
For a solution assume the letters "mat" being one entity and calculate the permutations with this entity and the rest of the letters. Luckily "mat" has the only repeating letters so the permutation will be easy.
Hope this helped


How to create a default value for an entity base field in Drupal 8

Question: Both the Examples module and the Drupal Console generate:entity:content both have code like this:
$fields['first_name'] = BaseFieldDefinition::create('string')
  ->setLabel(t('First Name'))
  ->setDescription(t('The first name of the Contact entity.'))
  ->setSettings(array(
    'default_value' => '',
    'max_length' => 255,
    'text_processing' => 0,
  ))

I was thinking that if I provided 'default_value' => 'Fred' in place of 'default_value' => '' that I might affect the default value of the field. I would expect to have seen Fred when creating an entity of this type, and I might have expected to see Fred as the default value in the entity's table definition, but it's not there.
I'm learning D8 and so have two parts to this question really, the first is just how to provide a default value, the second is if this default_value key isn't it, what is it for?
Answer: The code is outdated, you should create a patch to fix it.
There is a new separate method for the default value, setDefaultValue().
Comment: Thanks, I've had a go at [supplying a patch to examples](https://www.drupal.org/node/2511182#comment-10052862). Never done it before so I expect I've done something terribly wrong in the process so am bracing myself for correction!
Comment: Thanks, artfulrobot. You might also ping the console people, too.


Test for aggregation of binary events/successes (binomial/glm??)

Question: this has been vexing me for a while and I can't seem to solidify an answer beyond vague thoughts about Poisson distributions. I think this is a simple problem and I'm missing something obvious. Any thoughts appreciated, particularly with R snippets :)
Chris
Experiment: 2 replicate assays from each of 50 tissues. In the 100 samples, call a binary (0,1) event (without using tissue of origin; I'll call 1 outcomes "successes", per Bernoulli trial convention). Then score tissues for concordance (2 if both replicates are successful; 1 if only one; 0 otherwise). If the assay is working, we expect non-random numbers of concordance = 2 for tissues (i.e. the effect should replicate), given the total number of successes S.
How can I test that the distribution of (0,1,2) on tissues- or perhaps the proportions of (1,2) tissues - deviates from expectation?
thanks!
Answer: An appropriate null hypothesis is that all $n=50$ tissues are equivalent (at least from the point of view of the assays).  Therefore we may view the data as if $2n$ assay values were assigned completely at random to the $n$ cases, with two per case.
The data can be summarized concordance score (the number of successes per case): let $n_i$ be the number of cases with score $i$, $i=0,1,2$.  The total number of successful assays therefore is $s = n_1+2n_2$ and the total number of unsuccessful assays must be $u = 2n - s.$
I will interpret "expectation" as referring to the entire distribution of scores.  That is, for given values of $s$ and $n$, what is the distribution of the vector $(n_0,n_1,n_2)$ when $s$ successes are scattered randomly throughout the $2n$ results?  Because the foregoing relations imply $n_0 = n - s + n_2$ and $n_1 = s - 2n_2$, it suffices to find the distribution of $n_2$.  That is, how many concordance scores of $2$ would be produced under the null hypothesis of no difference among tissues?
The answer can be found recursively.  Writing $d(n,s,n_2)$ for the probability that the concordance score will equal $2$ and considering the three possible results for the last case (that is, two successes, one success, or no success) gives
$$d(n,s,n_2) = \frac{1}{2n(2n-1)}\left(s(s-1)d(n-1,s-2,n_2-1) + 2 s u d(n-1, s-1,n_2) + u(u-1) d(n-1, s, n_2)\right).$$
This formula relates the distributions of $n_2$ for $n$ cases to those for the first $n-1$ cases.  The fractions $s(s-1)/(2n(2n-1))$, $2 s u / (2n(2n-1))$, and $u(u-1)/(2n(2n-1))$ are the chances that the last case has $2$, $1$, or $0$ successes, respectively.  The value of $s$ accordingly goes down by the quantity $2$, $1$, or $0$.  The value of $n_2$ is decreased by $1$ only when two successes are observed.
The solution is uniquely determined by the initial conditions $d(n, 0, 0) = 1$ for $n\ge 0$ and otherwise $d(n,s,n_2)=0$ whenever $n=0$ or either of $s$ or $n_2$ is negative.
A closed form for the solution may be difficult to obtain, but computing it for small to medium sizes of $n$ is straightforward and fast (by looping over $n$).  As an example, here are plots of the probability mass functions of $n_2$ for $10, 20, \ldots, 90$ successes when $n=50$ (as in the question).

The plots at the left correspond to the smaller numbers of successes.
With this information exact tests of the null hypothesis can be performed in standard ways.  For instance, suppose that $s=63$ of the replicates were successes with $n=50$ but only $n_2=16$ of the $50$ cases had a concordance core of $2$. To conduct a symmetric two-tailed test at a level of $\alpha=0.05$, say, check whether $D(n,s,n_2)=\sum_{c\le n_2} d(n,s,c) \lt \alpha/2$ or $1-D(n,s,n_2-1)=\sum_{c\ge n_2} d(n,s,c) \gt 1-\alpha/2$.  In this case the first sum equals $0.0222\ldots$.  This is less than $0.05/2$, demonstrating significant evidence against the null hypothesis: concordance of successes is rarer than expected by chance alone.  Similar calculations show that for $n=50$ and $s=63$, any value of $n_2$ between $17$ and $22$ inclusive is consistent with the null hypothesis at the $\alpha=0.05$ level.
As a further example, suppose $n=50$, $s=40$, and $n_2=5$.  (From this we deduced earlier that $n_0=n-s+n_2=15$ and $n_1=s-2n_2=30$.)  The cumulative probability is $D(50,40,5)=0.0782\ldots$.  Considered as a two-tailed test, this results in a p-value of $2\times 0.0782 = 0.156$, which few people would consider strong evidence against the null.

To illustrate the theory here is an R function that returns the distribution $d(n,s,n_2)$ for a given value of $n$.  It is stored in an array with $s=0,1,\ldots,2n$ indexing the rows and $n_2=0,1,\ldots,n$ indexing the columns.  (The variable c represents $n_2$ in this code.)
f <- function(n) {
  shift <- function(x, i, j) {               # Shift x by i>=0 rows and j>=0 columns
    m <- dim(x)[1]; n <- dim(x)[2]
    y <- rbind(matrix(0, nrow=i, ncol=n), x)
    y <- cbind(matrix(0, nrow=m+i, ncol=j), y)
    y <- y[1:m, 1:n]
    dimnames(y) <- dimnames(x)
    return (y[1:m, 1:n])
  }
  s <- (-2):(2*n) # include a border of negative values of s
  c <- (-1):n     # include a border of negative values of c
  d <- zero <- matrix(0, nrow=length(s), ncol=length(c), dimnames=list(s=s, c=c))
  d["0","0"] <- 1 # Initial conditions
  for (i in 1:n) {# Apply the recursion
    u <- 2 * i - s
    t1 <- s * (s-1) * shift(d, 2, 1)
    t2 <- 2 * s * u * shift(d, 1, 0)
    t3 <- u * (u-1) * d
    d <- (t1 + t2 + t3) / (2*i * (2*i-1))
  }
  return (d[3:length(s), 2:length(c)]) # Strip the borders for negative s and c
}

As an example of its use, here is the code that produced the figure.  (It also makes an image plot of the entire distribution.)  Of interest is the post-processing of the distribution matrix x; notice in particular that its indexes begin at $0$ rather than $1$.
The time to compute this distribution was only $0.02$ seconds, but do not be deceived by that speed: because the algorithm scales as $n^3$, it will be practicable only for $n$ up to a thousand or so.  For instance, multiplying $n$ by $4$ will increase the time by a factor of $4^3\approx 60$: the calculation now takes $2$ seconds.  Another multiple of $4$ to $n=800$ will take about two minutes.  However, unless the observed value of $s$ is extreme, it is clear that Normal approximations will handle large values of $n$ accurately.
n <- 50
system.time(x <- f(n))
s <- matrix(rep(0:(2*n), n+1), ncol=1+n)
n.2 <- t(matrix(rep(0:n, 2*n+1), ncol=2*n+1))
n.1 <- s - 2*n.2
n.0 <- n - s + n.2
good <- n.2 >= 0 & n.1 >= 0 & n.0 >= 0
x[!good] <- NA
par(mfrow=c(1,1))
image(0:(2*n), 0:n, t(apply(x, 1, rev)), asp=1/2, col=rev(topo.colors(100)),
      xlab="s", ylab="n2")

plot.strip <- function(dist, ...) {
  i <- (1:length(dist))[!is.na(dist)]
  lines(i, dist[i], ...)
  points(i, dist[i], ...)
}
successes <- floor(2*n/100 * c(10, 20, 30, 40, 50, 60, 70, 80, 90))
col <- hsv(successes/(2*n), .8, .9)
plot(c(0,n), c(0,max(x[successes+1,], na.rm=TRUE)), type="n",
     xlab="Number with score=2", ylab="Probability",
     main=paste("Distribution of Score=2 in", n, "Cases"))
for (i in 1:length(successes)) {
  plot.strip(x[successes[i]+1,], col=col[i], cex=1/2)
}

Comment: If I were to use this test in a publication, is there a proper way to cite the method? Or would it have to be written out?
Comment: @geoscience123 Press the "Cite" button just below the post for the citation text.
Comment: Thank you. I guess I was wondering if this is a commonly employed method for this type of question, or if it is present in any statistical literature.
Answer: Perhaps you can jigger with your data structure a little bit like this:
You say that each assay is produced twice on each tissue type. If both samples receive precisely the same assay, then it should not matter to you to arbitrarily call, say, one assay on the tissue "group A" and the other assay on the same tissue "group B".
So, if you code your outcome/success=1, and no outcome/failure = 0, your data could be thought of as looking like:
Tissue  Outcome A  Outcome B

     1       0         0
     2       1         1
     3       1         1
     .       .         .
     .       .         .
     .       .         .
    49       0         1
    50       0         0
These look like paired data (because one observation of success/no success in a tissue is paired with a second observation of success/no success in the same tissue type), and when someone says "I wanna examine the correlation between paired data with binomial outcomes" I head straight over to McNemar's test. This require rejiggering your data, because what you are analyzing are pairs, and there are four kinds of pairs, and you wanna set up the counts of each (totally made up numbers, yo):
   Group A    Group B  Kind of Pair  Count of Pairs
no success  no success   concordant        15
   success  no success   discordant        11
no success     success   discordant        19
   success     success   concordant        5
McNemar's test is a $\chi^{2}$ equivalent to the sign test. The test statistic only examines discordant pairs. Let's call the count of Group A successful, but Group B not successful $r$, and then let's call the count of Group A not successful, but Group B successful $s$ (which discordant pair you call which is arbitrary). The test statistic (which is including a Yates continuity correction in that "$-1$" business) is:
$$\chi^{2}_{\text{df=1}} = \frac{\left(\left|r-s\right|-1\right)^{2}}{r+s}$$
$$\chi^{2}_{\text{df=1}} = \frac{\left(\left|11-19\right|-1\right)^{2}}{11+19} = \frac{49}{30} = 1.6\bar{3}$$
These made up data give a $p$-value of about 0.20, so unless you are being outrageously libertine with your Type I error preferences, you would not reject the null hypothesis. As it so happens, the null hypothesis you are testing is that there is no association between group membership and probability of success.
R can perform McNemar's test using the, ahem, mcnemar.test() function
Comment: This frames the situation reasonably well, but I don't understand where the "groups" come in. All I can find in the question itself is a reference to $50$ *tissues* and the question seems to be asking about the distribution of concordance scores. It gives us little to go on concerning what the "expectation" of that distribution would be, but it might be fair to interpret the ultimate phrase in terms of a permutation test of outcomes A and B. Would your "groups" perhaps be synonymous with "outcomes"? If so, the data might not permit identification of the groups if only the scores are known.
Comment: @whuber Yes. I am making the assumption that the scores are divided into groups (say, first observation/second observation), based on the concern the OP had for concordance/discordance. What do you think? Tenable? If they are not, then I would probably go some mixed effect estimate accounting for within-tissues clustering.
Answer: This sounds like a classic use case for the good old Pearson $\chi^2$ test. There's a short R tutorial here.
Basically, you have data points in one of three categories (i.e. 0, 1, or 2). You have an expected distribution of frequencies over those categories; the $\chi^2$ test is explicitly intended to check whether the observed frequencies match your expectation. In this case you'd have:
$$
\frac{o_0+e_0}{e_0}+\frac{o_1+e_1}{e_1}+\frac{o_2+e_2}{e_2}\sim\chi^2_2
$$
where, e.g. "$o_0$" is the observed number of "0" tissues and $e_0$ is the number you expect.
Also -- the outcome (0, 1, and 2) in this case is binomial, not Poisson.
Comment: Hi all - OP here. Thanks for the discussion.

I had finally groped my way towards the Pearson's formulation too. Alexis has a point, however, that each tissue has a different overall concordance rate. I've calculated the Jaccard distance between pairs of samples and in each tissue it is different (likely reflecting sample, rather than assay, quality).

I think the assumption of iid observations hold - each sample is a biological replicate prepared separately rather than a true paired technical replicate.
Comment: Your answer ignores the pairing of the observations, and therefore hemorrhages power.
Comment: Not at all (I think). I'm treating each tissue sample as the unit of analysis, rather than each assay. Your answer addresses the correlation between replications, mine  addresses the number of successful replications. I interpreted the OP as asking about the latter.
Comment: And in doing so you are not accounting for the dependency of observations within tissue types; and Pearson's $\chi^{2}$ does not address the ordering of counts that your treatment of the data provides. Again: this analysis would hemorrhage power on these kind of data.
Comment: I'm not sure I understand how the dependency matters here, unless it means that $Pr(X=2)\neq Pr(X=1)^2$ (and based on the question it doesn't seem like that's the case).
Comment: 50 tissues. Tissue #1 has two measurements. If tissue #1 is different from tissue #2, then the within-tissue variance is different than between tissue variance. Pearson's test ignores this information.
Comment: Right. I think we have two different models. Your model is $\{X_i\}_1^{100}$ where $X_i\sim\operatorname{Bernoulli}{(p)}$ with 50 clusters (or pairs or whatever). My model is $\{X_i\}_1^{50}$ where $X_i\sim\operatorname{binomial}{(2,p)}$.
Comment: $\sigma^{2} = np(1-p)$, so your model assumes $p$ is constant (i.e. if different tissues have the same success probabilities).
Comment: Sure, but I don't see any reason in the question not to assume iid observations here. That's also not the same thing as talking about intra-cluster correlation. I guess we can wait for the OP to weigh in.
Comment: To clarify the model comparison comment from ssdecontrol, I am trying to reject Alexis' Bernoulli model - my alternative is that there *should* be concordance between tissue replicates, even though I didn't use that information in the assay procedure. So the null should be the Bernoulli model, right? I hadn't considered MacNamara's test for that, but it's a great idea.
Comment: This answer looks like it might work, but it needs considerable cleaning up: the $\chi^2$ formula is erroneous; something needs to be said about the degrees of freedom to use; and some indication of how to estimate $p$ is needed, too. It's likely that with 50 tissues the $\chi^2$ distribution will not be a good approximation to the true distribution of this test statistic, either.


What is the best ratio between width and height in a Bar Chart?

Question: A taller bar chart exalts its height, while a wider one diminishes the perception of the variations in height.

I have a bar chart where I try to demonstrate this idea ->
 http://ltw1556.web.cs.unibo.it/bias_barChartRatio.html
but I also want to display a "Golden Ratio", a wise proportion of width/height to show to some users.
How do I find this ratio?

UPDATE  @Glen_b

1) Assuming the data is correct as you said, I want to extinguish the extreme effects of both the flatter plot and the lofty one. Your answer sounds great (therefore I'm not going to make a flat chart), but how do I know if I'm going too far in lengthening the height of the chart?
For example, is Width: 800px, Height: 400px tall enough or should I go further in height in order to make dips more observable? Isn't there a surefire way of choosing the height, depending on the width?
2) The purpose of this chart was to clearly represent the growing trend of Oil Consumption. To be honest, I've randomly chosen some data from the BP report in order to prove a point: how the Width/Height ratio can change the perception of the data and how this can be used for lying with charts (the flatter plot could be used for corroborating lies).
Having said that, do you think I should change type of chart or simply change data?
Comment: Oh sorry, I edited the question with the correct link. I'll also add an image later
Answer:
For the moment, let's assume that you have data that are suited to a bar chart.
Then it depends on what you're trying to achieve (what do you want it to be "best" at?). What makes a good ratio might be considered from various points of view.
If the point is to best convey the numeric information, then Tufte's principle[1] of maximizing the data-ink ratio will tend to lead you in the right direction for making comparisons/extracting information[2] -- toward quite thin bars.  You can see that in your plot with the much taller bars that you can identify not just the general tendency to increase, but also the details (dips and changes in slope) that are simply lost in the flatter display. Consider this piece from the top right of your graph:

Taken further, that consideration might perhaps even lead you to a Cleveland dot-chart[3]).

If the point is to achieve some kind of visually-appealing shape of rectangles rather than convey the information, that's perhaps more a visual design question.
Now, is a bar chart suitable for the data you have?
Your example shows a time series of values. You should generally not use a bar chart for that (despite how common it is to do exactly what you have done). Bar charts are for displaying categorical data. Time series are generally best presented as points (possibly connected by thin lines).
[See for example, the left and right plots at the top of p9 of this report (the report is related to the data you use), which shows categorical data as a bar chart and time series data as lines (the lines are too thick to assess the values well but let's leave that aside)]

Some references:
[1]: Tufte, Edward R (2001), The Visual Display of Quantitative Information (2nd ed.),
Cheshire, CT: Graphics Press, ISBN 0-9613921-4-2.
[2]:
Cleveland, W. S. and McGill, R. (1985),
"Graphical Perception and Graphical Methods for Analyzing Scientific Data,"
Science, New Series, Vol. 229, No. 4716 (Aug. 30), 828-833.
[3]: Cleveland, W. S. (1993). Visualizing Data,
Hobart Press. ISBN 0-9634884-0-6.
Comment: @CrisBenois In your new edit you seem to be conflating two different things: the aspect ratio of the *bars* (which my answer says should be *large* -- quite tall and thin) and the aspect ratio of the plot as a whole (which I didn't intend to suggest should be unusually tall). The bars can be made essentially infinitely thin\* even if the plot is wider than it is tall. As a first attempt, I would probably be inclined to make the plot about 1.5 times as wide as tall. $\:$ (\* though as I suggested before, if you're plotting time series, I'd drop the bars altogether)
Comment: There is a case that the quantities shown here are annual totals and thus defined only for individual years and thus logically requiring distinct bars. The same logic would oblige touching bars too! That said, I'd agree that line charts for this kind of data are not only commonly used, but also much simpler here than bar charts and for that and other reasons defensible in practice.  (For example, line charts support multiple time series well.)
Comment: I've made some corrections: http://ltw1556.web.cs.unibo.it/bias_barChartRatio.html. Now the default Width/Height ratio is 1.5 while the Bars Thickness is 60%.
Answer:
You probably ought to plot this time series as a line chart rather than a bar (column) chart.
It is thought that the best aspect ratio for a chart is the one that "banks to 45°", that is, in which the average slope of the line segments connecting adjacent points is about 45°. In your second chart, the first third is a bit over this slope, while the rest is under, so this rule of thumb would tell you to make the second chart a bit taller. I don't have references at hand, but you could search further.
Comment: William S. Cleveland discusses this 45$^\circ$ rule in his books _Visualizing Data_ (1993)  and _The Elements of Graphing Data_  (1994), both Summit, NJ: Hobart Press.  The idea is older, e.g. Fisher, R.A. 1925. _Statistical Methods for Research Workers_. Edinburgh: Oliver and Boyd (and later editions).


Video thumbnail does not have a Play button on Facebook shared links

Question: The video links shared via my website on Facebook appear as only images in the shared link; Facebook doesn't seem to recognize the content as video.
I've debugged the URL via Facebook debugger, and every thing appears fine:
<http://developers.facebook.com/tools/debug/og/object?q=www.vlikeviral.com%2Fvideos%2Fplay%3Fid%3D10>
The thumbnail that appears under the link does not have a play button on it. As you can see in the debug details, the appropriate og tags are already present on the page.
Comment: Possible duplicate of [Shared Facebook video is not displayed inline in wall posts for HTTPS users](https://stackoverflow.com/questions/8267543/shared-facebook-video-is-not-displayed-inline-in-wall-posts-for-https-users)
Answer: For video playing Facebook is not considering og:video tag, instead of that it is looking for og:video:secure_url tag
refer-link: https://developers.facebook.com/blog/post/602/
Answer: You seem to be missing an og:video tag pointing to the video source.
See also Shared Facebook video is not displayed inline in wall posts for HTTPS users - you also need to include the HTTPS source if you want users browsing Facebook over HTTPS to see the inline video.
Comment: It's fixed, I don't really know how but, adding a couple of more og tags(video:tag, og:video and fb:app_id) solved the problem. Thanks for providing the right direction.
Comment: adding og:video tag does not fix the problem :(
Answer: It is very easy. You can add play button on an image like Facebook play button by using adobe Photoshop. Watch this video you will understand how to add it on the image.
http://mefmor.blogspot.com/2014/08/how-to-add-facebook-play-button-in-your.html


How to reset css fonts cache

Question: I've changed my fonts in the server, but the browser get the old version of the css file where fonts are writed, how to reset the cache?, i've tried to delete browser cache and delete the old file css, but they still are getting the old cs, i've tried to reload the server, how to fix that?
Answer: I've noticed this happen only in Firefox, which is very annoying, however, if this is the same situation as you here, refresh with SHIFT + CMD + R (if you're on a mac, I presume the windows alternative is CTRL + SHIFT + R)
That'll clear your cache for that page too + SHOULD show your fonts :)
Comment: This may work fine for you/the developer, but it is not a good solution for users who have the old css and fonts loaded.
Comment: Please forgive this answer was written in 2013 and the tech has changed since then, 6 years later
Comment: In Firefox the usual methods for reloading the page do not refresh the font cache. One method that may work is `History > Delete recent history - Everything`. See this [question](https://stackoverflow.com/questions/42002546/clear-firefox-font-cache).
Answer: Make sure your browser isn't displaying local fonts — I spent almost one hour trying to figure out how to clear the font cache in Firefox, while the issue had nothing to do with that.
Check your webserver logs : are font files downloaded ?  If not, then it's likely you're using local fonts.
Consider this real case scenario :
@font-face{
    font-family: SuperFont;
    src: url('../fonts/Superfont.ttf'),
}

I copypasted this code from somewhere, removing part of the src definition, not noticing the ending comma which made this line invalid CSS.  Therefore the font was not downloaded.
However, since I had Superfont already installed locally, it seemed to work because the browser recognized the font-family.  Well, until I decided to change the font file, but keeping the font-family definition to spare further modifications of the CSS file…
Morality : when testing fonts, use an unambiguous custom font-family name.
Answer: Have you tried viewing the page in a different browser to ensure the old font isn't still being added to the page?
If you're still using the same CSS file, you can navigate to the CSS file and do a hard refresh on that Ctrl+F5.
Also, I've found that closing the page completely before clearing your cache can help too!
Answer: Just add version for url:
@font-face{
    font-family: FontName;
    src: url('fonts/FontName.woff2?v=2.0') format('woff2'),
         url('fonts/FontName.eot?#iefix&v=2.0') format('eot');
}

Answer: Do a : Ctrl + F5 on your browser

How to reset css fonts cache


Posting a question only to answer it yourself

Question: Some users seem to post questions only to answer it a few minutes later. I'm not sure why they're doing this and in my opinion they questions themselves aren't of that high quality.
For example: Programmatically 301 Redirect. The question is something you can easily find with a Google search. So is this something we should ignore or should we delete / flag these kinds of threads.
In my opinion Magento SE shouldn't be someones place to store code snippets, there are enough online services already.
Comment: Related question on the network meta site: [What is this "answer your own question" jazz?](http://meta.stackexchange.com/questions/132886/what-is-this-answer-your-own-question-jazz)
Answer: I disagree with Marius on this, and agree with xyphoid's answer.
Whether a question is trivial or not, it shouldn't be an issue. When it's on topic and magento related, it should be allowed.
Like xyphoid said:

one person's trivial question is something someone else wasted an afternoon figuring out

The ability to find an answer with a Google search should be meaningless when the result isn't on http://magento.stackexchange.com (i.e. not a duplicate). The idea is having a large enough FAQ to cover most of possible Magento questions and issues that people have.
For example, I definitely disagree that the question linked in this question is trivial.
There are lots of way to do a redirect. So having a question mentioning what's the correct way to do it with the community agreeing/disagreeing (i.e. upvoting/downvoting) on how it's done, is really important.
Keep in mind, not everyone is a Magento or Zend or PHP expert. Someone could be coming from a <code>.NET</code> background for example.
Comment: Good point, thanks for sharing your view on the way Mage SE should work in relation to Googling and from that perspective I agree with you. My only concern is this becoming someones snippet bin. I guess it's a matter of opinion :)
Answer: If the question isn't a duplicate or anything I think this should be totally fine - one person's trivial question is something someone else wasted an afternoon figuring out.
http://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/
Answer: This has been a question of mine for a while, and I'm glad to see that it seems to be generally okay to do so. Many of the things I'm searching for seem to be obscure or partially answered on a blog from 4 years ago and would benefit from an updated answer here.
Answer: I don't see something wrong in posting answers to your own questions. But I agree with you on this. If the quality is poor or it's something (let's say) trivial, someone should take some actions. I say that we should just flag these questions and let the moderators decide on their quality.
Comment: Agreed, some awesome coding snippet that everyone should know about would actually be great but how to do a 301 redirect is a bit to trivial. Anyway, I flagged it. thanks for the answer :)


How can I find all the points where two functions of multiple variables intersect at the same value?

Question: Given two functions $f(x_1,x_2,x_3...x_n)$ and $g(x_1,x_2,x_3...x_n)$ in $n$-dimensional space, is there a straightforward way to find the set of points where $f$ and $g$ have the same output and the same input?
In 2D space, the intersection of two curves is "usually" a discrete set of points that can be solved for and manually plugged back into the equation if you're looking for points where the curves intersect at an interesting value. In 3D, the intersection of two surfaces is a curve or discrete set of curves and you can find the intersection of that curve with a plane if you want to know where the two surfaces intersect at a particular value.
For this problem, I have I have two functions of four variables. I want to find the set of coordinates where these functions both have the same input coordinates and both have a particular output value $U$, but I don't know where to begin. Are numerical methods my only hope? Or maybe there's just some standard terminology I'm missing.
For reference, here are the equations:
$P(w,x,y,z)=\frac{1}{\sqrt{wxyz}}$
$Q(w,x,y,z)=\frac{1}{\sqrt{2}}\left(\frac{1}{wy}+\frac{1}{wz}-\frac{A}{xz}\right)$
Comment: There is no straightforward way.
Comment: Oh well, at least that's a straightforward answer! ;) Luckily my computer can try every combination I need (the actual problem is selecting capacitors and resistors from the E Series of Preferred Numbers for an electric filter).
Answer: There is not a general procedure that works for any functions. But there is certainly much that can be done in your particular example.
You set the functions equal to each other:
$$\frac 1{\sqrt{wxyz}} = \frac 1{\sqrt 2}\left(\frac 1{wy}+\frac 1{wz}-\frac{A}{xz}\right)$$
A change of variables makes this a little prettier:
$$\frac 1{rstu} = \frac 1{\sqrt 2}\left(\frac 1{r^2t^2}+\frac 1{r^2u^2}-\frac{A}{s^2u^2}\right)$$
Multiply through by $r^2s^2t^2u^2\sqrt 2$:
$$\sqrt 2 rstu = s^2u^2 + s^2t^2 - Ar^2t^2$$
You can write this as a quadratic equation in each of the variables in terms of the others:
$$(At^2)r^2 + (\sqrt 2 stu)r - s^2(u^2 + t^2) = 0\\
(u^2 + t^2)s^2 - (\sqrt 2 rtu)s - Ar^2t^2 = 0\\
(Ar^2 - s^2)t^2 + (\sqrt 2 rsu)t - s^2u^2 = 0\\
(s^2)u^2- (\sqrt 2 rst)u + s^2t^2 - Ar^2t^2 = 0$$
For real solutions, each of the discriminants must be non-negative:
$$2s^2t^2u^2 +4(At^2s^2)(u^2 + t^2) \ge 0\\
2r^2t^2u^2 +4(Ar^2t^2)(u^2 + t^2) \ge 0\\
2r^2s^2u^2 + 4(Ar^2-s^2)s^2u^2 \ge 0\\
2r^2s^2t^2 + 4(s^2t^2)(Ar^2-s^2)\ge 0$$
Simplifying and switching back to $x,y,z,w$, the first two conditions turn out to be the same, as are the second two conditions. So it reduces to
$$z + 2A(z + y) \ge 0\\w + 2(Aw-x) \ge 0$$
Since $y,z > 0$ already, if $A \ge 0$, the first is automatically satisfied. The second requires $$x \le \left(\frac 12 + A\right)w$$
You can choose the values of any three of $w, x, y, z$ freely, as long as those two inequalities are observed. The fourth variable will have two possible values as determined by the corresponding quadratic equation in $r,s,t,u$. For example, if you've picked positive values for $x, y, z$, and set $s = \sqrt x, t = \sqrt y, u = \sqrt z$, then the value of $r$ is found by
$$r = \dfrac{-\sqrt 2stu \pm \sqrt{2s^2t^2u^2 +4(At^2s^2)(u^2 + t^2)}}{2At^2}\\
r = \frac{su}{\sqrt 2At}\left(-1 \pm\sqrt{1 + 2A\left(1 + \frac{t^2}{u^2}\right)}\right)$$
Squaring both sides and substituting for $w,x,y,z$,
$$w = \frac {xz}{2A^2y}\left(1 \pm \sqrt{1 + 2A\left(1 + \frac yz\right)}\right)^2$$
Similar equations can be derived to find each of the variables in terms of the other three.
Comment: Oh, this makes sense! Thank you! I had a feeling there was some way that was a way to narrow down the space of possible solutions from a volume to a plane to a line to points, but I didn't quite "connect the dots" by putting each variable in terms of the others. Now computationally in my case this might actually be more work for my computer than just iterating over every plausible combination of w, x, y, and z and seeing whether P and Q are close (the route I ended up taking) but I will keep this in mind for the future!


How to know how many nodes my website has?

Question: In /admin/content no specific number of nodes is available.
How to know how many nodes my website has, preferably without installing a module?
I want to know how many nodes I have in general, not of a specific content type.

I didn't find any native Drush command.
I personally would prefer Bash or JavaScript over PHP to count if I can.
Answer: The default /admin/content list is just another view. You can configure that view and temporarily add a result summary widget plugin in the header, which you can configure to get the total (it's the thing you use to render the "Showing X of TOTAL").
Comment: Yep I picked "Result summary" in the header of the view. Thanks.
Answer: Use an entity query:
$count = \Drupal::entityQuery('node')->accessCheck(FALSE)->count()->execute();

You can run this from a Bash shell with drush ev "..." or in an interactive PHP shell:
drush php
> \Drupal::entityQuery('node')->accessCheck(FALSE)->count()->execute();
= 123


all combinations of two and remove if they are same in R

Question: I would like your experise on this example. I need to have all combinations of two vectors and remove if they are same and remove one copy if they are duplicated.
v1 <- c("AS", "KS", "AZ", "AL", "MO")
v2 <- c("AZ", "KZ", "LM", "AZ", "ZK")

I woule like to get combinations of v1 / v2 and I don't want reciprocal V2 / V1, so I use
z<-outer(v1,v2, paste, sep="/")

which gives me
      [,1]    [,2]    [,3]    [,4]    [,5]
[1,] "AS/AZ" "AS/KZ" "AS/LM" "AS/AZ" "AS/ZK"
[2,] "KS/AZ" "KS/KZ" "KS/LM" "KS/AZ" "KS/ZK"
[3,] "AZ/AZ" "AZ/KZ" "AZ/LM" "AZ/AZ" "AZ/ZK"
[4,] "AL/AZ" "AL/KZ" "AL/LM" "AL/AZ" "AL/ZK"
[5,] "MO/AZ" "MO/KZ" "MO/LM" "MO/AZ" "MO/ZK"

But I need to modify to fit it in my analysis
Step 1. Remove same combination. I don't need to have the combinations which has same. In the above example there are two times AZ/AZ and both should be removed.
Step 2. Remove duplicated combinations. I don't need duplications. In the above example AL/AZ, AS/AZ, KS/AZ, MO/AZ are duplicated. One copy should be removed.
Step 3. Remove receprocal combinations if any. For instance AZ/AS is the same as AS/AZ.
Step 3. Sort all and keep them in single column.
"AL/AZ"
"AL/KZ"
"AL/LM"
"AL/ZK"
"AS/AZ"
"AS/KZ"
"AS/LM"
"AS/ZK"
"AZ/KZ"
"AZ/LM"
"AZ/ZK"
"KS/AZ"
"KS/KZ"
"KS/LM"
"KS/ZK"
"MO/AZ"
"MO/KZ"
"MO/LM"
"MO/ZK"

Thanks
Comment: Try `matrix(sort(unique(as.vector(z))), ncol=1)`, or just `sort(unique(as.vector(z)))`, depending on what you're really needing.
Comment: Does the order of the two values matter in the final result?
Comment: Don't you think it's rather unfortunate that you did not construct a test case that had any AS/AZ, AZ/AS combinations? And can you expalin why "AL/AZ, AS/AZ, KS/AZ, MO/AZ are duplicated" in your example?
Comment: Mr.Flick: The sorted final result helps !
Comment: BondedDust: Yes, in the example I didn't include a test case. Sorry. AL/AZ, AS/AZ, KS/AZ, MO/AZ are duplicated as 'AZ' is there in both V1 and v2
Comment: Josh O'Brien: Thanks for the simple soultion. But it doen't remove AZ/AZ
Answer: If the order of the two values doesn't matter in the final result, then this should work
v1 <- c("AS", "KS", "AZ", "AL", "MO")
v2 <- c("AZ", "KZ", "LM", "AZ", "ZK")
vv <- sort(unique(c(v1,v2)))

f1 <- as.numeric(factor(v1, levels=vv))
f2 <- as.numeric(factor(v2, levels=vv))
ff <- expand.grid(f1, f2)
ok <- unique(t(apply(subset(ff, Var1 != Var2), 1, sort)))

comb <- paste(vv[ok[,1]], vv[ok[,2]],sep="/")

which produces
 [1] "AS/AZ" "AZ/KS" "AL/AZ" "AZ/MO" "AS/KZ" "KS/KZ" "AZ/KZ" "AL/KZ" "KZ/MO"
[10] "AS/LM" "KS/LM" "AZ/LM" "AL/LM" "LM/MO" "AS/ZK" "KS/ZK" "AZ/ZK" "AL/ZK"
[19] "MO/ZK"

Answer: Here's another possible strategy using the igraph library.
library(igraph)
v1 <- c("AS", "KS", "AZ", "AL", "MO")
v2 <- c("AZ", "KZ", "LM", "AZ", "ZK")
gg<-graph.data.frame(expand.grid(v1,v2), directed=F)
ss<-simplify(gg)
apply(get.edgelist(ss),1, paste, collapse="/")

Basically we use all the logic if this graph library to define the values you want as nodes and then make all the connections between the two sets. Using simplify removes the nodes that are connected to themselves and also removes redundant connections between nodes. Perhaps a bit unorthodox to use the package like this, but as you can see it's relatively straight forward. Output:
 [1] "AS/AZ" "AS/KZ" "AS/LM" "AS/ZK" "KS/AZ" "KS/KZ" "KS/LM"
 [8] "KS/ZK" "AZ/AL" "AZ/MO" "AZ/KZ" "AZ/LM" "AZ/ZK" "AL/KZ"
[15] "AL/LM" "AL/ZK" "MO/KZ" "MO/LM" "MO/ZK"


How to update a field with data from another field from the same dataset with mysql?

Question: table
id  |  col1  | col2  | col3
I am looking for a SQL statement for update col2 with value of col1 where condition of col3 is fullfilled.
Any help would be great. Thanks!
Answer: Update sentence
<code>UPDATE theTable SET col2 = col1 WHERE col3 IS NOT NULL
</code>


Get raw video from gif to mp4 conversion

Question: I am in need of converting user uploaded gif files to mp4 format in php. Is this possible and if so, how?
The only current solution I have found is by uploading it to an api which would then provide me with a temporary link that I could use. That, however, would be a very bad solution because I would then have to crawl the link to obtain the raw video code. This is necessary as I am later uploading it to a WordPress media library.
Comment: Search `ffmpeg gif to mp4`.
Comment: Is it possible in pure php? **No.** Others have mentioned installing ffmpeg on your server and using it. That's the way to go.
Answer: Answer: not possible in pure php but is by installing and using ffmpeg on your server.