How to find frequency of n-grams and visualize it in wordcloud using R?

Question: I have dataframe with a column which includes strings of text, which I would like to do some analysis on. I would like to know what are the most used words and visualize this in a wordcloud. For single words (unigrams) I've managed to do so, but I'm failing in making my code work for n-grams (e.g. bigrams, trigrams). Here I've included my code for the unigrams. I'm open to adjusting my code to make it work, or to have a complete new piece of code. How would I best approach this?
library(wordcloud)
library(RColorBrewer)
library(wordcloud2)
library(tm)
library(stringr)

#Delete special characters and lower text
df$text <- str_replace_all(df$text, "[^[:alnum:]]", " ")
df$text <- tolower(df$text)

#From df to Corpus
corpus <- Corpus(VectorSource(df))

#Remove english stopwords,
stopwords<-c(stopwords("english"))
corpus <- tm_map(corpus, removeWords,stopwords)
rm(stopwords)

#Make term document matrix
tdm <- TermDocumentMatrix(corpus,control=list(wordLenths=c(1,Inf)))

#Make list of most frequent words
tdm_freq <- as.matrix(tdm)
words <- sort(rowSums(tdm_freq),decreasing=TRUE)
tdm_freq <- data.frame(word = names(words),freq=words)
rm(words)

#Make a wordcloud
wordcloud2(tdm_freq, size = 0.4, minSize = 10, gridSize =  0,
           fontFamily = 'Segoe UI', fontWeight = 'normal',
           color = 'red', backgroundColor = "white",
           minRotation = -pi/4, maxRotation = pi/4, shuffle = TRUE,
           rotateRatio = 0.4, shape = 'circle', ellipticity = 0.8,
           widgetsize = NULL, figPath = NULL, hoverFunction = NULL)

Answer: Change Corpus to VCorpus so tokenising will work.
# Data
df <- data.frame(text = c("I have dataframe with a column I have dataframe with a column",
                          "I would like to know what are the most I would like to know what are the most",
                          "For single words (unigrams) I've managed to do so For single words (unigrams) I've managed to do so",
                          "Here I've included my code for the unigrams Here I've included my code for the unigrams"))

# VCorpus
corpus <- VCorpus(VectorSource(df))
funs <- list(stripWhitespace,
             removePunctuation,
             function(x) removeWords(x, stopwords("english")),
             content_transformer(tolower))
corpus <- tm_map(corpus, FUN = tm_reduce, tmFuns = funs)

# Tokenise data without requiring any particular package
ngram_token <-  function(x) unlist(lapply(ngrams(words(x), 2), paste, collapse=" "), use.names=FALSE)

# Pass into TDM control argument
tdm <- TermDocumentMatrix(corpus, control = list(tokenize = ngram_token))
freq <- rowSums(as.matrix(tdm))
tdm_freq <- data.frame(term = names(freq), occurrences = freq)
tdm_freq

                               term occurrences
code unigrams         code unigrams           2
column dataframe   column dataframe           1
column like             column like           1
dataframe column   dataframe column           2
included code         included code           2
...


O que é uma classe, atributos e métodos virtual?

Question: O que é uma classe, atributo e método virtual?
public virtual class nomeclasse {

    public virtual int id { get;set; }

    public virtual void metodo() { }

}

Qual diferença?
Quando usar?
Answer: Primeiramente, no C# não é possível utilizar a palavra chave virtual diretamente na classe. É possível usar, sim, abstract para indicar uma classe abstrata.
Também no mundo .Net, geralmente se chama de propriedade o que você chamou de atributo, sendo que atributo no .Net significa outra coisa... isso gera um certo grau de confusão.
Partindo disso, podemos dizer que a palavra chave virtual marca os métodos e propriedades que podem ser extendidos por uma sub-classe, ou seja, que permite ter o comportamento alterado através de um override. Assim sendo, ao criar uma subclasse, é possível tornar ela mais específica, mas sem ter de reimplementar toda a classe, pois é possível alterar o comportamento pontualmente.
Exemplo:
public class PessoaBase
{
    public virtual string QuemEVoce()
    {
        return "Não sei quem sou!";
    }
}

public class PessoaMiguel : PessoaBase
{
    public override string QuemEVoce()
    {
        return "Eu sou Miguel!";
    }
}

Note que eu extendi a classe PessoaBase alterando o seu comportamento... no que ela respondia "Não sei quem sou!", eu alterei o comportamento na nova classe de forma que responda "Eu sou Miguel!".
O mais importante nisso tudo é que ambas as classes podem ser tratadas da mesma forma, pois ambas são de fato do tipo PessoaBase. Isso quer dizer que, através de uma variável do tipo PessoaBase eu consigo operar tanto um objeto do tipo PessoaBase como também uma do tipo PessoaMiguel:
List<PessoaBase> pessoas = new List<PessoaBase>
{
    { new PessoaBase() },
    { new PessoaMiguel() },
};

foreach (var pessoa in pessoas)
{
    Console.Write(pessoa.QuemEVoce());
}

Comment: Estranhei quando li, `virtual class`, tava vendo se era possível e qual seria o comportamento, mas você já respondeu. Já que não faria muito sentido o conceito de `virtual` em uma `class`. +1
Comment: Acho que confundi class virtual com partial, rsrsrs também não sei a diferença entre partial, quanto a métodos, eu entendi, ficou claro, mas necessariamente precisa ser virtual para eu sobreescrever?
Comment: @Rod: não necessariamente... para dar `override`, o membro na classe de base deve possuir um desses modificadores: `abstract`, `virtual` ou `override`... sendo que no último caso, a classe de base já deu `override` na base da base.
Comment: Ficou claro, obrigado
Comment: @Rod: quanto ao `partial`... é só uma forma de separar o código de uma classe em dois blocos, podendo estar em arquivos distintos. É geralmente usado para código gerado por ferramenta, na qual a ferramenta gera a classe com `partial` para que o programador possa adicionar mais código nesta mesma classe de dentro de outro arquivo... sendo assim, se a ferramente gerar o arquivo novamente, o código do programador não será afetado. Não recomendo utilizar classes parciais para organização de código... se você vir algo do tipo sendo feito, então tem algo cheirando mal.
Comment: Ótima exemplificação de como funciona a palavra chave virtual.
Answer: Classe é uma estrutura/modelo que representa um objeto/propósito do mundo real.
Exemplos:
class Veiculo {...}
class Animal {...}
class Pessoa {...}

Atributos são características que a classe possui.
Exemplo - Uma pessoa tem nome, data de nascimento, CPF, RG, estado civil, etc...:
class Pessoa {
    public String Nome { get; set; }
    public Date DataNascimento { get; set; }
    ...
}

Métodos são ações que a classe pode fazer.
Exemplo - Na classe pessoa, podemos ter uma ação Andar(), Dormir(), etc. Se tratando de programação, podemos ter métodos como Salvar(), Excluir(), GetById(), etc.
public class Pessoa {
   ...
   public void Andar(int qtdePassos);
   public boolean Salvar(Pessoa pessoa);
   ...
}

Existem vários atributos o qual podemos associar a um atributo, método e classe.
No caso do atributo "VIRTUAL" ele diz que o método pode ser sobrescrito na classe descendente (que herda da classe principal), ou seja, permite usar o código da classe principal ou então ignorar re-escrevendo o código na classe herdada.
Existem outros atributos como o "abstract" que diz que a implementação será feita na classe herdada e não na principal; "static" diz que o método/classe não necessita de uma instancia criada para acessa-la; dentre outras...
Uma boa referencia é:
http://andrielleazevedo.wordpress.com/2011/08/11/conceitos-basicos-de-poo-programacao-orientada-a-objetos-para-c-parte-1/
Answer: CLASSE: Uma classe é uma construção que permite que você crie seus próprios tipos personalizados, agrupando variáveis de outros tipos, métodos e eventos. Uma classe é como um modelo. Define os dados e comportamento de um tipo. Se a classe não é declarada como estática (STATIC), o código do cliente pode ser usado por meio da criação de objetos de ou de instâncias de que são atribuídas a uma variável. A variável permanece na memória até que todas as referências a ela saiam de escopo. Nesse momento, o CLR seleciona marca a variável como elegível para ser descartada. Se a classe é declarada estático (STATIC), apenas uma cópia existe em memória e o código do cliente só pode acessá-la por meio da classe propriamente dita, não por uma instância variável. Para obter mais informações, consulte Classes estáticas e membros de classe estáticos.
EX:
public class Person
{
    // Field
    public string name;

    // Constructor that takes no arguments.
    public Person()
    {
        name = "unknown";
    }

    // Constructor that takes one argument.
    public Person(string nm)
    {
        name = nm;
    }

    // Method
    public void SetName(string newName)
    {
        name = newName;
    }
}
class TestPerson
{
    static void Main()
    {
        // Call the constructor that has no parameters.
        Person person1 = new Person();
        Console.WriteLine(person1.name);

        person1.SetName("John Smith");
        Console.WriteLine(person1.name);

        // Call the constructor that has one parameter.
        Person person2 = new Person("Sarah Jones");
        Console.WriteLine(person2.name);

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
// Output:
// unknown
// John Smith
// Sarah Jones

MÉTODO: Um método é um bloco de código que contém uma série de instruções. Um programa faz com que as instruções sejam executados chamando o método e especificando todos os argumentos necessários do método. Em C#, todas instruções são executadas por métodos. O método Main é o ponto de entrada para cada aplicativo C# e ele é chamado pelo CLR (Common Languege Runtime) quando o programa é iniciado.
Métodos são declarados em um classe ou struct , especificando - se o nível de acesso como public ou private, modificadores opcionais, como abstract ou sealed, o valor de retorno, o nome do método. Essas partes são junto a assinatura de método.
abstract class Motorcycle
{
    // Anyone can call this.
    public void StartEngine() {/* Method statements here */ }

    // Only derived classes can call this.
    protected void AddGas(int gallons) { /* Method statements here */ }

    // Derived classes can override the base class implementation.
    public virtual int Drive(int miles, int speed) { /* Method statements here */ return 1; }

    // Derived classes must implement this.
    public abstract double GetTopSpeed();
}

ATRIBUTOS: Os atributos fornecem um método eficiente de associar metadados ou informações declarativas ao código (assemblies, types, métodos, propriedades e assim por diante).
Atributos fornecem um método poderoso de associar metadados ou informações declarativas, com código (assemblies, tipos, métodos, propriedades e assim por diante).
Depois que um atributo estiver associado a uma entidade do programa, o atributo pode ser consultado em tempo de execução usando uma técnica chamada reflection. Para obter mais informações, consulte Reflexo (guia de programação C#) .
Atributos têm as seguintes propriedades:
Atributos adicionam metadados para o seu programa. Metadados são informações sobre os tipos definidos em um programa.
Todos os assemblies .NET contêm um conjunto de metadados que descrevem os tipos e seus membros. Você pode adicionar atributos personalizados para especificar qualquer informação adicional necessária. Para obter mais informações, consulte, Criando atributos personalizados (C# e Visual Basic).
Você pode aplicar um ou mais atributos à assemblies, módulos ou elementos pequenos do programas como classes e propriedades.
Atributos podem aceitar argumentos da mesma forma que métodos e propriedades.
Seu programa pode examinar os metadados em outros programas ou seus próprios metadados por meio de reflexão. Para obter mais informações, consulte Acessando atributos com reflexo (C# programação guia).
Usando atributos
Atributos podem ser aplicados a maioria dos elementos de código, embora um atributo específico possa restringir os tipos de elementos ao qual ele é pode ser aplicado. No C#, especifica-se um atributo colocando o seu nome entre colchetes ([]) acima da declaração da entidade à qual ele pode ser aplicado. No Visual Basic, um atributo deve ser usado entre colchetes angulares (< >). Ele deve aparecer imediatamente antes do elemento ao qual ele é aplicado, na mesma linha.
Neste exemplo, o SerializableAttribute atributo é usado para aplicar uma característica específica a uma classe:
[System.Serializable]
public class SampleClass
{
    // Objects of this type can be serialized.
}

Usos comuns para atributos
A lista a seguir inclui alguns dos usos comuns de atributos no código:

A marcação de métodos usando a WebMethod atributo nos serviços Web para indicar que o método deve ser acessível através do protocolo SOAP . Para obter mais informações, consulte WebMethodAttribute.
-Descrever como os parâmetros dométodo realizar marshalingquando interoperar com código nativo . Para obter mais informações, consulte MarshalAsAttribute.
-Descrever as propriedades COM classes, métodos e interfaces.
Chamada de código não gerenciado com o DllImportAttribute classe.
-Descrever o seu assembly em termos de versão, título, descrição ou marca registrada.
-Descrever quais membros de uma classe para serializar para persistência.
-Descrevendo como mapa entre membros de classe e nós XML paraserializaçãode XML.
-Descrever os requisitos de segurança para métodos.
-Especificando as características usado para reforçar a segurança.
-Controlando otimizações pelo compilador Just-In-Time (JIT) para que o código permanece fácil de depurar.
-Obtendo informações sobre o chamador para um método.

Dei uma resumida, todos os links estão aqui:
Metodo,Atributo,
Classe
Answer: Resolvi responder porque há várias confusões nas outras respostas.
Vamos começar entender o que é uma classe e como ela se diferencia de um objeto. Classe é só um modelo, não necessariamente para representar um objeto do mundo real. E mesmo quando ele tem ligações com o mundo real, ele não é o mesmo que o objeto do mundo real como alguns costumam dizer.
Atributo é um termo errado em C# e praticamente todas as linguagens de programação. Já dei mais detalhes em outra resposta.
O termo até existe em C# e outras linguagens, mas não para o que as pessoas costumam explicar e como está em algumas respostas aqui. Uma das respostas quase acertou, mas o que le chama de atributo é, na verdade, o atributo personalizado.
Mas ele não é característica que uma classe possui, ele é característica que membros dos tipos possuem. O que a pergunta fala na verdade chama-se campo. Um campo tem algumas características para serem declaradas, esses são atributos dele, alguns especificados na linguagem e pode-se usar os tais custom attributes também.
Então public é um atributo (de visibilidade) de um campo ou outro membro. string é um atributo (de tipo) do membro, id é um atributo (de nome) de uma propriedade que não é nem campo, nem método, é um padrão de projeto chamado getter/setter que faz um ou dois métodos acessar ou modificar um estado na classe ou no objeto com uma sintaxe de campo.
Campo e propriedade são coisas distintas e nenhum deles é um atributo. É muito comum que uma propriedade esteja diretamente vinculada a um campo. Uma propriedade pode ser virtual, até porque ela é um par de métodos.
Usar o padrão sem uma propriedade em C#, como mostrado em uma resposta, não costuma ser adequado.
Também já respondi sobre método virtual. Curiosamente lá falando da diferença entre virtual e abstract que deveria ser usado na classe da pergunta (um método pode ser abstract também.
Para entender sobre o uso do virtual precisa entender sobre polimorfismo e herança.
Vou dar um exemplo um pouco melhor sobre como ele funciona (exemplos artificiais costumam ensinar o mecanismo bem, mas o conceito de forma errada), e de forma moderna:
using static System.Console;
using System.Collections.Generic;

List<Pessoa> pessoas = new() {{ new() }, { new PessoaFisica { Nome = "Rod" }}};
foreach (var pessoa in pessoas) WriteLine(pessoa.EuSou());

public class Pessoa { //não usei abstract para facilitar o exemplo
    protected int id; //campo
    public virtual string EuSou() => "Não sei quem sou!"; //método virtual
}

public class PessoaFisica : Pessoa {
    public string Nome { get; init; } //propriedade
    public override string EuSou() => $"Eu sou {Nome}!"; //método virtual sobrescrito
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Por fim, em comentário o AP tem dúvida sobre partial.
Vai te interessar sobre o uso: Pra que usar de private?.
Aproveite para ver o padrão de nomenclatura de C# nos nomes.
Aprenda os termos corretos para não treinar e perpetuar o erro. Muitas pessoas aprendem errado, inclusive eu aprendi várias e ainda devo saber algumas coisas erradas, e de tanto praticar o erro elas não conseguem admitir que sempre estiveram erradas. Quando eu aprendo o certo eu começo usá-lo. Errar é humano, insistir no erro é teimosia, pra ser elegante.
Seguiu todos os links? Depois não reclama de aprender errado ;)


pytest-django: django_db_keepdb Does Not Prevent Destruction of Test Database

Question: I am testing a Django (v. 4.1) application using pytest-django (v. 4.5.2).
I want to preserve the database that is created during testing so that I can examine it afterward.
According to the pytest-django documentation:

django_db_keepdb

Returns whether or not to re-use an existing database and to keep it after the test run.

Here is how I am using it:
import datetime
import pytest
from annotations import import_data

@pytest.mark.django_db
def test_import_data(django_db_keepdb):
    start_date = datetime.datetime(2016, 1, 1)
    end_date = datetime.datetime(2016, 6, 1)

    import_data.import_data(start_date, end_date)

The test runs but pytest destroys the test database after the test run.
Creating test database for alias 'default' ('test_vita')...
PASSED                     [100%]Destroying test database for alias 'default' ('test_vita')...

Perhaps I am misinterpreting what django_db_keepdb is supposed to do?
How can I prevent the test database from being destroyed?
Answer: i don't know so it will work or not but try this:
add this into the settings.py file
TEST_RUNNER = 'yourapp.tests.ClassName'

create test.py file
from django.test.runner import DiscoverRunner

class ClassName(DiscoverRunner):
    def teardown_databases(self, *args, **kwargs):
        pass


Why querying Androids MediaStore returns empty cursor?

Question: I'm using Android's MediaStore to retrieve duration/dateTaken of video files I record with my app. It works fine for older files, latest files I record do return empty (not null) cursor though. I cant see why this is happening, is MediaStore not updating instantly or there is a problem with the code I use below? Thanks for any help!
Uri uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.MediaColumns.DISPLAY_NAME + " LIKE '"+file.getName()+"'";
Cursor cursor = getContentResolver().query(uri, new String[]{MediaStore.Video.VideoColumns.DATE_TAKEN,MediaStore.Video.VideoColumns.DURATION}, selection, null, null);

Comment: Did u resolve this problem?
Answer: I was also facing the same problem. Printing the stacktrace revieled the issue.
Please add this permission in Manifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Answer: Seems like MediaScanner didn't scan latest files into MediaStore yet. You have to trigger if there are new files in your external storage.
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"
                            + Environment.getExternalStorageDirectory())));

Comment: Triggering a media scan does not help. Anyother solution available to this problem?

Does someone know the root cause of this problem?
Answer: Check to make sure that having your Android device plugged in isn't messing with the external storage. If your phone is mounting as USB storage, then you won't have direct access to the files in external storage. You can check for this by opening the gallery while your phone is connected to your computer.
I just went through developing an app that had to access all of the pictures on the phone, and it doesn't work while the phone is plugged in. However, it works just fine if I unplug it.


How to implement a text field formatter that renders a URL as the image?

Question: If a node has a text field with the url of an image as its value, how can I render this field as the image?
The image does exists it will be given the image url. I have to write that url into the text field.
Now using this url the value of this field should be an image when the node is viewed. But should be again editable textfield when editing the node.
And if in case the image doesn't exits a string can be shown "no image available".
Comment: Arpitk welcome to the Drupal stackexchange. Please edit your question and make it a little clearer.  The image exists already ? You want the image text to be replaced by an equivalent image ? Would greatly help to give a specific example.
Comment: Hi @GiorgosK thanks for the quick reply. Yes the image does exists i will be given the image url. I have to write that url into the text field. Now using this url the value of this field should be an image when the node is viewed. But should be again editable textfiled when editing the node And if in case the image doesnt exits a string can be shown "no image available". i am working on drupal 8
Comment: Please reformat the question with these details.
Comment: Have you reviewed the Field Formatter example at Drupal.org (https://www.drupal.org/docs/8/creating-custom-modules/creating-custom-field-types-widgets-and-formatters/create-a-custom-0)?
Answer: You can follow the Drupal.org example on creating a custom Field Formatter. Inside the viewElements function, you can add an if statement to check if the remote file exist. If it does, assign the url to the markup. If not, assign some text:
viewElements(FieldItemListInterface $items, $langcode) {
    $element = [];

    foreach ($items as $delta => $item) {
        $file = $item->value;
        $file_headers = @get_headers($file);
        if(!$file_headers || $file_headers[0] == 'HTTP/1.1 404 Not Found') {
            $url = Url::fromUserInput($file);
            $markup = "toUriString()} \>";
        }
        else {
            $markup= "File Not Found";
        }
      // Render each element as markup.
      $element[$delta] = ['#markup' => $markup];
    }

    return $element;
  }

Part of this answer is from stackoverflow.
I have not tested this, but it should be close.
Answer: Use a view to display this content type. Then set the view to display fields.
You can then add the text field and then add a template for this specific field.
You can technically override the output of the field and put the html there, but it's bad practice to put html into the database. So I would stick with doing it with a view template file. Then you can also put in an alt tag from the title field or wherever. The only issue is you won't have the image height/width which is best practice to include, you could use some fancy javascript to do this but it may not be worth the cost.
Drupal.org documentation on views template naming: https://api.drupal.org/api/drupal/core%21modules%21views%21views.theme.inc/group/views_templates/8.2.x


Error setting up project with latest version of jQuery Mobile and MDS AppLaud for Eclipse

Question: I am starting with PhoneGap development. I had set up Eclipse-ADT bundle and MDS AppLaud plugin. When creating a new PhoneGap project, I can chose built-in versions of PhoneGap (1.4.1 to 1.9) and jQuery Mobile 1.1. There's an option to use already installed versions for each one. No problem whith PhoneGap 3.4, but with jQuery, I have this error:

All .js and .css files in the jQuery Mobile directory
  /foo/bar/jquery.mobile-1.4.2 must have the same version number of the
  form jquery.mobile-{version}.*

I removed Demos directory and min versions of css and js, but I still get the same error, maybe because there are some more css files with the form jquery.mobile.something-1.4.2.css
How can I solve this error using latest jQuery Mobile?
Thanks
Answer: I had the same problem, but when I delete everything without /images/ folder and these: jquery.mobile-1.4.5.css, jquery.mobile-1.4.5.min.css, jquery.mobile-1.4.5.js, jquery.mobile-1.4.5.min.js and everything works great with Eclipse. :)
Comment: Thanks for your answer. I finally gave up (this question is older than one year) and started using NetBeans where everything works great without big configuration


Formula of regular 2m-gon inscribed in a unit cirlce

Question: From pg 80 of Introduction to Calculus and Analysis I by R. Courant:
If we let$f_m$ denote the area of the regular $m$-gon inscribed in a unit circle, the area of the inscribed $2m$-gon is given by the formula:$$f_{2m}=\frac{m}{2}\sqrt{2-2 \sqrt{1-(2f_m/m)^2}}$$
Another formula is $f_m=\frac{m}{2}\sin{\frac{2\pi}{m}}$
The second formula is easy to derive but I have no idea how to derive the first one no matter how hard I try. I have tried to verify the first formula by first calculate for example the area for $m=10$ polygon using the second formula then the first formula by $m=5$. It is correct for $m\ge4$ but when I try to calculate for the case $m=3$, I get $1.5$ from the first formula instead of the correct $2.598$(that is the area of regular hexagon inscribed in a unit circle). Can someone please guide me? Thanks.
Answer: From the rule of the sum:
$$
\cos(2\alpha) = \cos^2 \alpha - \sin^2 \alpha = 1-2\sin^2(\alpha)
$$
hence the bisection formula
$$
\sin(\alpha) = \sqrt{\frac{1-\cos(2\alpha)}{2}} = \sqrt{\frac{1-\sqrt{1-\sin^2(2\alpha)}}{2}}
$$
Now replace $f_m = \frac m 2 \sin \frac{2\pi}{m}$...


AngularJS - ng-repeat with array checkboxes

Question: here's the demo:
JSFiddle
var app = angular.module('app', []);

    function Ctrl($scope) {

        $scope.selection = [];

        $scope.categories = [ { "name": "Sport", "id": "50d5ad" } ,
        {"name": "General", "id": "678ffr" } ];

    }

If i check any checkbox I need to see it's name in the array, but nothing happens, why ?
Answer: I'd suggest adding a function that either add or delete an element on click, depending on the state of your checkbox :
Updated JSFIDDLE
HTML :
<input type="checkbox" ng-click="addToSelection(category)" ng-model="category.selected" name="group" id="{{category.id}}"/>

Controller :
$scope.addToSelection = function(category) {
            if (category.selected == true)
          $scope.selection.push(category.name);
        else
        $scope.selection.splice($scope.selection.indexOf(category.name),1);
    }

Answer: You have to bind listener for ng-change event. Something like
ng-change="selection.push(category.name)"

Updated fiddle: http://jsfiddle.net/0m3qc4s6/2/
Answer: You could try to change
$scope.selection = [];

with
$scope.selection = {};


How can i shorten this java-script code length and add animation?

Question: Hy!
i am currently learning java-script to utilize in web development. Somehow i believe this snippet o code i used is the long route and there should be a shorter way to do it.
it is a drop & retractable menu(content) on click.
Is there any better way i could have done this rather than writing all those codes?
Also, how do i add transition to the menu  ? I wish for it to pop out and in slower.
Thanks in advance!

function droping(){
                let dropdown = document.getElementById('dropdown');
                let dropped = dropdown.style.display;
                let cross = document.getElementById('cross1');
                let plus = cross.style.display;
                let dash = document.getElementById('minus1');
                let minus = dash.style.display;
            if(dropped == 'none'){
                dropdown.style.display = 'block';
                cross.style.display = 'none';
                dash.style.display = "inline-block";
            }
            else {
                dropdown.style.display = 'none';
                cross.style.display = 'inline-block';
                dash.style.display = "none";
            }

        }
button {
    cursor: pointer;
    width: 100%;
    text-align: left;
    display: flex;
    align-items: center;
    text-decoration: none;
    background-color: transparent;
    border: none;
    padding: 1.3rem;
}

button:visited {
    background-color: teal;
    border: none;
}

.cross i{
    margin-left: auto;
    margin-right: 0.3rem;
}

.move {
    transition: ease-in-out 0.6s;
}
<button class="maintop cross" onclick="droping()">
                What did the lion say to the king?

            </button>

 We can have another meal of your body!

Answer: For showing/hiding elements, the simplest way is to make use of the build-in hidden API:

function droping() {
  const dropdown = document.getElementById('dropdown');
  const cross = document.getElementById('cross1');
  const dash = document.getElementById('minus1');
  dropdown.hidden = !dropdown.hidden;
  cross.hidden = !cross.hidden;
  dash.hidden = !dash.hidden;
}
button {
  cursor: pointer;
  width: 100%;
  text-align: left;
  display: flex;
  align-items: center;
  text-decoration: none;
  background-color: transparent;
  border: none;
  padding: 1.3rem;
}

.cross i {
  margin-left: 3em;
}

[hidden] { display: none !important; }
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<button class="maintop cross" onclick="droping()">
    What did the lion say to the king?

</button>

 We can have another meal of your body!

Both your solution and this one depend on showing/hiding using the display property. Unfortunately display cannot be animated.
If you need transitions, I suggest you either implement this based on your own CSS classes which you then add/remove instead of changing the display property, or simply use jQuery.toggle():

function droping() {
  $('#dropdown, #cross1, #minus1').toggle('slow');
}
button {
  cursor: pointer;
  width: 100%;
  text-align: left;
  display: flex;
  align-items: center;
  text-decoration: none;
  background-color: transparent;
  border: none;
  padding: 1.3rem;
}

.cross i {
  margin-left: 3em;
}

<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<button class="maintop cross" onclick="droping()">
    What did the lion say to the king?

</button>

 We can have another meal of your body!

Comment: THANKS! its better now


SQL query with case, when AND cast combined

Question: I need a query but I can't find a answer.
select IS_ALT = case when IS_ALT IS NULL THEN Cast(0 as bit) else 1 end as veraltet
From Gemeinde

The Problem is I can't give an Alias. In this Case the Alias is veraltet.
Comment: Tag your question with the database you are using.  Also explain the logic you want to implement.
Answer: I don't know what IS_ALT = is supposed to be, but you provide an alias with as, so:
select (case when IS_ALT IS NULL THEN Cast(0 as bit) else 1 end) as veraltet
From Gemeinde

Answer: Maybe you are assigning a variable in TSQL, in that case an @ is missing like this:
select @IS_ALT  = cast(case when IS_ALT IS NULL THEN 0 else 1 end as bit) as veraltet
From Gemeinde


Prove chain-completeness of a poset

Question: How can I prove chain-completeness of a poset?
In particular this is the problem:
$\langle D, \leq \rangle$ is a chain-complete poset (every chain has a least upper bound). Prove or disprove $\langle convex(D),\subseteq \rangle$ is a chain-complete poset.
Where $convex(D)=\{S \subseteq D |\forall x,y\in S, z\in D. (x\leq z \leq y \Rightarrow z\in S\}$
My naive opinion, probably wrong:
I think, it's quite obvious that is true, and given a chain $c_1,c_2,...,c_n \in convex(D)$, $c_1\subseteq c_2...\subseteq c_n$ we just take $c_n$ as LUB.
Comment: Where it says $S\subseteq$, do you mean $S\subseteq D$?
Comment: In your last paragraph, you seem to be assuming that $D$ or at least $\operatorname{convex}(D)$ is finite. Is this a premise that you forgot to state?
Comment: No, finiteness is not a premise. Honestly I don't have any ideas in how to approach this, and probably my last paragraph is completely wrong
Comment: Since $\mathrm{convex}(D)$ is ordered by inclusion an obvious candidate for the least upper bound of a chain $\{c_i\mid i\in I\}$ is $\bigcup_{i\in I} c_i$. Can you see why this does (or doesn't) work?
Answer: To show that $\langle \operatorname{convex}(D),\subseteq\rangle$ is chain-complete, it suffices to show that for any chain $C_i$ in $\operatorname{convex}(D)$ with $C_i\subseteq C_{i+1}$ the union $C=\bigcup_iC_i$ is also in $\operatorname{convex}(D)$, since this can then serve as the least upper bound. This is trivial if the chain is finite, since in that case $C$ is its last element.
To prove that $C\in\operatorname{convex}(D)$ also for infinite chains, let $x,y\in C$ be given. Then $x\in C_i$ and $y\in C_j$; without loss of generality assume $i\le j$. Then also $x\in C_j$, so $x,y\in C_j$ and thus for all $z\in D$ we have $x\le z\le y\Rightarrow z\in C_j$ and thus also $x\le z\le y\Rightarrow z\in C$. Thus $C\in \operatorname{convex}(D)$.

Prove chain-completeness of a poset


Nonlinear Differential Euqation

Question: I need to solve the following differential equation
\begin{align}
y' = \frac{6-7y-\sqrt{y(24-23y)}}{9\sqrt{1-y}}
\end{align}
with initial condition $y(0) \in [0, \frac{1}{2}]$.

How do I know if there exists an analytically solution?
And how would you proceed?

EDIT: Sorry I forgot to cancel something out. The correct equation reads
\begin{align}
y' = \frac{6-7y-\sqrt{y(24-23y)}}{9}.
\end{align}
I used the software maxima to solve it, but I don't understand the output.
\begin{align}
q(t) = \textrm{ilt}\left(-\frac{\textrm{laplace}(\sqrt{24q(t)-23q(t)^2},t,s)-6}{7s}, s, t\right)
\end{align}
I think it is somehow related to trigonometric functions?!
EDIT II: With respect to Jan Eerland's answer I used Maxima to integrate the following term
\begin{align}
&\int{\frac{6-7u + \sqrt{u(24-23u)}}{72u^2 - 108u +36} du} \\[4mm]
=& \int{\frac{\sqrt{24-23u}\sqrt{u}}{72u^2-108u+36}du} + \frac{-5\ln(2u-1)+12\ln(u-1)-14\ln(\sqrt{u}+1)-14\ln(\sqrt{u}-1))}{72}
\end{align}
which gives me a hard time, because there still is an integral in the expression and $\ln(u-1)$ is not defined since $u\in[0,\frac{1}{2}]$.
Comment: Show us some of your work, and notice it is a seperable equation
Comment: What are your initial conditions? It would seem you need $0 \leq y \leq \frac{24}{23}$ to make the square root in the numerator Real and you need $y < 1$ to make the square root in the denominator Real and non-zero, which would suggest you're considering $y \in [0,1)$.  How did you come across such an equation? Did you derive it from something? If so, what?
Comment: I added the initial condition. The equation stems from an dynamic optimization problem.
Answer: HINT:
$$\int\frac{y'(x)}{6-7y(x)-\sqrt{y(x)(24-23y(x))}}\space\text{d}x=\frac{1}{9}\int1\space\text{d}x$$
Use:

$$\int1\space\text{d}x=x+\text{C}$$
For the RHS, substitute $u=y(x)$ and $\text{d}u=y'(x)\space\text{d}x$:

$$\int\frac{1}{6-7u-\sqrt{u(24-23u)}}\space\text{d}u$$
Now rationalize and expand the integrand:
$$\frac{1}{6-7u-\sqrt{u(24-23u)}}=\frac{6-7u+\sqrt{u(24-23u)}}{72u^2-108u+36}$$
EDIT
When:
$$\text{I}=\int\frac{y'(x)}{6-7y(x)-\sqrt{y(x)(24-23y(x))}}\space\text{d}x$$
The closed form is:
$$\text{I}=\frac{\sqrt{23}\arcsin\left(1-z\right)-2\left(5\ln|l|+\ln|12-11y(x)+q|\right)+5\ln\left|12+y(x)+5q\right|}{72}$$
Where:

$$q=\sqrt{y(x)(24-23y(x))}$$
$$z=\frac{23y(x)}{12}$$
$$l=1-2y(x)$$
Comment: Okay, thanks. Now I need to integrate the RHS of the last expression?
Comment: @clueless Yes, in order to find the original LHS.
Comment: I'm stuck and have no idea how to continue. Can you confirm that there exists a closed form solution?
Comment: @clueless yes, for the integral exists a close form, do I need to give you the closed from or the way to a closed form?
Comment: I would really appreciate if you could show me how to derive the closed form. My background is econ and I'm only familiar with simple ODEs, i.e., I'm literally clueless. Thanks already for your patience.
Comment: @clueless you're welcome, the way of finding the closed form is hard. So you can use sites like wolframalpha to find it for example.
Comment: Thanks. This is implict right? That is, there is no solution of the form y = f(x)?
Comment: You've to solve $y(x)$ out of those absolute value things and you will not get it that way
Comment: Can I get rid of those absolute value things if I knew that $y\in[0,0.5]$?
Comment: Notice that for $\ln(x)$ the point zero not well defined is!

Nonlinear Differential Euqation


Modifying script with sep. Inconsistent behaviour

Question: I am trying to eliminate the <..>  tags out of this small script (its name is test):
<changes><comment>Testing

Comment

Footer
</comment></changes>

Whevener I try with cat test | sed -e "s/<\/comment>//g; s/<comment>/ /g" > test1,
the output is correct:
<changes> Testing

Comment

Footer
</changes>

But when I try cat test | sed -e "s/<\/changes>//g; s/<changes>/ /g" > test1, the script stays unchanged.
I have copy/pasted every command on the shell and tested it before putting it here, so I believe it is not a matter of typos.
Anyone knows what kind of dark magic this is?
Comment: there are some weird characters in your `changes` text. If I copy it I see `chan<200c><200b>ges`.
Comment: Looks like XML. Is it XML? Because if it is, you should use a parser.
Answer: Supposing you want to convert:
<changes><comment>Testing

Comment

Footer
</comment></changes>

To:
<changes>Testing

Comment

Footer
</changes>

You can use (?:<(comment)>)(.*)(?:<\/\1>) and replace to \2
https://regex101.com/r/rC1rP6/1
Edit: Simpler regex and sed example:
cat test | sed 's/<\/\?comment>//g

Replace comment with changes to match other balise.
Notice: The reason you failed is because changes is written with an unicode character:

cat test | xxd shows:
0000000: 3c63 6861 6ee2 808c e280 8b67 6573 3e3c  <chan......ges><

when echo '<changes>' | xxd shows:
0000000: 3c63 6861 6e67 6573 3e0a                 <changes>.

Comment: I am aware there are lots of possibilities to improve the regex, but what I want is to delete ``, `` and `` already get replaced with the current command. The regex tool is great, though. Thanks for that
Comment: You are right, the original text is written in unicode. +1 for explaining how to see that.
Comment: You want to avoid the [useless `cat`](http://www.iki.fi/era/unix/award.html), too.
Answer: I'm of the opinion that the correct tool for the job is not a regex. Because one thing regex isn't very good at is tag matching. I would instead suggest using a parser - this is a perl snippet that'll do what you require:
#!/usr/bin/env perl

use strict;
use warnings;

use XML::Twig;

print XML::Twig -> parse ( \*DATA ) -> get_xpath('//*',0) -> text;

__DATA__
<changes><comment>Testing

Comment

Footer
</comment></changes>

NB - had to clean your source data, which had some odd characters when I copied and pasted, which may actually be the root of your problem.
This you could one liner as:
perl -MXML::Twig -0777 'print XML::Twig->parse(<>)->get_xpath('//*',0)->text;' you_xml_filename

(Or it'll accept input on a pipe).
For more complicated scenarios, this won't work quite as well, but it's pretty trivial to adapt to a more general tag-stripping:
E.g.:
#!/usr/bin/env perl

use strict;
use warnings;

use XML::Twig;

print map { $_ -> text } XML::Twig -> parse ( \*DATA ) -> get_xpath('//#PCDATA');

__DATA__
<changes><comment>Testing

Comment

Footer
</comment>
<anothercomment>fish here
</anothercomment>
<some_other_tag an_attribute="some_attribute">More text here</some_other_tag>
</changes>

(XML::Twig may need installing. This should be as simple as cpan XML::Twig or using your package manager)


Load specific view in Navigation View Controller

Question: I have a tab bar controller with 3 view controllers and one navigation view controller in it.
That navigation view controller has a table view controller and detail view.
In my first view controller (first tab) there are three buttons. I want the first button to load the detail view in the navigation controller. (as seen on image below)
Storyboard
How can i achieve this ?
I have tried calling the method that performs the segue in LocationsTableViewController, but that gives me the error "Receiver () has no segue with identifier 'addLocation'". Although a segue "addLocation" certainly exists.
Method connected to button in StartViewController:
- (IBAction)addLocationView:(id)sender {

    LocationsTableViewController *LTVC = [[LocationsTableViewController alloc] init];
    [LTVC addLocation];

}

LocationsTableViewController:
-(void)addLocation
{
    [self performSegueWithIdentifier: @"addLocation" sender: self];
}

Answer: Your "addLocation" segue is from the Locations Table View Controller to the Add Location View Controller, so the segue exists on the LocationsTableViewController. That is correct. However, if your current view controller isn't LocationsTableViewController, it doesn't make sense to call that segue.
You have a few options:

Storyboard Option #1: Make a new segue from StartViewController to AddLocationViewController, and perform that segue in addLocationView:.
Storyboard Option #2: Make a new segue from the button to the AddLocationViewController, and remove your IBAction. The storyboard will automatically call that segue when the button is clicked.
Programatic Option: Instantiate a new AddLocationViewController and push it onto the navigation stack: [self.navigationController pushViewController:[[AddLocationViewController alloc] init] animated:YES].
Comment: Hi,

I have tried option 1 and 2, but only the view shows up, without the tabbar and navigation bar.

Option 3 doesn't work, because of self.navigationController. Startview is not a navigation controller.

I have tried

    LocationsViewController *LVC = [[LocationsViewController alloc] init];
    [self presentViewController:LVC animated:YES completion:Nil];
    [LVC.navigationController pushViewController:[[AddLocationViewController alloc] init] animated:YES];

but only an empty tabbar gets displayed here.


Graphviz: how to create an edge where parts of the label have different colors

Question: I'm not sure how to color one part of the text with one color and another part with a different color. It's probably just easier to show you what I want with a picture.
This is the best I can get it to do.
Incorrect:

This is what I want (I edited this image in photoshop)
Correct (with photoshop):

Here is some code for reference.
import graphviz

graph = graphviz.Digraph()
graph.attr(rankdir='LR')
graph.attr('node', shape='circle')

graph.node("1", label="1")
graph.node("2", label="2")

graph.edge("1", "2", label="abcdef", fontcolor="red")

display(graph)

Answer: Here is the answer in straight Graphviz.  Create an HTML-like textitem (https://graphviz.org/doc/info/shapes.html#html)
digraph C {
 {rank=same
   a->b [label=<a bcd ef g h i>]
 }
}

Giving:
Comment: Thanks. I didn't know you could use HTML in the edge labels.  The line of code I needed in python was:

graph.edge("1", "2", label="""""")


$f(x)(1+2x+2x^2+x^3)=\frac{1}{(1-x)^3}$

Question: We have $f(x) = \sum_{i=0}^\infty a_ix^i$. We know that $f(x)(1+2x+2x^2+x^3)=\frac{1}{(1-x)^3}$.
We need to find $a_0, a_1, a_2$.
Also we need to find numbers $r, s, t$ from $a_n=D(3,n)-ra_{n-1}-sa_{n-2}-ta_{n-3}$ for n≥3.
I already get that $f(x) =\sum_{i=0}^\infty x^i \times \sum_{k=0}^\infty x^{2k} \times \sum_{j=0}^\infty x^{3j}$.
I am sure that this problem is connected to this.
Also there is a problem connected with two first ones: To write generating function for calculating number of integer solutions of the equation: $x_1 + 2x_2 + 3x_3 = n$.
Thank you and merry Christmas!
Comment: you can use [Partal Fraction Decomposition](https://en.wikipedia.org/wiki/Partial_fraction_decomposition)
Answer: For a start.
Consider that
$$f(x)(1+2x+2x^2+x^3)(1-x)^3=1$$ must hold for any $x$ that is say
$$(1-x-x^2+x^4+x^5-x^6)f(x)=1$$ Replace $f(x)$ by a few terms (since you just want $a_0,a_1,a_2$) and identify the coefficients.
Answer: Your finding is correct. Indeed:
$$f(x)(1+2x+2x^2+x^3)=\frac{1}{(1-x)^3} \Rightarrow \\\\
f(x)(1+x)(1+x+x^2)=\frac{1}{(1-x)^3} \Rightarrow \\
f(x)=\frac{1}{(1-x)(1-x^2)(1-x^3)}=\sum_{i=0}^{\infty} x^i\sum_{j=0}^{\infty} x^{2j}\sum_{k=0}^{\infty} x^{3k} \Rightarrow\\
i+2j+3k=n, \ \ \ i,j,k,n\ge 0.$$
So, if you need to find a few terms:
$$\begin{align}n&=0\Rightarrow (0,0,0) \Rightarrow a_0=1;\\
n&=1 \Rightarrow (1,0,0) \Rightarrow a_1=1;\\
n&=2 \Rightarrow (2,0,0), (0,1,0) \Rightarrow a_2=2;\\
n&=3 \Rightarrow (3,0,0), (1,1,0), (0,0,1) \Rightarrow a_3=3.\end{align}$$
Wolfram answer.
For more, you can see here.
Comment: Thank you very much for your comment. Could I have one more minute of your attention for explaining how can i get to  $a_n=D(3,n)-ra_{n-1}-sa_{n-2}-ta_{n-3}$ for n≥3?

$f(x)(1+2x+2x^2+x^3)=\frac{1}{(1-x)^3}$


Angular Module 'cordovaHTTP' is not available

Question: I am running Ionic and trying to use cordovaHTTP for SSL pinning. I followed the instructions on the the github but I get the error that the module isn't there.
My index.html

My app.js:
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'cordovaHTTP'])

In services.js:
angular.module('starter.services', [])

.service('MyService', function(cordovaHTTP) {

    cordovaHTTP.enableSSLPinning(true, function() {
        console.log('successful ssl pin');

        cordovaHTTP.useBasicAuth("user", "pass", function() {
            console.log('successful basic auth!');

            cordovaHTTP.get(url, function(response) {
                console.log(response.status);
            }, function(response) {
                console.error(response.error);
            });
        }, function() {
            console.log('error basic auth');
        });
    }, function(){
        console.log('error ssl pin');
    });
});

This results in the error:
Uncaught Error: [$injector:modulerr] Failed to instantiate module starter due to:
Error: [$injector:modulerr] Failed to instantiate module cordovaHTTP due to:
Error: [$injector:nomod] Module 'cordovaHTTP' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

I have tried messing with this countless times but no dice. Any help is appreciated.
Comment: just load `app.js` at last
Comment: Nothing changed :/ Wouldn't think it would either because that would break the controller and service anyway.
Comment: You should use one module instance for a single application. You may be getting this error due to initilization of two modules.
Comment: @Vineet, so just do var app = angular.module('starter') then do app.service() ?
Comment: Could it be that because cordova.js 404's during development that the Cordova plugin fails as well?
Comment: @PizzaPleb have you solved it?
Comment: @Shay, unfortunately I did not. I couldn't tell if it needed to be imported/required in more places throughout the project or if the app had to be built/deployed first (for cordova to start working).
Comment: Thanks anyway, that plugin was badly planned imo... angular code inside the plugins directory... There is a relatively new plugin that does ssl pinning that i'm using, maybe it'll help you out in the future! https://github.com/EddyVerbruggen/SSLCertificateChecker-PhoneGap-Plugin
Comment: Cool, thanks! I agree, the plugin did not seem very robust.
Comment: @Shay can you explain how to define SSLCertificateChecker plugin in angular module ionic, because after try to install that plugin, I got module not available too ?
Comment: @Redturbo The SSLCertificateChecker as I remember does not use the angular module dependency, it's a pure javascript library working on the global window.plugins object, used by many other cordova plugins...
Comment: @Shay but why when I try call window.plugins.sslCertificateChecker.check, this error message appear : "Cannot read property 'sslCertificateChecker' of undefined" ?
Comment: @Redturbo First check if the plugin is installed properly, secondly this plugin as some other cordova plugins only works in the **device**, it will not work on the browser, therefore test it on the device using the github's instructions on how to use it, and i'm sure you'll be successful ^^
Comment: @Shay Okay thanks, now it worked, I just forget to add Content-Security-Policy in index.html
Answer: Actually I think you're initializing your module multiple times. In angular factories / services are singleton. Your code look like something this
angular.module('starter', ['ionic', 'MyService', 'cordovaHTTP']) //setters for a module

Please make sure you're injecting right service or factory name. You should change your service declaration way too, like below
angular.module('starter') //Don't use [] it is only getter of above initialized module

.service('MyService', function(cordovaHTTP){
      //Code
});

Also please don't forget to load app.js at last. Hope it may help you.
Comment: Tried all of this. Still nothing. Also, putting app.js at the bottom throws errors because the main (starter) module in app.js that the service uses hasn't been defined yet. Thanks for helping, though. I feel like it's something small that I'm missing.
Comment: what is `ionic` in module init ?
Comment: I'm guessing the angular methods used in the mobile UI framework, Ionic, that I'm using. Disabling it didn't do anything.
Comment: angular methods ?? Will you please elaborate it for me ?
Comment: Perhaps method isn't the right word. For instance: ionic.Platform.isFullScreen = true;
Answer: I found the solution from github issues.

Make sure that you load the angular js files after cordova js files in index.html.

Here's my index.html:

Is angular defined?

cordova-HTTP will only instantiate the cordovaHTTP module if angular is defined otherwise it will fall back to window.cordovaHTTP.

You could use this this:
document.addEventListener("deviceready", function () {
  console.log(window.cordovaHTTP);
  console.log(window.CordovaHttpPlugin);  // For some version it's instantiated in this name if angular is not defined.
}, false);

Manually bootstrap your AngularJS app instead of using the ng-app attribute.

Code:

When using it in your controller or service, do not need to add the $.

Just use it like this:
angular.module('MyAppName.services', [])
.service('MyService', ['cordovaHTTP', function(cordovaHTTP){
    // Your codes are here.
}]);


Como comparar duas colunas e retornar a soma?

Question: Fala pessoal,
Tenho a seguinte tabela abaixo, o que eu quero é que ele some o Preço (Coluna D) de todos os livros que estão com a Situação (Coluna E) "Vendido".
Sei que dá para fazer com a função PROCV. Mas já estou a horas estudando essa função e até agora eu não consegui implementar na minha tabela. Se alguém puder me ajudar, ficarei extremamente grato.
No mais, agradeço a atenção e compreensão do problema.
Answer: Dá uma olhada nessa função SOMASE Aqui
=SOMASE(E2:E22, "Vendido", D2:D22)

Comment: Nossa, mais fácil do que eu pensava. Muito obrigado, Willys!


Keeping many databases in sync all the time

Question: I have a network of desktop PCs (Windows 7) which are located geographically apart from each other (connected with LAN).
The network has an Oracle back-end.
I want to install a database locally on each PC (about 12 of them, currently thinking of SQLite but open to other possibilities).
I need to guarantee the local databases are kept in sync with each other and with the Oracle db all the time or at least as long as there is network connectivity (mesh topology).
The synchronization involves only a single table.
What are some possible effective solutions for this problem ? preferably something you have worked with beforehand.
Comment: It sounds as if you are still at the decision step given your 'The front end isn't implemented yet (probably a Windows Forms)' comment. A web front end with a single, central database instance would be my preference unless there is a compelling reason not to. Yes it can suffer from network problems, which will need to be considered in caching and other design concerns, but that'll be nothing to the pain that will result from trying to keep multiple databases in sync with one another.
Comment: I believe that the "central database replicating to/from a bunch of local databases" is a classic database anti-pattern. I don't think you understand the kind of quagmire you're planning on diving into. If your network is so unreliable that connecting to a central database will be a problem I suggest you invest your time and money into improving your network; it will be easier and much cheaper to do so. Besides, if you have network problems now, adding additional database sync traffic will just make it worse - so you'll have to invest in your network anyways. Best of luck.
Comment: For 13x13 DB synching you need proper software - this is not trivial. The minimum price for something like GoldenGate would be $8,750  going up to $227,500ish (it's worth talking to an Oracle representative). If your network's down then you could have 12 people simultaneously updating the same record - what happens when it comes back up again? I'm with everyone else. Put your app online and if you're into ultra-special-once-in-a-millenium DR then have a redundant network with a secondary non-VPN route to the open interwebs - you can then access your app if your network exists or not.
Comment: Modifications can be made on any of the nodes?
Comment: @bpgergo I guess so, but what modifications are you thinking of ?
Comment: What is the reasoning for wanting these local databases?  WHat is the front-end that currently accesses this oracle db?
Comment: @OldProgrammer The front end isn't implemented yet (probably a Windows Forms) but it doesn't affect anything. The local dbs are used to keep the nodes up and running during network down times.
Comment: @BobJarvis The network is pretty good actually but the chance of trouble is always there. You say it's an anti-pattern, then what is the pattern ?
Comment: @Elliveny Well there are two concerns with a website. First of all, the application need to read from the computers serial port so it will need to access hardware ( I don't know if this is possible without an ActiveX and it will complicate matter otherwise because you will need a service or something). The other thing, what if the network is down. You will need to install the website locally on each device while in the other situation you can continue working and then sync later.
Comment: @Ben We are not expecting conflicts due to the nature of the application. Nevertheless there will be a policy to handle them if they happen. In our scenario every PC is like a service point. Customers come in very regularly and need to be served in real time, we can't afford any delays so if the network is down then the user works locally until restore. It is like if these PCs are roaming users that might lose connectivity and need to access stock for instance.
Comment: Ok, interesting situation. "The synchronization involves only a single table" - how much data will the table contain? What frequency of update do you need to support (i.e. how frequently will the table's rows be inserted/updated/deleted in each local database)?
Comment: @Elliveny a lot of data. CRUD frequency depends on business circumstances but on average we are expecting a CRUD operation every 4-5 minutes.
Comment: I'm working right now in a sychronization mechanism across SQLite databases hosted on Windows destop having SharePoint as the central store. I have just finished the local change tracking part. In my scenario no changes are done on server, it just serves as the central store. I use SQLiteConnection.Update and SQLiteConnection.Commit events to track changes. Changes are tracked on a separate database with just one table LocalChanges, this table has the changed data as JSON. This JSON is uploaded later to SharePoint. Apps poll SharePoint for changes. If you are interested I can share my code
Comment: @JesúsLópez Thank you for the offer. When I asked about this I expected for well proven solution using perhaps a popular framework. I had in mind that I might implement a custom solution like yours. Nevertheless if you are willing to share then I will consider it.
Comment: Ok, I will create a repo on GitHub.By the way, this is the third time I create a solution like this.
Comment: Two questions. Will the table on the ORACLE database be modified directly by some application?. You will need to create a web service that will be called by the destop apps to upload and download changes. Have you got a web server in your environment to deploy it?
Comment: Do you need to support each CRUD operation on each database? For example if you can allow just select on the SQLite databases and you do the other work on Oracle then the problem becames much easier and in case the network is down your app can warn the user about this and support just select (read) operation from the local SQLite "cache".
Comment: @sc3w Unfortunately that is not possible.
Answer: As I do not vast Knowledge in this area I'm not sure this will completely address your problems,but reading this question I realized that you need a database replication software package,so I would like to suggest if you could look into SymmetricDS Why I am suggesting this ? Basic Introduction from its official website.SymmetricDS is open source software that is free to use

SymmetricDS is open source software for multi-master database
  replication, filtered synchronization, or transformation across the
  network in a heterogeneous environment. It supports multiple
  subscribers with one direction or bi-directional asynchronous data
  replication. It uses web and database technologies to replicate tables
  between relational databases, in near real time if desired. The
  software was designed to scale for a large number of databases, work
  across low-bandwidth connections, and withstand periods of network
  outage.
By using database triggers, SymmetricDS guarantees that data changes
  are captured and atomicity is preserved. Support for database vendors
  is provided through a Database Dialect layer, with implementations for
  MySQL, Oracle, SQL Server, SQL Server Azure, PostgreSQL, DB2,
  Informix, Interbase, Firebird, HSQLDB, H2, Apache Derby, Greenplum,
  and SQLite included.

Synchronization can be configured to push data or pull data on a periodic basis. SymmetricDS allows for synchronization between two or more tiers of nodes, as might be needed in the following scenarios:

A handful of regional servers synchronizing from the general office
to remote geographical areas
Dozens of Point of Sale (POS) register nodes using an embedded
database to sync with a store server
Thousands of store server nodes using a departmental class database
to sync with a regional node

Features

Data Channels - Table synchronizations are grouped into independent
channels
Guaranteed Delivery - Synchronized data is guaranteed to arrive at
the target destination. If a synchronization fails, the same batch of
data will be retried until it succeeds or manual intervention is
taken. All other data synchronization is halted for the failed
channel only.
Transaction Aware - Data updates are recorded and replayed with the
same atomicity
Centralized Configuration - All configuration is downloaded from a
central registration server
Multiple Deployment Options - Standalone engine, web application,
embedded software component
Data Filtering and Rerouting - Allows for localized passwords and
sensitive data filtering/routing
HTTP Transport - Pluggable transport defaults to Representation State
Transfer (REST-style) HTTP services
Payload Compression - Optionally compresses data on transport
Notification Schemes - Push (trickle-back data) or Pull (trickle-poll
data) changes
Symmetric Data Protocol - A fast streaming data format that is easy
to generate, parse, and load
Plug-In API - Add customizations through extensions and plug-in
points
Two-Way Table Synchronization - The same table can be synchronized
both to and from the host system while avoiding update loops
Database Versioning - Specify data synchronization by version of
target database
Auto Database Creation - Optionally allow creating and upgrading of
database schema
Embeddable - Small enough to embed or bootstrap within another
application (i.e. a POS application)
Multiple Schemas - Supports multiple database schemas naturally
through the existence of Data Channels
Primary Key Updates - Captures the "before" and "after" data being
changed, allowing updates to primary key data
Remote Management - Administration through a Java Management
Extensions (JMX) console
Remote Database Administration - SQL can be delivered and run at
remote databases via the synchronization infrastructure
Initial Data Load - Prepare the satellite database with an initial or
recovery load of data

Hope My answer Helps!


Wicket setting window close callback not possible everywhere?

Question: I have a modal window with form inside it. There are two way user can close the window: either by filling up correctly form and submit change, or clicking an "x" in top right corner.
Now I'm trying to do following thing:
When user sucesfully fills up the form and submit change, on parent page I'm trying to display (with jQuery) some information about success.
When user clicks an "x" I want the modal window to be closed without any additional info. However setWindowClosedCallback is not working as I expected. Take a look at my code, first I'm getting reference to modalWindow (I omitted some not interesting parts of the code like adding form inputs etc.):
<code>public EditEmailForm( String id, final ModalWindow modalWindow,final User u )
{
    super( id );
    modalWindow.setWindowClosedCallback(new ModalWindow.WindowClosedCallback()
    {
    private static final long serialVersionUID = 1L;

    @Override
    public void onClose(AjaxRequestTarget target)
    {
            //here some code doing jQuery magic for parent page
    }
});
    AjaxSubmitLink closeBtn = new AjaxCloseCancelBtn( "close-x", this );

    add( new AjaxSubmitLink( "save", this )
    {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onSubmit( AjaxRequestTarget target, Form<?> form )
        {
        //here's user info change
        }

        @Override
        protected void onError( AjaxRequestTarget target, Form<?> form )
        {
            target.add( feedbackPanel );
        }
    } );
    add( closeBtn );
}

protected class AjaxCloseCancelBtn extends AjaxSubmitLink
{
    private static final long serialVersionUID = 1L;

    public AjaxCloseCancelBtn( String id, Form<?> form )
    {
        super( id, form );
        setDefaultFormProcessing( false );
    }

    @Override
    protected void onSubmit( AjaxRequestTarget target, Form<?> form )
    {
        modalWindow.setWindowClosedCallback(new ModalWindow.WindowClosedCallback()
        {
            private static final long serialVersionUID = 1L;

            @Override
            public void onClose( AjaxRequestTarget arg0 )
            {
            }

        });
        // revert fields values
        form.clearInput();
        // close popup
        modalWindow.close( target );
    }

    @Override
    protected void onError( AjaxRequestTarget target, Form<?> form )
    {
    }

}
</code>
This code works 50% good, as it displays what I want on parent page, but it also does it when I hit an "x" even tho I'm trying to set new window close callback which is empty. Any solution how can I overcome this?
Answer: You need to call org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow.close(AjaxRequestTarget)


One-to-one mapping of port range from Hardware Node to VZ Containers with iptables

Question:
At anytime I have about 3-4 VZ containers on a server(the Hardware Node on CentOS6). I have webservers, ssh, mail, etc running on the different Containers. From another host in the network, they are accessed as ip.of.hardware.node:port and iptables forwards them with a rule in the nat table.
To explain what I really want:
Assume my Container IDs are 2, 3, 4. And their IPs respectively are 192.168.0.2, 192.168.0.3, 192.168.0.4.
I want a setup where in if anyone accesses ip.of.hardware.node:2080, the connection should be forwarded to 192.168.0.2:80. Similarly:
ip.of.hardware.node:2022 => 192.168.0.2:22 (ContainerID: 2)
ip.of.hardware.node:3022 => 192.168.0.3:22 (ContainerID: 3)
ip.of.hardware.node:4080 => 192.168.0.4:80 (ContainerID: 4)
ip.of.hardware.node:4443 => 192.168.0.4:443 (ContainerID: 4)
... and so on.
This way, each Container gets a block of 1000 ports to work in. Is there a way to achieve this without specifying 1000 rules for each Container?
Answer: On the hardware node, you would need to create an IPtables DNAT rule for each forwarded service you want.
Using your example scenario:

iptables -t nat -A PREROUTING -p tcp --dport 2022 -i eth0 -j DNAT --to-destination 192.168.0.2:22
iptables -t nat -A PREROUTING -p tcp --dport 3022 -i eth0 -j DNAT --to-destination 192.168.0.3:22
iptables -t nat -A PREROUTING -p tcp --dport 4080 -i eth0 -j DNAT --to-destination 192.168.0.4:80
iptables -t nat -A PREROUTING -p tcp --dport 4443 -i eth0 -j DNAT --to-destination 192.168.0.4:443

If you plan on deploying many more containers and services, you could script the creation of these rules based on your port conventions.
Comment: Yes, this is what currently exists, but I want to forward all of 1000 ports. And a thousand rules are not desirable, or practical. So I just wanted to know if there is anyway with a manageable number of rules to forward all of 1000 ports. Anyways, I'm down to writing a module and hoping it works.


point-slope form problem

Question: Why is the slope not -0.4 like it says in the point-slope form. Isn't the format of the point-slope form y − y1 = m(x − x1) with "m" being slope. The answer says the slope is -2.5, which makes sense after converting to slope-intercept form. But why can't you just take the slope ("m") from the point-slope form?
Answer: Look again at the problem statement. The equation is given in the form $x-x_0=\frac1m(y-y_0)$, not $y-y_0=m(x-x_0)$. It's not in point-slope form. It's a bit of a trick problem meant to test if you're really paying attention.
Comment: is there any trick to knowing when it is 1/m vs m?
Comment: @user532526 No trick. The slope $m=\Delta y/\Delta x$, so if you swap $x$ and $y$ you end up with $1/m$. Try converting $y-y_0=m(x-x_0)$ into $x-x_0=a(y-y_0)$ for yourself and see what $a$ turns out to be.

point-slope form problem


manage roles in rails

Question: I want create roles in my project. Each user can be: admin, registered or demo. Each role see different things.
How can I do that? What is the best gem to do roles?
This is a example in 'bad programming" of what I want:
  def index
    if current_user.role[:name] == 'admin'
      @installations = Installation.all
    elsif current_user.role[:name] == 'registered'
      @installations = current_user.installations
    elsif current_user.role[:name] == 'demo'
      @installations = current_user.installations.first
    else
    end
  end

Answer: Some gems that might be interesting for you :

rolify
role_model

If you decide to implement it yourself, then within some page you might want to change the content, for that you might want to do something like this :
Add a role to the user model using a migration :
class AddRoleToUsers < ActiveRecord::Migration
  def change
    add_column :users, :role, :string, default: :demo
  end
end

Then in your app you can use it as follows:
def index
  case current_user.role
    when :admin
      @installations = Installation.all
    when :registered
      @installations = current_user.installations
    else
      @installations = current_user.installations.first
  end
end

You can also simply create a boolean admin for instance.
What you might want to do also is create some methods in your model so that you can call current_user.admin? or current_user.registered? . You can do that by doing (if you chose to use a string to store the role):
class User < ActiveRecord::Base
  def admin?
    self.role == "admin"
  end

  def registered?
    self.role == "registered"
  end
end

One advantage I see of having a role stored in a string is that if you have 5 roles for instance then you do not have 4 booleans (as when you store admin in a boolean) but only one string. On the long run you might want to store actually a role_id instead of a string and have a separate role model.
An excellent alternative pointed out by Jorge de Los Santos (another answer) is to use enum :
class User < ActiveRecord::Base
  enum role: [:demo, :admin, :registered]
end

It is an excellent alternative because it will automagically add the methods described above such as current_user.admin? without hard coding them.
With your roles, you might want to do some authorization (admins can have access to specific pages, demo users are restricted to only a subset of pages, etc.). For this, you can use the gem called cancancan. You can look at this railscast to learn more about it. Also, you can have some infos here : How to use cancancan? .
Answer: There are plenty of solutions available to you.
Starting by gems:
https://github.com/RolifyCommunity/rolify
https://github.com/martinrehfeld/role_model
By using Devise architecture (in case you use it):
https://github.com/plataformatec/devise/wiki/How-To:-Add-a-default-role-to-a-User
By using enums in rails 4:
class AddRolesToUser < ActiveRecord::Migration
  #add_column 'role', :integer, default: 0 to the users table
end

class User < ActiveRecord::Base
  enum role: [:demo, :admin, :registered]
end

That will enable role methods.
user = User.find(1)
user.role #:demo
user.admin? #false
user.registered? #false

And consequently:
if user.admin?
  #somethig
elsif user.registered?
  #another something
else
  #another another something.

And last but not least, what you are searching is not the manage roles solution, is the manage permissions solutions:
https://github.com/ryanb/cancan
Answer: Add a boolean, :admin to your User model.
class AddAdminToUsers < ActiveRecord::Migration
  def change
    add_column :users, :admin, :boolean, deafult: false
  end
end

Create a method for a registered user to separate them from demo users, such as verifying their email, providing a home address and phone number, filling out a profile, etc. This is up to you though, first you need to decide how a registered and demo user should be different.
Answer: The CanCan gem adds authorization to your project, and is especially useful if you want to implement multiple roles with differing abilities.  When used with an authentication system like devise, you get a full suite of capability for your site.
You're in full control of what roles you want to define and what abilities they have.  CanCan manages tracking, assignment, and querying of roles, and then gets out of your way to let you build what you need.
You can find the CanCan gem in Github: https://github.com/ryanb/cancan
It's simple to use, and the documentation is straightforward and easy to follow.

manage roles in rails


Internet routing through linux speeds down

Question: I'm having the most odd problem:
I'm providing internet routing for a network of pcs through a server based on linux. I used a broadband modem and everything worked fine.
Now, to the question, I got an optic fiber modem (PON Huawei Echolife HG8240) with the same speed as the broadband modem, but connecting the PON directly to one pc give's me full speed (10 mb/s up and down) but connecting the PON to a network adapter on the linux box slows down the internet connection to the PON at a rate that it can't even reach the 1mb/s (downloading, because uploading works at 10mbps at any link speed).
I was amazed and still am, but tuning and tweaking I found that using ethtool and setting the network adapter connected to the PON to 10 mb full duplex raises the throughoutput to 8,5mb/s. Still it's not the 10+ mb I get connecting it directly to one windows pc so... I'm at a loss here.
Thanks in advance!
Comment: Problem may be negotiation only, Use the ethtool to set the speed to maximum supported by the port on modem, and set **autoneg on**.
Comment: That's the thing, on windows the port on the modem it's set for 1 Gbps, on linux, autonegotiating it sets on 1Gbps too. But on linux neither 1 Gbps nor 100 mbps will download at a rate greater that 1mbps
Comment: Verify there are **tc**, **wondershaper** , or even iptables burst-size not running.
Comment: I checked, but it has to be something else, because just setting the network adapter link to 10mb boosts up the download speed to 8mbps. Setting it on 100 or 1000 and the download rate can't reach 1mbps.
Answer: Well, odd problem, odd solution. The whole problem was a rule on the firewall that prevented big packets from coming down the line:
"-j TCPMSS  --clamp-mss-to-pmtu"
Removed that from the firewall and worked like a charm.
Thanks Anirudh for your comments


Best way to generate a consecutive id in Python

Question: Given a class that has an attribute self.id I need to populate that attribute with a counter starting at 0 and all objects of that class need a unique id during a single run of the program. What is the best/ most pythonic way of doing this? Currently I use
def _get_id():
    id_ = 0
    while True:
       yield id_
       id_ += 1
get_id = _get_id()

which is defined outside the class and
self.id = get_id.next()

in the class' __init__(). Is there a better way to do this? Can the generator be included in the class?
Answer: Use itertools.count:
from itertools import count

class MyClass(object):
    id_counter = count().next
    def __init__(self):
        self.id = self.id_counter()

Comment: @joaquin - just because there is no reason to do the extra attribute access every time.
Comment: @cdhowie: the documentation doesn't say anything about it, so I wouldn't count on it. If you're worried about thread safety you can protect the ID assignment with a `threading.Lock`. (_EDIT_: actually [this page](http://29a.ch/2009/2/20/atomic-get-and-increment-in-python) suggests that `counter.next()` is atomic, although that would probably be implementation-dependent)
Comment: Why not `id_counter = count()` and `self.id = id_counter.next()`?
Answer: Why use iterators / generators at all? They do the job, but isn't it overkill? Whats wrong with
class MyClass(object):
  id_ctr = 0
  def __init__(self):
    self.id = MyClass.id_ctr
    MyClass.id_ctr += 1

Comment: Because this is what `count` is for. Yes, it's simple to reimplement, but then you can forget to increment the counter in a subclass that overrides `__init__`. You can't forget to increment the counter if it's done automatically.
Comment: good point regarding overriding __init__, but doesn't the solution with count() still require the subclasser to 'magically know' they should call self.id_counter() -  either that or as I would normally expect, calling Myclass.__init__(self) in the overriding __init__ is a sensible thing to do?
Comment: Yep, no way to remove the need to do it right, it's just one less thing to possibly get wrong.
Comment: One thing to do per subclass is better than two things to do per subclass. The `count` approach is more neatly factored.
Answer: Updated answer for Python 3
Use itertools.count:
from itertools import count

id_counter = count(start=1)
def get_id():
    return next(id_counter)

first_id  = get_id() # --> 1
second_id = get_id() # --> 2


como usar max-height e display table

Question: tenho uma div que a largura e altura dela é de acordo com o conteúdo, e preciso deixar ela no centro da página, estou com problema com o max-height, ele simplesmente não funciona, o min-height funciona perfeitamente, quando eu tiro o display:table o max-height funciona, só que eu perco a centralização da div, alguém sabe como arrumar isso ?

.miniatura
{
 display:table;
 margin:2% auto 0 auto;
 padding:2% 2%;
        max-width:500px;
        max-height:390px;
 width:auto;
        height:auto;
        background:green
}

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
   tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
   quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
   consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
   cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
   proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
   Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
   tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
   quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
   consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
   cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
   proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
   Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
   tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
   quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
   consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
   cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
   proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
   Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
   tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
   quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
   consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
   cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
   proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
   Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
   tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
   quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
   consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
   cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
   proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
   Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
   tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
   quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
   consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
   cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
   proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Comment: Coloca o código na seguinte plataforma e partilha na pergunta para que possamos ajudar: https://jsfiddle.net
Comment: aqui está. se tirar o `display:table` funciona perfeitamente https://jsfiddle.net/hdzns75u/
Comment: visualmente qual é o teu objetivo?
Comment: meu objetivo é, deixar a largura dela de acordo com o conteúdo porém não passando de `500px`, e a altura mesma coisa tendo no maximo `390px` e ela centralizada, com `position:absolute` da certo oque eu quero, só que eu perco outras propriedades do meu layout
Comment: Bruno aqui tem nada menos que 20 respostas de como centralizar elementos na página, vc chegou a dar uma olhada? https://pt.stackoverflow.com/questions/2817/qual-a-melhor-forma-de-centralizar-um-elemento-vertical-e-horizontalmente
Comment: @hugocsl meu problema é o `max-height` que não funciona com `display:table`, como minha largura também é de acordo com o conteúdo da div, tendo no maximo `500px`, eu só preciso que a div fique responsiva conforme seu conteúdo respeitando o `max-width, max-height`, seu eu tirar o `display` ele funciona, ai eu centralizo com `position:aboslute`, porém bagunça meu layout tudo
Comment: Cara vc não precisa de display:table, vc pode centralizar de 20 maneiras diferentes, com Flex, com Grid, Com Transform:translate, usar display:table pra isso é coisa do passado. e usar position:absolute tb não é necessário... vou fazer um exemplo pra vc e vc testa no seu projeto pra ver se quebra o layout.
Comment: Cara eu dei uma lida rápida aqui em outras perguntas no STOF em ingles, e não é possível colocar altura em uma tabela, a não ser que essa tabela esteja dentro de uma div que tenha a altura definida e overflow setado, mas ai vc cria uma paradoxo, pq para a altura funcionar vc precisa do display:block da div, mas para alinhar vc precisa do display:table da tabela.... Então de qq forma acho que o Flex foi a melhor opção pra vc nesse caso...
Answer: Como te falei, veja que com display:flex vc alinha o item facilmente, sem precisar de position ou display:table. Funciona do IE 10 para frente de boa. (IE9 é usado por menos de 0,05% das pessoas no Brasil) https://caniuse.com/#search=flex

html, body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}
section {
  width: 100%;
  height: 100%;
  display: flex;
}
.miniatura
{
  margin: auto;
  padding:2%;
  max-width:500px;
  max-height:390px;
  overflow-y: auto;
  background:green
}

      Lorem ipsum dolor sit amet consectetur adipisicing elit. Harum maiores numquam provident, soluta, debitis eveniet tempore placeat deserunt perspiciatis ex exercitationem voluptatem neque esse corrupti doloremque qui laudantium. Praesentium enim ipsam necessitatibus dolor veniam fugiat dicta harum. Minima eveniet totam aspernatur facilis numquam corrupti deserunt. Minus, quisquam ex! Incidunt est deserunt dolore unde dolorem error vitae, nobis cum tempore reprehenderit modi quo eum neque quos, cupiditate esse quaerat commodi earum a sit iusto animi. Exercitationem, neque! Dolorum culpa cumque alias excepturi dolores maxime cupiditate assumenda voluptas harum architecto. Fuga enim quae quis corporis! Ipsum eveniet, fuga voluptate cum corporis iusto nisi aut ipsam mollitia sed unde vitae, quas suscipit sint saepe sapiente ab omnis at exercitationem. Nihil soluta ratione rerum amet ad vel laborum eum unde similique alias accusamus consequuntur sequi est reiciendis, doloribus, perspiciatis voluptas repudiandae vitae debitis dolorem at in quo voluptatibus dolores. Nulla odit natus quas aperiam voluptatem, consequatur, nihil incidunt ipsum ex quo alias ab ipsam provident distinctio sint sunt cum obcaecati voluptatibus enim, aut porro. Beatae eveniet voluptatum iusto consequuntur magnam doloremque accusantium maiores dolore necessitatibus corporis saepe, earum nulla amet? Laudantium labore beatae expedita. Perspiciatis placeat quos expedita dignissimos! Deleniti sed voluptatum dolor obcaecati, iste reiciendis repellat exercitationem dolorem necessitatibus? Amet quaerat nemo veritatis quis maxime quae doloribus nostrum, ea minus fuga ad nesciunt alias aspernatur illo ipsam voluptates delectus voluptas aperiam iusto libero. Facilis provident eveniet nemo consequatur voluptatibus aliquid, at libero ipsa exercitationem qui officia atque dolore adipisci odio perspiciatis ex voluptate deleniti nam tenetur soluta ipsum quod quas voluptatem odit? Beatae atque, cumque neque itaque dolor earum quam sit eum corporis facilis dolores quos harum adipisci fugit recusandae esse dicta soluta praesentium eos, sint quis ullam consequatur accusantium. Deleniti iure neque iusto illo esse rem rerum asperiores veniam soluta non? Expedita!

Answer: O problema não está no código e sim no conceito de box-model do CSS, pois por default elementos como a
 são do tipo block-level.
Quando você defini um valor de display, algumas propriedades passam a ser comportar de forma diferente, afinal a
 não é mais block-level e sim table, assim como inline-level.
Por fim seu código está ok, porém o que deve ser analisado é o contexto do elemento div - table, ou melhor dizendo seu parent (pai).
Abaixo um exemplo sem excessos usando CSS 2.1:
simples diplay Table

como usar max-height e display table


Identificar o ID/Número de cada Shape de Caixa de Texto

Question: Comecei a usar o VBA para o powerpoint e precisava começar a referenciar no meu código cada Shape dentro da apresentação. Mas não sei qual é o nome de cada Shape para referenciar. Como sei que uma caixa de texto é o shape(1), shape(2) ou shape(40).
Detalhe, eu estou trabalhando com powerpoints prontos, ou seja, não sei a ordem com que cada shape foi criada.
Existe algum lugar que eu possa consultar o número de cada Shape?
Comment: Qual é a alteração que você quer fazer em cada Shape? É uma alteração massificada, ou individual? Neste caso, depende do quê (conteúdo do shape, cor, forma)? Esclareça melhor a pergunta!
Comment: Na verdade, eu gostaria de alterar tanto texto e cor, bem como substituir um shape por outro quando necessário. Minha idéia é gerar um material publicitário de forma automática conforme algumas condições definidas pelo o usuário, mas para isso preciso alterar diversas informações do slide
Comment: Ainda não estou entendendo bem uma coisa: você quer:
(1) em tempo de execução, sem supervisão humana, descobrir o tipo e a referência de todos os Shapes e aplicar automaticamente mudanças em alguns deles, ou você quer (2) enquanto está programando o código, com um arquivo-exemplo aberto, descobrir como referenciar uma ou outra forma que você vê naquele arquivo específico, para experimentar o que você consegue fazer com AQUELA caixa de texto DAQUELA apresentação powerpoint que está aberta à sua frente?
Comment: Estou querendo fazer o 2. Dada uma apresentação, alterar um Shape específico conforme as instruções do meu código. Para isso, preciso saber referenciar cada shape da apresentação e é isso que não estou conseguindo
Answer: Caixas de Texto
Se você deseja obter somente de caixas de texto como da imagem abaixo:

A propriedade .HasTextFrame pode ser usada num loop em todas apresentações e shapes.
Código
Dim sld As Slide
Dim shp As Shape

    For Each sld In ActivePresentation.Slides
        For Each shp In sld.Shapes

            If shp.HasTextFrame Then
                Debug.Print "Texto: " & shp.TextFrame2.TextRange & " " _
                ; "ID: " & shp.Id & " " _
                ; "Nome: " & shp.Name
            End If

Next shp
Next sld

Todos os Shapes
Já para todos os Shapes da apresentação, você pode obter o Tipo, ID e Nome.
Código
Dim sld As Slide
Dim shp As Shape
Dim sr As Series
Dim txt As Chart

    For Each sld In ActivePresentation.Slides
        For Each shp In sld.Shapes
                Debug.Print "Tipo: " & shp.Type & " " _
                ; "ID: " & shp.Id & " " _
                ; "Nome: " & shp.Name
Next shp
Next sld

Lista de Tipos
+----------------------+-------+----------------------------------+
|         Nome         | Valor |            Descrição             |
+----------------------+-------+----------------------------------+
| msoAutoShape         |     1 | AutoForma.                       |
| msoCallout           |     2 | Texto Explicativo.               |
| msoCanvas            |    20 | Tela.                            |
| msoChart             |     3 | Gráfico.                         |
| msoComment           |     4 | Comentário.                      |
| msoContentApp        |    27 | Suplemento de conteúdo do Office |
| msoDiagram           |    21 | Diagrama.                        |
| msoEmbeddedOLEObject |     7 | Objeto OLE incorporado.          |
| msoFormControl       |     8 | Controle de formulário.          |
| msoFreeform          |     5 | Forma Livre.                     |
| msoGraphic           |    28 | Elemento gráfico                 |
| msoGroup             |     6 | Grupo.                           |
| msoIgxGraphic        |    24 | Gráfico SmartArt                 |
| msoInk               |    22 | Tinta                            |
| msoInkComment        |    23 | Comentário à tinta               |
| msoLine              |     9 | Linha                            |
| msoLinkedGraphic     |    29 | Gráfico vinculado                |
| msoLinkedOLEObject   |    10 | Objeto OLE vinculado             |
| msoLinkedPicture     |    11 | Imagem vinculada                 |
| msoMedia             |    16 | Mídia                            |
| msoOLEControlObject  |    12 | Objeto de controle OLE           |
| msoPicture           |    13 | Imagem                           |
| msoPlaceholder       |    14 | Espaço reservado                 |
| msoScriptAnchor      |    18 | Âncora de script                 |
| msoShapeTypeMixed    |    -2 | Tipo de forma misto              |
| msoTable             |    19 | Tabela                           |
| msoTextBox           |    17 | Caixa de texto                   |
| msoTextEffect        |    15 | Efeito de texto                  |
| msoWebVideo          |    26 | Vídeo da Web                     |
+----------------------+-------+----------------------------------+

Obs. 1: Veja A documentação de Shapes para mais informações
Obs. 2: Para visualizar o que é impresso com o comando Debug.Print, é preciso habilitar a janela de Verificação Imediata.


How can one print out the fully qualified type of a Chapel variable?

Question: To print out the type of a variable, I normally just use
<code>writeln(x.type : string);
</code>
However, this doesn't print out the fully qualified name (which is useful when one is debugging shadowed variables). Is there a way to do this?
Comment: @brad -- yes. Just to give this more context, this was prompted by https://github.com/chapel-lang/chapel/issues/11907 which was caused by one variable shadowing another.
Comment: To clarify: By "fully qualified" do you mean "including the name of the module in which it was defined?"
Answer: Unfortunately, I don't think Chapel has any support for that today.  Off the top of my head, it seems like it would be reasonable to request a routine in the Reflection module that would take a symbol as an argument and give back its fully qualified module path as a string.  If that would be of interest, I'd suggest opening a feature request on Chapel's GitHub issues page.
Comment: done. For future reference, this can be tracked here : https://github.com/chapel-lang/chapel/issues/11925


Acceptable extensions in file dialog

Question: How can I set acceptable extensions in file dialog using JSP and Spring MVC? This is how I do:
<form:form method="post" enctype="multipart/form-data"
        modelAttribute="uploadedFile" action="fileUpload">

                Upload File:
                <input type="file" name="file" />
                <form:errors
                        path="file" />

                <input type="submit" value="Upload" />

    </form:form>

Can I do something like this with Spring:
<input type="file" name="file" ext="xml, txt"/>

Answer: Try this..

<input type="file" name="fi" accept="text/xml, text/plain"/>

You don't need spring to do this. It is just simple HTML.

Acceptable extensions in file dialog