Qual a diferença de DLL e lib?

Question: Sei que .dll e .lib são bibliotecas, a primeira é dinâmica e a segunda é estática. Mas o que isso realmente quer dizer? Como cada uma funciona?
Se eu tiver que gerar uma biblioteca a partir de um código, o que eu devo ter em mente para decidir se eu faço uma .dll ou uma .lib?
Comment: ve se isso te ajuda http://www.differencebetween.net/technology/difference-between-lib-and-dll/
Answer: Conceituação inicial
Aplicação e executável são coisas diferentes. Aplicação é um conjunto de coisas (eventualmente pode ser só o executável quando é algo muito simples), de funções, tarefas, atividades que beneficiam o usuário, é um conceito mais abstrato. Quando um executável principal (EXE no Windows) precisa de uma DLL ele já não representa sozinho a aplicação. Se sem a DLL a aplicação não funciona, se o executável tem dependências, a aplicação certamente não se confunde com o executável.
Comparação

DLL
LIB

Vários arquivos executáveis
Um arquivo monolítico

DLL/Dependency Hell
Incompatibilidades entre bibliotecas

Aplicações no geral ficam maiores
Executável fica maior

Permite carregar códigos não previstos
Tudo que for necessário precisa estar no executável

Não permite certas otimizações
Otimizações globais são possíveis

Carga mais lenta pera mapear todos os símbolos
Carga mais rápida, todos os vínculos estão prontos

Pode ser usada livremente com LGPL
Precisa de uma licença comercial ou mais liberal

Permite reusa de binários distribuídos
Duplica binária comum durante o build

Melhor interação com ferramentas de terceiros
Só interage se a ferramenta gera executável custom

Permite injeção de código malicioso facilmente
Dificulta injeção de código malicioso

Permite um binário canônico
Risco de confusão entre versões

Alguns itens dependem da forma como a biblioteca é criada/usada.
Biblioteca estática
Uma biblioteca estática não pode ser usada por uma aplicação diretamente, não pode ser executada. Ela é usada para gerar um executável (EXE, DLL) de uma aplicação. Ela é necessária para o processo de montagem do executável, o que frequentemente chamamos de tempo de compilação (embora tecnicamente isto seja feito após a compilação propriamente dita).
A biblioteca é composta por diversos arquivos chamados objetos que são gerados pelo compilador. Na verdade é possível inserir estes objetos na aplicação mesmo sem a existência da LIB que é uma forma de agrupar e facilitar o trabalho de construção da aplicação. Estes arquivos são unidades de compilação. Existem utilitários para administrar estes arquivos na LIB.

Quando você usa uma função de uma destas unidades de compilação todo o objeto é incluso no executável (que pode ser chamado de monolítico se não depende de nada externo).
Os objetos que não possuem funções referenciadas por sua aplicação não entram mesmo que eles tenham sido indicados para seleção durante a linkedição. O processo de linkedição é inteligente neste aspecto. A vinculação (binding) da função com a aplicação é feita em tempo de linkedição ao contrário da biblioteca dinâmica onde isso é feito em tempo de execução.
Note que o termo correto é "tempo de linkedição" e não "tempo de compilação". As bibliotecas são montadas ou vinculadas à uma aplicação após o código já ter sido compilado.
Em bibliotecas bem construídas os objetos devem conter apenas funções que devem ser usadas obrigatoriamente juntas, como os métodos de uma classe, por exemplo.
Biblioteca dinâmica
Uma DLL/SO é um executável independente em um arquivo independente. É possível até mesmo executá-la como um executável normal sob certas circunstâncias. Nela também tem esses objetos (são binários).
A definição de quais objetos estão lá é responsabilidade de quem construiu a DLL (ou SO, falo mais em DLL para simplificar), assim como em um executável normal. A DLL pode conter muita coisa que sua aplicação não precisa e o executável não chama. E se a(s) DLL(s) não contiver(em) tudo que sua aplicação precisa, você terá problemas durante a execução.
A não ser que esteja usando o .NET, onde as DLLs funcionam de forma especial já que não são códigos nativos, não é possível administrar o conteúdo depois que o arquivo for gerado.
Uma DLL tende a ser maior por causa destes possíveis códigos desnecessários que são pré-vinculados e porque ela precisa de informações adicionais para efetuar a chamada dinâmica. Isto nem sempre é uma grande desvantagem mas é bom ter isso em conta.
É possível usar uma técnica de carga sob demanda que permite que uma DLL que não seja efetivamente usada pela aplicação em uma execução específica não seja carregada na memória.
Mas uma DLL específica não pode carregar apenas as funções que serão usadas pela aplicação, até porque ela nem sabe o que será usado. É tudo ou nada (na verdade em nível mais baixo isso não é bem assim, mas é um controle da memória virtual e não dos objetos).
Dado o problema de DLL Hell (em inglês) e dependência (em inglês) cada vez mais frequente, as vantagens da DLL ficam cada vez menores já que para solucionar estes problemas costuma-se evitar o reuso do binário e opta-se pela distribuição das DLLs necessárias junto com o executável principal.
No fim temos a DLL só porque todo mundo faz assim. Eu vivo falando que os desenvolvedores, especialmente os mais novos, não pensam no todo, seguem fórmulas.
Além disso, conforme já foi dito, algumas otimizações não são possíveis nestas condições a não ser que o código execute em uma máquina virtual (.NET, Java) que normalmente prepara o ambiente e faz as últimas otimizações em tempo de execução (o que tem um custo).
No .NET a vinculação é feita em tempo de execução - feito pelo JITter - o que torna possível fazer algumas otimizações até melhores do que o linkeditor estático faria. É um processo semelhante ao do Java. O .NET Native permitirá binários, obviamente nativos, monolíticos.
Guia de escolha pela DLL

Sua aplicação usa alguma API externa que só está disponível por DLL ou há alguma praticidade real em optar pela DLL.
Você tem a opção de linkagem estática ou dinâmica mas a licença que você precisa só permite a dinâmica (Qt por exemplo que usa LGPL).
A aplicação precisa de flexibilidade e tem um sistema de plugin nela que utiliza códigos executáveis que podem ser chamados no processo vinculando o código novo ao executável principal.
Linkar estaticamente duas bibliotecas está causando algum conflito ou dificuldade e dinamicamente resolve.
Você está produzindo algo que deve ser usado com uma aplicação que espera uma DLL. Pode ser porque aquele código precisa ser garantidamente único entre aplicações ou terceiros precisam disto (uso com outra linguagem) ou ainda é um plugin.
Sua aplicação faz parte de uma solução maior ou uma gama ampla de produtos que costumam ser instalados na mesma máquina e tem muitas partes em comum. Pense um pouco mais se deve usar DLL ou não. Eu tendo a não usar. Hoje o reuso do binário é um argumento fraco na maioria dos casos.

Muitas vezes o benefício não compensa o prejuízo, estamos no século XXI, não temos os mesmos problemas do século passado. Ou seja, opte pela DLL/SO quando você não tem outra opção ou está tendo um problema difícil de ser solucionado de outra forma.
Conclusão
O uso de DLL tende deixar a aplicação maior e mais lenta. Apesar de que isto não seja um grande problema na maior parte dos casos. O uso de DLL pode dar a falsa impressão que a aplicação fica menor baseada no tamanho do executável principal. Mas a aplicação é mais do que ele.
Se puder escolher, a primeira opção deveria ser o uso de biblioteca estática e só se houver um motivo específico para usar a biblioteca dinâmica é que ela deveria ser escolhida.
Um único executável facilita a manutenção, depuração, implantação e diagnóstico sem falar na confiabilidade da aplicação que tem menos dependências após construída como já citado nesta e outra resposta.
Mas se for necessário ter uma biblioteca dinâmica, deixe para usar só onde é necessário. Ou seja, dá para fazer um misto. Uma forma não impede a outra. Crie um executável principal com o máximo de código embutido e use arquivos auxiliares no que for estritamente necessário, com isto você diminui a superfície de risco.
Enfim, o assunto é amplo, dá para fazer dezenas de perguntas e não esgotar tudo o que tem para falar.
Artigo na Wikipedia (em inglês).
Coloquei no GitHub para referência futura.
Comment: `O uso de DLL tende deixar a aplicação maior e mais lenta`, a aplicação não deveria ficar menor? Pois o executável não incorpora a biblioteca em seu binário. Ou com "aplicação" você queria dizer "biblioteca"? E tem um typo: "disgnóstico".
Comment: Não, este é um erro clássico. Nos detalhes a resposta mostra que ocorre o oposto. A DLL faz parte da aplicação. O máximo que pode acontecer é dar a ilusão dela estar menor na distribuição dela **se** você puder ter certeza que a DLL apropriada já está no computador do usuário. Você pode garantir isto? Não. Então tem que mandar ela junto. Se estiver você pode usá-la ao invés de instalar a sua que é igual, mas corre o risco do DLL Hell. Você acha que isto deixa a aplicação menor? Tem algum ganho? Espaço em disco era problema no século passado. Na memória que é o mais importante c/ ctz fica maior
Comment: Entendi, então: `código+dll` > `código+lib`. A diferença é que quando usa a `lib` o `exe` fica maior, quando usa a `dll` a distribuição fica maior. Correto? É que por "aplicação" eu estava entendendo como `exe`. Agora acho que ficou claro para mim.
Comment: O que pode acontecer na memória é a carga acontecer de forma atrasada e por algum momento não consumir a memória mas quando a DLL carregar provavelmente carregará coisas que a aplicação não precisa. É verdade que se **dependendo** de como a aplicação for feita, se você não usar determinada função, a DLL não será carregada. Eu entendi sua comparação mas para conceitar certo `exe+dll > monolithic exe`. A `lib` faz parte do exe, ela não pode ser dissociada. O `exe` fica maior, e daí se ele precisa e outras coisas? Não adianta ganhar um brinde e pagar o todo mais caro do que se comprasse o brinde.
Comment: trabalhei a um tempo atras em um sistema que registra as `dll` como objeto COM no servidor de aplicação e os terminais de aplicação se conectavam via RPC nesse servidor, acho que hoje os programadores estão mais preocupados em separar em camadas para seguir algum design patterns do que realmente usufruir do uso da `DLL` como uma  biblioteca para ser usada uma unica vez em todas as aplicações que foram publicadas no servidor.
Comment: confesso que sou um desses, pois no mesmo servidor, tenho o mesmo sistema rodando para clientes diferentes e para cada instância do sistema, tenho as mesmas `DLLs` que poderiam ter sida registras no windows e serem compartilhadas entre os sistemas
Answer: Ambas tem a mesma finalidade: são bibliotecas que permitem reutilizar um determinado código. Uma é estática (*.lib, *.a) e a outra dinâmica (*.dll ou *.so). Isso você já sabe.
Mas as diferenças são:

As bibliotecas estáticas aumentam o tamanho do binário gerado, pois elas são "embutidas" ao seu próprio código. Enquanto as dinâmicas são armazenadas em um arquivo a parte e são carregadas em tempo de execução.
Um programa pode carregar um biblioteca dinâmica de uma versão diferente da original, o que permite que você atualize apenas a biblioteca sem ter que recompilar o código principal. O que é bom, mas tem que tomar alguns cuidados (DLL Hell ou Dependency hell).
Como as bibliotecas estáticas são incluídas ao binário do programa principal, é possível que o compilador execute otimizações entre o seu código e o código da biblioteca.
Em comparação com as estáticas, as bibliotecas dinâmicas consomem um tempo para serem carregadas (isso na maioria dos casos não é problema). E algumas funções, que poderiam ter sido otimizadas, não são (otimizadas para inline, por exemplo).
Vários programas diferentes podem reutilizar a mesma biblioteca dinâmica.
As dlls das bibliotecas dinâmicas devem ser distribuídas junto com o programa principal, no caso das estáticas isso não é necessário.
Há questões legais que exigem o uso de bibliotecas dinâmicas em vez de estáticas. Por xemplo: códigos licenciados em LGPL podem ser utilizadas para fins proprietários, mas apenas em forma de biblioteca dinâmica.
Uma biblioteca dinâmica escrita em C ou C++ pode ser reutilizada em um programa escrito em outra linguagens. Por exemplo, python pode usar uma dll feita em C utilizando o módulo ctypes.
Comment: @Math Várias aplicações podem acessar a mesma DLL ao mesmo tempo. Esta é uma vantagem. Mas cada vez é mais difícil isto realmente acontecer e só costuma acontecer em DLLs muito estáveis que fazem parte do sistema operacional. O reuso não é uma das melhores vantagens da DLL hoje em dia. O reuso neste caso é do **binário final**. Pense bem, isto ajudava quando os computadores mal passavam de bem poucos MB e os HDDs mal chegavam aos GBs. O ganho hoje é irrisório na maioria dos casos e a prática mostrou que é comum nem ter esse ganho. DLL criou um problema e para solucioná-lo criou-se outro.
Comment: Python só consegue usar uma biblioteca em C se for dinâmica? As linguagens que eu uso que permitem o uso destas bibliotecas podem montar executáveis que incluem as bibliotecas C.
Comment: `Vários programas diferentes podem reutilizar a mesma biblioteca dinâmica.` você quer dizer que uma única biblioteca dinâmica pode ser acessada por vários programas **ao mesmo tempo**, correto? Enquanto a lib, é carregada na memória embutida no executável principal, por consequência não pode ser acessada por outros programas. Pois "reutilizável", as duas bibliotecas são: `Ambas tem a mesma finalidade: são bibliotecas que permitem reutilizar um determinado código`
Answer: Resumidamente, uma DLL é uma biblioteca que contém funções, as quais podem ser chamadas em tempo de execução pela aplicação, dando assim um dinamismo no seu uso.
Já a LIB é uma biblioteca estática podendo seus métodos só serem invocados em tempo de compilação.
Logo o uso de LIB resultaria em um arquivo maior, que poderiam ser divididos com o uso de DLLs, tornando assim as DLLs mais reutilizáveis, mas em contra partida o uso de DLLs tem-se um problema com o seu versionamento.
O dinamismo do uso da DLL está ligado ao fato de a mesma DLL proporcionar um compartilhamento entre diferentes programas em execução.
Tempo de execução ou runtime (termo em inglês), é o período em que um programa de computador permanece em execução. O termo runtime também pode se referir a uma máquina virtual que gerencia um programa escrito em uma linguagem de computador enquanto está sendo executado.
O termo tempo de execução é um contraponto ao termo tempo de compilação, que é uma referência ao período em que o código é compilado para gerar um programa executável.
Vantagens DLL
A lista a seguir descreve algumas das vantagens que são fornecidas quando um programa usa uma DLL:

Usa menos recursos: Quando vários programas usam a mesma biblioteca de funções, uma DLL pode reduzir a duplicação de código que é carregado no disco e na memória física.
Promove a arquitetura modular: Uma DLL ajuda a promover a desenvolver programas modulares.
Instalação e implantação de atenuações: Quando uma função em uma DLL precisa de uma correção ou uma atualização, a implantação e a instalação da DLL não requer o programa a ser vinculados novamente com a DLL.

Resumindo
Ao usar LIB ao final da compilação tudo fará parte de um executável, com a utilização da DLL tem-se uma fragmentação dos módulos do executável, podendo esses módulos serem utilizados após a compilação do executável.
Fonte: http://www.differencebetween.net/technology/difference-between-lib-and-dll/
Comment: Por que a função chamada em tempo de execução dá dinamismo? O que significa `uma função ser chamada em tempo de execução` e `um método ser invocado em tempo de compilação`? No final das contas o executável não vai usar os dois tipos de bibliotecas do mesmo jeito? A única diferença é o tamanho maior do executável quando usa lib? Por que a dll é mais reutilizável que a lib?
Comment: @Math toda função é chamada em tempo de execução e método "nunca" é invocado em tempo de compilação (até tem algo raramente usada e não faz diferença para essa pergunta), provavelmente é só o uso errado de nomenclatura. O que ele talvez tenha tentado falar é quando ocorre a vinculação da função. Editei minha resposta para refletir isto.
Comment: @Math, nesse caso tempo de execução é o de execução do compilador e não do programa.
Comment: Dei uma editada na minha resposta com base em mais conteudo que estudei sobre o assunto.

Qual a diferença de DLL e lib?


Average number of bits required to store one letter of British English using perfect compression in python

Question: I have an assignment which is written under:
What is the average number of bits required to store one letter of British English if perfect
compression is used?
Since the entropy of an experiment can be interpreted as the minimum number of bits required to store its result. I tried making a program calculating the entropy of all letters and then add them all together to find the Entropy of all letters.
this gives me 4.17 bits but according to this link
With a perfect compression algorithm we should only need 2 bits per character!
So how do I implement this perfect compression algorithm on this?
import math
letters=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
sum =0

def find_perc(s):

perc=[0.082,0.015,0.028,0.043,0.127,0.022,0.02,0.061,0.07,0.002,0.008,0.04,0.024,0.067,0.075,0.019,0.001,0.060,0.063,0.091,0.028,0.01,0.023,0.001,0.02,0.001]

letter=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
pos = 0
temp = s.upper()
if temp in letter:
    for x in xrange(1,len(letter)):
        if temp==letter[x]:
            pos = x
return perc[pos]

def calc_ent(s):
P=find_perc(s)
sum=0
    #Calculates the Entropy of the current letter
temp = P *(math.log(1/P)/math.log(2))

    #Does the same thing just for binary entropy (i think)
#temp = (-P*(math.log(P)/math.log(2)))-((1-P)*(math.log(1-P)/math.log(2)))
sum=temp
return sum

for x in xrange(0,25):
    sum=sum+calc_ent(letters[x])

print "The min bit is : %f"%sum

Comment: Note that the author is on SO: @Matt Mahoney but not really active.
Answer: There is no such thing as perfect compression, since it is provably impossible to compute the number of bits if "perfect compression" is applied.  See Kolmogorov Complexity.
You will not be able to implement a compressor in a few lines of code that approaches what appears to be the limits of the compressibility of English text by computer programs, around one bit per character.  Humans may be able to do a little better.
Comment: @Becktor http://en.wikipedia.org/wiki/Mark_Adler Now I believe that whatever Mark told us on this is right:) +1
Comment: If instead we describe what the OP intended to do as "per-charcter perfect compression", will that be okay? Or maybe it already has some different canonical name?
Answer: The page you link to again links to this page:
Refining the Estimated Entropy of English by Shannon Game Simulation
If you read carefully, the entropy computed there is not naively computed using the probability of occurrences for each letters - instead, it is computed by

The subject was shown the previous 100 characters of text and asked to guess the next character until successful

So I think you are not wrong, only the method you use differ - using only naive occurrence probability data, you cannot compress the information that well, but if you take the context into consideration, then there are so much more the redundant information. E.g., e has a probability of 0.127, but for th_, e probably has something more like 0.3.
Comment: Also as any cryptographer will tell you (well linguist really), there are many more rules in English for that kind of thing. For example q is pretty much always followed by a u, etc.
Comment: Okay! I think what was throwing me off was "perfect compression". So finding the entropy is the same as the size of perfect compression?
Comment: Yeah but this assingment was for one letter only not for common duplets and triplets
Comment: Should be since the entropy is the information, and you cannot use any bit less to represent the information. Since the assignment is for one letter, I guess your answer should be fine - it is just as if you are working with a shuffled English text, with the same letter distribution but the other information destroyed.


ASP.NET repeater dynamic value

Question: I try to use a repeater in repeater in ASP.NET, but I want to change datasource from every repeat.
My aspx markup is:

    <asp:Repeater ID="RepeaterKategori" runat="server" OnItemDataBound="ItemBound">
        <ItemTemplate>

<%#Eval("kategoriAd") %>

                <asp:Repeater ID="RepeaterAltKategori" runat="server">
                    <ItemTemplate>

                                <img src="<%#Eval("altkategoriResim") %>" class="card-img-top" alt="...">

<%#Eval("altkategoriBaslik") %>

<%#Eval("altkategoriAciklama") %>

                                    Teşekkürler : <%#Eval("altkategoriDestekci") %>

                    </ItemTemplate>
                </asp:Repeater>

                Tümünü Görüntüle

        </ItemTemplate>
    </asp:Repeater>

My aspx.cs code behind is:
rehber kod = new rehber();

protected void Page_Load(object sender, EventArgs e)
{
    RepeaterKategori.DataSource = kod.getDataTable("SELECT KategoriAd FROM kategoriler");
    RepeaterKategori.DataBind();
}

protected void ItemBound(object sender, RepeaterItemEventArgs args)
{
    if (args.Item.ItemType == ListItemType.Item || args.Item.ItemType == ListItemType.AlternatingItem)
    {
        DataTable katsay = kod.getDataTable("SELECT * FROM altkategoriler");
        int kategoris = katsay.Rows.Count;

        for (int i = 1; i == kategoris; i++)
        {
            Repeater RepeaterAltKategori = (Repeater)args.Item.FindControl("RepeaterAltKategori");
            RepeaterAltKategori.DataSource = kod.getDataTable("SELECT TOP 3 * FROM altkategoriler WHERE kategoriId="+i+"");
            RepeaterAltKategori.DataBind();
        }
    }
}

I want another id data like 1,2,3,4 for every repeat. How can I do this? Thanks..
Answer: You need to nest two repeaters then.
You have
top table - feed the main repeater - 1 record for each.

child table - feed the child repeater - child table - many records for each.

Also, make sure you ALWAYS use if (!isPostBack) to have a real first page load - if you don't do most (if not all) of your loading and databinding inside of the !IsPostback?
you cannot even really quite much build a working page that can survive post-backs.
Ok, so we have the master (top) repeater.
for the child repeater, you might have one record, maybe many. It don't matter. But WHAT DOES matter is you now have a whole new seperate data set and whole new set of Eval() and binding that belongs to that child table or child data set.
So, lets take a main repeater (our hotels), and for each instance, we drop in another repeater to display the child data (in this case people booked in the hotel).
So, we have this mark-up - note the nested 2nd repeater.
        <asp:Repeater ID="repHotels" runat="server" OnItemDataBound="repHotels_ItemDataBound">
            <ItemTemplate>
                <asp:Label ID="txtHotel" runat="server" Width="240px"
                    Text='<%# Eval("HotelName") %>' Font-Size="X-Large"                 >
                </asp:Label>

                <asp:TextBox ID="txtDescription" runat="server"
                    Text='<%# Eval("Description") %>'
                    TextMode="MultiLine" Rows="5" Columns="40" Style="margin-left:20px" >
                </asp:TextBox>

People Booked

                <asp:Repeater ID="repPeopleBooked" runat="server">
                    <ItemTemplate>
                        <asp:Label ID="lFirst" runat="server" Text='<%# Eval("FirstName") %>'>
                        </asp:Label>
                        <asp:Label ID="lLast" runat="server" Text='<%# Eval("LastName") %>'
                            style="margin-left:10px">
                        </asp:Label>

                    </ItemTemplate>
                </asp:Repeater>
                <%-- our repeat separator --%>

            </ItemTemplate>
        </asp:Repeater>

And our code to load. We ONLY load the main repeater data source, and THAT will trigger the item data bound event, and in that event then we deal with EACH separate instance of the child repeater.
Code like this:
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            LoadData();
    }

    void LoadData()
    {
        SqlCommand cmdSQL = new SqlCommand("SELECT * from MyHotels ORDER BY HotelName");

        repHotels.DataSource = MyRstP(cmdSQL);
        repHotels.DataBind();
    }

    protected void repHotels_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if ( (e.Item.ItemType == ListItemType.Item) ||
            (e.Item.ItemType == ListItemType.AlternatingItem))
        {
            // get child nested repeater
            Repeater rChild = e.Item.FindControl("repPeopleBooked") as Repeater;

            DataRowView rRow = ((DataRowView)e.Item.DataItem);
            string strSQL = "SELECT * FROM People WHERE Hotel_ID = @id";
            SqlCommand cmdSQL = new SqlCommand(strSQL);
            cmdSQL.Parameters.Add("@id", SqlDbType.Int).Value = rRow["ID"];

            rChild.DataSource = MyRstP(cmdSQL);
            rChild.DataBind();

        }
    }
    public DataTable MyRstP(SqlCommand cmdSQL)
    {
        DataTable rstData = new DataTable();
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
        {
            using (cmdSQL)
            {
                cmdSQL.Connection = conn;
                conn.Open();
                rstData.Load(cmdSQL.ExecuteReader());
            }
        }
        return rstData;
    }

and we now get this:

So, we see the 3 main records that drive the main repeater, and then we see the child records for the nested repeater.
Now, in your case, you might only ever have one child record - but it don't matter. What really matters is that you have the ability to deal with, and bind, and have separate Eval() and data for that child repeater.
Comment: Dude thank you so much, you are so kind but its so hard for me. I just want to my repeater datasource "id" grownin at every repeat like thist:

First repeat datasource is id 1 Second repeat datasource is id 2 ....

Thanks again for everything
Comment: Ok, but the repeating change is for the child or "inner" repeater? So, you are free to shove or put in any child data or change the data source of that inner repeater to whatever you want. Note how the outer repeater we get the data row, and are free then to fill the inner repeater with any data, or any data source you want. Note how I pulled the "ID" from the main repeater, and then used that to set the child repeat. So, drive the main outer repeater as you have with kategoriler, and then you are free to fill child repeater with your top 3 or whatever.

ASP.NET repeater dynamic value


prevent parent DOM manipulation for a child iframe script

Question: I have a page containing another page on the same domain inside a frame. Is it possible to prevent that a script in the framed page can manipulate the top page DOM (for example adding an element or a script)?
Answer: You could experiment with getting rid of "dangerous" functions but saving anonymous references to them something like..
(function(){
    var hiddenrefs = {};

    hiddenrefs.dGetElementById = document.getElementById;
    document.getElementById = null;
})();

and so on. However, this would be a very tedious job and bound to fail anyway. If this is an attempt to let users run Javascript in a controlled environment inside an iframe, this is a misguided form of security. The iframe could just issue top.location = "http://www.myevilpage.com" in which case it's game over for you anyway. (This is true even with a different domain. The iframe can still redirect the user and all sorts of nasty stuff, even if it strictly speaking can't access the parent's DOM.) Letting users run JS code is never ever safe without filtering the source code for malicious code, and even with filtering it's fairly unsafe because it's mostly easy to bypass the filtering. Many have tried and many have failed. I'd recommend not letting users run Javascript, ever.
Answer: The best solution is probably to use the HTML5 sandbox attribute on the iframe, which (by default) explicitly disables both scripting and same-origin access to the parent DOM.
See http://msdn.microsoft.com/en-us/hh563496.aspx


Mosquitto not starting

Question: I posted this on stack overflow however they reccomended I post it here,
I recently installed the Mosquitto MQTT broker on Windows 11, and I managed to get it working locally between different command prompt windows. However, after restarting my laptop Mosquitto will not start from the services tab. If I try to start it from the services menu I get an error saying:
Mosquitto started and then stopped. Some services stop automatically if they are not in use by other services or programs
If I try to start it through the command line with sc mosquitto start it appears to start normally. However, if I try to publish or subscribe to a topic it gives me the error:
no connection could be made as the target machine actively refused it
I had edited the mosquitto.conf file so I tried undoing my edits by replacing my version with an unedited version from GitHub, but it didn't change anything.
Comment: The default config has the same impact as a blank file (all options are commented out) so try emptying the config. It's also worth trying to run it manually (`cd C:\Program Files\mosquitto` then `.\mosquitto.exe -v -c mosquitto.conf`. If that starts without issue, it's worth checking the `MOSQUITTO_DIR` environmental variable (this determines the determines where Mosquitto looks for the config when running as a service).
Comment: @Brits Thanks for that, I tried running running it manually and I got the following error:  1697098990: Error: Empty acl_file value in configuration.
1697098990: Error found at mosquitto.conf:20.
Comment: Check line 20 of the `mosquitto.conf`.
Comment: Thanks for your help. Line 20 had nothing in it. I ended up fixing the problem by uninstalling and reinstalling mosquitto. Thanks @brits
Answer: This was fixed by uninstalling and reinstalling mosquitto.
Thanks

Mosquitto not starting


Over represented gender in linear modelling data

Question: I am fitting a model to some sales data and looking to accurately represent male/female behaviour (e.g basket analysis).
For example, I know the proportion of females/males in the population buying these products are 50:50, and my products are identical to competitor products, however, my data contains 30% females and 70% males. I believe this may bias my model, and from what I can learn, I need to apply a weighting function.
I am using R and lm() to model. If using weighting is the right way to go, how is it represented in lm(x,y,weighting=)? E.g. do males receive a weighting of .3 to counter their over representation? or what would be the appropriate weighting in this case?
Answer: Your population of interest is the set of people that have bought something from your company--not the overall population of all living humans around the world...
If your sales data represents that of the entire company then you have your population data right there. If not, is your data a simple random sample? Or is there reason to suggest a systematic bias in the way the data was collected? (The mere fact that 70% of the data comes from men does not necessarily mean that your data is biased--it could just mean that 70% of your customers are men).
Suggestion: Your first step should be to test whether the average sale generated from a male buyer is different from that of a female buyer--if they aren't different than there's no point worrying about prediction on the basis of sex. My suggestion is that you use Welch's t-test (it's like a regular t-test but the variances don't necessarily have to be equal) and first test to see if the buying habits really are different.
First do this and then save the prediction stuff for later.

EDIT:
The best (and also the easiest) approach is to analyze your data according to either a per-customer (if possible) or a per-sale basis--that way you won't have to worry about the discrepancy in representation between men and women. This approach will simplify your current step but also lead to a more nuanced analysis down the road since you'll be able to decompose total revenue into:

Avg. revenue generated per sale
Total number of sales

Make sense?
Comment: Thanks Steve, you're right, my question looked silly after what you said. I am trying to put it as simply as I can, I've reworded the question accordingly.
Comment: @user13506: It's not silly--it's a perfectly valid issue to raise... I'll try to edit my answer accordingly.


Algorithm to estimate aggregated outcome variable

Question: I am looking for an algorithm that can estimate weights for an aggregated weighted average. The difficulty is that my outcome variable is an aggregated group variable.
I have the following data that could train an algorithm:
There are N groups. Say, for each group there are 3 observations that each makes up one row. Each row includes y* and n explanatory variables. For each group, there is an outcome variable y. The following table gives an example of the data:
<code>+------+----+---------------+-----+---------------+-------+
|  y   | y* | Explanatory 1 | ... | Explanatory n | Group |
+---------------------------------------------------------+
|      | 3  |        1      | ... |      500      |   1   |
+      ---------------------------------------------------+
|      | 3  |        0      | ... |      1214     |   1   |
+      ---------------------------------------------------+
| 4.25 | 5  |        1      | ... |      71       |   1   |
+---------------------------------------------------------+
|      | 3  |        1      | ... |      23       |   2   |
+      ---------------------------------------------------+
|      | 2  |        1      | ... |      821      |   2   |
+      ---------------------------------------------------+
| 2.00 | 2  |        1      | ... |      200      |   2   |
----------------------------------------------------------+

</code>
If I had an outcome variable y for each row, I could use a multivariate regression algorithm. Instead, y is a weighted average of all rows of the group. The explanatory variables make up a weight (which is unknown) for y*:
wij y*ij = (ß1*Explanatory 1ij + ... + ßnExplanatory nij) yij
with index i denoting the group and j the row. The outcome variable yi then is the sum of the weighted yij* for all rows of the group.
yi = ∑13(wij yij*)/ N
I am now looking for an algorithm that is able to estimate the weight given the outcome variable y, such that I can estimate a ŷ for each row that takes all observations from preceding rows into account.
This is my first question on StackOverflow. If you have any ideas, how I could clarify my question, please let me know.
Similarly, I am totally new to working with algorithms. All hints are highly appreciated!
Answer: Let me change your notation somewhat:
z = w1 x1 + w2 x2 + w3 x3. The xi are your y*, the wi are the weights.
wi = sum( aij yj ) over j. The yj are the explaining vars.
Then you get
z = sum( wi xi ) = sum( sum( aij yj ) xi ) = sum( aij xi yj ).
So use multivariate regression to estimate the aij. Then use the formula above to estimate the wi.
Comment: Thanks @Henrik4 for answering so quickly! I will try that out!


Continuous functions in Isabelle

Question: I want to define a continuous function on an interval of the real line -- [a,b), [a,b], (a,b), or (a,b] (where a < b and either could possibly be infinite) -- in Isabelle, or state that a function is continuous on such an interval.
I believe what I want is continuous_on s f because
"continuous_on s f ⟷ (∀x∈s. (f ⤏ f x) (at x within s))"
(which I got from here:https://isabelle.in.tum.de/library/HOL/HOL/Topological_Spaces.html#Topological_Spaces.topological_space_class.at_within|const)
So I think "s" should be an interval but I'm not sure how best to represent that.
So I would like to know how I could set "s" to any of the types of set intervals I list above.  Thank you!
Comment: The Zulip chat works fine for me.
Comment: I would like to also add that I wanted to try to post this question on the site recommended from the Isabelle website (https://isabelle.in.tum.de) namely Zulip Chat (https://isabelle.zulipchat.com) but it would not successfully load for me so I am curious if Zulip Chat is still operational or if it is possibly something on my end.
Answer: The answer to your question
In every ordered type you can write {a..b} for the closed interval from a to b. For the open/half-open variants there are {a<..b}, {a..<b}, {a<..<b}, {a..}, {..b}, {a<..}, and {..<b}.
These are defined in HOL.Set_Interval and there internal names are things like lessThan, atLeastAtMost, etc.
So in your case, you can simply write something like continuous_on {a..b} f.
It takes some time to understand how to do arguments about limits, continuity, etc. in a theorem prover efficiently. Don't be afraid to ask, either here or on the Zulip. You can of course always do things the hard way (with e.g. ε–δ reasoning) but once you become more proficient in using the library a lot of things become much easier. Which brings me to:
Addendum: Filters
Note however that to really reason about continuity in Isabelle in an idiomatic way you will have to understand filters, which are (among other things) a way to talk about 'neighbourhoods of points'. There is the definition continuous which takes a function at a filter and can be used to say that a function is continuous at a given point with some conditions.
For instance, there are filters

nhds x, which describes the neighbourhoods of x (i.e. everything that is sufficiently close to x)
at x within A, which describes the pointed neighbourhood of x intersected with A – i.e. you approach x without every reaching it and while staying fully inside the set A
at x, which is simply at x within UNIV, i.e. the pointed neighbourhood of x without further restricitions
at_left x and at_right x for e.g. the real numbers, which are defined as at x within {..<x} and at x within {x<..}, i.e. the left and right neighbourhoods of x

Then you can write things like continuous (at x) F or continuous (at_right x) F. If I recall correctly, continuous_on A f is equivalent to ∀x∈A. continuous (at x within A) f.
Filters are also useful for many other related things, like limits, open/closed sets, uniform continuity, and derivatives.
This paper explains how filters are used in the Isabelle analysis library. It also has a short section about continuity.
Comment: Hi. For some reason this wants to convert reals to their integer part!?  Example: Suppose we have a continuous function f on the interval [a,b] such that f(a)*f(b) < 0  then we know there should be a root.  However, when I state this as:

  assumes a_less_than_b: "(a::real) < (b::real)"
  assumes continuous_f: "continuous_on {a..b} f"
  assumes opposite_signs: "f(a)*f(b)<0"
  shows "∃ (c::real). (f(c) = 0 ∧ a < c ∧ c < b)"

I get the following goal:
"∃c. f c = 0 ∧ real_of_int a < c ∧ c < real_of_int b"
But "real_of_int" takes nats and ints and coerces them to reals!
Comment: Also if I just remove the continuity condition ("continuous_on {a..b} f") (which is obviously necessary for the proof) then my goal is just the "shows" statement.  I'm curious as to why "continuous_on" seems to want integers.
Comment: I cannot reproduce that at all. My guess would be that you already have one of the variables `f`, `a`, `b` floating around in the context with an integer type. Most of your type annotations are also redundant, but what you *are* missing is that the result type of `f` has to be `real`. The easiest way is to add `fixes f :: "real ⇒ real"` to the beginning of your lemma. It can then be proven fairly easily using the theorems `IVT'` and `IVT2'` (the naming scheme for the intermediate value theorem is unfortunately somewhat annoying).

Continuous functions in Isabelle


Calculating contour integral two ways with different results

Question: I'm trying to resolve an apparent contradiction and have yet to find my mistake. The goal is to calculate
$$
I = \int_{\Gamma_R} \frac{1/(w-1)^2}{w-z} dw
$$
where $z \in \mathbb{C}$ is fixed and $\Gamma_R$ is a circle of radius $R$ centered at $1$. Take $R$ to be arbitrarily large. Then the integral is the sum of the poles of the integrand, which is just the pole at $z$ since the pole at $1$ is second order with zero residue. From this approach I find
$$
I = \frac{2\pi i}{(z-1)^2}
$$
On the other hand, it's immediately clear that the integrand goes as $R^{-3}$ while the length of the contour goes as $R$, so that as $R\rightarrow\infty$, $I\rightarrow 0$. From this approach
$$
I = 0
$$
Obviously I have overlooked something. Can anyone help me track down my error?
Comment: @math Why does the pole at $1$ have zero residue?; I get the residue to be minus the residue at $z$ (assuming $z \ne 1$)
Comment: this doesn't resolve everything, but if $z=1$, then you don't have a pole at $1$, since you just have a zero of order $3$ at $1$. but, of course, you can tell me that $z=1.00001$.
Comment: @BrevanEllefsen it is inside. how is the question at all vague? you fix $z$ and then take $R$ very large (larger than $2|z|$, say).
Comment: @Conrad don't second order poles have 0 residue?
Comment: @math - the Laurent series may have a term of order $1$ (does here using the formula for residues)
Comment: @Conrad can you be more precise please? is your answer to my question "second order poles do have $0$ residue, but there is not a second order pole at $1$ in this question"? also, what Laurent series are you talking about?
Comment: @math $\frac{1}{z^2}+\frac{1}{z}$ has a pole of order $2$ but also non zero residue
Comment: @Conrad ok, it seems me and bgreen were viewing $\frac{1}{(w-1)^2(w-z)}$ the same as $\frac{1-z}{(w-1)^2}$ pole-wise, but I guess that is not the case, by looking at the Laurent series of $\frac{1}{(w-1)^2(w-z)}$ (why didn't you answer my question)?
Comment: @math - wasn't sure what you asked, sorry
Comment: @Conrad you said "the laurent series may have a term of order $1$" and then "[it] does here". I asked "what Laurent series are you talking about". May I ask how you are unsure?
Comment: @math again I apologize if  I was unclear but I thought we use the same notions - I will put an answer below which shows how I thought of this problem when i saw it
Comment: @Conrad dude, I'm just asking you which function were you referring to when you said "the Laurent series here has a term of order $1$"? how is this confusing?
Answer: The residue formula at a pole of order $2$ for some analytic $f$ at some point $y$ is $lim_{w \to y}((w-y)^2f(w))'$
So here $f(w)=\frac{1/(w-1)^2}{w-z}, y=1$ and we assume for simplicity $z \ne 1$
Then $g(w)=(w-1)^2f(w)=\frac{1}{w-z}$, so $g'(1)=-\frac{1}{(1-z)^2}$ hence there is a residue at $1$ and it cancels the residue at $z$, so no contradiction as the integral is indeed $0$
Comment: Thank you! I had initially tried to do this by a power series expansion of $\frac{1}{w-z}$ about $w=1$ but had found no -1st term in $\frac{1/(w-1)^2}{w-z}$. I returned to those calculations and found I had misread/mentally reversed the numerator and denominator in the expansion - fixing that, I find the same result as you. It's always the simple mistakes...
Answer: HINT;
Using partial fraction expansion, we have
$$ \frac1{(w-z)(w-1)^2} =\frac{1/(z-1)^2}{w-z}-\frac{1/(z-1)^2}{w-1}+\frac{1/(z-1)}{(w-1)^2}$$
Can you finish now?
Comment: Thank you! I had initially tried to do this by a power series expansion of $\frac{1}{w-z}$ about $w=1$ but had found no -1st term in $\frac{1/(w-1)^2}{w-z}$. I returned to those calculations and found I had misread/mentally reversed the numerator and denominator in the expansion - fixing that, I find the same result as you. It's always the simple mistakes...


how to override the HTML of the search results page?

Question: i am trying to override the search-results page with no luck. All of the answers that i have found in google are about overriding the results template. since i am using a subtheme i want to override the whole HTML output of the page. I want to change the header, the footer etc..
Instead results page is using the page.tpl.php. So far i found this How to theme the page template for search results with no success.
Any correct way i can succeed this ?
Also i am trying to force the search to search only in specific content types and languages! Any suggestions?
Answer: Hope this will help you,
In Drupal 7, you can also achieve this
Using theme_search_results OR theme_search_result to override search results page.

theme_search_results : invoked for the search result page.
OR
theme_search_result : invoked to render a single result
Both these theme functions used in a template file (search-results.tpl.php and search-result.tpl.php).
Source
Comment: Yes i have read about that and also tried them. what i did was actually took the theme_search_reults.tpl.php file from the module path and pasted it to my template file. I edited the template and added the HTML and Regions i wanted to be displaed. Clean my cache and ran a search but still the page did not change. Is this the correct way to override the whole page? Because currently my results page seems exactly as my page.tpl.php template.
Answer: I would suggest you to do it by help of Display Suite module for search results.
Once you enable this module, you will find Manage Display tab when you visit your edit content type. Click to Manage Display -> Custom display setting -> check Search result & save.
Now you can manage your Search result display by clicking sub-tab in the Manage Display page. Arrange your field in the way which you want to be displayed & save.
For full page layout, you can go for making a page--search.tpl.php. Remove or add the regions or HTML text which you want, clear the cache & ready to go.
If this TPL doesn't work then you have to declare it in template.php using theme_hook_suggestions in the same way as answer of your linked question. See for the URL which your instance is using for giving search result.
For $base_url/search use
//replace your theme name with MYTHEME
function MYTHEME_preprocess_page(&$vars) {
  if (arg(0)=='search') {
    $vars['theme_hook_suggestions'][] = 'page__search';
  }
}

Add this in your template.php & as you are suggesting TPL for page, you have to use THEME_preprocess_page($vars).
Comment: I have tried the Full page layout but the path in Drupal when i ran a search becomes $base_url/search/node/search-term. Anything that i might doing wrong?
Comment: @paranod What is name of your search tpl file ?
Comment: i named  it page--search.tpl.php .
Comment: @paranod - Did you put my given code into your template.php & cleared your cache after replacing MYTHEME with your theme name ?


Error using for loop to handle fetching records from CloudKit query

Question: I am not sure how to handle this error below, this code used to work in my app:

ERROR: "For-in loop requires 'Result<(matchResults: [(CKRecord.ID, Result<CKRecord, any Error>)], queryCursor: CKQueryOperation.Cursor?), any Error>' to conform to 'Sequence'"

func fetchLocations()
    {
        var locationArray: [CLLocation] = []

        let publicDB = CKContainer.default().publicCloudDatabase
        let query = CKQuery(recordType: "location", predicate: NSPredicate(value: true))

        publicDB.fetch(withQuery: query, inZoneWith: nil) { (records) in
            if records != nil{
                for record in records {
                    if let location = record["location"] as? CLLocation {
                        locationArray.append(location)
                    }
                }//end for
            }else {return}
        }//end fetch

    }

Answer: Please have a look at the documentation:
records is actually a Result type with signature
Result<(matchResults: [(CKRecord.ID, Result<CKRecord, Error>)], queryCursor: CKQueryOperation.Cursor?), Error>

and which is never nil by the way.
You have to switch over the cases. Something like this
publicDB.fetch(withQuery: query, inZoneWith: nil) { result in
      switch result {
           case .success(let matchResults, let queryCursor):
               for matchResult in matchResults {
                   switch matchResult.1 { // the second item in the tuple
                       case .success(let record):
                           if let location = record["location"] as? CLLocation {
                               locationArray.append(location)
                           }
                       case .failure(let error): print(error)
                    } //end 2nd switch
                } //end for
           case .failure(let error): print(error)
      }//end 1st switch
}//end fetch

And you have to handle the queryCursor for more coming results


MSSQL Server Remote Login Issue on Windows Server 2012 R2

Question: I have installed MSSQL Express 2012 on Windows Server 2012 R2, I have set up database and logins. Everything works fine while I'm logged in at the server, but once I want to login from another machine I got the message:

"login failed for user sa".

Settings that I have made:

Added permission for port 1433 in Firewall,
Named Pipes,
TCP/IP,
VIA are enabled from Sql Server Configuration Manager.

Also for TCP/IP I have set IPALL - TCP Dynamic Ports (blank) and TCP Port 1433. ( These settings are used on other versions of windows that are working, but cant get it on Windows Server 2012 R2 when I want to connect from another machine ).
Comment: What do the logs on the host server say? I also **assume** you have enabled remote connections (I think this is enabled by default, but may depend on the SQL Server version you're using)?
Comment: It does not appear in the SQL Server Logs. Remote connection enabled. Version 11.0.2100 ( 2012 )
Comment: If you can't see the connection attempt in the logs, then the connection attempt is never reaching the host server. Is the instance name the default (MSSQLSERVER) or have you given it a different name? Can you see the host in the SQL Server Browse list (Enable the SQl Server browser service, albeit it temporarily and check if it isn't currently on). You've allowed connection to port 1433, I *assume* SQL Server is running on the default port. Edit, also version 11.0.2100??? Why such an old version? That's the base version. I'd **strongly** suggest updating to SP3 GDR at least, if not SP4.
Answer: Thank you Larnu - I have just checked the instance name and it was another instace, because also on that machine was installed and older version and I was doing settings on that older version using that older Sql Server Configuration Manager.


Finitely Presented Infinite Group has an Element of Infinite Order?

Question: Is it true that an infinite group which is finitely generated must have an element of infinite order? If not, I'd like a counterexample.
[Edit]
Somewhat easily proven false.
More interesting (and as it happens, more relevant to my particular problem domain), what about finitely presented groups?
Comment: There are infinite Burnside groups.  See http://en.wikipedia.org/wiki/Burnside%27s_problem
Comment: (Someone should wrap all these comments into an answer...)
Comment: See also the [Grigorchuk group](http://en.wikipedia.org/wiki/Grigorchuk_group) for a standard counterexample to many similar questions.
Comment: More interesting to ask this question for *finitely presented* groups.
Comment: The Tarski monster groups deserve a mention - they are finitely generated groups such that every people, non-trivial subgroup is cyclic of order a fixed prime $p$. These exist for all primes greater than some number which has been calculated by I cannot recall of the top of my head. They were first proven to exist by Ol'shanskii in the early 80s.
Comment: It is true for *abelian* groups.
Comment: @SteveD this should be my question, and had I thought more about it before asking, it would have been. Are you implying the problem is open?
Answer: In full generality, this is false.  As mentioned in the comments, the Burnside groups can be infinite groups, finitely generated by construction, such that every element has bounded finite order. One can even force such a group to be simple.
There are positive results for certain families of groups, however.  Immediately I am reminded of solvable groups and hyperbolic groups.
Perhaps a much more interesting question is if there is a finitely presented, infinite group, with no element of infinite order.  AFAIK, this question is still wide open.


Storage Spaces with Azure Disk: how can we extend virtual disks?

Question: We have on Azure several Windows Server 2019 virtual machines whose data disks are configured with Storage Spaces.
How can we extend a virtual disk configured for simple redundancy (NumberOfDataCopies is set to 1) on those machines without wasting physical storage?
Answer: You may follow this process, but please be careful, as mistakes may lead to data loss:

The first step is to add a new disk (or more new disks, depending from your scenario) to the virtual machine from the Portal.
Once the new disks are attached, login to the virtual machine, go on Server Manager\File and Storage Services\Volumes\Storage Pools, right click on the Storage Pool you would like to increase, the one providing the resources for the virtual disk you would like to extend, then add the new disks to that pool.
Do not extend the virtual disk straight away, and if you really have to do it (e.g. if your virtual disk is full and you need some storage to restart a depending service), leave at least 2 GB per disk from the target.
E.g. if the sum of the target physical disks is 512 GB and that is reached with 2 disks, extend max to 508 GB, that's it:

available physical storage (512 GB) - ( disks (2) * 2 GB)

Find the UniqueId of the disk to retire using this command on a elevated PowerShell prompt:

Get-PhysicalDisk | select DeviceId, FriendlyName, UniqueId, Size, PhysicalLocation

Look on the Azure portal on which LUN the disk has been attached, match that with the LUN reported on PhysicLocation (towards the end of the report, please don't mix it with the DeviceId at the beginning). You need the UniqueId, which is an hexadecimal number that looks like 6002243673DD16EBB4CF0579AE3A7647.

Give a friendly name to the disk to retire you have identified on the previous step:

Set-PhysicalDisk -UniqueId 6002243673DD16EBB4CF0579AE3A7647 -NewFriendlyName ToRetire

Retire the disk identified in step 5:

Set-PhysicalDisk -FriendlyName ToRetire -Usage Retired

being careful to choose the correct storage pool, start the repair job for the virtual disk, to move all the data from the disk to retire to the newly added disk(s):

Get-StoragePool –FriendlyName SQLVMStoragePool1 | Get-Virtualdisk | Repair-VirtualDisk -Asjob

You may check storage job, probably multiple times, until its completion, with the following command:

Get-StorageJob

Once the storage jobs are completed, it is possible to remove the retired and drained disk(s) from the GUI under Server Manager\File and Storage Services\Volumes\Storage Pools, then Physical Disks. Before removing the disk(s) I usually look at their properties, to ensure that used space should be less than 1 GB (around 750 MB to 850 MB). The corresponding cmdlet is Remove-PhysicalDisk. Please be careful, as per the relevant documentation if sufficient space does not exist in the storage pool to tolerate this removal, this can result in a data loss. In this scenario both the GUI and the cmdlet will warn you. Please read carefully before proceeding.

Once the disk is removed, you can unattach it from the Azure Portal. To find out the LUN of the removed disk run the following command:

Get-PhysicalDisk | where CanPool -eq $true  | select DeviceId, FriendlyName, UniqueId, Size, PhysicalLocation | ft

At the same time, once the disk is removed, feel free to extend the virtual disk to the max (which is a bit more than what calculated above).

If you don't need to retire the pre-existing disk(s), you may follow a shorter and simpler process:

The first step is to add a new disk (or more new disks, depending from your scenario) to the virtual machine from the Portal.
Once the new disks are attached, login to the virtual machine, go on Server Manager\File and Storage Services\Volumes\Storage Pools, right click on the Storage Pool you would like to increase, the one providing the resources for the virtual disk you would like to extend, then add the new disks to that pool.
Extend the virtual disk to the max (or to what you need) consuming the storage added in the storage pool in the previous step.
being careful to choose the correct storage pool, optionally, you may try to run the repair job for the virtual disk, to attempt to spread the data from the old disk(s) to  the newly added disk(s):

Get-StoragePool –FriendlyName SQLVMStoragePool1 | Get-Virtualdisk | Repair-VirtualDisk -Asjob

You may check storage job, probably multiple times, until its completion, with the following command:

Get-StorageJob
You may find here the full documentation for all Windows Storage Management-specific cmdlets.


Are there songs written using non-functional harmony

Question: I have been trying to write music that does not resolve to a tonic. Would this be non-functional harmony?

CMaj7 / Dbdim7 / BMaj7 / Eb7b5
Comment: I claim that you utilize the phenomena and mechanics of functional harmony even if you only flirt around and never actually deliver a tonic. The lack of a fulfilled dominant-tonic motion doesn't mean that the music is 100 % non-functional. A dance can be said to be sexual, even if it doesn't lead to actual intercourse, so to speak. (I hope this nature-inspired analogy doesn't offend anyone, but I will remove the comment upon request.) If you interrupt a piece of functional music just before it gets to the tonic, does it become non-functional?
Comment: Pieces that use exclusively nonfunctional harmony can still have a tonic. Heavy metal comes the most easily to me when it comes to examples of this, although I believe the piano piece "Spring Celebration" by Stephen Chatman is also another example.
Comment: @ piiperi I agree. And your analogy doesn't offend **me**. I do become non-functional if interrupted though.
Answer: Your terminology is incorrect. Normally we speak of a chord resolving: not a series of chords. Though it is true that your chords have not (yet) given any indication of a tonic.
None of your chords - Maj7, dim7 and 7flat5 - have 'functions', but it is not an example of 'non-functional harmony'.
The term 'non-functional harmony' comes from classical music, and applying it to other types of music is risky. According to the rules of harmony a dominant seventh had to be immediately resolved. G7 had to lead straight to C (or Cm), for example. After Bach's time all the rules were gradually eroded. Dominant sevenths didn't always resolve 'correctly'.
In Debussy's La cathédrale engloutie, at 4'50", (at the word 'molto' of 'molto dim') there begins a series of ten dominant seventh chords, none of which resolve. These chords aren't there to perform their traditional function. They are non-functional. It was their colour, their weight and their texture that Debussy wanted. It's very like a C20th artist painting for the sheer love of colour rather than to represent something.
We are used to such music now, but in 1910 it was unusual. There had been many earlier examples of dominant sevenths not resolving, in Mahler for example, or in Liszt's more experimental piano music; just as in painting there had been Turner, the Impressionists and others. But Debussy's writing a whole string of them was unusual. His prelude is tonal - it's clearly in the key of C - yet here in the middle of a piece, beginning with that chord of D#7, we are a long way from home. In fact the music seems to have lost its way home. Worse - it doesn't even seem to be interested in going home. Early audiences would have found that disconcerting.
In blues/jazz/rock music the term 'non-functional harmony' is as meaningless as it has been in the context of 'classical' music since Schoenberg.


Conversion from ISO-8859-2 to UTF-8

Question: I am trying to convert following string from ISO-8859-2 to UTF-8 but not converting properly.
$content = 'Mieszkanie dla Młodych. Od dziś kredyty z pomocą państwa';
$xy = utf8_encode($content);
echo $xy;
Output - Mieszkanie dla MÅodych. Od dziÅ kredyty z pomocÄ paÅstwa

i am not able to understand what is going wrong.
Any one expert in conversion could you please share some idea.
I may be missing something here.
Thank you
Update :-  i tried iconv but that also not working
iconv("ISO-8859-2", "UTF-8", $content);
iconv("ISO-8859-2", "UTF-8//TRANSLIT", $content);
iconv("ISO-8859-2", "UTF-8//IGNORE", $content);

Output - Mieszkanie dla MĹodych. Od dziĹ kredyty z pomocÄ paĹstwa

Comment: Use [iconv()](http://www.php.net/manual/en/function.iconv.php) or [mb_convert_encoding()](http://www.php.net/manual/en/function.mb-convert-encoding.php); utf8_encode() is specifically for ISO-8859-1 to UTF-8
Comment: Reverse the order of your charsets: 1st argument is the input (from) charset, 2nd is the output (to) charset
Comment: Thank you @MarkBaker i tried iconv("UTF-8", "ISO-8859-2//TRANSLIT", $content); but that also does not work. Does something different.
Comment: You are sure that your input string (`$content`) is encoded in ISO-8859-2?
Answer: Use iconv for conversion.It provides Original , TRANSLIT, Plain , IGNORE.I guess you need to try all to get your desired output
<?php
$text = "This is the Euro symbol '€'.";

echo 'Original : ', $text, PHP_EOL;
echo 'TRANSLIT : ', iconv("ISO-8859-2//TRANSLIT", "UTF-8" ,$text), PHP_EOL;
echo 'IGNORE   : ', iconv("ISO-8859-2//IGNORE","UTF-8",  $text), PHP_EOL;
echo 'Plain    : ', iconv("ISO-8859-2","UTF-8",  $text), PHP_EOL;

?>

Comment: Yep, that's definitely UTF-8. XML files are UTF by default unless there's a `Content-Type:...charset` or `<?xml encoding` stating otherwise. That RSS file has neither.
Comment: That's odd, I have now seen it both with and without the 8859-2 prolog. Not sure what makes it vary. When there *is* the encoding parameter,  `iconv("ISO-8859-2", "UTF-8", $content)` will be the right thing to do to convert to UTF-8. However by far the best approach would be to use a proper XML parser, which would cope with the encoding prolog automatically.
Comment: We are talking about ISO-8859-2, I guess.
Comment: Hi Freak - i tried that as well but no luck.. Yes i am sure it is ISO-8859-2 Estshy.  Thank you in advance... No idea what is going wrong... For more info this is RSS - www.money.pl/rss/main.xml  which is in ISO-8859-2 format.
Comment: Hi Estshy/bobince - if you do view source you will see  there on that file. Thank you.

Conversion from ISO-8859-2 to UTF-8


Parameter shown as "0:" in ajax request

Question:  var frm = $('#updateStickyForm');

            frm.submit(function (e) {
                var id = "{{note.id}}"
                e.preventDefault();

                $.ajax({
                    type: frm.attr('method'),
                    url: frm.attr('action'),
                    data:
                    frm.serialize() + '&' + $.param(id),

                    success: function (data) {

                        console.log('Submission was successful.');
                        $('#test').show();
                    },
                    error: function (data) {
                        console.log('An error occurred.');
                        console.log(data);

                    },

                });
            });

When I look at the network logs in Chrome the parameter is shown as "0:". I'm able to access the parameter just fine with Django and do what I want to do with it, I just want to know how I can change it from "0" to something of my choosing.
Answer: id seems to have a key 0 for the value you want to post, you can construct an object to pass to $.param with the key you want
frm.serialize() + '&' + $.param({"myid":id['0']}),

Comment: Thank you. This is just what I needed.

Parameter shown as "0:" in ajax request


Why Windows is not picking up the 128 pixels icons from my exe file?

Question: I created and exe file in which I added 32, 48, 64 and 128 pixels icons.
When I put the exe on my desktop or navigate to the folder where the exe is stored, Windows Explorer shows only the 32 and 48 pixels icons. If I set my desktop to show 'Large icons' it still shows the 48 pix icon. Why?

Windows 7 32 bit, RBG+Alpha icons, EXE built with Delphi 7
Answer: How are you making your .ico file ? I think generally you need to start with adding the highest resolution first, and work down from there. You could troubleshoot by starting with only the 128x128 one, seeing if that works, then adding the 64x64 one and so on.
An easy alternative way is to try generating the .ico file using http://iconverticons.com/ instead, it's free and pretty painless.
Comment: I have tried both ways - 128 pixel first then deleted all and put 32 pixel first. No luck. I have tried that EVEN if my resource file editor allows me to change the order of the icons. Anyway your idea with 128 pixels only is good! Thanks.


Hibernate Search - Compare field to another field in the index

Question: I am looking for a way to compare if two fields match in my index.
I would like to do something like this:
<code>org.apache.lucene.search.Query luceneQuery = qb.keyword().onFields("favourites.dataItem.dataId").matching(<another field>).createQuery();
</code>
Can't seem to find it in the official docs. I'd appreciate it if someone can point me in the right direction.
Answer: You cannot do that in Hibernate Search or Lucene. If I understand correctly you want to know whether a given entity (back by a Lucene Document in the Lucene index) has the same value for two fields. Really, this is much better suited for SQL or a Hibernate Criteria query.


How does Entity Framework 6 order migrations

Question: What's the order of the migrations that get run when the db context is configured with MigrateDatabaseToLatestVersion? The autogenerated migration classes don't seem to contain any ordering. The only place that seems to have a clue about the order is the migration filename / the timestamp - but that doesn't seem likely or available at runtime... right?
Answer: The initial migration name is actually what is used. This is also the same as the initial file name but you can obviously change that.
In EntityFramework, when you generate a migration, you may be familiar with editing the file to customize the migration.

    public partial class InitialCreate : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.Blogs",
                c => new
                    {
                        BlogId = c.Int(nullable: false, identity: true),
                        Name = c.String(),
                    })
                .PrimaryKey(t => t.BlogId);

        }

        public override void Down()
        {
            DropTable("dbo.Blogs");
        }
    }

But a designer file is also generated and it has a few properties that you shouldn't edit:
[GeneratedCode("EntityFramework.Migrations", "6.4.4")]
public sealed partial class InitialCreate : IMigrationMetadata
{
    private readonly ResourceManager Resources = new ResourceManager(typeof(InitialCreate));

    string IMigrationMetadata.Id
    {
        get { return "202111200213248_InitialCreate"; }
    }

    string IMigrationMetadata.Source
    {
        get { return null; }
    }

    string IMigrationMetadata.Target
    {
        get { return Resources.GetString("Target"); }
    }
}

In the source code of EF6, you can see the migrations are reflected from your migration assembly:
Every class that inherits from DbMigration is used and then ordered by the Id property.
_migrations
    = (from t in migrationsAssembly.GetAccessibleTypes()
        where t.IsSubclassOf(typeof(DbMigration))
                && typeof(IMigrationMetadata).IsAssignableFrom(t)
                && t.GetPublicConstructor() != null
                && !t.IsAbstract()
                && !t.IsGenericType()
                && t.Namespace == migrationsNamespace
        select (IMigrationMetadata)Activator.CreateInstance(t))
        .Where(mm => !string.IsNullOrWhiteSpace(mm.Id) && mm.Id.IsValidMigrationId())
        .OrderBy(mm => mm.Id)
        .ToList();

Even if you rename the files, the Id will still have its initial value when you created the migration keeping the migrations in lexical and chronological order as EF6 sees it.
It's pretty much the same for EFCore except that it has moved from a property to an attribute on the designer file:
    [DbContext(typeof(MyContext))]
    [Migration("20211118001328_InititialCreate")]
    partial class Init {}

And EFCore looks for that attribute on classes that inherit from Migration.
var items
    = from t in Assembly.GetConstructibleTypes()
        where t.IsSubclassOf(typeof(Migration))
            && t.GetCustomAttribute<DbContextAttribute>()?.ContextType == _contextType
        let id = t.GetCustomAttribute<MigrationAttribute>()?.Id
        orderby id
        select (id, t);


Add table record using jquery

Question: I have the HTML structure like like:
<button type="button">Add Column Record</button>

     Header 1

     L1
     L1

 Header 2

     L2
     L2

     Header 3

     L3
     L3

I want to add a vertical record to the rightest column after pressing a button. How should I implement this effect using jQuery?
Answer: You can try something like this:
$('button').on('click', function() {
    var table = $('table');
    var newCell = null;

    table.find('tr').each(function(index) {
        newCell = $('');
        newCell.text('L' + (index+1));
        $(this).append(newCell);
    });
});

Demo here: http://jsfiddle.net/8RmS8/
Answer: check this out: http://jsfiddle.net/MMXnY/1/
$('button').click(function(){
   $('table tr').each(function(i, v){
     $(this).append($('td:last',this).clone().text('L'+parseInt(i+1)));
   });
});

You can iterate through each tr then make a clone of the last td and then put text and increase the number by parsing it then append it after last td.
Answer: http://api.jquery.com/append/
http://api.jquery.com/appendTo/
http://api.jquery.com/prepend/
Each of the functions do a slightly different append.  Read them and find out what one you want to use.
Example:
BEFORE

SCRIPT
$('
Test
').appendTo('.area');

AFTER

Test

Hope this helps!
Answer: If you want to add one column, you can iterate on each tr of your table and add a new td
Example:
$("#id_of_your_table > tbody > tr").each(function(index, trElement) {

    // Add a new TD at the end
    $(trElement).append($(document.createElement("td")));

});

Note : Don't forget to add a tbody in your table for a good behaviour (Some browser will add it by default if it's not present)
example:

            .....

Here is a complete example:
<button id="addColumn">Add new column</button>

            col 1
            col 2
            col 3

             col 1
             col 2
             col 3

Add table record using jquery


How can i call through app automatically?

Question: Hi can anyone suggest me How can I call through app automatically I mean I used following code in my app.
NSURL *url = [NSURL URLWithString:@"telprompt://123-4567-890"];
[[UIApplication sharedApplication] openURL:url];

Its working properly and after call end its returning back to app too but problem is it will not take call event automatically,we have to click call button.so is there any way to call without giving any user interaction??
Thanks in advnce...
Answer: Try
NSURL *url = [NSURL URLWithString:@"tel:123-4567-890"];
[[UIApplication sharedApplication] openURL:url];

The telprompt URL scheme is designed to ask the user to confirm the call. If you just use tel, the call will be initiated immediately.
Comment: But if I use this, after my call ends it will not return back to app this my problem.I have to make call automatically and should return back to app after call ends.Any idea...?? Thanks a lot..


Como fazer os ands do where dinamicamente com linq e Entity Framework?

Question: Como posso fazer os ands dinamicamente no where utilizando o Linq e entityFramework?
Desde de já agradeço por qualquer ajuda.
return _dbContext.TbParceiro
//Preciso fazer algo do tipo mas isso não funciona, não sei como posso fazer aqui.
.Where(p =>

    if (!string.IsNullOrEmpty(mdlParceiroFiltro.FiltroId))
    {
         p.ParceiroId = mdlParceiroFiltro.FiltroId;
    }
)
.OrderBy(p => p.ParceiroId)
.Skip(mdlParceiroFiltro.Pula)
.Take(mdlParceiroFiltro.Pega)
.ToList();

Abaixo tem um exemplo que funciona ultilizando comando em string, preciso fazer a mesma coisa só que com linq.
        sql.Append("SELECT u.Id, u.Nome, u.Usuario ");
        sql.Append("FROM usuario u ");
        sql.Append("WHERE 1 = 1 ");

        if (model != null)
        {
            if (!string.IsNullOrEmpty(model.Nome))
            {
                sql.Append("AND u.Nome like @Nome ");
                lstParametros.Add(new MySqlParameter() {
                    ParameterName = "@Nome",
                    MySqlDbType = MySqlDbType.String,
                    Value = "%" + model.Nome + "%"
                });
            }

            if (!string.IsNullOrEmpty(model.Usuario))
            {
                sql.Append("AND u.Usuario like @Usuario ");
                lstParametros.Add(new MySqlParameter()
                {
                    ParameterName = "@Usuario",
                    MySqlDbType = MySqlDbType.String,
                    Value = "%" +
                    model.Usuario + "%"
                });
            }
        }

Answer: O que você quer é adicionar o Where somente se o mdlParceiroFiltro.FiltroId não for null ou empty.
IQueryable<ParceiroModel> entidades = _dbContext.TbParceiro;

// Verifica o FiltroId é válido
if (!string.IsNullOrEmpty(mdlParceiroFiltro.FiltroId))
{
    // Se for válido, você insere o Where
    entidades = entidades.Where(p => p.ParceiroId == mdlParceiroFiltro.FiltroId);
}

return entidades
    .OrderBy(p => p.ParceiroId)
    .Skip(mdlParceiroFiltro.Pula)
    .Take(mdlParceiroFiltro.Pega)
    .ToList();

Você pode adicionar quantos Where quiser com o LINQ. Ele vai automaticamente transformar em and por baixo dos panos.
Comment: Não, o `dbContext` só executa o select quando você chama um método finalizador, tipo o `ToList` ou `ToArray`, por exemplo. Enquanto você só adicionar filtros, ele vai montando o select sem executar.
Comment: Legal, mas nessa linha "var entidades = _dbContext.TbParceiro;" ele não vai fazer um full select no banco?
Comment: Perfeito. Valeu
Comment: Ele reclamou de uma conversão ai invés de eu usar o var coloquei IQueryable entidades = _dbContext.TbParceiro;
Comment: Entendi, pensei que o `var` fosse pegar automaticamente o tipo `IQueryable`.
Comment: Alterei a resposta pra refletir o que você comentou.
Answer: tente com operador ternário:
Sintaxe:  ((bool) ? (se true) : (se falso))
[...].Where(p => (!string.IsNullOrEmpty(model.Nome) ? p.Nome.Contains(model.Nome) : p.Usuario.Contains(model.Usuario))).[...]

Outro exemplo:
[...].Where(p => (!string.IsNullOrEmpty(mdlParceiroFiltro.FiltroId) ? p.ParceiroId = mdlParceiroFiltro.FiltroId : true)).[...]

Comment: Obrigado por sua ajuda +1


Bounds on $P(A_1\cap \ldots\cap A_n) - P(A_1)\ldots P(A_n)$

Question: In Székely's Paradoxes in Probability Theory and Mathematical Statistics, it is stated without proof or reference that for any $n\geq 2$ and events $A_1,\ldots,A_n$,
$$-\left(1-\frac 1n\right)^n \leq P(A_1\cap \ldots\cap A_n) - P(A_1)\ldots P(A_n)
\leq \frac{n-1}{n^{n/(n-1)}}.$$
When $n=2$, the bound rewrites as $|P(A_1\cap A_2) - P(A_1) P(A_2)|\leq 1/4$, which is well-known and tight.
What about $n\geq 3$ ? I'm looking for a reference or a proof.
Answer: THE UPPER BOUND
Let $p=P(A_1\cap \ldots\cap A_n)$ then each $P(A_i)\ge p$.Therefore
$$P(A_1\cap \ldots\cap A_n) - P(A_1)\ldots P(A_n)\le p-p^n.$$
On the interval $0\le p\le 1$, the maximum of $p-p^n$ is attained when $$1-np^{n-1}=0.$$
This gives the upper bound of $\frac{n-1}{n^{n/(n-1)}}$.
THE LOWER BOUND
The union of the $A_i'$ is the complement of $A_1\cap \ldots\cap A_n$ and so has probability $1-p$. Therefore $\Sigma P(A_i') \ge 1-p$.
Then $\Sigma P(A_i) =n-\Sigma P(A_i')\le n-1+p$. Therefore
$$P(A_1\cap \ldots\cap A_n)-P(A_1)\ldots P(A_n)\ge p-\left(\frac{n-1+p}{n}\right)^n.$$
The bound has no T.P. in the interior of $0\le p\le 1$. The minimum is at the endpoint  $p=0$ and is $-(1-\frac{1}{n})^n$, as required.
Answer: Just adding to the crisp solution of @user1172706:
The defining inequalities for $P(A_1\cap \ldots \cap A_n)$ are
$$ -(n-1)+\sum_{i=1}^n P(A_i) \le P(A_1\cap \ldots A_n) \le \min_{1\le i\le n} P(A_i) $$
i.e. this is the description of the $(n+1)$ convex body of possible values $(P(A_1), \ldots, P(A_n), P(A_1 \cap \ldots \cap A_n) )$.
About the inequality in the post, the LHS $(1-\frac{1}{n})^n$ is decreasing with $n$ to $\frac{1}{e}$, and the RHS is increasing with $n$ to $1$. Therefore, an inequality independent of $n$ is meaningful only on LHS
$$-\frac{1}{e} < P(A_1 \cap \ldots \cap A_n) - P(A_1) \cdots P(A_n) $$


simulation of t distribution - repeated sampling

Question: I am new to simulation exercises in R. I want to create 1000 samples of size 25 from a t distribution with degrees of freedom 10.
Do I need to create a single vector of data from the rt generator, and then sample repeatedly from that? So, for example, I could create the vector:
singlevector <- rt(5000, 10) , which generates data from a t -distribution of size 5000 and df = 10. So, I would treat this as my population and then sample from it. I chose the population size of 5000 arbitrarily here.
OR, should I create my 1000 samples calling on this random t generator every time?
In other words, create a matrix with 25 rows and 1000 columns, each column containing vector corresponding to a new call of rt(25, 10).
Thank you.
Comment: @mdewey This looks like a purely statistical question to me, concerning how to use random number generators appropriately.
Comment: I agree with whuber here -- while phrased as if it were a question about how to do something in R, the central issue here is about how to use random number generators. We should not regard a question as off topic merely because the poster doesn't yet understand enough to clearly disentangle their language issues from their statistical issues (that's why they're asking questions). To some extent it's our job as (hopefully) knowledgeable statisticians to spot the statistical questions lurking in these posts and help the OP to focus on them; remaining language issues may then be solved elsewhere.
Comment: I think you might be better on R-help or StackOverflow
Comment: @Glen_b I see your point. I had interpreted it purely in terms of which method made more sense programmatically rather than the question of when is a sample from a random sample also a random sample.
Comment: @whuber I finally worked out how to retract my vote. See also my response to Glen_b above.
Answer: Your population is the (notionally) infinite population of values you might have got from a t-distribution with 10 df. (In practice a random number generator can only generate a finite number of distinct values, because precision is finite. However this doesn't change the way you should normally look at it.)
Any finite population can't literally be t-distributed (though it may have a distribution-function that's quite close to that of the $t$).
You should not generate fewer values than you will need and then sample those with replacement, as you seem to propose.
While there would be no harm in sampling some larger-than-needed set of t$_{10}$-distributed values (i.e. more than 25000) and then sampling without replacement from those, there's no point in doing so -- simply simulate all the values you need directly from the generator when you need them.
[Personally, if I were doing it, I'd probably simulate 25000 values and arrange them into an object in one go, such as by a call to rt inside a call to matrix, but there's a variety of ways to do it that would reasonable (it's such a small number of values it hardly matters how you do it as long as you don't grow any data structures as you go). If I only needed something computed from each sample I'd probably use replicate instead.]


Every finite Galois extension of $\mathbb{Q}_p$ has a solvable Galois group.

Question: I have found the statement as in the title of this post on wikipedia, however, there is no reference for its proof. How does one prove it?
Answer: This follows from the theory of ramification groups (in the "lower numbering").
Answer: Let $K/{\Bbb Q}_p$ be a Galois extension and $k$ the residue field of $K$. As Galois actions preserve integrality there is an induced action of $G$ (the Galois group) on ${\frak O}_K$ fixing $\Bbb Z_p$; it futhermore fixes powers of the maximal ideal of ${\frak O}_K$ and so induces an action on $k$ over ${\Bbb F}_p$, and more generally $G$ acts as automorphisms of ${\frak O}_K/{\frak m}^i$ for all $i\ge0$. We define $G_i:=\ker(G\to{\rm Aut}({\cal O}_K/{\frak m}^{i+1}))$ for $i\ge-1$ to be the ramification groups of $K/{\Bbb Q}_p$. We have $G_{-1}=G$, and $G_0$ is called the inertia group of the extension, while $G_1$ is called the wild inertia group. There is now a ramification filtration
$$G=G_{-1}\trianglerighteq G_0\trianglerighteq G_1\trianglerighteq G_2\trianglerighteq\cdots $$
Via $1$st iso thm there is a canonical isomorphism $G/G_0\cong{\rm Gal}(k/{\Bbb F}_p)\cong C_f$ where $f$ is the residue degree of $K/{\Bbb Q}_p$ (that is $f=\dim_{\,{\Bbb F}_p}k$). Then, if $\pi$ is a uniformizer (principal generator of ${\frak O}_K$'s max ideal ${\frak m}$), the map $\sigma\mapsto \sigma(\pi)/\pi$ is an injective group homomorphism $G_i/G_{i+1}\to U_i/U_{i+1}$ where $U_i:=1+{\frak m}^i$ are the higher unit groups  (under multiplication). The quotient $U_0/U_1$ is clearly $k^\times\cong C_{p^f-1}$, and $U_i/U_{i+1}\hookrightarrow {\frak m}^i/{\frak m}^{i+1}\cong k^+\cong C_p^f$ hence is elementary abelian.
Thus $G_1\hookrightarrow G_0\hookrightarrow G$ where $G_1$ is a $p$-group (hence solvable), $G_0/G_1$ is cyclic of order dividing $|k^\times|=p^f-1$ and $G/G_0$ is cyclic of order $f$. Therefore, $G$ is a solvable group.
For more detail and some proofs, I like Boston's The Proof of Fermat's Last Theorem's Chapter 3, from Definition 3.6 up to Corollary 3.9 (which is the desired claim). (The link is an official pdf.)


Proving $(I -cP)^{-1} = I+ \left(\frac{c}{1-c}\right)P$ , $P$ idempotent matrix.

Question: Given that a matrix $P$ is idempotent how to prove the following relation:
$$(I -cP)^{-1} = I+ \left(\frac{c}{1-c}\right)P$$ $c$ is any real constant.
Comment: $c$ is not ANY real constant .. $c\ne 1$ else the RHS doen't exist.
Answer: Let's multiply these two matrices together:
$$(I-cP)\left(I+\frac{c}{1-c}P\right)$$
If we get $I$ as a result, then we know that they are inverses. Use the distributive property:
$$I^2-cP+\frac{c}{1-c}P-\frac{c^2}{1-c}P^2$$
Use idempotence of $I$ and $P$:
$$I-cP+\frac{c}{1-c}P-\frac{c^2}{1-c}P$$
Factor out a $P$ from the last three terms:
$$I+\left(-c+\frac{c}{1-c}-\frac{c^2}{1-c}\right)P$$
Use algebra to simplify:
$$I+0P=I$$
Thus, the two matrices we started with in the original product are inverses.
Answer: $$\begin{aligned}
(I - cP)^{-1} &= I + cP + c^2P^2 + c^3P^3 + \ldots &\text{(Maclaurin series)}\\
&= I + (c + c^2 + c^3 + \ldots) P &\text{(idempotence)}\\
&= I + \frac{c}{1-c} P &\text{(geometric series)}
\end{aligned}$$
Comment: OK for $|c|<1.$  But if  $|c|\geq 1$ (and $c\ne 1,$ of course) and  if $p\ne 0$ then the  series will not converge.  E.g. if $P=I$ and $c=-1.$


Does StackExchange screen suspicious voting behavior?

Question: We have a user who I have never heard of and who has cast 500 votes.
 (I noticed because I am vain and I wanted to see if anyone but me has this badge.)
I don't really care about his badge, but I think this guy is just voting randomly on questions, probably via script. My reason for believing this is that he got the same badge in a dozen communities in a span of few days. A sample:
 Movies
 Math
 Qaunt
 Tex
 Computer Science
I do care about not having random votes on questions and answers. I find people being quirky provides enough randomness. Is SE doing anything to filter such spurious voting?
Comment: Perhaps you should add the "support" tag, to certainly alert SE associates. They may not have a mechanism in place, but once they are alerted, they may put their engineers to look into the specific case.
Comment: His profile says he was last seen four and a half months ago.
Comment: @AlecosPapadopoulos As the link by 404 explains his presence may be disruptive even if he is not here anymore because his activity can disturb the Community and Roomba algorithms.
Answer: So, to directly answer the question: Yes, SE does monitor voting algorithmically, but this is not the kind of behaviour that gets picked up (the system is more targeted at users trying to inflate their own reputation or that of other specific other users).
As can be seen in "Spam Voting" - Should we stop it?, linked by @404, this kind of behaviour is a contentious issue. I have gone with what seems to be the consensus best response and written a moderator's warning to the user. The text of the warning is as follows:

Hello,
I'm writing in reference to your Economics Stack Exchange account.
Some users of the site have noticed that your account has very little activity besides the very large number of up-votes. Moreover, this pattern of behavior appears to have been replicated across a number of Stack Exchange sites in the space of a few days (other spend months accumulating such vote totals) and therefore looks quite suspicious.
The voting system is the main mechanism that we have available to direct attention to the best content on the site, and is important in helping users to identify wrong, low-quality, or unreliable posts. Improper use of the voting system undermines this function by distorting the information implied by others' votes. Please, therefore, refrain from voting except in cases where you have taken time to carefully evaluate the content in question.
Regards,
Ubiquitous
Economics Stack Exchange moderator

Honestly, I don't think this will make too much difference. If the user's objective is, indeed, to obtain the badge then the damage is already done. Site moderators are not able to reverse user votes.


Probability involving sum of natural numbers

Question: Second week into my course on probability and I'm perplexed by this question. I understand that it has to do with the sum of natural numbers and that k varies based on the length of the series that is $x$. I can follow the solution up to a point.

A discrete random variable $X$ has a probability function (pf)
$pX(x) = kx$, $x = 1,2,3,...,2n$
a) Find $k$

The solution I have is
$1 + 2 + 3 +···+ 2n = \frac{2n(2n + 1)}{2}$
$k = \frac{2}{2n(2n + 1)} = \frac{1}{n(2n + 1)}$
The follow up question however has me confused.

b) Determine $P(X \leq n)$

I feel as though I may be missing some intuition about probability functions despite the examples given in the text being fairly straight forward.
Apologies for any obvious blunders as I'm just getting back into math study after a long break.
Comment: $P(X\leq n)=\sum_{x=1}^np_X(x)=\sum_{x=1}^nkx=k\sum_{x=1}^nx=\cdots$ Also you can substitute $k$.
Answer: So the probability that $X$ is less than $n$ is therefore the probability that $X$ is $1$ or $2$ or $3$ ... or $n$.
You know that the probability that $X$ is $1$ is given by $p_X(1)$, same for probability that $X$ equals $2$ is $p_X(2)$ etc...
Therefore the probability that $X$ is $\leq n$ is
$$
P(X \leq n) = \sum_{i=1}^n p_X(i)
$$
From the first question you know that $p_X(i) = k\cdot i$ with $k$ the constant you calculated. Putting that in the formula above and proceeding the computation gives :
$$
P(X \leq n) = \sum_{i=1}^n p_X(i) = \sum_{i=1}^n ki = k\sum_{i=1}^n i = k \frac{n(n+1)}{2} = \frac{1}{n(2n+1)} \frac{n(n+1)}{2} = \frac{n+1}{2(2n+1)}
$$
Comment: Excellent thanks for the effort in explaining, it's quite clear now


regex subtraction

Question: Is it possible to use regex character class subtraction in some way in GNU sed, GNU awk, GNU grep, or anywhere else from bash?
Is it supported in C++11?
Where this feature is supported? I was unable to find any references except this one: http://msdn.microsoft.com/en-us/library/20bw873z.aspx (at the bottom).
To be more specific: what's the best way to convert all the digits except 2 and 5 to asterisks, something like
sed -re 's/[0-9-[25]]/*/g'
Comment: What is the target language? C++? C#? Each language has different level of support for regex.
Comment: bash and c++11. «bash» means also sed, grep, tr, awk…
Answer: The way to do it is with negative lookaheads, but not all regex engines support them.
>>> re.match(r'(?![25])[0-9]', '2')
>>> re.match(r'(?![25])[0-9]', '3')
<_sre.SRE_Match object at 0x25108b8>

Answer:
Is it possible to use regex character class subtraction in some way in GNU sed, GNU awk, GNU grep, or anywhere else from bash?

No, not with those tools/regex-implementations.
Most (popular) languages do not support this. Java has a way to do this: [0-9&&[^25]] (matching any (ASCII) digit except '2' and '5'), but I know of no other implementations that support this.
Either use negative look-ahead (?![25])[0-9], as Ignacio already suggested, or do it "the hard way": [1346-9]
See:

http://www.regular-expressions.info/refflavors.html
http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html
Comment: Thank you, your links are very interesting.

regex subtraction


Código responsivo para dispositivos mobile

Question: Boa tarde!
Gente, existe alguma forma de adequar um código como o abaixo para que fique responsivo de forma geral em qualquer dispositivo mobile?
Todas as formas que tentei ajustando os atributos widht e height não ajustaram o código, principalmente o video que ficou bem ruim de visualizar no Mobile.

            <div
              code='\n'
              class="div-6"
              data-name="div-1"
            >

                <iframe
                  width="560"
                  height="315"
                  src="https://www.comercial.customic.com.br/news/videos_site_customic/CustomicDezAnos_Proteja_seu_mundo.mp4?controls=0&&autoplay=1&mute=1;&loop=1&playlist=83xyE4zJggw;"
                  title="YouTube video player"
                  frameborder="0"
                  allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                  allowfullscreen
                >

          <picture>
            <source
              srcset="
               https://www.comercial.customic.com.br/news/imagens_site_customic/assets_986e144735c045578f7903725872417c_fc4b5059c6e64c10a9966e7887503498.webp?format=webp&width=100   100w,
                https://www.comercial.customic.com.br/news/imagens_site_customic/assets_986e144735c045578f7903725872417c_fc4b5059c6e64c10a9966e7887503498.webp?format=webp&width=200   200w,
                https://www.comercial.customic.com.br/news/imagens_site_customic/assets_986e144735c045578f7903725872417c_fc4b5059c6e64c10a9966e7887503498.webp?format=webp&width=400   400w,
https://www.comercial.customic.com.br/news/imagens_site_customic/assets_986e144735c045578f7903725872417c_fc4b5059c6e64c10a9966e7887503498.webp?format=webp&width=800   800w,
                https://www.comercial.customic.com.br/news/imagens_site_customic/assets_986e144735c045578f7903725872417c_fc4b5059c6e64c10a9966e7887503498.webp?format=webp&width=1200 1200w,
               https://www.comercial.customic.com.br/news/imagens_site_customic/assets_986e144735c045578f7903725872417c_fc4b5059c6e64c10a9966e7887503498.webp?format=webp&width=1600 1600w,
               https://www.comercial.customic.com.br/news/imagens_site_customic/assets_986e144735c045578f7903725872417c_fc4b5059c6e64c10a9966e7887503498.webp?format=webp&width=2000 2000w,
                https://cdn.builder.io/api/v1/image/assets%2F986e144735c045578f7903725872417c%2Ffc4b5059c6e64c10a9966e7887503498
              "
              type="image/webp"
            />
            <img
              loading="lazy"
              src="https://www.comercial.customic.com.br/news/imagens_site_customic/assets_986e144735c045578f7903725872417c_fc4b5059c6e64c10a9966e7887503498"
              srcset="
                https://www.comercial.customic.com.br/news/imagens_site_customic/assets_986e144735c045578f7903725872417c_fc4b5059c6e64c10a9966e7887503498?width=100   100w,
                https://www.comercial.customic.com.br/news/imagens_site_customic/assets_986e144735c045578f7903725872417c_fc4b5059c6e64c10a9966e7887503498?width=200   200w,
                https://www.comercial.customic.com.br/news/imagens_site_customic/assets_986e144735c045578f7903725872417c_fc4b5059c6e64c10a9966e7887503498?width=400   400w,
                https://www.comercial.customic.com.br/news/imagens_site_customic/assets_986e144735c045578f7903725872417c_fc4b5059c6e64c10a9966e7887503498?width=800   800w,
                https://www.comercial.customic.com.br/news/imagens_site_customic/assets_986e144735c045578f7903725872417c_fc4b5059c6e64c10a9966e7887503498?width=1200 1200w,
                https://www.comercial.customic.com.br/news/imagens_site_customic/assets_986e144735c045578f7903725872417c_fc4b5059c6e64c10a9966e7887503498?width=1600 1600w,
                https://www.comercial.customic.com.br/news/imagens_site_customic/assets_986e144735c045578f7903725872417c_fc4b5059c6e64c10a9966e7887503498?width=2000 2000w,
                https://www.comercial.customic.com.br/news/imagens_site_customic/assets_986e144735c045578f7903725872417c_fc4b5059c6e64c10a9966e7887503498
              "
              class="image"
            />
          </picture>

          Conheça nossas coleções

Aguardo O Help De Vocês!!
Forte Abraço a comunidade!
Answer: Fiz algumas modificações no seu HTML e CSS, o motivo do video ficar sempre pequeno é que você está trabalhando com métricas estáticas, isso prejudica a responsividade, tenta utilizar métricas dinâmicas, e para coisas simples como essa sua página aconselho utilizar o Bootstrap.
Se ainda tiver dúvida pode falar.
Espero ter ajudado.

    <link href="https://email@example.com/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

            <div code='\n'
                class="ratio ratio-16x9" data-name="div-1">

                <picture>
                    <source srcset="
                https://www.comercial.customic.com.br/news/imagens_site_customic/assets_986e144735c045578f7903725872417c_fc4b5059c6e64c10a9966e7887503498.webp?format=webp&width=100   100w,

              " type="image/webp" />

                </picture>

                    Conheça nossas coleções


How to receive snmp v3 traps without specific enginedID?

Question: I'm using snmptrapd on linux from net-snmp package. I'm trying to make some perl script to handle snmp traps. I'm already have such script and it works with snmp v1, v2c traps and with snmpv3 traps but only when I specify engineID explicitly both in config and in command sending trap. But when I configure cisco router to send me linkDown trap it uses MAC address with some extra bytes as engineID. And I can see trap arrives on interface in wireshark, but snmptrapd does nothing. Is it possible to configure snmptrapd to accept all traps by authenticated users without specifying engineID?
Here is my snmptrapd.conf
# Example configuration file for snmptrapd
#
# No traps are handled by default, you must edit this file!
#
createUser -e 0x0102030405 myuser MD5 mypassword DES myotherpassword
createUser -e 0x0102030405 myuser2 MD5 mypassword DES myotherpassword
createUser -e 0x0102030406 myuser2 MD5 mypassword DES myotherpassword
createUser cisco SHA cisco123 DES cisco123
authUser log,execute myuser
authUser log,execute myuser2
authUser log,execute cisco
authCommunity   log,execute public
perl do "/usr/local/share/snmp/snmptrapdhandler.pl";

I'm using Fedora 21 linux,
$ uname -a
Linux 4.1.13-100.fc21.x86_64 #1 SMP Tue Nov 10 13:13:20 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux

and net-snmp version is net-snmp-5.7.2-23.fc21.x86_64
Answer: It took a long time to figure this out to be able to use snmptrapd without needing the engineID.  This works with a brand new Cisco Nexus switch (nx-os) and hoping this will help someone else:
format2 %V\n% Agent Address: %A \n Agent Hostname: %B \n Date: %H - %J - %K - %L - %M - %Y \n Enterprise OID: %N \n Trap Type: %W \n Trap Sub-Type: %q \n Community/Infosec Context: %P \n Uptime: %T \n Description: %W \n PDU Attribute/Value Pair Array:\n%v \n -------------- \n

/etc/snmp/snmptrapd.conf:
traphandle default /etc/snmp/send_to_email_script # make sure it is executable
traphandle default /etc/snmp/snmp-traphandle_script # can be any program
doNotLogTraps no
authUser log,execute,net ${snmp_user} # username variable
createUser ${snmp_user} MD5 ${snmp_auth} AES-128 ${snmp_auth}

Example user could be:
# createUser networkmonitor MD5 cisco1234! AES-128 cisco1234!

On cisco switch make sure this user exists with same username/password and priv/auth. Also add snmp host (which is the how you send the trap to snmptrapd):
# snmp-server host ip_address traps version 3 priv networkmonitor

Make sure ip_address is not switch ip, but the snmptrapd receiver's ip
Answer: We receive traps without specifying engine-id from cisco devices with snmpv3. But we are using MD5/DES on cisco device.
Linux 02asdf 4.4.0-38-generic #57-Ubuntu SMP Tue Sep 6 15:42:33 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

ii  snmp                                  5.7.3+dfsg-1ubuntu4     amd64                   SNMP (Simple Network Management Protocol) applications
ii  snmp-mibs-downloader                  1.1                     all                     Install and manage Management Information Base (MIB) files
ii  snmpd                                 5.7.3+dfsg-1ubuntu4     amd64                   SNMP (Simple Network Management Protocol) agents
ii  snmpsim                               0.2.4-1                 all                     SNMP agent simulator
ii  snmptrapd                             5.7.3+dfsg-1ubuntu4     amd64                   Net-SNMP notification receiver
ii  snmptt                                1.4-1                   all                     SNMP trap handler for use with snmptrapd

Comment: Can you show your snmptrapd.conf?