Spectrum of Artinian ring

Question: I'm trying to understand links between Artinian property of a ring $R$ and its spectrum. I suppose that $R$ is noetherian.
This answer is perfect, particulary: TFAE
5) $R$ is Artinian
6) $\operatorname{Spec}(R)$ is discrete
7) $\operatorname{Spec}(R)$ is finite and discrete
It is clear for me that (5) is equivalent with $\operatorname{Spec}(R)$ is $T_1$ i.e. points are closed so I get: (6) $\Rightarrow$ (5)
It is clear that (7) $\Rightarrow$ (6).
Any idea to conclude?
Comment: If $R$ is Artinian, all prime ideals are maximal (since an Artinian domain is a field), and there are finitely many of them (take a minimal element of the set of finite intersections of maximal ideals, then prove there are no other maximal ideals). It is then easy to see that $\mathrm{Spec}(R)$ is discrete.
Comment: Thanks! $\operatorname{Spec}(R)$ is discrete because it's a finite space builded with closed points
Answer: Let $R$ be artinian, with Jacobson radical $J$. Then $J$ is nilpotent and $R/J$ is product of fields. We can lift these idempotents to $R$, and hence $R$ is a finite product of local rings.
Assume therefore that $R$ is local artinian, with maximal ideal $J$. Since $J$ is nilpotent, it is contained in every prime ideal, so is the unique prime. Thus $\mathrm{Spec}\,R$ is a single point.

Spectrum of Artinian ring


Delphi invalid pointer operation using ADO

Question: When calling this code more than once (It's called on the change of a combobox), I'm getting the error "Operation not allowed when the object is open" on the second change and on the third onwards i'm getting "invalid pointer operation".
if loadfile.Database <> nil then
    loadfile.Database.destroy;
Loadfile.Database := Tdatabase.create(CardSets.Text, false);
LoadFile.Database.create(CardSets.Text, false);
refreshlist;

The create code is just
DataSource :=
    'Provider=Microsoft.Jet.OLEDB.4.0' +
    ';Data Source=' + Path +
    ';Jet OLEDB:Engine Type=5';
with MainWindow do
begin
    ADOConnection.ConnectionString := Datasource;
    ADOConnection.LoginPrompt := False;
end;

And refreshlist just updates a visual list of the data in the database.
I've looked at some similar stackoverflow questions but i am unable to see how the answers could help my problem.
Side question, When to use .Destroy or .Free? .Free in this case just gives a different error.
Thanks.
Comment: Why are you calling `create` twice?
Comment: Anyway, use `FreeAndNil` - neither `destroy` nor `free` set the value to nil.
Comment: Is that not how you create an object? NVM: I'm an idiot , thanks!
Comment: Any time you see two dots in the same expression, that suggests your design is weak. You should not be assigning to LoadFile.Database. A method in the class of LoadFile should be assigning to Database. It would seem that Database is read/write. Step 1 is to make it read only, or even private. More broadly it looks like your model is mixed in with your GUI. That's a mess.
Answer: First, you're calling Create twice; the second is unnecessary:
if loadfile.Database <> nil then
    loadfile.Database.destroy;
Loadfile.Database := Tdatabase.create(CardSets.Text, false);  // First call
LoadFile.Database.create(CardSets.Text, false);               // Second call

Change your code to simply:
LoadFile.Database.Free;
LoadFile.Database := TDatabase.Create(CardSets.Text, False);

Second, never directly call Destroy. Use Free instead, as it checks first for an unassigned pointer and then calls Destroy if it's safe to do so. TObject.Free is basically this code:
procedure TObject.Free;
begin
  if Self <> nil then
    Destroy;
end;

Comment: If i call  `Loadfile.Database.Free` when the object hasn't been created will i get an error? So is the If business useless?
Comment: You've not provided enough context. The constructor of LoadFile (whatever that is) should be creating the initial database instance; I'm not sure how it would get accessed before it is created. I'm not even clear why you'd want to free the database and recreate it, frankly. You can simply disconnect, change the connection string, and then reconnect, without the overhead of calling the constructor at all.
Comment: To directly answer your comment's question, however: `TObject.Free` checks first to ensure `Self <> nil` before calling the destructor (you can see that yourself in `System.pas`). The code there is `if Self <> nil then Destroy;`. (See my edited answer.)
Comment: Loadfile is a form, and (currently) the TDatabase object is pretty much just a holder for a bunch of database altering functions and the holder of an ADOX_TLB catalog type. Yes i see what you're saying, my way is a bit convoluted. Thanks


Is there any relationship between DBMS and File Processing System?

Question: Friends I need some information regarding that is there any relationship between DBMS and File Processing System? If so then please tell me and also tell me some easy example as well as complex example if u can?
Comment: This is a very general question for this site. Why do you ask it? Can you be more specific? What is wrong with [this answer](https://answers.yahoo.com/question/index?qid=20120221021136AA4VsMR)?
Answer: There is no relationship between DBMS and FPS except from the fact that you can store, retrieve and manipulate the data in both the system. But due to some disadvantages like data incosistency, data redundancy FPS was deprecated and DBMS has been introduced which helps in maintaing the relationship between the data & follows ACID property as well.
Hope this answers your question ... :)


Can a tremolo have a value of over one quarter note per note?

Question: I was wondering if tremolos can make a note separated into quarter notes. For example, a half note with a bar over it means to divide it into eighth notes, and a whole note with three bars over it means to divide it into thirty-second notes.
Is there any way to notate a note divided into quarter notes, as quarter notes don't have flags to denote as bars above a note?
Moreover, does the same apply to half notes, etc.?
Comment: Why would you want to do that?
Comment: @PiedPiper It's just some weird music theory I'm willing to try out, I'm currently composing a piece with the meter of 16/4 and it's Presto so I'm asking to make a tremolo so I don't have to spam the chords 32 times
Comment: If you wrote it in 16/8 it would be much easier to read
Comment: Just change to 4/4 and adjust your note lengths accordingly, i.e. 16/4 quarter notes become sixteenth notes.
Answer: Basically no.  You'd need rather unusual meters for that to save a useful amount of space.  Remember that tremolo notation is a shorthand and can always be written out explicitly.
Answer: PiedPiper and user65529 are right: why would you want to and basically no. But if you're familiar with sim. (simile) it might be useful. I can't really picture what you're doing though.
Answer: Tremolo repeats cannot be used for notes as long as crotchets (quarter notes).
However, you could use simile slashes/percent repeats. For example:
Answer: According to this...
https://en.wikipedia.org/wiki/Abbreviation_(music)#Repetition_of_a_single_note_or_chord
...divisi dots can be placed over long notes to show quarter note repetition.

...you may want to confirm that with source other than Wikipedia.


Validar captcha antes de enviar formulário

Question: Preciso de um captcha bem simples, mas que possa ser validado antes do formulário ser enviado, como posso fazer isso?
Atualmente uso esse:
index.html
<form method="post" action="valida.php" id="form" name="form">

        Captcha*:
        <input type="text" name="palavra" id="palavra" class="form-control input-lg" required>

</form>

captcha.php
<?php
session_start();
header("Content-type: image/jpeg");

function captcha($largura,$altura,$tamanho_fonte,$quantidade_letras){
    $imagem = imagecreate($largura,$altura);
    $fonte = "verdana.ttf";
    $preto  = imagecolorallocate($imagem,243,243,243);
    $branco = imagecolorallocate($imagem,0,151,182);

    $palavra = substr(str_shuffle("ABCDEFGHJKLMNPQRSTUVYXWZ23456789"),0,($quantidade_letras));
    $_SESSION["palavra"] = $palavra;
    for($i = 1; $i <= $quantidade_letras; $i++){
        imagettftext($imagem,$tamanho_fonte,rand(0,0),($tamanho_fonte*$i),($tamanho_fonte + 10),$branco,$fonte,substr($palavra,($i-1),1));
    }
    imagejpeg($imagem);
    imagedestroy($imagem);
}

$largura = $_GET["l"];
$altura = $_GET["a"];
$tamanho_fonte = $_GET["tf"];
$quantidade_letras = $_GET["ql"];
captcha($largura,$altura,$tamanho_fonte,$quantidade_letras);
?>

valida.php
if ($_POST["palavra"] == $_SESSION["palavra"]) {
    //...
}

mas não sei como verificar se o captcha foi preenchido corretamente antes de enviar o formulário.
Comment: Com esse `if` que tem em baixo não faz isso?
Comment: sim, mas pra chegar ali o formulário já foi enviado, eu queria que ele verificasse antes de enviar. Tem como @Miguel?
Comment: O problema é a definição de "já foi enviado". "Não" há como você saber se está preenchido corretamente (ou não), sem que envie uma requisição ao servidor. O que você pode fazer é criar um ajax para quando o usuário digitar enviar uma requisição ao servidor. Então retornar ao javascript se está correto ou não. Se estiver correto o usuário poderá permitir o usuário enviar o formulário. Eu aconselharia usar o Google ReCaptcha, para tal finalidade, de qualquer forma.
Comment: Entendi, mas não tem como comparar o que o cara ta digitando com o que está em sessão @Inkeliz? Pensei nisso agr mas não sei se funcionaria nem como seria.
Comment: Existe, desde que use Javascript para essa finalidade. Mas qual seria o real intuito de verificar o captcha antes de enviar o formulário? Acredito que exista alguma outra solução, melhor do que fazer duas requisições, sendo uma apenas para verificar o captcha.
Comment: É que o formulário é integrado com uma ferramenta externa para computar os dados enviados e isso é feito no ato do envio do formulário, então se o captcha estiver certo ou não ele vai computar de qualquer forma se eu tiver de enviar pra verificar.
Comment: Utilize recaptcha no google, entre https://www.google.com/recaptcha/intro/index.html é mais facil de grátis e tem tutorial facilidade para fazer.
Answer: No método ou função que trata o envio do formulário, você poderá consultar o Captcha via Ajax, então, se estiver OK, você pode submeter os demais dados do formulário.
Answer: Bom, consegui da seguinte forma:
No meu input do captcha em chamo uma função Cap():
<form method="post" action="#" id="form" name="form">

        Captcha*:
        <input type="text" name="palavra" id="palavra" class="form-control input-lg" onkeyup="Cap();" required>

</form>

A função Cap() por sua vez envia o form via ajax para verificar o captcha e habilitar ou desabilitar o botão de envio do formulário de acordo com a resposta.:

O valida.php ficou assim:
<?php
session_start();
if ($_POST["palavra"] == $_SESSION["palavra"]) {
    echo "success";
} else {
    echo "error";
}
?>

O captcha.php permaneceu da mesma forma. Não sei se é a melhor forma de se fazer, mas está funcionando bem e suprindo a necessidade atual.


Mapeamento de Herança Type per Type Asp.Net

Question: Em meu projeto, possuo um tipo de herança que mapeei por TPT. Analisando os documentos e vários exemplos não consigo identificar onde estou errando, pois o mapeamento aparentemente está correto, as definições das classes, tudo.
Problema: Possuo três classes: Pessoa, Cliente e Corretor. Cliente e Corretor herdam de Pessoa e assim está no mapeamento.
Quando no sistema faço qualquer busca utilizando o DbSet das subclasses, a query que o identity monta é buscando da classe pai, ou seja, se fiz uma busca utilizando o tipo Cliente, o identity monta uma query partindo da superclasse (Pessoa) e não da subclasse (Cliente).
public abstract class Pessoa
{
    public Pessoa()
    {
    }

    public string Nome { get; set; }
    public string NumeroCpfCnpj { get; set; }
    public string NumeroRgIe { get; set; }
    public string FlagEstadoCivil { get; set; }
    public string Profissao { get; set; }
    public DateTime DataDeNascimento { get; set; }
    public string TelefoneFixo { get; set; }
    public string TelefoneCelular { get; set; }
    public string Fax { get; set; }
    public string Endereco { get; set; }
    public string Numero { get; set; }
    public string Complemento { get; set; }
    public string NomeMae { get; set; }
    public string NomePai { get; set; }
    public string NomeConjuge { get; set; }
    public DateTime DataNascimentoConjuge { get; set; }
    public DateTime DataCasamento { get; set; }
    public string Email { get; set; }
    public float RendaFamiliar { get; set; }
    public string Bairro { get; set; }
    public string CEP { get; set; }
    public int? CidadeId { get; set; }
    public string Observacoes { get; set; }
    public int RegimeCasamentoId { get; set; }
    public int EstadoCivilId { get; set; }
    public bool IsDeleted { get; set; }
    public DateTime DataEmissao { get; set; }
    public string OrgaoEmissor { get; set; }
    public string EstadoEmitente { get; set; }
    public Sexo Sexo { get; set; }
}

public class Cliente : Pessoa
{
    public Cliente()
    {
        FlagMauPagador = false;
        StatusCobrancaId = 1;
        FlagImpedirRealizarVenda = false;
        FlagImpedirGerarBoleto = false;
        FlagImpedirSairNoRelatorioCobranca = false;
    }

    public bool FlagMauPagador { get; set; }
    public int StatusCobrancaId { get; set; }
    public bool FlagImpedirRealizarVenda { get; set; }
    public bool FlagImpedirGerarBoleto { get; set; }
    public bool FlagImpedirSairNoRelatorioCobranca { get; set; }
}

public class Corretor : Pessoa
{
    public Corretor()
    {
        Produtos = new List<Produto>();
        Loteamentos = new List<Loteamento>();
    }

    public int CodCorretor { get; set; }
    public string NomeCorretor { get; set; }
    public string Creci { get; set; }
    public decimal ValorDescontoMaximo { get; set; }
    public int? IdParceiroVenda { get; set; }
    public bool flgAtivo { get; set; }
    public ICollection<Produto> Produtos { get; set; }
    public ICollection<Loteamento> Loteamentos { get; set; }
}

public class PessoaConfiguration : EntityTypeConfiguration<Pessoa>
{
    public PessoaConfiguration()
    {
        ToTable("pessoa");

        HasKey(c => c.Id);

        Property(c => c.Id)
            .HasColumnName("cod_pessoa")
            .IsRequired();

        [...]

     }
}

 public class CorretorConfiguration : EntityTypeConfiguration<Corretor>
{
    public CorretorConfiguration()
    {
        ToTable("corretor");

       [...]
    }
}

public class ClienteConfiguration : EntityTypeConfiguration<Cliente>
{
    public ClienteConfiguration()
    {
        ToTable("cliente");

          [...]
     }
}

Comment: Como está configurado o seu `DbContext` Coloque toda a classe na pergunta? e suas classes também e qual código se está realizando a pesquisa?
Comment: E as consultas e o DbContext????
Answer: Observação: Tem ajustes a fazer, na classe abstrata Pessoa tem que possuir a Id que tem a finalidade de gerar o código identificador da tabela Pessoa e que será utilizado para gravar nas tabelas Cliente e Corretor que também possui um campo de Id mas, não é auto incremento, inclusive em Corretor não precisa ter o campo CodCorretor é para remover
public abstract class Pessoa
{
    public Pessoa()
    {
    }
    public int Id { get; set; } // campo a ser inserido
    public string Nome { get; set; }
    public string NumeroCpfCnpj { get; set; }
    public string NumeroRgIe { get; set; }
    public string FlagEstadoCivil { get; set; }
    public string Profissao { get; set; }
    public DateTime DataDeNascimento { get; set; }
    public string TelefoneFixo { get; set; }
    public string TelefoneCelular { get; set; }
    public string Fax { get; set; }
    public string Endereco { get; set; }
    public string Numero { get; set; }
    public string Complemento { get; set; }
    public string NomeMae { get; set; }
    public string NomePai { get; set; }
    public string NomeConjuge { get; set; }
    public DateTime DataNascimentoConjuge { get; set; }
    public DateTime DataCasamento { get; set; }
    public string Email { get; set; }
    public float RendaFamiliar { get; set; }
    public string Bairro { get; set; }
    public string CEP { get; set; }
    public int? CidadeId { get; set; }
    public string Observacoes { get; set; }
    public int RegimeCasamentoId { get; set; }
    public int EstadoCivilId { get; set; }
    public bool IsDeleted { get; set; }
    public DateTime DataEmissao { get; set; }
    public string OrgaoEmissor { get; set; }
    public string EstadoEmitente { get; set; }
    public Sexo Sexo { get; set; }
}

Já nas classes Corretor e Cliente não precisa ter esse campo Id, somente nas tabelas como explicado na observação.
Reconfigure a parte do mapeamento das 3 classes, referente as mudanças

Para ter o efeito esperado deve-se agora criar um classe herdando do DbContext com o seguinte código:
public class Database : DbContext
{
    public Database()
        :base("connectionString") { }

    public DbSet<Pessoa> Pessoa {get;set;}
}

Para inserir dados crie classes
Database db = new Database();

Cliente c = new Cliente();
c. ... // aqui sãos os campos e seus valores

db.Pessoa.Add(c);
db.SaveChanges();

e
Corretor co = new Corretor();
co. ... // aqui sãos os campos e seus valores

db.Pessoa.Add(co);
db.SaveChanges();

Para recuperar as informações deve utilizar o metodo OfType<> oferecendo o tipo corresponde para recuperação (que no caso é Cliente ou Corretor), exemplo:
//Corretor
Corretor co = db.Pessoa.OfType<Corretor>().where(c => c.Id == 1).FirstOrDefault();

//Cliente
Cliente c = db.Pessoa.OfType<Cliente>().where(c => c.Id == 2).FirstOrDefault();

Um exemplo claro seria nesse link, que pode ser utilizado como exemplo também.
Referencias:

Entity Framework Working with DbContext
Método ObjectQuery.OfType()
Inheritance with EF Code First: Part 2 – Table per Type (TPT)
Entity Framework Designer TPT Inheritance


Loading continues even though all data has already been fetched

Question: Opera keeps loading on my page, it shows something like 64/64 elements loaded or 44/44. How do I find out what makes it load so long? This problem only occurs in Opera, Chrome, Ie and FF just finish loading.
Answer: One easy way to see if it is indeed a pending network request (for an image resource, or css, etc) is to install Fiddler debugging proxy. After starting the Fiddler tool and navigating with your browser your website you'll see what network requests are issued and their respective status (pending, completed, error, etc)... Check for a "pending" network request...
Comment: Fiddler does not intercept opera calls. It works with Chrome, but that does not help me.
Comment: You can set Opera to use Fiddler as a proxy. Go to opera settings you'll find it somewhere. Th proxy address will be: http://127.0.0.1:8888 or http://yourlocalip:8888
Comment: I cannot find the status statement. Are you referring to 404, 200, 403 etc? What would be pending then?


How to analyse a right skewed dataset

Question: I am trying to analyse several heavily right skewed datasets in order to determine their mode.
The story behind the sets is that they are calculations of performance data from marketing posts. The datasets are the calculations and I am trying to use to determine a baseline for scoring future posts. My theory is that the centre of the mode (after binning the data and creating a histogram) would be the target baseline and new posts will be scored against this baseline to determine a score from 0-100. The reason for the heavily right skewed datasets are largely due to badly performing posts. The tail of these sets can be huge. I am aware of major outliers and have ways to manage that.
The reality is though... I am not a mathematician and this is essentially a side project I am doing my best to see it through. My theory above is as close as I have got to a working model for the scoring system but I'm open to suggestion on better/more accurate statistical frameworks for doing this... I would say though that any suggestions should be explained as if I'm 5.
Thank you in advance for your help and understanding.
Comment: Hi, welcome to the site! Can you expand on what you mean by "mode"? Because I think it's something different than what statisticians have in mind :)
Comment: Hi John, thank you for responding and apologies if I've got my terminology mixed up. I am binning the data then checking for the bin with the highest number of data points in that bin. This is what I am interpreting as the 'mode'. None of the numbers are the same in any of the datasets, so finding the actual 'mode' was not possible. Hence why i went down the binning/histogram route. TIA
Comment: Ah no OK we have the same idea for "mode"! I'm going to try to rephrase your question, and you let me know what I got wrong. You're saying "I have these results I want to use to help calibrate/quantify future performance data by assigning them a score from 0-100." And you were essentially viewing the mode of the data you've collected so far as a means of doing that, is that right?
Comment: That sounds about right yes
Comment: Yeah word, I'm going to ditch the idea of using the mode in my answer, let me know if that was essential for some reason.
Comment: Ah wait actually one more question: you say you have right-skewness (i.e. some very big numbers) due to underperformance. Does that mean that for your dataset, a big number means low performance?
Comment: Yes, that would be true of these datasets.
Answer: The approach I would take is to score new performance data by computing what its percentile would be on your existing data. You can either do this directly or by modeling your data with a probability distribution.
Or, well, because a percentile tells us what percent of our previous data is less than a particular datapoint, we probably want to look at 100-the percentile instead, that way 100 is as good as possible instead of as bad as possible.
I'm going to demonstrate this procedure using python. I'm going to be using these libraries:
import numpy as np
import scipy.stats as stats

The first thing I'm going to do is create some example data (you can skip this step, since you already have some):
# Create some fake data (you already have some so can skip this :)).
old_data = stats.gamma.rvs(5, scale=22, size=1000)
new_data = np.array([50, 80, 100, 200])

Here's the first approach, of manually computing percentiles. We just calculate what percent of the existing performances we exceed:
# Approach 1: Empirical Percentiles.
for i in range(len(new_data)):
    print(100-np.mean(new_data[i] > old_data) * 100)

The result of this is
91.5
68.1
49.4
5.5

If you fancy it, you can use a parametric distribution instead. I'm trying the Gamma distribution out:
# Approach 2: Model-based percentiles.
# Step 1: Find a Gamma distribution that fits your data
alpha, _, beta = stats.gamma.fit(data, floc = 0.)

# Step 2: Use that distribution's CDF to get percentiles.
scores = 100-100*stats.gamma.cdf(new_data, a = alpha, scale=beta)
print(scores)

The result of this is:
[92.38913684 70.38297238 52.46867026  4.86655548]

It would have to be a rather precocious 5 year old who understands this, so feel free to fire off questions.
Comment: @bubbaspaarx happy to help. The parametric approach smooths the data, but also imposes additional assumptions. Frankly, it's probably an inferior approach unless you have very few historical data, but it does allow for nonconstant scoring outside of the range of our previous data, which our first approach does not.
Comment: @bubbaspaarx can you clarify: it sounds like rather than just doing this once, you've got several datasets for which you would like to develop individual scoring rules? In this case, it's a little more complex, but it may be possible to reliably go below "100 data" by borrowing strength between datasets. I have "100 data" in quotes cause it's not clear to me off the top of my head what a reasonable cutoff is.
Comment: @bubbaspaarx gotcha, the good news is that it's not hard to implement ourselves using Method of Moments estimation. If you look at the Wiki page for the Gamma distribution, the "info panel" on the right at the very bottom you'll see method of moments. E[X] means your sample mean, and V[X] means your sample variance, and its how we go from data to parameters for the Gamma distribution. One "gotcha" is that there are two common parameterizations of the Gamma (hence the two columns on Wiki), and you've got to figure out which one your Ruby Gamma cdf function is using.
Comment: @bubbaspaarx doesn't matter whether you use N-1 or N for variance calculation (lord knows why society has spent so much time thinking about that) i.e. whether you use Bessel's correction or not. The inverse of the CDF is either called just the "inverse cdf" or the "probability point function" (ppf), I don't see it in the docs you linked unfortunately.
Comment: Wow! Thank you John!
I understood everything up to the word parametric and also tried the python code myself. I'm building this in ruby due to the projects code base but I can convert the calculations.
It's a really neat and tidy model for creating the scores and I believe it will produce more accurate results too.
If you could expand on the parametric side of things, I would be grateful. I assume this is smoothing the data in some way?
Comment: I have asked many many people in my circle of friends, family and work but have not had anyone able to resolve this. Most people had suggested z-scores or standard deviation which don't work well with skewed data. I'm over the moon with this.
Thank you again. If you are ever in the Warwickshire area of the UK. Send me a message and there's a drink with your name on it
Comment: That may actually help me in some ways. I'll see if there's a ruby implementation that could assist in doing this. A large problem I have is that the datasets to perform this task on are regularly in the low hundreds. I've set a min of 100 datapoints for a dataset but I'm sure this is realistically too low. Would the parametric approach help or hinder this situation do you think?
Comment: The datasets are similar but are worked from different variables. Hard to explain but I don't think it would be a good idea to mix them in any way.
Actually, I chose 100 primarily because I was binning the data and with some sets this could be really unreliable. Perhaps with this approach it will be fine to go lower.

The vast majority of datasets will be (low = good) but there are some where it's the other way around. I.e. some are 'cost per x' type calculations so low is good, but others are 'x as a rate of x' so high would be good. Not sure if that helps
Comment: Struggling to find something that can perform the 'gamma.fit' function in ruby at the moment. I have looked at a couple of statistics packages but nothing stands out as being able to create the needed alpha and scale.
Comment: Hi John, thank you very much for the latest info. I have been attempting to calculate the alpha, beta, K and O(rate). So far I think I must have got something wrong.
I started by looking at how to get the sample variance for my data and the mean too. I have those figures but when I use them on the ruby cdf packages, I don't get what I expected. One of the packages just returns 1.0 and the other (99.99207541099827) regardless of what number you pass it.. bit lost here.
Comment: The two packages in question

https://github.com/phillbaker/rubystats/blob/master/lib/rubystats/gamma_distribution.rb

https://rubydoc.info/gems/distribution/Distribution/Gamma/Ruby_
Comment: Ah... I think I solved it. I hadn't seen on the Distribution Gems docs that beta should be input as '1 / beta'

100-100*(Distribution::Gamma::Ruby_.cdf(55, alpha, 1/beta))
Comment: I have a question about bessels correction for sample variance. I understand that it should only be used on a "sufficiently large data set" which is a touch ambiguous. Is under 1000 points too small or even, too large for bessels correction to be used?
I'm also trying to find out what the 50th percentile of my new gamma distribution is. Not sure there's a simple backwards calculation for that though
Comment: Brilliant. Thank you again. I've learnt a huge amount!
Comment: Think I found it in the docs but under a slightly different title... I tried with alpha and theta instead of beta and it appears to be right... I reversed the value and the percentile it returned was 49.99 recurring.
Comment: https://www.rubydoc.info/gems/distribution/Distribution/Gamma/GSL_#quantile-class_method
Comment: 1 last question John. Is there a way to arbitrarily set a minimum to the distribution?
For instance. If I know that the absolute lowest number possible is 1, can I set that so that the distribution works with that. Or is this now a completely different calculation?
Thank you again for all your help.
Comment: The Gamma distribution starts at zero, but you can make your performance data start at zero too by subtracting 1 from each :)

How to analyse a right skewed dataset


What python 3 library should I use for MySQL?

Question: As far as I know MySQLdb still isn't ported to Python 3.
There seems to be another library called PyMySQL on pypy but the installation for python 3 looks strange (run a .sh script?). Also there is a library called PyMySQL3 but I can't find info about what it's about.
What's the preferred way to use MySQL with Python 3 these days?
Is there an elegant solution that could be installed with pip or with a python setup.py install command?
Answer: I've used the basic mysql-connector from MySQL for a few Python 3 projects, along with SQLAlchemy.
I also tried PyMySQL, but if I remember correctly I had a more difficult time configuring it.
Comment: mysql-connector is externally hosted, so, now, in March 2015, it's necessary to do  `pip3 install mysql-connector-python --allow-external mysql-connector-python` to install it
Comment: Update: now in October 2016 the '--allow-external' option is deprecated. To install mysql-connector now, you have to specify directly the url of the setup archive (hosted on the mysql servers): `pip3 install http://cdn.mysql.com/Downloads/Connector-Python/mysql-connector-python-2.0.4.zip#md5=3df394d89300db95163f17c843ef49df` It is possible to obtain the latest url for the file on https://pypi.python.org/pypi/mysql-connector-python/
Comment: Awesome, mysql-connector seems to be working. Supported by the mysql team and I could install it very easily with pip (`pip-python3 install mysql-connector-python`). I just created a table. I hope everything else works too but I see no reason why it wouldn't. Thank you very much!
Answer: For people porting code that previously used MySQL-python on Python 2 (imported with import MySQLdb), the drop-in replacement is mysqlclient, a fork of MySQL-python that:

Is imported under the same name (MySQLdb)
Remains C-accelerated for speed
Is compatible with Python 2 and 3 and fixes several bugs from the original MySQL-python

mysql-connector is perfectly fine (it's the Oracle developed solution), though the interface differs a bit, and being implemented in Python makes it slower. Same general comments apply to PyMySQL. If performance/compatibility doesn't matter, all of them are good, but for maximum performance and full compatibility with MySQL-python/MySQLdb, you want mysqlclient (for a code-base that's otherwise fully Py2/Py3 compatible, it will work on either version, and require no changes to the source code, just the dependencies declared in setup.py).


Understanding the 'axis' parameter in the softmax activation function

Question: Suppose i have an input tensor carrying one embedded word per timestep, eg for a time window of 5 and word embedding vector width of 64 i get the shape:
(None, 5, 64, 1)
I apply 4 filters with a kernel shape of (1, 64) to look for specific words at each time step, each filter produces 1 value per timestep denoting "word/meaning exists" or "word/meaning does not exist". It produces an output tensor of shape:
(None, 5, 1, 4)
How do i define the 'axis' parameter of the softmax layer such that the outputs of all convolutions per timestep are normalized, like in a classification task?
More specifically, i want the output to look like the following (height is time, width is channels):
[[[.1, .4, .4, .1]]
 [[.9,  0,  0, .1]]
 [[.8,  0, .1, .1]]
 [[ 0,  1,  0,  0]]
 [[.6,. 1, .1, .2]]]

Ie the components per row/timestep add up to one, the softmax should only normalize rows.
Code snippet:
model.add(layers.Conv2D(
    filters=words_of_interest,
    kernel_size=(1, embedding_length),
    strides=(1, embedding_length),
    padding="same")
)
model.add(layers.Softmax(axis=3)) # <- is this correct for what i described above?

Answer: For all values of axis its okay. Tensorflow normalized the values of the array in same way. Here you can check the difference between tensor and normalized using below code.
import numpy as np
import tensorflow as tf

array = np.random.random((5, 4))
tensor = tf.convert_to_tensor(array)

norm0 = tf.keras.activations.softmax(tensor, axis=0)
norm1 = tf.keras.activations.softmax(tensor, axis=1)
norm2 = tf.keras.activations.softmax(tensor, axis=2)
norm3 = tf.keras.activations.softmax(tensor, axis=3)

print(sum(tensor[0]))
print(sum[norm0[0]])
print(sum[norm1[0]])
print(sum[norm2[0]])
print(sum[norm3[0]])


Multiclass vs Multilabel (How to Build Training Data Labels)

Question: Currently, I am working on projects in which I have to classify the restaurant review data. I am using multinomial Naive Bayes algorithm. I am bit confused that my problem is related to multiclass or multilabel.
review example-

Please treat your customer like customer, not dogs. .I will never go or advice anyone to go at Naivedyam, Hauz Khas.They guys are sick and complete businessman. Food was ver bad in taste, but place and staff were too dirty
  It contains three different classes like

Bad Experience
Staff Behavior
food quality
How to create the training data set?
If problem is related to multilabel then how I can create the training data set. example
<code>ID Content                    Tags
1, "content of the review#1", Bad Experience,Staff Behavior,food quality
</code>
or
<code>    ID    Content                    Tags
   1, "content of the review#1", Bad Experience
   2, "content of the review#1", Staff Behavior
   3, "content of the review#1", food quality
</code>
Any suggestion
Answer: Although I doubt that classification is the way to tackle this problem, I would recommend you to encode your variables as follows:
<code>   ID    Content                    Bad Experience Staff Behavior Food Quality
   1,    "content of the review#1", 1,             1,             1
</code>
For each tag you write a 1 if it is active for a review and 0, if not. Using such encoding would make your problem a multilabel problem with only binary classes for each label.
Answer: What's all of the available Tags? It seems the tags are describing the experience from different perspective. If that is the case, I would suggest you to build multiple models to classify different on different perspective. Say

Classifier 1: classification on if food quality, good or bad on food.
Classifier 2: classification on if staff behavior, good or bad on service
Classifier 3: classification on overall experience, good or bad on overall experience.


Create menu tabs with views

Question: How can create menu views tabs of node? In Drupal 7 i can create views like this:

when i visit node/1/teaser it's show good.

But with same setting in drupal 8.

when i visit node/1 show error:

Symfony\Component\Routing\Exception\MissingMandatoryParametersException:
  Some mandatory parameters are missing ("arg_0") to generate a URL for
  route "view.menu_tabs.page_1". in
  Drupal\Core\Routing\UrlGenerator->doGenerate() (line 171 of
  core/lib/Drupal/Core/Routing/UrlGenerator.php).

and node/1/teaser show error:

Symfony\Component\Routing\Exception\MissingMandatoryParametersException:
  Some mandatory parameters are missing ("node") to generate a URL for
  route "entity.node.devel_load". in
  Drupal\Core\Routing\UrlGenerator->doGenerate() (line 171 of
  core/lib/Drupal/Core/Routing/UrlGenerator.php).
Answer: This is a known issue in views.
The issue is that the route parameter for entities needs to be named:

This view will be displayed by visiting this path on your site. You
  may use "%" or named route parameters like "%node" in your URL to
  represent values that will be used for contextual filters: For
  example, "node/%node/feed" or "view_path/%". The named route
  parameters are necessary when used within paths used by entities such
  as "taxonomy/term/%taxonomy_term" or "user/%user/custom-view

This is for the first error message.
The second one is caused by the devel module. If you still get this error after renaming the route parameter, you have to check the issue queue from this module.

Create menu tabs with views


Help me pick the perfect string!

Question: I busted my strings while trying to tune by ear.
This is my guitar.
As for the type of music I am looking to learn, I'd say it would be rock and blues. I also love Tommy Emmanuels which is to say that I am also looking to learn fingerstyle (without the thumbpick).I will probably be playing mostly in E standard.
With my current strings, I am able to fingerpick just fine, but when it comes to doing barre chords (in the first few frets near the nut), it proves to be near impossible. I have literally taken the guitar on my lap, squashed the strings with my THUMB and still failed to produce a clean strum, let alone using my index finger.
I decided on these strings for the following reasons:
-Phosphor , so prolonged lifespan( idc about volume all too much)
-Reduced tension would help me barre more easily at the places where I am currently struggling and also allow me to experiment with some bending. Probably help in a solo I suppose.
But I have some concerns:
-Would I be able to play strumming songs like say, Wonderwall or Boulevard of Broken dreams without worrying about them breaking?
-Would these strings be able to handle the 25'' scale length of my guitar?
Any suggestions/correction and most importantly advice is needed!
Answer: 25" scale is fairly common, and often acoustic guitars with that are sold with .011s, so .010s will be fine. I'd go (and often do) to .009s, or even .008s, but that's me.
With standard tuning, there should be no breakages strumming. Maybe you need to examine your technique, and not strum so hard, and feather the pick better.
Your problem with barring could well be the action which could be too high, meaning it's difficult to press down with as little effort as it should be. For now, you could try tuning down a semitone, like so many have and still do. This relieves the tension a little, making barring easier.
People tell me that thin strings break more easily: in 50 years using them, I've never found it to be true.
Comment: Out of curiosity, do thin strings feel flimsy or awkward when doing power chords?
Comment: My strumming isn't all too hard, and I usually strum moderately hard using the nail of my index finger (it feels far more comfortable)
Comment: @chirag - no, I don't think so - one can get used to the feel. Having said that, I don't play 'power chords' - they just don't do anything for me! Using a fingernail, how do you upstrum?
Comment: I use my index for the downstrum and my thumb for the upstrum. But I use a pick when I feel some discomfort or I just want it to be less mellow.
Comment: is ernie ball a reliable brand?
Comment: Only used them for 30+ yrs. Not sure yet...
Comment: Haha.K Good to know!
Answer: Trying to find a "perfect string" is a huge red herring.  How do you know you have a half way descent guitar, or pick, or proper finger nails, or technique?
If you cannot do barre chords it could be the action on the guitar, in which case no string will feel good.  But you should also know that it takes years to develop proper technique and feel in the hands.  Once you get it right you won't remember how or why you couldn't do it but you need patience. Even if the guitar is set up beautifully and have a good quality set of light gauge strings you might still have trouble getting a clean sound on some chords until you've put in the 10k hours of practice.
As a comparison, I use medium gauge Martin bronze strings on my 12 string and strum with all my might at times (for example playing Pinball Wizard by The Who) and never break a string.  It might help to know where they break (if and when they do).  If it's at a certain fret then they frets need filing (to be dressed).  If it's by the bridge then the grooves for the string might be too sharp.
Comment: It broke at the tuning knob for me, so I don't know for sure if I have overly exertive strumming. But assuming I do, by perfect I meant if that set of strings would allow me some room to strum that way or not, along with having the ease of playing.
Comment: It is still a red herring.   You need to have someone knowledgeable do a complete set up so everything is adjusted correctly.   No matter what, you can always break a string.   Are you taking lessons and are you s beginner?
Comment: Did it break at the tuning peg or nut?
Comment: The peg. I am learning by myself online after picking up the instrument after nearly 3  years (starting from scratch all over again).

Help me pick the perfect string!


How to make node title translatable?

Question: I have a content type in D8 that requires translation, however at the moment I appear to be only able to translate the individual fields and not the title.

The language selector is available on the content type edit page, but there seems to be no way of selecting to translate the title:

Other fields have a checkbox that allows them to be translatable:

Any ideas? Thanks in advance!
Comment: The title is set as translatable by default (in the entity definition). Somehow you've disabled translation for this field. You can check the translatable fields for all content types here: /admin/config/regional/content-language
Comment: Ah yes, that's the one! I don't think anyone has actively turned it off, it's a site in alpha build at the moment..! If you post this as an answer, I'll accept. Thanks!
Answer: The title is set as translatable by default (in the entity definition). Somehow you've disabled translation for this field. You can check the translatable fields for content entities here:
<code>/admin/config/regional/content-language
</code>
This includes all fields, also the base fields, which you can't configure in Manage Fields of the content type.

How to make node title translatable?


TRUNCATE error -1 obliterating my sites

Question: I keep getting a cache related error.

PDOException: SQLSTATE[HY000]: General error: 1030 Got error -1 from storage engine: TRUNCATE {cache} ; Array ( ) in cache_clear_all() (line 165 of C:\Program Files (x86)\EasyPHP-DevServer-14.1VC9\data\localweb\projects\web2\includes\cache.inc).

The issue is tied to the query file. The fix is to replace TRUNCATE with DELETE FROM in a query.inc file. That's all fine and dandy, and that error is gone. But, now I have a new one: The site is completely broken and thinks that the cache database folder still exists, which prevents me from importing the backup database, even if I drop the whole database.
In short: Backups are useless, as this error seems to do some heavy damage. As well, it shuts down the EasyPHP server.
To make things even worse, I was going over the huge site-crashing error report I just got, and it looks like the fix doesn't even work.
In regards with the above, I think it worked, but something else tied in with it is causing more cache errors.

PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'webone.cache_views_data' doesn't exist: DELETE FROM {cache_views_data} ; Array ( ) in cache_clear_all() (line 165 of C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\projects\webONE\includes\cache.inc).

I applied the fix I first mention to a new website, as a preventative this time. Low and behold, it came back on the first module install.
Answer: Why are these paths different when you talk about "your project":
path 1:
C:\Program Files (x86)\EasyPHP-DevServer-14.1VC9\data\localweb\projects\web2\includes\cache.inc
path 2:
C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\projects\webONE\includes\cache.inc)
This smells like something is horribly misconfigured.
I've made dozens of drupal sites, typically under Linux, but I have used WAMP myself in the past (not EasyPHP-DevServer). This makes me think it's an issue with the EasyPHP-DevServer and not drupal itself.
While you may not be familiar with it ... have you tried like copying your site files and DB to a Drupal 7 Quickstart project VirtualBox virtual machine, or  DrupalPro ... another off the shelf VM drupal-in-box ...
Comment: so seriously try and install drupal on windows either using the Windows Web Installer which is supported by Microsoft, or maybe XAMPP itself. https://www.drupal.org/documentation/install/windows  Because it seems like your server configuration is simply broken.
Comment: The paths are so different because I've changed a lot around. I was using V9 because EAsyPHP V11 wouldn't work no matter what. I figured using VC9 was the issue so I tried to figure out how to get VC11 working and succeeded there only to have the same error show up. Also, it seems like Drupal just doesn't like truncating and that is where conflicts come from.
Comment: I believe so. I didn't want to use any other products because I want my websites to be as authentic as possible while avoiding legal issues from unknowingly using closed-source software. But I've realized that my plan is in vain and that mostly anything to do with Drupal is open source. Right now this book has me installing Aptana and git. I'm probably going to submit to XAMPP.
Comment: Another +1 for xampp. That's what I use on windows.

TRUNCATE error -1 obliterating my sites


The statement "Any two opposite sides of a parallelogram are congruent" implies the parallel postulate

Question: Proving the converse is easy enough: you can construct a line between vertices of a parallelogram and then show the resulting triangles are congruent because of adjacent interior angles and ASA congruence of triangles.
However, doesn't the mere existence of a parallelogram imply the parallel postulate? I'm not really sure how to approach this.
Answer: It depends what you mean by a parallelogram. Suppose you have three sides of a parallelogram, defined as a figure with four sides, the opposite pairs being parallel (not meeting when extended indefinitely in either direction). What happens when you try to construct the fourth side?
You need a parallel to the "opposite" side. Pick a point for the fourth side to pass through (eg a presumed vertex). If there is a unique parallel, all is well. But what if there is more than one? You need to show that in this situation the congruence of the parallels means that there is only one, and hence implies the parallel postulate.

The statement “Any two opposite sides of a parallelogram are congruent” implies the parallel postulate


entity_lookup for user entity type

Question: I'm trying to link a field in my spreadsheet file to a user that is previously created with a migration from the same spreadsheet. The Backup column consists of multiple names divided by the backward slash (Firstname Lastname/Firstname Lastname)
migrate_plus.migration.profiles.yml:
process:
  field_backup:
    -
      plugin: explode
      delimiter: '/'
      source: 'Backup'
    -
      plugin: entity_lookup
      value_key: name
      ignore_case: true
      entity_type: user
      bundle_key: uid
      bundle: people

migrate_plus.migration.users.yml:
process:
    name:
      plugin: concat
      source:
        - 'Firstname'
        - 'Lastname'
      delimiter: ' '

The backup field is just skipped when migrating the profiles. The only error I'm getting is when i go to a profile page and check the log messages.

User error: "attributes" is an invalid render array key in
Drupal\Core\Render\Element::children() (regel 97 van
/var/www/html/web/core/lib/Drupal/Core/Render/Element.php) #0
/var/www/html/web/core/includes/bootstrap.inc(587):
_drupal_error_handler_real(256, '"attributes" is...', '/var/www/html/w...', 97, Array) #1 [internal function]:
_drupal_error_handler(256, '"attributes" is...', '/var/www/html/w...', 97, Array) #2
/var/www/html/web/core/lib/Drupal/Core/Render/Element.php(97):
trigger_error('"attributes" is...', 256) #3
...

Can you not use entity_lookup for users or am I doing something wrong in my configuration?
Any help would be much appreciated
Answer: bundle_key is the name of the column and bundle is any value associated with that column.
In the below example the migration process will look for those column in user table whose status is 1 and uid value is equal to userid.
 plugin: entity_lookup
 source: userid
 value_key: uid
 bundle_key: status
 bundle: 1
 entity_type: user
 ignore_case: true

Comment: *bundle_key* is the key containing the entity bundle. It cannot be used for other fields, as it would compare those to the entity bundle in the site receiving the migration.
Answer: If entity_lookup is searching for users, then the bundle should also be user, since there is no people bundle.

entity_lookup for user entity type


Change the format of the Data into JSON

Question: I want to change my data into desired JSON format. My data looks like this:
[
  "{
     id:001,
     name:akhilesh,
   }",
  "{
     id:002,
     name:Ram,
   }"
]

I want to convert the above data to valid JSON:
[
   {
     "id":"001",
     "name":"akhilesh"
   },
   {
     "id":"002",
     "name":"Ram"
   }
]

I tried the following, but none of these helped:

JSON.serialize
JSON.parse
eval

I need help for this.
The exact data response from server side is:
{
    "d": [
        "{id:413,title:ranjan,start:413,end:413}",
        "{id:414,title:raja,start:414,end:414}",
        "{id:415,title:raja g,start:415,end:415}",
        "{id:416,title:abhh,start:416,end:416}",
        "{id:417,title:chta,start:417,end:417}",
        "{id:418,title:Raju,start:418,end:418}",
        "{id:419,title:Ranjan,start:419,end:419}",
        "{id:420,title:Raja,start:420,end:420}",
        "{id:421,title:chitti,start:421,end:421}",
        "{id:422,title:Raja,start:422,end:422}",
        "{id:423,title:raja,start:423,end:423}",
        "{id:424,title:yash,start:424,end:424}",
        "{id:425,title:vsg,start:425,end:425}",
        "{id:431,title:Vimal11,start:431,end:431}",
        "{id:432,title:Aruhi,start:432,end:432}",
        "{id:434,title:Aruhi,start:434,end:434}",
        "{id:435,title:,start:435,end:435}",
        "{id:436,title:xs,start:436,end:436}",
        "{id:437,title:rajkj,start:437,end:437}",
        "{id:438,title:mmt,start:438,end:438}",
        "{id:439,title:xaxa,start:439,end:439}",
        "{id:440,title:yash,start:440,end:440}"
    ]
}

Server Side Code
[System.Web.Services.WebMethod]
public static List<string> getData()
{
    List<string> data = new List<string>();

    using (SqlConnection con = new SqlConnection("Data Source=ACME-PC\\SQL;Integrated Security=true;Initial Catalog=ClinicApplication"))
    {
        SqlCommand cmd = new SqlCommand("select DISTINCT Patient_ID,First_Name,fromtime,totime,Date from tbl_AddPatientInfo", con);
        {
            con.Open();
            SqlDataReader dr = cmd.ExecuteReader();

            while (dr.Read())
            {

                string id = "{" +
                    "\"id:\"" + dr["Patient_ID"].ToString() + "," +
                    "title:" + dr["First_Name"].ToString() + "," +
                    "start:" + dr["Patient_ID"].ToString() + "," +
                    "end:" + dr["Patient_ID"].ToString() +
                    "}";
                string ids = id.Replace(@"""", "");

                data.Add(ids);
            }
            return data;
        }
    }
}

Comment: why can't you return proper json from server itself ?
Comment: Fix the server side code to emit **valid** JSON. Do not attempt to fix broken JSON in JavaScript.
Comment: There is only one proper way to solve problems of incorrect data formats - stop using them. It is like "my web-server returns text in French and with many typos; I want it to be displayed in proper English".
Comment: @AkhileshSingh You should change the server to return valid JSON, now the data is not consistent. `title` contains space for 415 and it is not present for 435, if changing data format to JSON is not possible, at least make the data consistent
Comment: If that server is under control of your country, then you need to tell your manager that the server team is producing broken JSON. It's quite clear that they _intend_ to produce JSON but are just failing miserably. That's gross incompetence.
Comment: @Tushar i already go through to this link but its not working in my case, I tried again. After that i say to you sir and thanx for you precious time Sir.
Comment: @SalmanA: It's actually valid JSON (as far as I can see), just quite useless: It's an array in a dictionary, containing strings. Just the strings don't contain text, but something that seems to look a little bit like JSON. I've seen people sending strings containing _actual_ JSON (or XML, or HTML) which is enough of a pain, but this isn't.
Comment: @gnasher729 let me rephrase then: tweak the server side script to send useful JSON. Is that better?
Comment: @AkhileshSingh Please add the data exactly as you're getting in the response, no need of formatting it here as it'll invalidate the string.
Comment: 17 upvotes to do this guy's job for him!? Some day, you will go to a doctor's office and they will be running the code that this guy is asking for on Stack Overflow. Don't be an enabler.
Comment: Because i used list to return this , In list the data itself coming dynamically itself
Comment: Change `},]` to `}]` and `,}` to `}`. The extra commas suggests another item in the arrays. . For example, you want to keep the comma between `}{`.
Comment: @AkhileshSingh are you talking about `List` in java ?
Comment: List in C sharp @Susheel Singh
Comment: @Tushar i update the Code please lets a look.
Comment: @AkhileshSingh Can you change the server side API to return JSON encoded data?
Comment: i tried sir but its not changing , so i thought i can change it to client side, It is possible or not sir.
Comment: please post your `c#` code lets see if we can help you better
Comment: @AkhileshSingh See [How to return JSon object](http://stackoverflow.com/questions/16441880/how-to-return-json-object) and [How can My Asp.Net C# class return a json format](http://stackoverflow.com/questions/5300855/how-can-my-asp-net-c-sharp-class-return-a-json-format). Try `return new JavaScriptSerializer().Serialize(new data);` after including `using System.Web.Script.Serialization`
Answer: If you've control on how the response is sent from the server, I'd recommend to use json_encode(response); if using PHP or JSON.stringify(response) if using Javascript(node.js) or similar method for other languages. And then on client-side, you can use JSON.parse(response) directly on the response to get JSON object.
The elements of array need to be wrapped in quotes, so that it can be converted to JSON using JSON.parse. Then map can be used with JSON.parse.

var arr = [
    '{"id":"001","name":"akhilesh"}',
    '{"id":"002","name":"Ram"}'
];

arr = arr.map(JSON.parse);

console.log(arr);
document.getElementById('result').innerHTML = JSON.stringify(arr, 0, 4);

If you don't have quotes in the string, you can use regex to add them and make it suitable to pass to JSON.parse.
Demo

var arr = [
    "{id:001,name:akhilesh}",
    "{id:002,name:Ram}"
];

arr = arr.map(function(e) {
    // Add quotes on every alphanumeric character
    return JSON.parse(e.replace(/(\w+)/g, '"$1"'));
});

console.log(arr);
document.getElementById('result').innerHTML = JSON.stringify(arr, 0, 4);

Comment: did you read his question clearly ? he doesn't have double quotes in before and wants double quotes in after.
Comment: @SusheelSingh That's not **valid string**, that's formatted when added in question, there will be no spaces when the response is sent from the server
Comment: yes, but I don't feel good tinkering code on client side. I think it would be better if he can return json properly. so your answer is correct now. upvote
Comment: My data is coming dynamically it should work for this??
Comment: hope so, let the OP reply with exact data
Comment: @SusheelSingh I feel the same way, you can read my comments on answer and start of my answer :)
Comment: @Tushar Just a small note, PHP is `json_encode`, with an `_`, not a `.` :)
Answer: Instead of doing a complex regex(which is might not work in some conditions) by using javascript. Its better to do server side changes to get JSON data correctly.

Avoid building the JSON by string concatenation, since you risk sending broken data when the string contains certain special characters in JSON. This should be done with JSON serializer.

[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string getData(){
   List<Dictionary<string, string>> data = new List<Dictionary<string, string>>();
   Dictionary<string, string> item;
   using (SqlConnection con = new SqlConnection("Data Source=ACME-PC\\SQL;Integrated Security=true;Initial Catalog=ClinicApplication"))
   {
       SqlCommand cmd = new SqlCommand("select DISTINCT Patient_ID,First_Name,fromtime,totime,Date from tbl_AddPatientInfo", con);
       {
           con.Open();
           SqlDataReader dr = cmd.ExecuteReader();

           while (dr.Read())
           {
                item = new Dictionary<string, string>();
                item.Add("id", dr["Patient_ID"]+"");
                item.Add("title", dr["First_Name"]+"");
                item.Add("start", dr["Patient_ID"]+"");
                item.Add("end", dr["Patient_ID"]+"");
                data.Add(item);
           }
           return new JavaScriptSerializer().Serialize(data);
       }
    }
}

modification to your existing code:
[System.Web.Services.WebMethod]
public static List<string> getData(){
    List<string> data = new List<string>();
    using (SqlConnection con = new SqlConnection("Data Source=ACME-PC\\SQL;Integrated Security=true;Initial Catalog=ClinicApplication"))
    {
       SqlCommand cmd = new SqlCommand("select DISTINCT Patient_ID,First_Name,fromtime,totime,Date from tbl_AddPatientInfo", con);
       {
           con.Open();
           SqlDataReader dr = cmd.ExecuteReader();

           while (dr.Read())
           {
                string id = "{" +
                   "\"id\":"  + "\""+dr["Patient_ID"].ToString()+"\"" + "," +
                   "\"title\":" + "\""+dr["First_Name"].ToString()"\"" + "," +
                   "\"start\":" + "\""+dr["Patient_ID"].ToString()"\"" + "," +
                   "\"end\":" + "\""+dr["Patient_ID"].ToString() + "\""+
                   "}";
                data.Add(id);
           }
           return data;
       }
    }
}

Comment: just made a small change check again
Comment: are you getting correct response now. If not please post the updated output, I will help you further
Comment: Avoid building the JSON by string concatenation, since you risk sending broken data when the string contains certain special characters in JSON. This should be done with JSON serializer.
Answer: Fixing JSON via JavaScript is wrong. Using string functions to generate JSON on server side is equally rubbish. Your code will break for example when the data contains ", new lines and what not.
I would rather use some library that generates JSON. Here is a complete example that uses JavaScriptSerializer. It can convert various objects. Here we use a List of Dictionary objects:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Script.Serialization;

[WebService]
[ScriptService]

public class WebService1 : System.Web.Services.WebService
{
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string getData()
    {
        List<Dictionary<string, object>> data = new List<Dictionary<string, object>>();
        using (SqlConnection con = new SqlConnection("Data Source=ACME-PC\\SQL;Integrated Security=true;Initial Catalog=ClinicApplication"))
        {
            SqlCommand cmd = new SqlCommand("select DISTINCT Patient_ID,First_Name,fromtime,totime,Date from tbl_AddPatientInfo", con);
            {
                con.Open();
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    Dictionary<string, object> item = new Dictionary<string, object>();
                    item.Add("id", dr["Patient_ID"]);
                    item.Add("title", dr["First_Name"]);
                    item.Add("start", dr["Patient_ID"]);
                    item.Add("end", dr["Patient_ID"]);
                    data.Add(item);
                }
            }
        }
        return new JavaScriptSerializer().Serialize(data);
    }
}

Testing with jQuery:
jQuery.ajax({
    url: "/testing/WebService1.asmx/getData",
    method: "POST",
    contentType: "application/json",
    dataType: "json",
    success: function (json) {
        var data = jQuery.parseJSON(json.d);
        console.log(data);
    }
});

Console Log:
[{
    "id": 413,
    "title": "ranjan",
    "start": 413,
    "end": 413
}, {
    "id": 414,
    "title": "raja",
    "start": 414,
    "end": 414
}]

Comment: It is just for illustration. See Susheel's revised answer who borrowed code from my example to create complete example using data reader.
Comment: Sir you assign the value statically but my data is coming from database and then add to the list. How it can be done?

Change the format of the Data into JSON


Kerberos, delegation and how to do this correctly?

Question: I've got two separate homemade applications that need to communicate among themselves. One is a frontend application (asp.net actually), the other is a backend interface to an accounting application. The backend interface was not created specifically for this frontend - it is a generic interface that many other applications use to integrate with our product.
For the convenience of users we wish to provide a Windows Authentication in our frontend application. That means however that we need to pass the credentials on to the backend application which has to check them.
We do not wish to set up our frontend as a "trusted" application to the backend which can authenticate itself as any user. If the frontend was to be hacked, it would then also compromise the backend system.
As I understand it, one way to do it with Windows Authentication is Kerberos Delegation. However this requires to be explicitly enabled for the user that is to be delegated, and the machine which does the delegation (the server with our frontend). By default these options are disabled in Active Directory, and I suspect that many sysadmins will have their reservations about turning them on for all their users.
Also, I'm not really sure that this is what Kerberos Delegation was meant for. I don't need our frontend to impersonate the user that is connecting. I just need to prove that this user has authenticated itself to me.
How would you do this?
Comment: What's the back end authentication?  You indicate the front end is Windows Integrated (so an intranet app), but is the back end app WIA also?
Comment: Kerberos _is_ for this - eg Users on our LAN connect to a webserver which in turns connects to a SQL Server _using the users credentials_. This allows us to have per-table/field permissions depending on the user. The difficulty here is that both systems need to be aware of Kerberos delegation - the website to get the various tokens and the back-end to validate them against the same authority. I don't believe this will be possible directly but you may be able to set up a delegation-aware proxy between the UI and back-end.
Answer: I'm not clear what you can and can't do with your use case but I can answer the question what Kerberos Delegation was meant for.
First let's talk about what Kerberos does prior to delegation.  It is important to understand this part well because it is subtle.

Kerberos authenticates the identity of BOTH ends of a communication between two end-points across a network, those end-points can be interactive users or services running on a computer.

This is strong authentication so it will not allow a man-in-middle attack in any form.  If set up correctly an end point can guarantee they won't be compromised.  To the level of the service name (if you are connecting to IIs on a machine it is different than connecting to SQL Server on the same machine).  It makes heavy use of modern encryption techniques and requires the use of secure certificates.  The details of the authentication protocol are complicated and not worth going into now, but it involves about 20 different distinct steps of confirmation between the two authenticating end points and authentication server (in windows the Domain Controller is the authentication server).
So what the heck is delegation?

Delegation is a Microsoft extension to the Kerberos standard which
  allows a trusted source to continue the authentication to another
  end-point.

This allows you to act as a "man in the middle" -- however many settings have to be explicitly setup, certificates installed, etc to allow this to work.  It is far from simple. (EDIT: Here is another SO answer on the details - https://stackoverflow.com/a/954154/215752)
So, for example, you could have someone authenticate to a website and then have the .NET code connect to an SQL Server AS THE SAME USER to read data with that user's rights.

Now to answer your question, since I'm not sure what you want to do I present three choices:
1) You want to connect to the back end system as the SAME user as the one authenticating at the website.

In this case Kerberos delegation is perfect -- it does exactly what you want.

2) You want to connect to the back end system as a DIFFERENT user than the one authenticating at the website (eg a service account).

In this case you don't want delegation.  Kerberos to the website and Kerberos (as a different user) to the back-end will work great.

3) You want to connect to the back end system as the SAME user some of the time and as a DIFFERENT user other times.  (For example, you need to validate this is a legal user for the back end system, but want to perform trusted actions as a system account other times.  This is (in my experience) the most common use case.)

In this case you use both.  Delegation for the connections which need to validate the user identity and then revert to the service account identity for the times when you need system access to the back end. (A previous question of mine went into the details of how to revert to the system identity on the .NET platform see How to "un-impersonate" (un-delegate?) in Kerberos.)
Comment: this should be the accepted answer, good overview that is relevant to many situations before specifically answering the OP.
Answer: Here is a post describing how Kerberos works and how to set it up.
ASP.NET passing along Windows Authentication credentials
Comment: Well, yeah, that is MY post. :) And this is the next one. The questions are different. Your answer there made me doubt if I'm using Kerberos in the right way at all.
Comment: opps Sorry too early.  I thought it was odd that two questions like that would come so close together.
Answer: Actually Kerberos delegation is designed exactly for this use case. But the challenge here is craft this on a legacy system and with AD's settings that you do not want to change.
One possible hack is to  have the Front End just send the user and the time of authentication  but the backend can query the Active Directory Event Logs to determine whether that user has authenticated to the Front end. This requires you to use WIndows Event Log API.and also play around with Event Log settings in AD to log the issue of service tickets. (MY recollection is that this is the default)
  -
Comment: I'd say this is open to abuse and the busier the system is, the more likely a false-approval is to occur. It also assumes all clocks are perfectly in sync (hopefully true but not guaranteed)


How do Variational Auto Encoders backprop past the sampling step

Question: From my understanding of VAE's, there's a step during training in the middle where, after the encoder produces a mean and standard deviation, random samples are drawn from the given learned distribution to create the encoded vector that the decoder works to decode. I understand how one uses the KL divergence to force the learned distribution to be approximately the standard Gaussian, but I don't understand how the reconstruction loss can be back propagated past this sampling step. Random sampling is not a differentiable operation, so how can the gradients propagate past it? Is my understanding of VAE's wrong?
Comment: Does this answer your question? [How does the reparameterization trick for VAEs work and why is it important?](https://stats.stackexchange.com/questions/199605/how-does-the-reparameterization-trick-for-vaes-work-and-why-is-it-important)
Answer: The reparameterization trick.
$$x = \text{sample}(\mathcal{N}(\mu, \sigma^2))$$
is not backpropable wrt $\mu$ or $\sigma$. However, we can rewrite this as:
$$x = \mu + \sigma\ \text{sample}( \mathcal{N}(0, 1))$$
which is clearly equivalent and backpropable.
Comment: But in theory the normal distribution is all you'll ever need, since a sufficiently powerful function approximator can always map the normal distribution to any arbitrary probability distribution.
Comment: @blue-phoenix Scaling a random variable by a factor of $k$ scales the variance by a factor of $k^2$
Comment: @blue-phoenix there's no need to add the square root. The fact that a particular implementation of the normal distribution is parameterized by the standard deviation rather than the variance doesn't change any of the math.
Comment: Does this mean that we can't build autoencoders that use a different distribution that can't be reparameterized this way?
Comment: @enumaris most distributions can be reparameterized. For example, you can use a categorical latent space using the gumbel softmax trick.
Comment: @shimao: excuse me, why is it not backpropagatable with respect to mu and or std?
Comment: @Hossein it is, it's just that the elegant solution is to reparametrize (because we want unbiased gradients from a MC sample)
Comment: Hey, thank you for this answer - this really helped me! But I have a question: Why is $\sigma$ squared when using as an argument for the function but not squared when used outside?
Comment: So when I have a normal() implementation which takes the standard deviation as argument, not variance (is not backpropable, therefore I'm asking). Than I need to use the square root of $\sigma$ when using as a factor outside?
Comment: @blue-phoenix by convention, the two arguments to $\mathcal{N}$ are mean and variance respectively. $\sigma$ is the typical letter for standard deviation.
Comment: Concretely I'm talking about the pytorch implementation `normal(mean, std, out=None)` - `The :attr: 'std' is a tensor with the standard deviation of
each output element's normal distribution.` So I assumed this function takes $\mu$, $\sigma$ instead of $\mu$, $\sigma^2$. So I'm wondering if the formula above changes then to: $x = \mu + \sqrt{\sigma} * \text{sample}( \mathcal{N}(0, 1))$? Or doesn't it make any difference because variance resp. standard deviation equals 1?


How can I theme individual fields?

Question: I have views of ubercart products which are displayed in a table by standard drupal view standards.
How can i theme individual product fields ?
views-view-field.tpl is having the complete product listed inside $output variable..
I want to solve this in a template file where all fields are available individually ..
Answer: Inside the views-view-field.tpl.php, you can use the $row variable to get your other fields.
If you're using the Devel module, just send a dsm($row); to get the path to the fields you want to access.
For example I've this inside a views field template, to check if a user have something inside the field "twitter_account" :
<code>$twitter_account = "";
if(isset($row->field_field_twitter_account[0]['raw']['value'])){
    $twitter_account = $row->field_field_twitter_account[0]['raw']['value'];
}
</code>
Answer: You could use Display Suite and DS Extras, then enable Field Templates. This gives you full control of the field markup in your view modes. It might also be a bit cleaner as well, depending on what you're trying to accomplish.

How can I theme individual fields?


Core Data NSManagedObject - ObservedObjects not updating

Question: I have a data entry view that lets the user add an image and see the preview after doing so.
The ImagePickerView I have returns a UIImage which I save to Core Data as type Data through the .pngData converter. However, after selecting the image, the view does not update to show it even though I am using @ObservedObject and objectWillChange
I can't use @State because the draft object is an NSManagedObject
import SwiftUI
import CoreData

struct AddItemView: View {
    @Environment(\.managedObjectContext) var moc
    @Environment (\.presentationMode) var presentationMode

    @State var showImagePicker: Bool = false

    @ObservedObject var draft: Item    //Core Data entity

    var body: some View {

        NavigationView {
            VStack {
                if (draft.image != nil) {
                    Image(uiImage: UIImage(data: draft.image!)!)
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .frame(width: UIScreen.main.bounds.width - 32, height: UIScreen.main.bounds.height / 4)
                        .clipShape(RoundedRectangle(cornerRadius: 20))
                } else {
                    Button(action: {
                        self.showImagePicker = true
                    }, label: {
                        RoundedRectangle(cornerRadius: 20)
                    })
                    .padding([.all], 20)
                }

            }
            .sheet(isPresented: $showImagePicker) {
                ImagePickerView(sourceType: .photoLibrary) { image in
                    draft.objectWillChange.send()
                    draft.image = image.pngData()
                }
            }

        }
    }
}

Answer: Try using objectWillChange.send() after you make your changes:
.sheet(isPresented: $showImagePicker) {
    ImagePickerView(sourceType: .photoLibrary) { image in
        draft.image = image.pngData() // #1
        draft.objectWillChange.send() // #2
    }
}

Comment: hmm.. unfortunately this ended in the same exact behavior for me even after rearranging them


Debian preseed - US language - DK keymap

Question: I can't get the debian preseed.cfg to work (I am using debian 11.5)
I am trying to setup the fully automated install with US language but Danish keyboard layout.
This is where I am now - which obviously is not correct.
My grub.cfg:
menuentry --hotkey=i 'AutoInstall' {
    set background_color=black
    linux    /install.amd/vmlinuz language=en country=DK locale=en_DK keymap=dk preseed/file=/cdrom/preseed.cfg vga=788 --- quiet
    initrd   /install.amd/initrd.gz
}

preseed.cfg
d-i debian-installer/locale string da_DK
d-i debian-installer/locale string da_DK.UTF-8
d-i debian-installer/language string da
d-i debian-installer/country string DK

# Keyboard selection.
d-i keyboard-configuration/xkb-keymap select dk
d-i keyboard-configuration/variant select Danish
d-i keyboard-configuration/layoutcode string dk
d-i keyboard-configuration/layout select da

Comment: Hi Anders, still got the same errors as yours (even if i use legacy bios instead of uefi) if you want to have a look on some answers : https://serverfault.com/questions/1119075/advices-on-automating-installation-for-debian-11/1119160?noredirect=1#comment1461949_1119160
Answer: Are you booting from EFI or isolinux(regular bios) ?
The grub files are located different places.
If you want to make sure your booting correctly, press "e" when you see the grub menu, and make sure its the kernel parameters you specified here.


Interrater reliability with multi-rater, multi-label dataset

Question: I'm trying to calculate interrater reliability with 3 coders, and each question is multiple choice. An example tagging would be:
QUESTION: What is the theme of this video?

VIDEO_0:

 - Coder0: food, sports
 - Coder1: food
 - Coder2: sports, education, music

VIDEO_1:

 - Coder0: sports
 - Coder1: sports
 - Coder2: sports, education

VIDEO_i etc.

After some reading,  I saw that Fleiss's Kappa and Krippendorff's Alpha are the two most common metric to calculate multiple label dataset. The following is my code:
import nltk
from nltk.metrics import agreement,masi_distance,jaccard_distance
from nltk.metrics.agreement import AnnotationTask

task_data = [('coder1','video0',frozenset(['food','sports'])),
            ('coder2','video0',frozenset(['food'])),
            ('coder3','video0',frozenset(['sports', 'education', 'music'])),
            ('coder1','video1',frozenset(['sports'])),
            ('coder2','video1',frozenset(['sports'])),
            ('coder3','video1',frozenset(['sports', 'education']))]

jaccard_task = AnnotationTask(data=task_data,distance = jaccard_distance)
masi_task = AnnotationTask(data=task_data,distance = masi_distance)

print(f"Fleiss's Kappa using Jaccard: {jaccard_task.multi_kappa()}")
print(f"Fleiss's Kappa using MASI: {masi_task.multi_kappa()}")
print(f"Krippendorff's Alpha using Jaccard: {jaccard_task.alpha()}")
print(f"Krippendorff's Alpha using MASI: {masi_task.alpha()}")

And got
Fleiss's Kappa using Jaccard: 0.4090909090909091
Fleiss's Kappa using MASI: 0.28863636363636364
Krippendorff's Alpha using Jaccard: 0.15217391304347838
Krippendorff's Alpha using MASI: 0.12971750574627405

My questions are

Why is Jaccard and MASI distance would result in such significant difference?
Are there better score for this type of dataset?
Answer: I've decided to go with Fleiss's Kappa using Cosine distance (+sklearn.MultiLabelBinarizer) and Jaccard distance. My simple pipeline for Cosine distance for reference; the Jaccard version is simpler and referenced above.
from nltk.metrics import agreement,masi_distance,jaccard_distance,binary_distance
from nltk.metrics.agreement import AnnotationTask
from sklearn.preprocessing import MultiLabelBinarizer
from sklearn.metrics.pairwise import cosine_similarity
from scipy import spatial
import numpy as np

# cosine similarity is assuming full rank matrices, won't work for rank-deficient
# go through dimension reduction for matrices with all 0s column
def cosine_distance(vec_a,vec_b):
    distance = spatial.distance.cosine(vec_a,vec_b)
    return distance

# dropping columns with all 0s in the matrix
def dim_reduction(vector):
    vector = np.array(vector)
    idx_zero_cols = np.argwhere(np.all(vector[..., :] == 0, axis=0))
    res = np.delete(vector, idx_zero_cols, axis=1)
    return res

#sample pipeline
coder_dict = {"rater1":df_1, "rater2":df_2, "rater3":df_3}
answer_list = [{'sports'}, {'food', 'sports'}, {'music', 'education'}]
arr = dim_reduction(mlb.fit_transform(answer_list))
task_data = []
for pair in zip([list(r) for r in arr],coder_dict.keys()):
            answer, coder = pair
            annotation = coder, row["videoId"], tuple(answer)
            task_data.append(annotation)

cosine_task = AnnotationTask(data=task_data,distance = cosine_distance)
print(f"Fleiss's Kappa using Cosine distance: {cosine_task.multi_kappa()}")


PowerShell - Use "Get PnPListItem" with a value parameter

Question: Just started with PowerShell - I wanted to get some list items from SharePoint BUT only those which have the value "true" in field "hidden"
So my Code is:
Get-PnPListItem -List O365GroupConfig

So the Question is - can I do a "where" like in SQL or somethin like that?
Thanks ;)
Comment: Take a look at [`Where-Object`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/where-object?view=powershell-5.1). Give it a few tries and if it still doesn't work - update your question :)
Comment: But if you take a look at the [`Get-PnPListItem`](https://learn.microsoft.com/de-de/powershell/module/sharepoint-pnp/get-pnplistitem?view=sharepoint-ps) command, you can also see that there is an `-Query` Parameter which works as an filter as well. This is probaly much faster than piping it to `Where-Object`.
Comment: Tried this: `Get-PnPListItem -List O365GroupConfig -Query "Nein"` But didnt work :/
Comment: Well you point out that the `Value Type` should be `Boolean`. If I had to guess, the possible Values could be `true`/ `1` or `False`/`0` and not 'Nein'. Try again with the Value `0` or `false`.
Comment: Thanks for the fast answer! :)
Comment: If you take a look at [CAML-Abfragen in SharePoint](https://andifandrich.wordpress.com/2010/12/03/caml-abfragen-in-sharepoint/): You will find `Bei Ja/Nein-Feldern muß als Value 0 oder 1 angegeben werden. True oder false funktionieren nicht!` == Try with the Value `0`. :)
Comment: Thanks so much! Tried it again but doesnt work `Get-PnPListItem -List O365GroupConfig -Query "0<
/Where>"`
Comment: You have a whitespace between `<` and `/` in the closing `Where` - this might be a problem. Please try to describe what exactly doesn't work. What is your error-message?
Answer: There are at least 2 ways to reach that goal:

Query all the items, and store the results of the cmdlet in a $var. Afterwards, just filter the values you want, like this example:

$filtered_var= $var | where-object {$_.FieldValues.MyColumn -eq $true  }

Another option is to leverage the  -Query flag, as this example:

$var = get-pnplistitem  -List O365GroupConfig -query "<View><Query><Where><Eq><FieldRef Name='MyColumn'/><Value Type='Boolean'>1</Value></Eq></Where></Query>    </View>"
This way you will be already filtering results at query level, using CALM
Answer: (Get-PnPListItem -List O365GroupConfig -Fields "HiddenFromAddressListsEnabled").FieldValues | Where-Object HiddenFromAddressListsEnabled -eq 0
Worked! :)
If you ask by PowerShell about the paramenters of the ListItem the Value is "false" not "0". So, you have to know it ;)


Dictionary : Will calling .Keys be ordered consistently with .Values?

Question: Suppose I have a dictionary, and call .Keys, and then .Values with no intervening operations. Will the ordering of the keys be consistent with the ordering of the values?
Put another way, will the nth key correspond to the nth value as they did before in the dictionary?
Comment: @DanielA.White: The order of the entries wasn't what the OP asked about - he was asking about whether the keys and values would be in the same order, and the answer is "yes". So while you can't predict what the order of keys will be (given just the contents) you *can* predict that it'll be consistent with the order of the values.
Comment: http://stackoverflow.com/questions/1453190/does-the-enumerator-of-a-dictionarytkey-tvalue-return-key-value-pairs-in-the
Comment: dictionaries are not guaranteed to have order.
Comment: probably its not clear, what you are asking
Comment: No.  Especially if you have one key for many values like Dictionary>.  The key for a dictionary is a hash table to reduce the time to extract items.
Answer:
Will the ordering of the keys be consistent with the ordering of the values?

Yes, it's guaranteed by the documentation of both IDictionary<,>.Keys and IDictionary<,>.Values.
Keys documentation:

The order of the keys in the Dictionary<TKey, TValue>.KeyCollection is unspecified, but it is the same order as the associated values in the Dictionary<TKey, TValue>.ValueCollection returned by the Values property.

Values documentation:

The order of the values in the Dictionary<TKey, TValue>.ValueCollection is unspecified, but it is the same order as the associated keys in the Dictionary<TKey, TValue>.KeyCollection returned by the Keys property.
Comment: @OP: For readability reasons, I recommend against simultaneously enumerating the keys and values.  `Dictionary` implements `IEnumerable>`, so a cleaner alternative is `foreach (KeyValuePair kvp in dict) {/*code*/}`
Answer: According to MSDN's documentation for Dictionary.Keys, yes.

The order of the keys in the Dictionary<TKey, TValue>.KeyCollection is unspecified, but it is the same order as the associated values in the Dictionary<TKey, TValue>.ValueCollection returned by the Values property.


XSLT FOP: force page break within fo:block

Question: I'm generating a table with different length strings in one column:

The page break within an <fo:block/> in the Arbeitsgangbeschreibung-column makes me probles.
As you can see, the string normaly starts on the same line like the numbers and takes the rows it needs.
But the string which is after the page break (starting with 'Schleifen Stirnseite Gewinde sauber...') won't start on the same line like the numbers it belongs to. It seems the <fo:block/> forces it together within one page.
But I just want the <fo:block/> to break at the end of the page. Which means

Schleifen Stirnseite Gewinde sauber | -

should stand on the first page. And the rest

Leisten unter Vorrichtung unterlegen (damit Schraubenkopf frei ist)

should stand on the next page.
There arent any keep-together-calls which it could accidentally inherit from.
Thats the <fo:block/>:
<fo:table-cell border-right="{$Standardrand}">
   <fo:block margin-top="4pt" font-size="9pt" font-weight="bold"margin-left="3pt">
      <xsl:value-of select="beschreibung" />
   </fo:block>
</fo:table-cell>

Comment: One thing I would look into is try to make the height of the contents of the POS and AF columns 100%
Answer: Add widows="1" and orphans="1" to the fo:block.
widows (https://www.w3.org/TR/xsl11/#widows) and orphans (https://www.w3.org/TR/xsl11/#orphans) set the minimum number of lines of a block of text to be left at the bottom or top of a page, respectively.  The initial value for both is 2, with the result that you can't split a three-line block of text.  By default, the minimum number of lines that can be split is 4.


Tapping noise when using airship rising (Garage Band)

Question: When using the following sound airship rising I hear a tapping noise, which I am sure is not part of the synth sound, at the audio peaks (I don't hear at lower volumes) and I think it's something to do with the speakers are resident frequency can anyone else recommend how I can stop this.
I hear it both from laptop speakers and headphones.
I am  unable to upload the sound here, maybe someone can test? It really sounds like a bug with airship rising synth, as I have MBP 16" with quality speakers, or maybe its my layer effects.

Edit,  I noticed when you turn the SINE down this tapping disappears
Answer: I opened up GarageBand 10.3.4 and played around with the Airship Rising software instrument. I can clearly hear a "tapping" sound as you describe, but I believe it is an intentional part of the sound.
This sort of sound is characteristic of what an analog synthesizer user would call a "filter ping": any resonant filter, if it receives a sharp edge on its input (imagine a very low frequency square wave), will "ring" briefly, producing a sine wave at the resonant frequency after the initial "strike", very much like a percussion instrument. The "tapping" noise you are hearing is the strike itself, just like you would hear a mallet or drumstick hit. The SINE knob is just controlling the mix of that part of the sound with the rest.
In this case, the filter/oscillator/resonator (whatever you want to call it; all are reasonable names depending on context) that produces the tap and sine tone is not the same thing as the filter which is filtering the other part of the sound, which has direct CUTOFF and RESONANCE controls. You can hear, if you turn up the RESONANCE, that that filter is being modulated (downward sweep of pitch) with each note, whereas the sine tone is stable. But in another synth being played this way by changing the controls or patching, there might be only one filter unit which can be either used as a conventional filter (having sound input from an oscillator) or pinged (having only the "ping" signal going in).


O que são os blocos Try/Catch?

Question: Gostaria de saber o que são os blocos try...catch.
Gostaria de mais informações em português, porque em inglês eu não entendi muita coisa, somente que seria uma espécie de if...else.

O que são esses blocos try...catch?
Quando tenho que utilizá-los?
Sempre (deveria) usar eles quando tenho uma consulta SQL?

Talvez alguns exemplos ajudem a compreender melhor
Answer: Para entender o bloco try/catch é necessário compreender o conceito de exceção. Não se assuste, é bem comum que este conceito cause estranheza quando você começa a estudar o paradigma de orientação à objetos.
Exceção
Na ciência da computação, exceção é um objeto que define um fluxo alternativo à execução normal do programa. Isso acontece quando algumas condições em parte do programa não são satisfeitas, mas que podem ser tratadas, por isso a expressão tratamento de exceções. É bastante utilizada quando for desenvolver bibliotecas reutilizáveis, em que a lógica de negócio implementada não pode ser tão rígida, pois ficaria preso a uma aplicação apenas.
Imagine que você tenha uma função que efetua a raiz quadrada de um número. O código seria semelhante a isso:
function sqrt ($number)
{
  // Calcula a raiz quadrada
  return $result;
}

Porém, considerando apenas números reais, a função só funcionará corretamente se o parâmetro de entrada for um valor não-negativo. Desta forma, se o parâmetro for negativo, você deve criar um fluxo alternativo para o programa através de uma exceção.
function sqrt ($number)
{
  if ($number < 0)
  {
    throw new \Exception("$number must be a non-negative number");
  }

  // Calcula a raiz quadrada
  return $result;
}

Desta forma, ao tentar calcular a raiz quadrada de um número negativo, teríamos:
> sqrt(-1);
Uncaught Exception: -1 must be a non-negative number ...

Tratamento de exceção
Com o bloco try/catch você tem a liberdade para decidir qual será o novo fluxo do programa. Neste exemplo, digamos que se o valor de entrada for negativo, eu desejo calcular a raiz quadrada do mesmo valor, porém positivo, emitindo um warning para o usuário. Poderiámos fazer algo como:
$value = -4;

try {
    $result = sqrt($value);
} catch (\Exception $e) {
    log($e->getMessage());
    $value *= -1; // Inverte o valor de $value
    $result = sqrt($value);
    warning("$value era negativo, então seu sinal foi alterado");
}

// Continuo com minha aplicação, onde $result = 2...

Sendo $e uma instância de Exception, o método getMessage retornará a mensagem de erro difinida na hora de seu disparo. Nesse caso, seria armazenado no log do sistema a mensagem $number must be a non-negative number.
Seu exemplo
Utilizando a biblioteca PDO para a conexão com o banco de dados, podemos ver na documentação que o construtor da classe dispara uma exceção do tipo PDOException caso a conexão falhar. Portanto, fazendo:
Colaboração de @bonifazio
try{
  $pdo = new PDO(...);
  $pdo->setAttribute(...);
  ...
}catch(PDOException $e){
  // Omite a mensagem de erro para o cliente, só informando que houve um erro interno e salva o erro no log
  log($e->getMessage());
  http_response_code(500);
  die("Ooops! Algo errado não está certo. Por favor, volte mais tarde.");
}

Você garante que na linha $pdo->setAtributte a variável $pdo seja uma instância de PDO com a conexão ativa, pois, caso a conxeão falhe, o rumo do programa é alterado para o bloco catch. Sem a utilização dos blocos try/catch você não tem essa garantia. Se a conexão não for bem sucedida, é emitido o código 500 de resposta HTTP, informando um erro interno, mostrando, também, a mensagem ao usuário (considerando que a conexão com o banco seja trivial para o funcionamento do sistema, que é o que geralmente ocorre).
Você pode se perguntar: mas basta eu colocar um if ali que consigo a mesma garantia. Consegue, mas imagina que você esteja utilizando uma biblioteca de terceiro na sua aplicação. Se um erro assim acontecer, não é uma boa prática que você edite o código fonte diretamente, alterando-o para a sua aplicação. Se a biblioteca foi bem feita, ela disparará a exceção quando situações assim ocorrer e você capturando-as consegue fazer o tratamento sem alterar o código.
Answer: Um bloco "try" é chamado de bloco "protegido" porque, caso ocorra algum problema com os comandos dentro do bloco, a execução desviará para os blocos "catch" correspondentes.
isso é, caso o código que esteja dentro do try contenha erro (não erro de lógica e sim de sintaxe), ele cairá no catch onde você pode tratar a exception.
Comment: Exceção capturando erro de sintaxe? Tem certeza disso?
Comment: Achei meio rala a explicação, o `try` `catch` cria uma estrutura onde o erro sera tratado como uma exceção e não um erro(essa exceção pode ser salva em um log, por exemplo, onde somente o desenvolvedor terá acesso, e poderá corrigir o erro), o código pode continuar a execução sem nenhum problema, coisa que normalmente não ocorreria sem o bloco `try` `catch`
Comment: @AndersonCarlosWoss talvés não sobe me explicar direito, erros de sintexe o próprio compilador encontra, mas existem erros em bibliotecas que utiliza que o compilador não encontra, e quando ocorre esse tipo de erro ao usar o try catch ele cairá no catch.

O que são os blocos Try/Catch?


Reorder the Basic page list in views .How?

Question: I have created views to display basic pages in blocks.I what to reorder the list according to me .How to do?Plz help......
Comment: Add sort fields to view...
Comment: Do you want to **sort basic pages** based on **created date** (ascending or descending)? Or your trying to sort based on your requirement?
Answer: In Drupal 7 you use VIEWS SORT CRITERIA

If you want to sort based of Content: Post date OR Content: Updated date just use these fields in VIEWS SORT CRITERIA.
If you want to sort based on your requirement then, just add one more extra field to basic page like weight.

Edit your VIEW and just add this field in the Views SORT CRITERIA and sort is as per
your requirement.
Comment: It really helped me....solved my problem.thanks a lot...