Ao selecionar uma opção no select trocar os campos do formulário

Question: Estou criando o site de um evento para um amigo, e para o formulario de inscrição tenho a seguinte situação:

Formulario de Inscrição

<form name="incrição">
Nome Completo:
 <input type="text" size="100" placeholder="Digite seu nome completo" required>

Endereço:
 <input type="text" size="100" placeholder="Digite seu endereço - Rua ******** ***** ****** Nº***" required>

Telefone:
 <input type="text" size="100" placeholder="(DDD) 9XXXX -XXXX" required maxlength="12" >

Incrição para o campeonato de:

<select name="Inscrição">
    <option method="post" value="Cosplay" name="Cosplay">Cosplay</option>
    <option method="post" value="Smite" name="Smite">Smite</option>
    <option method="post" value="" name="K-pop">K-Pop</option>
    <option method="post" value="Bey Blade" name="Bey Blade">Bey Blade</option>
    <option method="post" value="Just Dance" name="Just Dance">Just Dance</option>
    <option method="post" value="Quadribol" name="Quadribol">Quadribol Terrestre</option>
    <option method="post" value="Anime Quiz" name="Anime Quiz" value="cosplay">Anime Quiz<option>
    <option method="post" value="Desenho"  name="Desenho" value="cosplay">Competição de Desenho</option>
</select>
</form>

Preciso que quando a opção "Cosplay" for selecionada por exemplo, apareçam novos inputs abaixo da opção com novas perguntas, já que cada inscrição tem requisitos diferentes...
 Ex: Personagem:
Comment: Oi Fernanda, bemvinda! Acho que o mais simples é criares o HTML todo e depois ajudar-mos-te a a escondêr (e desabilitar) as partes que nõ são selecionadas. Dessa maneira não precisas de criar elementos novos.
Comment: Boa noite, gostaria de saber se a resposta lhe ajudou, se não por favor comente o que acha que falta.
Answer: Você terá que usar um pouco de css e um pouco de js
Notas antes de começar

Recomendo não usar acentos nos atributos names e ids, ex: troque <select name="Inscrição"> por <select name="inscricao">
Não use mais de um value dentro de um <option>, ex: troque <option method="post" value="Anime Quiz" name="Anime Quiz" value="cosplay"> por <option method="post" value="Anime Quiz">
Não use nos atributos dos options, o name deve ir dentro do select apenas, ex: troque <option method="post" value="Cosplay" name="Cosplay">Cosplay</option> por <option value="Cosplay">Cosplay</option>
Tag <option> não deve ter o atributo method, este atributo é apenas para a tag <form>
No exemplo abaixo o atributo data- é necessário para detectar os campos que devem ser exibidos.
Recomendo usar jQuery para facilitar.

Recomendo adicionar a opção selecione, segue um exemplo completo:

$("#selecionar").change(function() {
    var $this, secao, atual, campos;

    campos = $("div[data-name]");

    campos.addClass("hide");

    if (this.value !== "") {
        secao = $('option[data-section][value="' + this.value + '"]', this).attr("data-section");

        atual = campos.filter("[data-name=" + secao + "]");

        if (atual.length !== 0) {
            atual.removeClass("hide");
        }
    }
});
.hide
{
   display: none;
}

Formulario de Inscrição

<form name="incrição">
    Nome Completo:
 <input type="text" size="100" placeholder="Digite seu nome completo" required>

    Endereço:
 <input type="text" size="100" placeholder="Digite seu endereço - Rua ******** ***** ****** Nº***" required>

    Telefone:
 <input type="text" size="100" placeholder="(DDD) 9XXXX -XXXX" required maxlength="12" >

    Incrição para o campeonato de:

    <select name="Inscricao" id="selecionar">
        <option value="">Selecionar...</option>
        <option data-section="cosplay" value="Cosplay">Cosplay</option>
        <option data-section="smite" value="Smite">Smite</option>
        <option data-section="k-pop" value="K-pop">K-Pop</option>
        <option data-section="bey-blade" value="Bey Blade">Bey Blade</option>
        <option data-section="just-dance" value="Just Dance">Just Dance</option>
        <option data-section="quadribol" value="Quadribol">Quadribol Terrestre</option>
        <option data-section="anime-quiz" value="Anime Quiz">Anime Quiz<option>
        <option data-section="desenho" value="Desenho">Competição de Desenho</option>
    </select>

        Campos cosplay: <input type="text" value="">

        Campos smite: <input type="text" value="">

        Campos kpop: <input type="text" value="">

        campos bey-blade: <input type="text" value="">

        just-dance: <input type="text" value="">

        quadribol: <input type="text" value="">

        anime quiz: <input type="text" value="">

        desenho: <input type="text" value="">

</form>
Comment: @FernandaGuedes se ajudou, por favor marque a resposta como Correta, fico agradecido
Comment: Muito obrigada, entendi mais ou menos o código, mas me explica só mais uma coisa? Para continuar fazendo o formulário se expandir para os outros campos como eu faço?
Comment: Cada um dos campos devera mostrar um tipo de formulário diferente, o cosplay por exemplo pergunta o personagem, o de smite pede os integrantes da equipe e assim por diante, mas ate agora, só consigo usar esse código com um dos option, quando tento executa-lo em mais de um, ele simplesmente não mostra nada...
O que devo fazer nesse caso?
Comment: @FernandaGuedes isto não foi bem especificada na pergunta, mas vou editar e adicionar um exemplo, por favor em quanto isto faça o tour: http://pt.stackoverflow.com/tour
Comment: Muito Obrigada @GuilhermeNascimeto! Ajudou bastante


for loop to populate dataframe

Question: I'm trying to populate a dataframe with the result of a for-loop, but I'm missing something. I've looked at the past questions about this, but I can't get my head around the solution, so...
The fictional data:
df <- data.frame(RA = c(rep("14005", 3), rep("14158", 3), rep("15458", 2), rep("15302", 2)),
             Level = c(rep("Grad", 6), rep("Undergrad", 4)),
             EntryYear = c(rep(2014, 6), rep(2015, 4)),
             ExitYear = c(rep(2016, 3), rep(2017, 3), rep(2018, 4)))

I want to fill a data frame with the result of a specific dplyr pipeline:
df %>%
filter(Level == "Grad", EntryYear <= year, ExitYear >= year) %>%
distinct(RA) %>%
summarise(year = n())

Where year is the specific year I'm interested (in my original data, it goes from 2010 to 2017). The formula above is to calculate, roughly, how many students are registered in the given year. [I'll use two more formulas, to calculate the number of graduates and freshmen, so I'll have two more row/columns]. And:
start.year <- 2010
end.year <- 2017

So, I made this for-loop, to see if it works:
for (year in start.year:end.year){
  mat <- df %>%
    filter(Level == "Grad", EntryYear <= year, ExitYear >= year) %>%
    distinct(RA) %>%
    summarise(year= n())
  print(mat)
}

It does print what I want, but then I'm not able to write it into a dataframe... The expected result is a dataframe with 7 rows. The final result is a dataframe with 7 rows and 3 columns (the two other formulas/pipelines that I'll apply).
Answer: Since you are already using dplyr, it is easy to also use purrr to merge the data.frames for you
library(purrr)
map_df(start.year:end.year, function(year) {
  mat <- df %>%
    filter(Level == "Grad" & EntryYear <= year & ExitYear >= year) %>%
    distinct(RA) %>%
    summarise(year= n())
})

Comment: This is beautiful, thanks! I've never used purrr before - guess I'll become acquainted with it.
Comment: Let me seize the opportunity: I'm trying to add another column to my newly created dataframe, but it only returns the last variable that I created... How do I do it all inside this function?
Answer: Just add these two lines in your final code:
new_df <- data.frame(). # <- this one
for (year in start.year:end.year){
    mat <- df %>%
        filter(Level == "Grad", EntryYear <= year, ExitYear >= year) %>%
        distinct(RA) %>%
        summarise(year= n())
    new_df <- rbind(new_df, mat) # <- this one
}

Answer: for (year in start.year:end.year){
  mat <- df %>%
    filter(Level == "Grad", EntryYear <= year, ExitYear >= year) %>%
    distinct(RA) %>%
    summarise(year= n())
  print(mat)

  if (year<2011){

    final <- as.data.frame(mat)

  }

  else{

    final <- rbind(final,as.data.frame(mat))

  }
}

Answer: # load packages
library(plyr)
library(dplyr)

# Filter function
filterdf<-function(year, level){
  mat <- df %>%
    filter(Level == level, EntryYear <= year, ExitYear >= year) %>%
    distinct(RA) %>%
    summarise(year= n())
  colnames(mat)<-paste0(level, "_number")
  return(mat)
}

# Create your input conditions
input<-as.data.frame(seq(2010,2017))
colnames(input)<-"year"
input$level<-"Grad"

# Output to a dataframe
output<-mdply(input,filterdf)

Answer: Here's a tidyverse alternative:
library(tidyverse)
df %>%
  filter(Level=="Grad") %>%
  mutate(year = map2(EntryYear,ExitYear,~.x:.y)) %>%
  unnest(year) %>%
  distinct(RA,year) %>%
  count(year)

# # A tibble: 4 x 2
#    year     n
#   <int> <int>
# 1  2014     2
# 2  2015     2
# 3  2016     2
# 4  2017     1

for loop to populate dataframe


Criptografar uma string em python

Question: Gostaria de saber se existe algum algoritmo de criptografia onde é possivel escolher qual a chave ou parte dela que sera usada para criptografar/descriptografar a mensagem
Um exemplo:
mensagem = 'string qualquer'

chave = 'chave escolhida'

mensagem_encriptada = encrypt(mensagem, key = chave)

print(mensagem_encriptada)

mensagem_recuperada = decrypt(mensagem_encriptada, key = chave)

print(mensagem_recuperada)

Saida esperada seria essa:
(uma string qualquer como dfg1tre*vf2d3jnh&&^/vfdfhgf34@@cfr%ws76z!)string qualquer
Comment: Veja se esta [lib](https://pypi.org/project/cryptocode/) te ajuda
Answer: Você pode usar alguma biblioteca para fazer a criptografia. Tem várias bibliotecas, como a pycrypto, cryptocode e etc. Tem dezenas de bibliotecas por aí.
Um exemplo simples desse seu mesmo programinha usando a biblioteca cryptocode:
import cryptocode

chave = "423338233093093"
mensagem = "Esta eh a minha mensagem! :)"

MensagemCriptografada = cryptocode.encrypt(mensagem, chave)
print("Sua mensagem criptografada: " + MensagemCriptografada)

MensagemDescriptografada = cryptocode.decrypt(MensagemCriptografada, chave)
print("Sua mensagem descriptografada: " + MensagemDescriptografada)

A saída será:

Sua mensagem criptografada: gSjdIssy9DOYfPnACctSaoNn4/VcTRzlLYh4PQ==*dv9iN+Uwsad+v8QMBUgF7A==*4G2FKJ2n+WJxwak9LpyaWw==*lvCp3brLC0nJVd1g4lf3Vg==
Sua mensagem descriptografada: Esta eh a minha mensagem! :)
Answer: Depende da criptografia  simétrica ou assimétrica.
Há bibliotecas que auxiliam a criar uma boa criptografia  usando AES e a RSA.
um simples exemplo usando a função xor:
Quanto maior a chave mais segura sera, quanto menor  mais fácil sera para identificar a mensagem
import string
import random

chave = ''.join(random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits + '^!\$%&/()=?{[]}+~#-_.:,;<>|\\') for _ in range(0, 1024))

print(chave)

mensagem = 'python'

print("Msg: " + mensagem + '\n')

def str_xor(s1, s2):
    return "".join([chr(ord(c1) ^ ord(c2)) for (c1, c2) in zip(s1,s2)])

secreta = str_xor(mensagem, chave)

print("Mensagem secreta :"+secreta + "\n")

recuperando_mensagem_secreta = str_xor(secreta, chave)
print("Mensagem descriptografada " + "\n" + recuperando_mensagem_secreta + "\n")

A cada vez que o código for iniciado uma nova criptografia sera criada

Criptografar uma string em python


Make stacked proportion bar graph for categorical and numerical data in ggplot

Question: I have a dataframe like the following:
df = data.frame(Age = c(rep(NA, 10), runif(40, 1, 100)),
                Duration = c(rep(NA, 20), runif(30, 0, 4)),
                cat = rep(c("A", "B", "C", "D", NA), each = 10),
                cat2 = rep(c("X", "Y", "Z", NA, "W"), each = 10))

Of note, it contains two numerical columns and two categorical columns. Each column has some NA values.
I want to make a stacked bar graph showing proportion of each of the groups in the categorical columns and a colorbar for the numerical columns. The order of the categories does not matter for categorical, except that I would like NA to always be at the top, and numerical should sorted from lowest at the bottom to largest at the top (but NA also at the top here).
Below is a brief sketch of what I was trying to make without much success. For the numerical colorbars, I want to annotate the value rounded to nearest whole number at 5 points on the bar.

I started by melting the data frame to make it long, but am unsure how to proceed from here.
library(reshape)
df_m = melt(df, id = c())

If you could help with this, I would greatly appreciate it.
Thanks,
Jack
Comment: +1 for including a sketch even when you couldn't make it with code. I see some aesthetic issues occurring: your columns display different types of data on difference scales, but you can only work with one color/fill scale per plot. It won't make sense to have a colorbar that spans ages of 0-100 and durations of 0-4. Similar issue for the categorical columns. You'll probably have better luck doing separate plots and sticking them together discretely with `cowplot` or `patchwork`
Comment: @camille I appreciate the upvote and your response. With my very limited ggplot knowledge, I'm not sure how to do that either. Would it be possible for you to post a solution with this? I would really appreciate it. Thanks!
Answer: This is probably a far more complicated problem than you were hoping, and with several steps, so this solution feels slightly hacky. It also might not be exactly what you're looking for, but there's room for adjustment.
What I'm doing first is breaking the numeric columns into intervals, which are factors, making sure the character vectors are factors, and giving every column an explicit factor level of "NA", rather than the value type NA. It's a subtle difference (you could call this level it something else), but it lets you put this level at the end of each factor so the NA bars will all be placed on top. However, fill scales automatically assign a gray value to NA, so you'll have to do this manually. I'm doing this by pulling the ColorBrewer palette "Blues," then placing a gray color alongside it in scale_fill_manual.
library(tidyverse)
library(patchwork)

set.seed(123)
df <- data_frame(Age = c(rep(NA, 10), runif(40, 1, 100)),
                 Duration = c(rep(NA, 20), runif(30, 0, 4)),
                 cat = rep(c("A", "B", "C", "D", NA), each = 10),
                 cat2 = rep(c("X", "Y", "Z", NA, "W"), each = 10))

df_breaks <- df %>%
  arrange(Age) %>%
  mutate(Age = cut(Age, breaks = seq(0, 100, by = 25)),
         Duration = cut(Duration, breaks = seq(0, 4, by = 1))) %>%
  mutate_if(is.character, as.factor) %>%
  mutate_all(~fct_explicit_na(., na_level = "NA"))

df_breaks
#> # A tibble: 50 x 4
#>    Age     Duration cat   cat2
#>    <fct>   <fct>    <fct> <fct>
#>  1 (0,25]  (3,4]    NA    W
#>  2 (0,25]  (1,2]    C     Z
#>  3 (0,25]  NA       B     Y
#>  4 (0,25]  (0,1]    C     Z
#>  5 (0,25]  (1,2]    D     NA
#>  6 (0,25]  (3,4]    NA    W
#>  7 (0,25]  (1,2]    NA    W
#>  8 (25,50] (0,1]    C     Z
#>  9 (25,50] NA       B     Y
#> 10 (25,50] (3,4]    D     NA
#> # ... with 40 more rows

palette <- RColorBrewer::brewer.pal(4, "Blues")

To make individual plots for each column, I'm using purrr::imap to call a function on each column, making a new data frame with the name of that column and the column itself, counting up the breaks, and making a bar plot. I added a geom_text to make labels, which also lets you skip the legends. (Like I said in my comment, the legends will give you trouble since all the scales are different.) I'm also removing the plot margins on the left and right sides, so that you'll be able to place plots right alongside each other, and removing the x-axis title, which would be redundant.
p <- imap(df_breaks, function(col, term) {
  data_frame(term = term, group = col) %>%
    count(term, group) %>%
    ggplot(aes(x = term, y = n, fill = fct_rev(group))) +
      geom_col(position = "fill") +
      geom_text(aes(label = fct_rev(group)), position = position_fill(vjust = 0.5)) +
      scale_fill_manual(values = c("gray70", palette)) +
      theme_minimal() +
      theme(legend.position = "none", plot.margin = margin(10, 0, 10, 0, "pt")) +
      labs(x = NULL)
})

That gets you a list of ggplot objects. I'm rearranging it into the order you showed.
p <- p[c("Age", "cat", "Duration", "cat2")]

Then using patchwork::wrap_plots, you can place the list of plots in a row together.
wrap_plots(p, nrow = 1)

There are some redundancies if you want this to look like a single plot, so you can remove the left-side theme elements from plots 2, 3, and 4, then wrap_plots again with the original p$Age:
p_no_y <- map(p[2:4], function(plot) {
  plot +
    theme(axis.title.y = element_blank(),
          axis.text.y = element_blank(),
          axis.ticks.y = element_blank())
})
wrap_plots(p$Age, p_no_y$cat, p_no_y$Duration, p_no_y$cat2, nrow = 1)

The advantage of using patchwork over cowplot for this is that the patchwork functions are aware of the space taken up in each plot by axes, so the columns come out the same width, despite the fact that one plot also has a y-axis. To see what I mean, replace wrap_plots with cowplot::plot_grid.
So that's already a whole lot! And there's plenty of room to do more:

You can further adjust margins and other theme elements and x- and y-axes to fit the plots together how you want.
If you want different color palettes for different columns—e.g. a continuous one like I showed here for the numeric variables but a qualitative one for the categorical variables—you could assign fill scales separately, rather than all the same like I did inside the imap function.
You might want to set break labels that aren't in interval notation, by supplying labels in cut.


How to send POST request to https using \Drupal::httpClient()?

Question: I want to send POST request to https using \Drupal::httpClient().
But ended up with error like

GuzzleHttp\Exception\RequestException: cURL error 60: SSL certificate
  problem: self signed certificate (see
  http://curl.haxx.se/libcurl/c/libcurl-errors.html)

Below is my code.
$post_fields['name'] = 'aa';
    $fields_string = json_encode($post_fields);
    $response = \Drupal::httpClient()
           ->post("https://localhost/example/api/user-update?_format=json", [
         'auth' => ['admin', 'admin'],
         'body' => $fields_string,
    'http_errors' => FALSE,
         'headers' => [
           'Content-Type' => 'application/json',
    ],
       ]);
    dsm($response->getBody()->getContents());

How to send POST request with \Drupal::httpClient().
Answer: We must pass the post values in http_client via form_params  . Here down is one of my code to make OAuth2 authentication to another drupal 8 REST api being used simple_oauth module.
$response = \Drupal::httpClient()->post($base_url . '/oauth/token', [
      'verify' => true,
      'form_params' => ['grant_type'=> 'password',
                        'client_id' => 'CLIENT-ID',
                        'client_secret'=> 'CLIENT-SECRET',
                        'scope'=>'',
                        'username'=>'admin',
                        'password'=>'admin',],
        'headers' => [
          'Content-type' => 'application/x-www-form-urlencoded',
        ],
    ])->getBody()->getContents();

Comment: If anyone is having any problems with any code in the answers, you need to change "form_params" to just "json", that may work for you :)
Answer: The error message should inform you what is going on. You are using a self-signed certificate locally. This probably won't be an issue on your production sites, but this is not really useful for local development.
Inspect the \Drupal::httpClient() static method you may discover that it uses the http_client_factory:fromOptions service. Use this directly allows you to pass options into Guzzle to allow requests to sites using self-signed certificates.
$clientFactory = \Drupal::service('http_client_factory');
$client = $clientFactory->fromOptions(['verify' => FALSE]);

Obviously this is not ideal. You should probably parameterize the URL that you are using instead of hard coding the URL. Then locally you can test without a self-signed cert or HTTPS. Or parameterize the options you pass into Guzzle so that verify => TRUE when you're on production. It is not recommended to set it to FALSE and this is a security risk.
Answer: $client = $clientFactory->fromOptions(['verify' => FALSE]); make me have an error.
I tried this line above, which is working :
$response = $client->request($methode, $url->toString(), ['form_params' => $options, 'verify' => false]);

Answer: You might get some idea from this doc
https://www.drupal.org/docs/8/core/modules/rest/3-post-for-creating-content-entities
Answer: I tried the various answers above, none did quite work. As it happens there was, in our case, a simpler solution.
We have several environments identified via $settings['environment'] in settings.php. One of those, "local", needs to work with self-signed certs. To avoid Guzzle/curl from complaining we do:
if ($environment == 'local') $params['verify'] = FALSE; // $params of course holds other needed bits for the call to happen...

$response = json_decode(Drupal::httpClient()
      ->post($target_url, $params)
      ->getBody()
      ->getContents());

Hope it helps.


Como fazer um "for each" no SQLite?

Question: Possuo uma tabela A com n registros. Para cada registro desta tabela, quero pegar a informação de um campo x para fazer um select e, a partir dos dados resultados deste select, fazer um insert em uma tabela B. Só que preciso fazer isso para todos os n registros de A.
Como faço isso no SQLite? Tem algo semelhante a um "for each" para esta situação? Ou só dá pra fazer essa operação por uma aplicação?
Answer: O SQLite é um banco de dados e não uma linguagem de programação, a linguagem de consulta, portanto declarativa que tem nele permite algo semelhante que é o select que já conhece. O for each é tipicamente imperativo.
É possível estender o SQLite para aceitar outras coisas. Ele é de código aberto e até tem algumas facilidades para incluir personalizações. Então você poderia criar uma espécie de stored procedure ou extensão do SQL contido nele. Claro, não não é algo simples de fazer. Poderia ser em C, uma linguagem própria, uma alteração do SQL padrão ou outra linguagem, como Lua, C#, ou outra já conhecida, cada uma com suas vantagens e desvantagens.
Portanto é mais fácil fazer a consulta de forma simples e e depois manipular na aplicação. Por isso que entender bem tudo o que dá para fazer em uma query pode ajudar filtrar só o que deseja. Eu vejo muitas consultas ruins em códigos por aí, incluindo de pessoas experientes. Em parte porque o modelo de consulta do SQL não ajuda, por isso muitos vão para o NoSQL, mas muitas vezes por motivos errados.
Dito tudo isto é possível fazer um insert baseado em um select, ou seja, a fonte de dados do insert pode ser o resultado de um select. Como a pergunta não diz o que precisa , não pude ajudar mais. Exemplo:
INSERT INTO b (meuX) VALUES (x)
    SELECT x FROM a;

Coloquei no GitHub para referência futura.
Comment: @JeffersonQuesado Em muitos, casos, inclusive esse bem simples, não precisa mesmo, mas tem vários que só pode ser assim, porque pode não haver uma relação direta, precisa mapear
Comment: Ajudou, Maniero!  Obrigado!
Comment: Quando eu uso `INSERT-SELECT`, não uso `INSERT-VALUES-SELECT`. Não conhecia essa sintaxe com o `VALUES` antes do `SELECT`

Como fazer um "for each" no SQLite?


PrimeFaces dialog closeDynamic not working

Question: We recently migrated to PrimeFaces 11 and changed our code to open and close the dialog as per https://primefaces.github.io/primefaces/11_0_0/#/core/dialogframework.
The opening of dialog which has Okay and Cancel buttons is working fine but when clicking on the Okay or Cancel button inside the dialog it's not closing the the dialog and there are no errors in the application as well as the server log.
The sample code is as follows:
Template Dialog.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>

<h:head>
    <h:outputScript library="js" name="growl_updater.js" />
    <h:outputScript library="js" name="spear.js" />
    <title><h:outputText value="#{dialogTitle}" /></title>
</h:head>

<h:body class="dialog-body">

        <s:tooltip />

            <ui:insert name="dialog_content">
                <ui:include src="content.xhtml" />
            </ui:insert>

        <h:form id="dialog_conversation_form" rendered="#{not empty killCid and not empty conversationModel}">

        </h:form>

            <ui:include src="/templates/blockui/loading.xhtml" />

        <ui:insert name="exception_handler">
            <ui:include src="exception-handler.xhtml" />
        </ui:insert>

        <ui:insert name="messages">

        </ui:insert>

</h:body>

TestDialog.xhtml
<!DOCTYPE html>

<ui:composition template="/templates/dialog/dialog.xhtml">
    <ui:param name="dialogTitle" value="#{testMsg}" />

    <ui:define name="dialog_content">
        <h:form id="test_form">

                    <h:panelGroup>

                    </h:panelGroup>

        </h:form>
    </ui:define>
</ui:composition>

TestAction.java
@Named
@RequestScoped
public class TestAction {

    public static final Map<String, Object> POPUP_OPTIONS;
    public static final String URL = "/popup/TestDialog.xhtml";
    static {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("modal", Boolean.TRUE);
        map.put("draggable", Boolean.FALSE);
        map.put("resizable", Boolean.FALSE);
        POPUP_OPTIONS = map;
    }

    private BigDecimal value;

    public void acceptAndClose() {
       PrimeFaces.current().dialog().closeDynamic(value);
    }

    public void cancel() {
       PrimeFaces.current().dialog().closeDynamic(null);
    }
}

The main.xhtml page has button called verify which has action to open the Dialog,

    <f:param name="cid" value="#{mainModel.conversationId}" />

MainAction.java
@Named
@RequestScoped
@ExceptionsReported
public class MainAction {

   public void openValueAction() {
      Map<String, List<String>> params = new HashMap<String, List<String>>();
      params.put("cid", Arrays.asList(new String[] { model.getConversationId().toString() }));
      PrimeFaces.current().dialog().openDynamic(TestAction.URL, TestAction.POPUP_OPTIONS, params);
   }

   public void valueListener(SelectEvent event) {
     // get value from Okay or Cancel from Dialog
   }
}

The same code is working with an older version of primefaces using RequestContext.getCurrentInstance().openDialog and RequestContext.getCurrentInstance().closeDialog.
I tried various solutions and have gone through https://github.com/primefaces/primefaces/issues but was not able to find the issue.
Answer: found the issue, we have custom .js file in remote system which overrides the opening and closing of the dialog functions which leads to this issue.
We update the this custom .js file according to primefaces 11 and then opening and closing of the dialog is working again.


NSFetchedResultsControllerDelegate and Alternating Table View Cells

Question: I have a UITableView that updates from a NSFetchedResultsController. The UITableView has alternating row colours for even and odd rows. I need to add support for the insertion and deletion of objects, so I implemented the NSFetchedResultsControllerDelegate to handle this. However, now my alternating colour scheme fils after inserting anywhere but at the end. Any ideas on how to solve this without reloading the table view (and not loose my animations)?
Here is my code thus far:
- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  CustomTableViewCell *cell = ...;
  indexPath.row % 2 == 0 ? [cell odd] : [cell even];
  return cell;
}

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)object
       atIndexPath:(NSIndexPath *)deleteIndexPath
     forChangeType:(NSFetchedResultsChangeType)type
      newIndexPath:(NSIndexPath *)insertIndexPath
{
  switch(type)
  {
    case NSFetchedResultsChangeInsert:

      [self.mainTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:insertIndexPath]
                    withRowAnimation:UITableViewRowAnimationFade];
      break;
    case NSFetchedResultsChangeDelete:
      [self.mainTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:deleteIndexPath]
                    withRowAnimation:UITableViewRowAnimationFade];
      break;
  }
}

Answer: The followings are what I did for one of my projects:
- (void)reloadRowsFromIndex:(NSUInteger)index {
    NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
    for (NSInteger i = index; i < [items count]; i++) {
        [indexPaths addObject:[NSIndexPath indexPathForRow:i inSection:0]];
    }
    [tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
    [indexPaths release];
}

reloadRowsFromIndex: is called within tableView:commitEditingStyle:forRowAtIndexPath:, with the first index path being changed.
Comment: Is this reloading the entire table? I have a fetched results controller with a few thousand records and this seems like it might kill it...
Comment: Ended up solving this by using: `[self.mainTableView reloadRowsAtIndexPaths:self.mainTableView.indexPathsForVisibleRows]`.


Python reading csv file with semicolon delimiter: too many values to unpack

Question: I am trying to read a csv file exported from Microsoft Excel, looking like this:
114.9;280.9;501.5;0;W10;Firewall south;A;1;2;;
119.0;280.9;501.5;0;W10;Southern escape route;B;2;3;asdasdf;
120.5;280.0;501.5;0;W10;Southern escape route;C;3;4;;

The delimiter is semicolon and some of the columns might be empty. For example column 10 may be populated with asdasdf as an example. My code looks like this:
reader = csv.reader(open(inFile), delimiter=";")

nodesTable = window.getNodesTable()
pathsTable = window.getPathsTable()
clearTable(nodesTable)
clearTable(pathsTable)

for x, y, z, safe, mod, descr_node, name, start, end, descr_path in reader:
    nodesTable.SetStringItem(counter, nodesTable_ID_x, x)
    nodesTable.SetStringItem(counter, nodesTable_ID_y, y)
    nodesTable.SetStringItem(counter, nodesTable_ID_z, z)
    nodesTable.SetStringItem(counter, nodesTable_ID_SafeArea, safe)
    nodesTable.SetStringItem(counter, nodesTable_ID_Module, mod)
    nodesTable.SetStringItem(counter, nodesTable_ID_Description, descr_node)

    pathsTable.SetStringItem(counter, pathsTable_ID_Name, name)
    pathsTable.SetStringItem(counter, pathsTable_ID_StartNode, start)
    pathsTable.SetStringItem(counter, pathsTable_ID_EndNode, end)
    pathsTable.SetStringItem(counter, pathsTable_ID_Description, descr_path)

I am getting the error ValueError: too many values to unpack. What am I doing wrong here?
Comment: It sounds like there is at least one row that does not contain all of the values.
Answer: There are 10 semicolons in each line of your CSV file, which means, that the line will be splitted into 11 elements. In your for loop, there are only 10 variables used. Change the line into:
for x, y, z, safe, mod, descr_node, name, start, end, descr_path, _ in reader:

and ignore the _ variable, which will get the empty character between the last ; in the line and the end of line.
Or change your whole loop into:
cols = (nodesTable_ID_x, nodesTable_ID_y, nodesTable_ID_z,
        nodesTable_ID_SafeArea, nodesTable_ID_Module,
        nodesTable_ID_Description, pathsTable_ID_Name,
        pathsTable_ID_StartNode, pathsTable_ID_EndNode,
        pathsTable_ID_Description)

for rec in reader:
    for col, val in zip(cols, rec):
        nodesTable.SetStringItem(counter, col, val)


Batch operation for consuming data from API via drupal_http_request

Question: I am consuming data from an API which provides a URL similar to:
http://data.something.com/api/records?pageIndex=0&pageSize=25
The API will return XML which I will then use to create nodes.
There are many thousands of records, so I will need to do this via batch. I have used batch before but never for drupal_http_request. What would be the best approach for this? Is batch API the best solution, or would another method be preferable?
Thanks
Answer: Hi You're probably best off using the feeds module to import from feeds it can do them as one off imports imports or periodic batch jobs and create nodes from the feeds automatically. Even though they're beta/alpha they're well used and actively developed.
Comment: Thanks, I've been fiddling with feeds, feeds_xpathparser and feeds_crawler. Just going through the docs.
Comment: Great. Tested and working.
Comment: Good stuff, glad I could help :)


Qual o conceito de máquina virtual? Quais são os pontos positivos e negativos?

Question: Gostaria de um comprativo de uma linguagem que usa máquina virtual e uma que não utiliza.
Comment: A [resposta do Manieiro](https://pt.stackoverflow.com/a/332794/129) traduz bem o que é uma maquina virtual. Hoje em dia, fala-se muito sobre containers, algo que vale a pena você pesquisar.
Eu costumo resumir e VM no seguinte. Se você precisa de um laboratorio para fazer alguns experimentos, uma VM é uma execelente escolha. Agora por exemplo, se voce precisa usar no mesmo computador um Windows e Linux, utilizar um VM para essa finalidade não seria interessante, por questões de performance. Um dual boot nesse segundo caso seria mais eficiente.
Answer: Vou responder com o viés de VM de aplicação e ignorar outros tipos.
Máquina virtual é uma simulação de uma máquina real através de um software. Portanto é criado um software que executará na máquina real (tecnicamente poderia rodar em cima de outra máquina virtual, mas faz pouco sentido) como uma aplicação normal, e sua função é reproduzir as características de uma máquina real para rodar um código de outra aplicação. Em alguns casos é só um passo intermediário.
A máquina virtual costuma ter uma linguagem Assembly própria assim como um processador tem, e as suas aplicações são escritas, em última análise, nesta linguagem, mas claro que a origem do código pode ser em outras linguagens. Normalmente o código fonte é compilado para este Assembly antes ou durante a execução.
Algumas máquinas interpretam esse Assembly e rodam em uma laço decidindo o que executar em um enorme switch com cada instrução. Outras usam um JITter que transformam este Assembly no Assembly do processador físico onde está rodando (que virará código de máquina) ou até direto o código de máquina dele, o mais comum.
É possível em alguns casos ter uma máquina virtual que ocorre uma interpretação onde toda tradução ocorre conforme vai executando. Ou até pode ter alguma VM que não tenha esse processo todo e sirva só para controle maior de acesso à aplicação, então ela pode usar o próprio Assembly do processador. Mas são implementações bem incomuns.
Vantagens

A maior vantagem é a independência de plataforma física. Em geral ela abstrai tudo e se torna a plataforma onde você programa. É problema dela como fazer aquilo rodar bem na plataforma física e a sua como programar é só fazer o seu código de acordo com a VM sem se preocupar se está rodando em x86, x64, ARM, Windows, Linux, iOS, Android, etc. Isto pode incluir uma facilidade maior por ter APIs mais simples de usar.
Outra grande vantagem é ter um controle sobre a execução podendo limitar o que a aplicação consegue acessar da plataforma real tais como: ter a memória gerenciada, ter outros controles, ou ter o código assinado. Dá mais segurança e robustez e pode rodar até mesmo como parte de outras aplicações. E nesse ambiente controlado pode ser mais fácil rodar certas ferramentas de controle, de depuração, de flexibilização e de análise. Nem sempre isso é verdade, depende de implementação.
Em alguns casos é possível dar mais performance por transformar na plataforma mais específica, ou adaptar o código, ou dar um viés mais específico. Mas na prática isso não acaba acontecendo quando comparado com alternativas avançadas de aplicações que rodam 100% nativas. Só vale para alguns tipos.

Em geral as vantagens dadas podem ser obtidas em aplicações nativas, apenas não da mesma forma, com compromissos um pouco diferentes. Nos dois casos é preciso abrir mão de algumas coisas, mas dá para ter facilidade, performance, segurança e capacidade de rodar várias plataformas.
Desvantagens

Obviamente é um custo adicional para alguém desenvolver e manter uma VM, sempre uma fonte nova de problemas e depende de uma plataforma menos consagrada (embora isto tende mudar ao longo do tempo em casos de VMs que fazem muito sucesso).
É uma plataforma nova para aprender. Pode compensar ou não.
É comum ela ter um custo extra porque é uma aplicação que vai junto ou precisa estar previamente instalada para rodar sua aplicação.
Há um custo de execução de alguma forma, em alguns casos bem caro. Mas algumas podem eliminar isso antes.

Também existe uma série e vantagens e desvantagens específicas de alguma VM ou de necessidade pontual.
O que muda para a linguagem de programação
Para a linguagem em si pouco ou nada, a menos que sua especificação determine algo específico em relação a isso, incluindo ter algum requisito que exija que só possa ser feito em uma VM ou que seja proibido usá-la.
Salvo o dito acima, implementações de linguagens podem ser feitas tanto para rodar em uma VM ou não. Cada uma terá suas vantagens e desvantagens desde que atenda a especificação da linguagem.
Exemplos de VMs conhecidas:

JVM (várias implementações e variações como a Dalvik)
CLR (algumas implementações do .NET e Mono)
LLVM (não costuma ir junto com a sua aplicação)
Parrot (tentativa de universalizar VMs para linguagens dinâmicas)
WebAssembly, Flash e JS (diversas que rodam em browsers e outras formas usando plataforma web)
SQL (quase todos DBs usam VM, exemplo)
BEAM (Erlang, Elixir e outras)
NekoVM (bem pouco usada)
HHVM - (Hack e PHP do Facebook)
p-code machine (implementação inicial de Pascal)
Valgrind (usado para controle de ambiente)

Em essência todas as linguagens chamadas dinâmicas rodam em uma VM. Não é obrigatório o seu uso, mas se o dinamismo for muito importante é muito mais fácil assim. Isto vale para JS, PHP, Python, Ruby, Perl, Lua, Smalltalk, VB (clássico) e vários BASICs, as linguagens xBase, várias implementações de LISP, etc.
Coloquei no GitHub para referência futura.


How do I create and store in a property a block that returns a string?

Question: I'm struggling with the syntax of blocks. I need a block that takes no parameters and returns a string and I need to store that block in a property. So far, this is what I have...
I declare this property:
@property (nonatomic, copy) NSString * (^myBlockThatReturnsAString) ();

I assign the block like this:
someObject.myBlockThatReturnsAString = ^NSString * () {
    return @"foo";
};

That all compiles fine.
I'm trying use it like this:
myString = someObject.myBlockThatReturnsAString;

but I get
-[__NSMallocBlock__ isEqualToString:]: unrecognized selector sent to instance 0xc16b3b0

Where am I going wrong?
Comment: I much prefer understanding it: http://nilsou.com/blog/2013/08/21/objective-c-blocks-syntax/
Comment: @Abizern It's handy but it seems to be only about declaring blocks. According to that page I've declared the property correctly but I still don't understand where I've gone wrong after that.
Answer: What's going wrong is that the way you are attempting to run the block doesn't actually run it, it just returns the block object and attempts to assign it to an NSString variable.
This should work:
myString = someObject.myBlockThatReturnsAString();
Here is a great article about understanding the block syntax and why it is the way it is.
Comment: Thank you Benoit for the explanation. It makes sense. However, when I add the parentheses I get EXC_BAD_ACCESS (code=2, address=0xc). So maybe the new question is how to execute a block stored in a property when the block takes no parameters?
Comment: How did you assign the block to the property? Also, are you using ARC?
Comment: Yes, ARC (Xcode 5, iOS7, same behaviour in iOS6). Assigning as above.
Comment: In your example, what is the type of the pointer that receives the `isEqualToString` message? (0xc16b3b0 in the example)
Comment: I'm not sure how to find out. In the console I type po __NSMallocBlock__ but it just returns. (when I save this comment the double underscores on either side get removed)
Comment: (You can put backticks ` around comments to make them use the code font) What if when you declare the block you assign it to a local variable, and then assign the local variable to the property? Similarly, what if you assign the property to a local block variable and execute that?
Comment: `(lldb) po [__NSMallocBlock__ class]` returns `__NSMallocBlock__`
Does that help?
Comment: Here's one thing. I changed the block declaration to take a string and changed the assignment to match. Then I used it like this `myString = someObject.myBlockThatReturnsAString(@"");` and it works.
Comment: I have no idea what I did but your answer is now working. I'll mark it as the answer and I'm going to remove some of the edit's I made to my question so that it's closer to the original.


foreign key references to a table problem here

Question: create database Exer4

use Exer4

create table customer (
    cus_code int,
    constraint PK_customer primary key (cus_code),
    cus_Lname varchar(20),
    cus_Fname varchar (30),
    cus_intial varchar (2),
    cus_areacode int,
    cus_phone int,
    cus_balance float
     )

create table charter (
    char_trip int,
    constraint PK_charter primary key (char_trip),
    char_date date,
    ac_number varchar(5),
    foreign key(ac_number) references aircraft,
    char_destination varchar(5),
    char_distance float,
    char_hours_flown float,
    char_hours_wait float,
    char_fuel_gallons float,
    cus_code int,
    foreign key(cus_code) references customer
    )

    create table aircraft(

    ac_number varchar(5),
    constraint PK_aircraft primary key(ac_number),
    mod_code varchar(10),
    foreign key(mod_code) references model,
    ac_itaf varchar(10),
    ac_tiel varchar(10),
    ac_tier varchar(10),
    )

    create table model(
    mod_code int,
    constraint PK_model primary key(mod_code),
    mod_manufacturer varchar(10),
    mod_name varchar(10),
    mod_seats int,
    mod_chg_mile int,
    )

create table crew (
    char_trip int,
    emp_num int,
    constraint PK_crew primary key (char_trip,emp_num),
    foreign key (char_trip) references charter,
    foreign key(emp_num) references employee,
    crew_job varchar(10)
    )

create table rating (
    rtg_code varchar(5),
    rtg_name varchar (30),
    constraint PK_rating primary key (rtg_code)
    )

create table employee (
    emp_num int,

    constraint PK_employee primary key (emp_num),
    emp_title varchar (4),
    emp_lname varchar (20),
    emp_fname varchar (30),
    emp_initial varchar (2),
    emp_dob date,
    emp_hire_date date,
    )

create table pilot (
    emp_num int,
    pl_license varchar (3),
    pl_ratings varchar (30),
    pl_med_type int,
    pl_med_date date,
    pl_pt135_date date,
    constraint PK_pilot primary key (emp_num)
    )

why is that when i reference to "aircraft" it said invalid table??
what is wrong with my code??
Answer: You have to specify which field to reference:
foreign key (mod_code) references model (mod_code),

The foreign key constraint consists of 2 parts:
ALTER TABLE aircraft
ADD CONSTRAINT fk_aircraft_model
FOREIGN KEY (mod_code)  -- here you specify the field(s) to reference from in the aircraft table
REFERENCES model (mod_code)  -- here you specify the field(s) to reference to in the model table

Comment: This is optional. e.g. try `CREATE TABLE T1 (c INT PRIMARY key); CREATE TABLE T2 (c INT REFERENCES T1)`
Comment: this does not work, it said "foreign key 'FK_aircraft__insertnumberhere' reference invalid table model"
Comment: you need to create table model before table aircraft
Comment: @Martin I didn't know that one. Not something I would use though.
Answer: You are creating the tables in the wrong order. charter references aircraft but create table aircraft doesn't appear until later.
Comment: @Jeo. Yes. You can't reference the table in a FK definition until it exists. You also have some datatype issues that you will find once you have the order correct.
Comment: @Jeo - So why did you accept the other answer that is irrelevant to your question then?


IIS sends connection reset on 2 out of 4 sites

Question: I have 4 websites on an IIS server (hosted on windows 2016)
2 websites works as expected,
for 2 websites the request doesn't reach IIS at all - and I get connection RESET.
running Wireshark I've noticed that the working websites gets client hello with TLSv1.2
and the non working websites gets client hello with TLSv1 that ends up with RST.
Not sure why it happens, or how to debug / solve this.

same server - another website:
Comment: Review SSL/TLS settings using tools like IIS Crypto https://www.nartac.com/Products/IISCrypto/ It is best practice to disable TLS 1.0 and 1.1 now, so I don't think resetting TLS 1.0 connections is a problem.
Comment: TLS Settings are global for the whole server, so it either affects all sites or none. I would compare the certificates of the working and not-working sites, are there still SHA-1 hashes used?
Answer: Problem solved - the certificate for that site was either wrong (for one) or none set (for the other).
For some reason - that caused the tls1.0 handshake and connection reset (why ?)


VMware Host-Guest intermittent communication on bridged mode

Question: I'm running 2 VMs (Unbuntu & Ubuntu Server), both of them are on bridged mode.
The host is a Win7 running VMware Workstation 7.
My purpose is to set up a PostgreSQL server on the Ubuntu Server VM, but i can't connect from host to the guest server.

Pinging Host from any VM shows Destination Host Unreachable.
Pinging Guest Vm's from Host, i get intermittent responses mixed with timeouts

I've disabled all firewalls for this test, both VMs have connectivity with internet and between them. I can also ping succesfully from any other machie on the subnet, the access point pings ok, but host<->guest is impossible.
The weirdest thing is that while i'm pinging guest VMs from host and i get the intermittent responses, sometimes i can connect with the postgresql DB, but only while i'm getting the responses from the ping.
Routing is OK, i'm bridging over a wireless NIC... ask me for any other data needed
Answer: Short answer is, don't bridge over wireless if you can avoid it. Also, you can add a second network interface for your VMs, and connect it to the host-only network. Use that for your host->guest communication, and the bridged interface for everything else.
I'm surprised bridging over a wireless NIC works at all. Apparently VMWare supports that in the latest version. It most likely implements some type of level3 forwarding. My guess is that it's having trouble capturing the packets that are being sent out over the wireless NIC, and handling them like incoming packets by forwarding them to the VM. That could be hardware/driver dependent, or just a bug in VMWare's implementation.


CentOS and MySQL

Question: So I have this VPS on CentOS. A few months ago, I installed apache2, mysql and some other stuff, to host a wordpress blog. Now, for some reason, the mysql service has shutdown, and I'm unable to restart it.

"which mysql" returns "/usr/bin/mysql" seems to confirm it is indeed installed
"/etc/init.d/mysql" returns "-bash: /etc/init.d/mysql: No such file or directory"
"service mysql start" returns "-bash: service: command not found"
Interchanging mysql for mysqld did not made any changes in those last two points
Only log file related to mysql, in the /var/log folder is named mysqld.log.rpmsave and is empty

Thruthfully, I'm a programmer and I am utterly confused by this situation. Any idea?
-- EDIT --
Thanks for your answers guys. I tried Caleb and lain's suggestion and unfortunately /sbin/service mysql start or /sbin/service mysqld start returns me unrecognized service.
As for the result of rpm -qa | grep mysql :
php-mysql-5.3.3-1.el5.remi
mysql-libs-5.1.53-1.el5.remi
mysql-5.1.53-1.el5.remi
remi being the repo where I found newer version of PHP (from 5.1.X to 5.3).
Answer: From the remi repo, you need mysql-server.  Try yum install mysql-server; you'll then be able to chkconfig and service mysqld to your heart's content.
If your remi repo isn't enabled by default, it'll be yum --enablerepo=remi install mysql-server; try that if you get a bunch of unresolved dependency messages.
Comment: Yep.  These other answers ignore the fact that you don't have the server installed.
Comment: To be fair, he edited the question to add the `rpm -qa` output.
Comment: Yeah that was pretty much the problem. For some freak reason, a repository conflict or something along those line, mysqld was uninstalled. Re-installed it and it's all good now.
Comment: Wow. I am a moron. Lucky I found your answer
Answer: My guess is that you somehow removed the server part of MySQL. /usr/bin/mysql is just the client part and doesn't have an entry in /etc/init.d. Can you post the output of rpm -qa | grep mysql?
Answer: On CentOS to start the mysql-server (mysqld) use the command
/sbin/service mysqld start

Answer: Try /sbin/service mysql restart.
Looks like your shell, including exec paths and such, is pretty messed up, but you have been on the right track.
Comment: Yeah that is probably related to the installation and setup step I did a few months ago, quite rashly.
Answer: You don't have the server installed.
# yum -y install mysql-server
# service mysqld start

CentOS and MySQL


What is difference between identity provider vs federation provider?

Question: I have been reading some article on Windows Identity foundation and there are some vague definitions on federation provider(may be my understanding is not accurate). However I didn't come across one article which dilettantes between Identity provider and Federation provider clearly. Can anyone please explain me the difference clearly?
Answer: There are different WEB authentication mechanisms and protocols. Each has its own (always changing) terminology. At times someone invents new terminology to clarify/confuse things.
In the WIF/Microsoft world "Identity Provider" (IP or IdP) is the term for a server that authenticates a user (the server is connected to some account database, AD in the current case of ADFS).
Federation server/provider is often used for a server that receives a SAML Token from another server. And then forwards it to the next Relying Party.
An ADFS server is often/typically *both*.
Comment: Does your use of capital letters for "WEB authentication" indicate it is an acronym for some phrase, or is it [Web Authentication](https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API), which I believe means simply "web" like found in "www"?


Reduce the radical

Question: Calculate $\sqrt{34 - 24\sqrt{2}}$
I thought of turning $\sqrt{34 - 24\sqrt{2}}$ into the form $ x + y \sqrt {2} $. So by squaring, we get $ x ^ 2 + 2xy \sqrt {2} + 2y ^ 2 $. Turning it into a system we have: $ xy = -12 $ and $ x ^ 2 + 2y ^ 2 = 34 $. I will get 4 solutions for $ x $ and $ y $,
how can I end the problem using this method?
Comment: What do you exactly want to do with this thing?
Comment: I want to arrive $\sqrt{3}-4$
Answer: As $xy=-12<0$  they will have opposite signs
$$x^2(2y^2)=2(-12)^2=288$$
So, $x^2,2y^2$ are roots of
$$0=t^2-34t+288=(t^2-16)(t^2-18)$$
If $x^2=t^2=16, x=\pm4, y=-\dfrac{12}x=\mp3$
What if $x^2=t^2=18?$
Answer: there might be integer solutions, not just rational.... Since $$17 \equiv 1 \pmod 8, $$ there is a solution to $u^2 + 2 v^2 = 17,$ namely $u=3, v = 2,$ giving $9+2\cdot 4 = 17.$ Since $2$ is also represented by $x^2 + 2 y^2,$ we can compose to get $4^2 + 2 \cdot 3^2 = 16 + 18 = 34.$ Finally, switching sign to $x=4, y=-3$ leads to $2xy = -24$
To check: what is
$$ \left( 4 - 3 \sqrt 2 \right)^2 \; \; ?  \;  $$
Answer: You have $xy=-12$ and $x^2+2y^2=34$.
To end it from there, solve $x^2+2\left(-\dfrac {12}x\right)^2=34$.
(This becomes a quadratic equation in $u=x^2$.)

Reduce the radical


How do I set selected item in a combobox class?

Question: I have populated a combobox with list class.
cboParentMenu.DataSource = listMenu;
cboParentMenu.DisplayMember = "caption";

This is the class variables.
public string caption { get; set; }
public string caption_style { get; set; }
public string cat_id { get; set; }
public int id_menu { get; set; }

Now, how do I set the selected item using the field id_menu? I'm thinking something like this one.
cboParentMenu.SelectedItem.id_menu = 123;

Answer: You can do
cboParentMenu.SelectedItem = listMenu.FirstOrDefault(x => x.id_menu == 123);

Make sure you import System.Linq.
Answer: Try this:
cboParentMenu.SelectedValue = listMenu.Find(i => i.id_menu == 123);

Comment: If nothing is found, an exception will be thrown. So you better use FirstOrDefault instead of Find. In that case, the result will be null then nothing is selected.


How to default a content type's Language field to the authenticated user's language?

Question: We are using Entity Translation so that content can be created in several language. One item we noticed is that on the basic page, for example, has a language field that you can set when you create a piece of content. As of right now, any users regardless of if their profile's preferred language is set to French (for example), the French user is still able to create a content in English.
Ideal scenario:
If a French user logs in and creates content of type basic page, then the language field should be set to French. If a German user logs in and performs the same actions, the language should be restricted to just creating content using the German language.
Any thoughts on how I would set this up?
Answer: actually, i would create a custom module (i hope, you know how to code a bit)
the code should be something like the following:
<code>    <?php
    function YOUR_CUSTOM_MODULE_node_presave($node){
        global $user; // gets the current user account
        $node->language=$user->language;
    }
</code>


How can I view n_lru_nuked in varnish 3.0.5?

Question: I'm trying to monitor varnish cache evictions and can't seem to find out how to view the n_lru_nuked counter on varnish 3.0.5. varnishstat isn't finding the counter:
$ varnishstat -f n_lru_moved,n_lru_nuked

0+21:44:54
Hitrate ratio:        1        1        1
Hitrate avg:     0.8292   0.8292   0.8292

       31943          .            .   n_lru_moved - N LRU moved objects

Is the method for monitoring cache evictions different in 3.0.5?
Answer: No one else has offered anything up here. I thought I would let you know you're not alone trying to find the answer.
I have the same question and I'm starting to think varnishstat perhaps doesn't report metrics with entirely null values.
I have a test-bed server that I might deliberately starve of cache storage and see what happens.  If I can confirm this behaviour, I will report back.
Perhaps someone might offer their expertise?
Update
OK I can confirm that varnishstat appears to save terminal space by not reporting counters that are entirely 0 or null.
This is because of the continuously updated display mode.
If you run varnishstat non-interactive / continuous then the stat does indeed show.
[root@test nginx]# varnishstat -1 -f n_lru_nuked,n_expired,n_sess,n_sess_mem
n_sess_mem                  20          .   N struct sess_mem
n_sess                       0          .   N struct sess
n_expired                   57          .   N expired objects
n_lru_nuked                  0          .   N LRU nuked objects
[root@test nginx]#

Comment: varnish 4 and ubuntu 16.04, you may need to add MAIN like as these:
varnishstat -1 -f MAIN.n_lru_nuked


Prove that $\frac{1}{\sqrt{1+a^2}}+\frac{1}{\sqrt{1+b^2}}+\frac{1}{\sqrt{1+c^2}} \leq \frac{3}{2}.$

Question:
Let $a,b,$ and $c$ be positive real numbers such that $a+b+c = abc$. Prove that $$\dfrac{1}{\sqrt{1+a^2}}+\dfrac{1}{\sqrt{1+b^2}}+\dfrac{1}{\sqrt{1+c^2}} \leq \dfrac{3}{2}.$$

This question seems tricky because how do we incorporate the $a+b+c = abc$ condition to solve this? I was thinking of solving for the variables and substituting like $a = \dfrac{b+c}{1-bc}$ etc., but I am not sure how that will help.
Comment: With the substitution $a=1/x, b=1/y, c=1/z$ it becomes a duplicate of [$\frac{a}{\sqrt{a^2+1}}+\frac{b}{\sqrt{b^2+1}}+\frac{c}{\sqrt{c^2+1}} \leq \frac{3}{2}$](http://math.stackexchange.com/questions/1603415/prove-that-fraca-sqrta21-fracb-sqrtb21-fracc-sqrtc21?rq=1)
Answer: Let $a=\tan(A)$, $b=\tan(B)$ and $c=\tan(C)$. We then have $$\tan(A)+\tan(B)+\tan(C) = \tan(A)\tan(B)\tan(C) \,\,\,\, (\spadesuit)$$
Recall that $(\spadesuit)$ is true iff $A+B+C = \pi$, i.e., $A$, $B$ and $C$ are angles of a triangle. (Infact the part we need is trivial, since we have $\tan(C) = -\dfrac{\tan(A)+\tan(B)}{1-\tan(A)\tan(B)} = \tan(\pi-(A+B))$.)
Further, since $a,b,c > 0$, we have that $0 \leq A,B,C < \dfrac{\pi}2$. We then have that
$$\dfrac1{\sqrt{1+a^2}} + \dfrac1{\sqrt{1+b^2}} + \dfrac1{{\sqrt{1+c^2}}} = \underbrace{\cos(A) + \cos(B) + \cos(C) \leq 3\cos\left
(\dfrac{A+B+C}3\right)}_{\text{By Jensen}} = \dfrac32$$
Comment: Nice technique !
Comment: Why is $\spadesuit$ true iff $A+B+C = \pi$?
Comment: @user19405892 I suggest that you take a look at the numerator of the tan(A+B+C) identity.
Answer: Change the notation using  $x=\frac{1}{a}$ , $y=\frac{1}{b}$ and $z=\frac{1}{c}$
Now the condition is that $xy+yz+zx=1$.
And the inequality to prove is :
$$\frac{x}{\sqrt{x^2+1}}+\frac{y}{\sqrt{y^2+1}}+\frac{z}{\sqrt{z^2+1}} \leq \frac{3}{2}$$
Now use the condition and notice that :
$$x^2+1=x^2+xy+yz+zx=(x+y)(x+z)$$
So now using the AM-GM inequality :
$$\frac{x}{\sqrt{x^2+1}}=\frac{x}{\sqrt{(x+y)(x+z)}} =\sqrt{\frac{x^2}{(x+y)(x+z)}} \leq \frac{1}{2} \left (\frac{x}{x+y}+\frac{x}{x+z} \right )$$
Do the same thing for the other terms and add them to get the conclusion .


Suppose $f:[0,\infty]\rightarrow$ to R and has continuous $f'(x)$ and $f''(x)$ f(x) → 0 as x → ∞. Show that f′(x)→0 as x→∞

Question: Suppose $f:[0,\infty)$ $\rightarrow$ R and has continuous $f'(x)$ and $f''(x) $ .
$f(x) $$\rightarrow $0 as $x$ $\rightarrow$ $\infty$. Given $f'(x)\rightarrow b$ as $x \rightarrow \infty$
show that $b=0$
Get stuck in the first place, but I tried to use Mean Value Theorem and then connected it to the limits.
Any hint?
Comment: I hope you mean: **given** $f'(x) \to b$ as $x \to \infty$, show that $b=0$.
Comment: Sorry. Robert is right. Given $f'(x) \rightarrow b$ as $ x \rightarrow \infty$ show that $b=0$
Answer: Hint: consider
$$ \lim\limits_{x \rightarrow \infty} \frac{f(x)}{x} $$
Further hint: use L'Hospital's rule.
Notice that to do that, you need the limit of $ f'(x) $ to exist. The counterexample has been mentioned
Comment: Sorry. After I get $$ \lim\limits_{x \rightarrow \infty} \frac{f(x)}{x}=0 $$ I still can't go on....
Comment: I'm not sure if L'Hospital's Rule can be used here. I believe what you mean is that $$ \lim\limits_{x \rightarrow \infty} \frac{f(x)}{x} =\lim\limits_{x \rightarrow \infty} \frac{f'(x)}{1} $$ But isn't L'Hospital's Rule only available when $$ \lim_{x \rightarrow \infty}{f(x)} =\lim\limits_{x \rightarrow \infty}{x}=\infty $$ or $$\lim_{x \rightarrow \infty}{f(x)} =\lim\limits_{x \rightarrow \infty}{x}=1$$
Comment: But, if I suppose that I already know f'(x)=0, I can have $$ \lim\limits_{x \rightarrow \infty} \frac{f(x)}{f'(x)} =\lim\limits_{x \rightarrow \infty} \frac{f'(x)}{f''(x)} $$ by L'Hospital Rule, as $$ \lim\limits_{x \rightarrow \infty} {f(x)}=\lim\limits_{x \rightarrow \infty} {f'(x)} =0$$


How to get a filename and set it as a property in Ant?

Question: I need to scan files in a folder and set property as file name in Ant so I can use it later.
For example, there's a test123.tar under Jenkins folder.  I need to use test*.tar to match this file and then set a property named "filename" to test123.tar
Is it possible to do it?
Thank you very much!
Answer: You could use pathconvert to convert a fileset into a list of files, then loadresource with a filterchain to extract the single required value from the list.
<project default="test">

    <target name="test">

        <pathconvert property="file.list" pathsep="${line.separator}">
            <map from="${basedir}${file.separator}" to=""/>
            <fileset dir="${basedir}">
                <include name="test*.tar"/>
            </fileset>
        </pathconvert>

        <loadresource property="file.name">
            <string value="${file.list}"/>
            <filterchain>

                <headfilter lines="1"/>
            </filterchain>
        </loadresource>

        <echo message="file.name: ${file.name}"/>

    </target>

</project>

Output:
$ ls test*.tar
test012.tar  test123.tar  testabc.tar
$
$ ant
Buildfile: C:\tmp\ant\build.xml

test:
     [echo] file.name: test012.tar

BUILD SUCCESSFUL
Total time: 0 seconds

Verbose output:
$ ant -v
test:
[pathconvert] Set property file.list = test012.tar
[pathconvert] test123.tar
[pathconvert] testabc.tar
[loadresource] loading test012.tar
[loadresource] test123.tar
[loadresource] testabc.tar into property file.name
[loadresource] loaded 13 characters
     [echo] file.name: test012.tar

BUILD SUCCESSFUL
Total time: 0 seconds

Comment: `${file.separator}` can be replaced with `/` to simplify
Answer: A combination of fileset (to search) and pathconvert will help.
<project name="SuperRoot" default="demo" basedir=".">
    <fileset id="afileset" dir="searchfolder" includes="**/test*.jar"/>

    <target name="demo" >
        <pathconvert property="result" refid="afileset" />
        <echo message="found : ${result}"/>
        <basename property="foo.filename" file="${result}"/>
        <echo message="found : ${foo.filename}"/>
        </target>
</project>


Compute maximum likelihood estimator and confidence interval

Question: Let $X$ have a Poisson distribution with parameter $\lambda$. Find the maximum likelihood estimator of $\alpha=\mathbb P(X=0)$. In a sample of size 100 from a Poisson distribution, it is found that the mean is 0.75. Calculate an approximate 95% confidence interval for ${\alpha}$.
For the MLE, we want to maximise $e^{-\lambda}$, but isn't that a constant?
For the confidence interval, I think it is an interval of radius $\frac{0.075}{0.075/100}$, but I can't quite remember. A few years since A levels...
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/14246/discussion-between-jsk-and-user134724)
Comment: For the MLE, certainly $\lambda$ is a constant: *but what value does it have?* MLE tells you to select the value that maximizes the likelihood.
Comment: @whuber we would like ${\lambda}$ as small as possible. So what is that?
Comment: You are not trying to maximize the function $e^{-\lambda}$, you are trying to maximize the likelihood with respect to the parameter $e^{-\lambda}$
Comment: Do you know how you would find the MLE for $\lambda$?  What function do you maximize to find the MLE for $\lambda$?
Comment: @jsk Yes for a sample $X_{1},..X_{n}$, the MLE of ${\lambda}$ is mean($X{1},..,X_{n})$. So are you saying I have to differentiate the joint denisty w.r.t $e^{-{\lambda}}$ instead of ${\lambda}$?
Comment: @user134724 Yes, though it will be easier to perform the differentiation if you write the log likelihood in terms of $\theta$ where $\theta=e^{-\lambda}$, then differentiate with respect to $\theta$.
Comment: @jsk $P(X=x)=e^{-\lambda}{\lambda}^x/x!$ Differentiating w.r.t $e^{-\lambda}$ gives ${\lambda}^x/x!$
Comment: See http://stats.stackexchange.com/a/54459 for details of finding the MLE for a Poisson distribution.
Answer: There are several things you need to recall in order to do this problem.
1) Invariance of the MLE to transformations.
2) Approximate normality of the MLE.
3) Delta method to create interval for $g(\lambda ) = e^{-\lambda}$.
4) Instead of using 3, you might want to recall that for monotonic functions $g(\lambda)$, you can start with a CI for $\lambda$, call it $(L,U)$.  Then a confidence interval for $g(\lambda)$ would be $( g(L), g(U) )$ if g is monotonically increasing, and $( g(U), g(L) )$ if monotonically decreasing.
As a sidenote, the method listed in 4 may be preferred to the method in 3 since it would be guaranteed to be a range respecting CI for $e^{-\lambda}$.
Comment: It's a useful property to recall that if you have the MLE for a parameter $\lambda$, call it $\hat{\lambda}$, then if you want the MLE for any function $g(\lambda)$ is $g(\hat{\lambda})$
Comment: Alternatively, if you're not familiar with that property of MLEs, you should define $\theta=e^{-\lambda}$, then rewrite the likelihood in terms of $\theta$ instead of $\lambda$, then maximize the likelihood with respect to $\theta$.
Comment: I'm confused about the first one. I don't know what I'm meant to be maximising
Answer: As this question is tagged as self-study, I will only sketch an answer.
First, you need to fix some notations. Denote $x_1, \dots, x_n$ the observed values of $X_1, \dots, X_n$, iid random variables of law $\mathcal P(\lambda)$.
You have $P( X_i = x_i ) = { \lambda^{x_i} \over x_i! } e^{-\lambda}$, hence a log-likelihood for the $i^{th}$ observation $\ell_i(\lambda ; x_i) = x_i \log \lambda - \lambda + \text{cste}$, and the log-likelihood for the whole sample is
$$ \ell(\lambda; x_1, \dots, x_n) = \left(\sum_i x_i \right) \log \lambda - n \lambda, $$
from which you could derive the MLE for $\lambda$, $\hat\lambda = \overline x$.
Yes, this is fine, but you are interested in $\alpha = e^{-\lambda}$, which gives an alternate parametrization of the Poisson distribution. The log-likelihood of $\alpha$ for the whole sample is
$$ \ell(\alpha ; x_1, \dots, x_n) = \left(\sum_i x_i \right) \log( -\log \alpha ) + n \log \alpha. $$
You can now find $\hat \alpha$ which is of course $e^{-\hat\lambda}$, but more importantly, you can compute the Fisher information $- {\partial ^2 \over \partial \alpha^2}\ell(\alpha ; X_1, \dots, X_n)$, and its expected value, and the variance of the (asymptotically normal) MLE of $\alpha$...
Hope this helps.
PS. Suggestion 4 from jsk's answer is surely better (easier to handle): compute a CI for $\hat\lambda$, deduce a CI for $\hat\alpha = e^{-\hat\lambda}$...


Reflection: Cast Array Of Objects To List

Question: Code:
object arrayOfObjs = new object[]{ 1, "test"};

Now I want to Add new element to this array. Is it possible like:
((IEnumerable)arrayOfObjs).Cast<object>().ToList().Add("test123");

This code doesn't add item.
Edit:
if we will make it strongly typed:
object arrayOfObjs = new string[]{ "1", "test"};

Adding work, thx:
var tmp = ((IEnumerable)arrayOfObjs).Cast<object>().ToList();
tmp.Add("test123");

How can we cast this list back to Array of T, if type is unknown at design time?
Answer: You'd need to capture the result in a local variable:
var items = ((IEnumerable)arrayOfObjs).Cast<object>().ToList();

items.Add("test123");

Comment: Thx. Found solution var arr = Array.CreateInstance(tag.GetType().GetElementType(), tt.Count);
                        Array.Copy(tt.ToArray(), arr, tt.Count);


Form and Table on same page

Question: I got a Form and a Table displayed on the same page. The weird thing is that when the form is submitted and the page are reloaded (after doing a database SELECT) with $_POST values, the table is not showing....why?
Here is the code (suppose $tabb2 have correct table data):
<?php

function collabinc_menu($may_cache) {
  $items = array();
  $items['admin/reporting/report_details2'] = array(
    'title' => 'Report: User details by stores',
    'access arguments' => array('access content'),
    'page callback' => 'say_report_details2',
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function say_report_details2($values = array()) {
  $output = "";

  if (isset ($_POST['search'])) {
     $output = theme("table", $tabb2);
  }

  $build['content'] = array(
    'this_does_not_matter_too_much2' => drupal_get_form("report_details_form"),
    'this_does_not_matter_too_much1' => array('#markup' => $output,),);

  return $build;
}

Please note that both Form and Table are working, and displayed correctly at the same time when not putting the "if (isset ($_POST['search']))" condition. Also note that the condition is fully working and checked.
Thanks!
Comment: Where is the Select query?
Comment: It is supposed to be inside the if statement before theming the table. I haven't posted all code in order to keep it simple.
Comment: Could you post the complete code.....
Answer: You can use the Table theme. Example :-
$form['data_field'] = array(
'#type' => 'textfield',
'#title' => t('Search!'),
'#id'   => 'search',
'#maxlength' => 1024,
'#description' => t('Search by using tags and free text'),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Go!!',
);
...
...
fill $table
...
...
if(sizeof($form_state['input'])!=0) {

$form['table'] = array(
'#theme' => 'table',
'#header' => $header,
'#rows' => $rows,
'#empty' => t('Empty Rows')
);
}
return $form.

Comment: What do you mean? Display my table and my form inside a new table?? Are table not supposed to only be using when displaying tabulated data and not for layout? How would it work? My form is the caption and my table the body of my containing table? I don't really understand what you mean...
Comment: What you are trying to do? Do you want that on form submit the table should display your records. and if the form is not submitted then the form is displayed with table having no rows.
Answer: It sounds like it might be related to this post: hook_form being called twice. After the page reloads the form_state is no longer retained. The solution they suggest:

Set $form_state['redirect'] = false to prevent redirection.

Form and Table on same page


Displaying contents of a list in a "bar graph"

Question: I am new to Python and I am trying to learn how to combine lists with for and while loops for an upcoming workshop at Uni. I am stumbling on one thing though:
Basically, I have numerical values stored in a list and I want to display it like this:
1  IIIII
2  II
3
4  III
5  II

So that I's represent the number, i.e 3 = III
I tried this code (I had already established count as a list earlier in my code):
listIndex = 1
while listIndex < len(count):
    print(listIndex, " ", end='')
    for number in count[listIndex]:
        print("I", end='')
    print()
    listIndex += 1

But I get the following error:
1   Traceback (most recent call last):
File "/Volumes/USB/workshop7.py", line 145, in <module>
for number in count[index]:
TypeError: 'int' object is not iterable.

I don't see what I've done wrong, I looked up the error and I don't see why I cant iterate through that for loop?
The for loop should use the listIndex variable to go to the corresponding index in the list and retrieve the value, displaying it as a series of Is to correspond with the number stored there? Any help in understanding where I've gone wrong would be much appreciated. This is for assessment (5%) so if you could help my thinking rather than give me the answer, it would be much appreciated.
Comment: +1: For mentioning that you would like help in flow and thinking rather than answer!
Answer: count[listIndex] is an int value, not list. You can use range() to make list, or even better you can use "string multiply", i.e. print('I' * count[listIndex]) and omit for loop.
Comment: That might be a little too much help for someone who asked for hints to help his thinking, rather than being straight-out given the answer.
Comment: I don't think I gave too much help :-) With `help("range")` she/he will see info about making list of integers. As a beginner she/he apparently don't know Python string multiplying like `"I" * 5`.
Comment: Try `print(type(count[listIndex]))`. In your code `count` is a list (array) of integers, and `count[idx]` is an integer. You can make list of integers from 0 up to idx by using `range(idx)`. This is used in loops where you need index.
Comment: Thanks for the reply.

I added to the code print(type(count)) and it did reveal that it was indeed a list. I also added a print(count) line and it did have positions in the list for all the values I needed.
Answer: So you have a list named "count" that contains counts, and you're fetching one of them with count[listIndex]. What's the result? An int, right?
That means that your for loop is trying to do something like:
for number in 3:
    print("I", end='')

Is "for number in 3" a valid way to do loops in Python? What would be a better way to write that for loop?
Answer:
In Python lists are 0 indexed, so you should start list_index from 0
Knowing the count, you don't need to loop to print 'I'. In Python you can simply do:
print 'I'*count[list_index]


Record ASP.Net user in IIS logs

Question: I have an ASP.NET 3.5 application (on IIS 6.0) which uses ASP.NET forms authentication. In my IIS logs, I have extended logging turned on including the cs-username field. Even after a user has logged in to my site, the cs-username still displays '-'.
Is there a way to get the authenticated ASP.NET user's name to appear in the username field in the logs?
Answer: Not easily.
cs-username by default is the HTTP authentication username, not forms authentication. You might be able to write an ISAPI DLL to intercept the call, parse the ASP.NET auth token cookie, decrypting it if you have to and retrieve the username from the membership providerthen intercept SF_NOTIFY_LOG and respond to the ON_LOG event to set the right name, but it's non-trivial.
Answer: Alernatively, use the ASP.NET memebership provider to write some customised codes to record them in the database!
Answer: yep, pretty lame of asp.net...you'd think they would have integrated it better w/ the IIS logs :-P
You can use this isapi filter, but I'm not sure it'll work for IIS7 (Windows 2008).  Should work fine in Win2003:
http://www.codeproject.com/KB/trace/isapilogger.aspx

Record ASP.Net user in IIS logs


SAP UI5 with ASP: Repeater Control

Question: Does anyone know how to use an sap ui5 control with the asp:repeater control.  Everytime I try to put a button, it only shows up in the first iteration of the repeater.  And not in the rest of the iterations
<asp:Repeater ID="NewsFeedID" runat="server" >
<ItemTemplate>

When I use this code it only shows up for the first iteration of the asp:repeater but I want it to show up for all iterations.  Does it have something to do with the div id=Comments?  Need help please
Answer: Your Repeater creates multiple
 elements with the same id, which causes conflicts.
One way to fix the problem is to add a runat="server" attribute to the
, making it a server-side control so that ASP.NET generates a unique ID for each instance:

Then pass the dynamically generated ID to the placeAt function:
}).placeAt("<%# Container.FindControl("Comments").ClientID %>");

Answer: You can rename every instance with the index of repeater item:

            <div id="<%# "Comments"+ Container.ItemIndex+1 %>">

SAP UI5 with ASP: Repeater Control


Criação de controles dinamicos em ASP.Net

Question: Estou querendo criar um componente para um cadastro padrão. No projeto em que estou desenvolvendo, estou utilizando Web Forms, onde eu tenho a minha masterPage com o layout do site (menu, cabeçalho e rodapé). Mas para facilitar a manutenção futura, criei uma classe e dentro dela criei um método onde esta pagina crie dinamicamente os meus botões, titulo desse cadastro e assim por diante. Porém quando vou fazer a chamada dele da minha pagina de cadastro de clientes por exemplo, ocorre um erro porque o meu panel do cadastro de cliente ainda não foi criado:

Additional information: Referência de objeto não definida para uma instância de um objeto.

Código do meu cadastro de grupo:
    protected void Page_Load(object sender, EventArgs e)
    {
        /****************************
        *   Declarando os Objetos   *
        ****************************/

        CadastroPadrao cp = new CadastroPadrao();
        Grupo gp = new Grupo();

        /********************************************
        *   Metodo que cria os objetos na pagina    *
        ********************************************/

        cp.GeraCadastro("Cadastro de Grupo", gp);
    }

Codigo da minha classe Padrao:
    public void GeraCadastro(string titulo, Object tela)
    {
        Button btnPesquisar = new Button();

        btnPesquisar.Text = "Pesquisar";
        btnPesquisar.ID = "btnPesquisar";
        btnPesquisar.Width = 100;

        if (Convert.ToString(tela) == "TulipaCB.Grupo")
        {
            CadastroPadrao pagina = new CadastroPadrao();

            pagina.pnBotao.Controls.Add(btnPesquisar);
        }

Erro ocorre no momento exato em que roda a linha:
pagina.pnBotao.Controls.Add(btnPesquisar);
Comment: Acho que seu botão não tem ViewState. Com isso, a página perde o botão a cada post - o botão que você a cada carga da página não é o botão que estava lá antes. Dá um ViewState pro botão que você cria e vê se resolve.
Comment: Parece que a propriedade `pnBotao` está nula, você pode mostrar o código da classe `CadastroPadrao`?
Comment: esse meu pnBotao, eu crio na pagina .aspx:

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="CadastroPadrao.aspx.cs" Inherits="TulipaCB.Cadastro.CadastroPadrao" %>

Answer: Consegui resolver a minha situação... Eu usei o User Control, nele eu desenho como eu quero os botoes,grid e tudo mais. Isso funciona como um componente, depois de pronto é só arrastar para a tela e pronto :)
Caso alguém precise tem o passo a passo aqui:
http://www.linhadecodigo.com.br/artigo/277/aspnet-utilizando-usercontrols.aspx


Extended chord semitone clashes

Question: I understand how, for instance, major 11 chords in their unaltered (diatonic) state are a problem as the 11th is a semitone away from the 3rd and so sharpening the 11th is a solution.
However taking the minor 9th on the ii degree as an example the 9th is a semitone away from the minor 3rd and yet this is okay. So in C, the ii degree is D, giving a m9 of DFACE - E is a semitone from F.
What gives?
Comment: I've also personally wondered why V9 of a minor key is considered OK, since the root and 9th are a minor 9th apart and still clash like heck when I play them together. Maybe it's because that particular clash is unavoidable? The only time I've used V9 of a minor key in my compositions, I purposefully wanted that painful sound.
Comment: @Dekkadeci - the first few notes of 'Misty' sound brassy?
Comment: I don't know the answer, but it seems related to the way that playing a major 7th interval by itself (say F-E) sounds dissonant, but fill in the gaps to make a full major 7th chord (F-A-C-E) it becomes "pretty."
Comment: @Theodore - Honestly, I find major 7th chords to be brassy and unpleasant to listen to, to the point that I never use them in classical music (including Romantic-era-style music).
Comment: @Tim - I'm not familiar with "Misty" (I've *looked* at arrangements of it, and the piece is probably too slow for my tastes), but based on a jazz piece I did compose that starts with a major 7th chord...I guess those first few notes wouldn't sound obviously brassy. The crunch of a major 7th is generally fairly obvious to me, though.
Comment: @Dekkadeci - have a listen to Ray Stevens' version - probably not your preferred listening, but what the heck?
Comment: @Dekkadeci Maj7 chords are not much to my personal taste either (thus the scare quotes around "pretty" in my prevoius comment).  I guess they fit a particular received notion of prettiness?  I almost never use them on piano, especially voiced as in my other comment.  I do occasionally like them on guitar where the voicing is usually much wider, like A-E-A-C♯-G♯.
Answer: In the OP's question and other comments three chords came up I11, ii9, and V9, each with either a major seventh or minor ninth.
It seems to me you need to put them in their diatonic context...

In I11 it isn't so much that the eleventh is dissonant but that it's non-tertian. Even if you don't play the third - so there is no actual minor ninth - the F sounds out of place. It's sort of like the third has been put in the wrong place, and that is what makes the sound jarring.
With ii9 and V9 the dissonant ninths form various dissonant intervals, but they are still tertian. Tertian in the sense that the eleventh is where tertian "stability" breaks down.
Also, the relative stability of tonic I versus more dynamic ii and V seems to matter regarding how much out of place the dissonances sound. The dissonances on ii and V add a little extra "push" when resolving to the next chords. They work with the harmonic dynamic. Whereas the eleventh on I works against the tertian aspect.

EDIT
Here is another attempt to combine chord function, scale degrees, and locating dissonant minor ninths in the various diatonic tertian stacks.

The minor ninths are highlighted red. Of those minor ninths at least one tone is either TI or FA. In the case of subdominants there are no minor ninths. In the dominants the TI involved in the minor ninth works with the dominant function of the chord. In the tonics the TI and FA work "contrary" to the tonic function.
Also put used hollow note heads for the stacked fifths above the roots (root, fifth, ninth, thirteenth) and solid note heads for the stacked fifths above the third (third, seventh, eleventh.) Of course if TI or FA in upper tones of either stack will result in tritones. The TI/FA tritone is associated with dominant function. It's interesting that the two stacks are "pure" - all perfect fifths - in the subdominant chords, contain function affirming tritones in the dominant chords, but function contradicting tritones in the tonic chords.
So one way to possibly make sense of the acceptability of the dissonances is to say the dissonant minor ninths or tritones that do occur in extended harmonies should not involve tonic function.

I don't necessarily find any of those ideas very convincing explanations. I'm just trying to make some sense of the original premise.
If you could somehow take the chords out of context and just play a tertian stack up to the eleventh...

...I have to honestly say I don't find it harshly dissonant. Sure, it's piquant, but it's kind of pretty too.
Sometimes in classical music a dominant seventh chord will be played over the tonic, either in a tonic pedal or as a type of suspension at a cadence. Those harmonies essential place a major seventh, major ninth, and perfect eleventh over the tonic like an incomplete I11. They are quite pretty, but strictly speaking those tones are NCTs which resolve not chord extensions.
To the extend that some extensions are considered unacceptable you could explain it as a contradiction of function between chord roots and the extensions.
Comment: There seems to be a contradiction here: at the outset you say the Imaj11 chord is "non-tertian", but then at the end, it's illustrated as a "tertian stack". Also, the post seems to imply that all 11th chords are non-tertian. Both points could use clarification.
Comment: @Aaron, "...I don't necessarily find any of those ideas very convincing explanations...." My personal sense is these chords all sound OK. To the extent someone else says major eleventh chords are a problem, this is how I would try to make sense of it.
Answer: They're not a semitone away, they're an octave and a bit !!
True, the note name sounds like it's close, but in reality, that's why it's called an 11th, or a 9th - it's just that the 11th or the 9th is over an octave from its named neighbour.
So, because there's no semitone or tone distancing the notes, there's no clash of pitches!
Sharpening or flattening the extension has little to do with the prospective clash (which isn't there anyway). Consider '7♯9' (Hendrix chord) which has an M3 in the basic triad, and ♯9 (sounding exactly like m3). Put next to each other, it sounds horrible. Separate them by an octave, it works!
Comment: I think you've missed the point of the question. By your logic, Maj11 chords would not be avoided in the way OP is referring to, but they are, because the dissonance of the 11 against the 3 is quite harsh.
Comment: As Aaron has stated, the point has been missed.  I should have mentioned I get totally the octave apart thing. But this doesn't explain why a major 11 is considered wrong. Since the 3rd and 11th are also over an octave apart
Answer: The convention is an aesthetic one, but there is an important technical difference between the two chords in question.
In a Maj11 chord, the 3 and 11 are are a minor ninth apart. For example, in a root position CMaj11 chord, C E G B D F, the E and F are a minor ninth apart.
In a Min9 chord, the 3 and 9 are a major seventh apart. For example, in a root position D-11 chord, D F A C E, the E and F (or, rather, the F and E) are a minor seventh apart.
In addition, the 11 in a Maj11 chord is dissonant not just against the 3, but also against the 1, 5, and 7. There are fewer dissonances in the Min9 chord. In that chord, the 9 is dissonant against the 1 and 3 only.
I will posit an answer, but again, since it's a fundamentally aesthetic question, this will be debatable: the problem is that the 11 (or the 4) has much stronger tendency to resolve to the 3 than the 9 does to either the 3 or 1. It's the sheer strength of that pull of the 11 that overwhelms the chord in a way the the 9 doesn't.
Comment: I think your first portion hits the nail on the head the way I've always conceptualized it: when this half step is voiced as a major seventh, it softens the dissonance. But the half step voiced as a minor second (or minor ninth), especially from the chordal third, is more problematic.
Comment: Maybe it is the tritone to the 7th that spells doom for the Maj11? I will try it as an add 11, see if that helps...

Extended chord semitone clashes


How to connect to local Mysql server from mobile using j2me

Question: I'm developing mobile application which will be able to download/upload mobile phone book contact from mysql database which is stored on my pc at localhost. I know to how to get contact numbers from/to the mobile phone & save them on the database, but I don't know how to locate to the local Mysql server (i.e http://localhost), I'm using wamp 2.0 for windows & MIDP 2.0 for mobile.Anyone please help me with the steps or procedure.
Thanking You,
Rittwick Banerjee
Answer: there is no such thing as mysql functions in j2me.
only a record store where you can put bytearrays which you can read in a loop not even with some key value scheme.
however you can do http connections so you could build your api that runs on a webserver.
i am really amazed that anybody is really still using j2me :D it is totally buggy, the latest developement kit was shit and didnt even run under 64 bit or linux.
and nowadays no device supports it anymore. only android and ios are relevant imo.
Comment: Then what technology on platform or whatever to use when you are planning to develop a software that will run on a wide range of mobile phones.
Answer: If your mysql database is published on localhost only then there is no way your mobile app will be able to connect to it.
My suggestion, you need a ISP that supports mysql and publish your database first, as a start.


Doubt regarding sum of a subring and an ideal need not be subring.

Question: We know that sum of two subrings need not be a subring, but then why is the following so:

Let $A$ be a subring of a ring $R$ and $I$ an ideal of $R$ . Then  $A+I=\{a+i\mid a\in A,i\in I\}$ is a subring of $R$.

This was written in statement for second homomorphism theorem, but I can't understand why is $A+I$ a subring.
Answer: Let $R$ denote a not-necessarily commutative ring. Assume that $A \subseteq R$ is a subring and that $I \subseteq R$ is a two-sided ideal.
Let us show that $A+I$ is closed under products, since closure under addition is trivial, and so too is closure under unary negation (by which I mean the function $x \in R \mapsto -x \in R$). So suppose $x,y \in A+I$. Then $x=a+i$ and $y=a'+i'$ for appropriate choices of $a,a' \in A$ and $i,i' \in I$. So
$$xy = (a+i)(a'+i') = \underbrace{aa'}_{\in A}+\underbrace{ia'+ai'+ii'}_{\in I} \in A+I$$
So $A+I$ is closed under products.
We can write the above argument in more compact notation as follows:
$$(A+I)(A+I) = \underbrace{AA}_{\subseteq A}+\underbrace{IA+AI+II}_{\subseteq I} \subseteq A+I$$
Remark. If $R$ has a unity element $1,$ and if $1 \in A,$ then since $1+0 \in A+I$, hence $1 \in A+I$.
Comment: @coool, try to work it out yourself. Its really not that hard. Just make a note of the fact that, in ring theory, $x-y$ can be treated as shorthand for $x+-y$. In fact this works in any Abelian group. If its still not making sense after a good 20-30 mins of pondering and scrawling, consider asking another question.
Comment: I can't deduce how to prove $ab^{-1}\in A+I$ for $a,b\in A+I$ to prove it is a subring..can you please help me out....
Comment: @coool, look at the definition of "ring" and "subring" again. There is no mention of $b^{-1}$, in fact reciprocals are not required to exist.
Comment: I meant $a-b\in A+I$
Comment: @coool, I prefer to just show $\dfrac{x,y \in A+I}{x+y \in A+I}$ and $\dfrac{x \in A+I}{-x \in A+I}$. These are both straightforward.
Comment: I can't get why did you replace the condition $a-b\in A+I$ by $x,y \in A+I \rightarrow x+y \in A+I$ and $x \in A+I \rightarrow -x \in A+I$
Answer: The usual method should work: just show closure under $0,1,+,-,\cdot$. It's hard to give any more advice than that without you showing why you're having problems: maybe you're forgetting the (usual) defining property of ideals?
For variety, another approach is to use the fact that if $f : R \to S$ is a ring homomorphism and $T \subseteq S$ is a subring, then $f^{-1}(T)$ is a subring of $R$.
Comment: I don't know How to prove $A+I$ closed under multiplication...to show it is subring..


Change child element background CSS

Question: I am a novice at CSS, here's HTML structure:

    <button class="navbar-toggler collapsed border-0" id="navbar-toggler" type="button">

    </button>

What I need to do is if I add a class "black" to navbar I need the css background color on navbar-toggler to turn white. How do I do that with CSS?
I thought it should be like:
. navbar .black .navbar-toggler span{
    background: #000 !important;
}

but it's not working
Comment: Maybe `.black > .navbar-toggler{background-color: white;}`
Answer: You were very close.
By going .navbar .black, you are targeting .black that is inside .navbar. But by doing .navbar.black you are targeting the element that has both .navbar and .black.
.navbar.black .navbar-toggler span{
    background: #FFF!important;
}

Answer: you can use javascript addEventListener

const nav = document.querySeletor('#navbar)
('#navbar_toggler').addEventListener('toggle',function(){
    nav.classList.toggle('bg')

})
.bg{
background-color:black;
}
Comment: No need for JS, I want to use CSS
Comment: if you only want to turn text color white only once, then use class text-light

Change child element background CSS


Login error: call to undefined function entity_load in User module

Question: I'm new to Drupal and I have a problem where no users can login (HTTP 500 and WSOD on POST of valid credentials, Drupal 7). The error message is:
"E_ERROR Error in file »user.module« at line 291: Call to undefined function entity_load()"
Any ideas on how to approach troubleshooting this?
Answer: Your error's stating that it can't find a function that should be in drupal core. Check you includes folder. There should be a file in there called common.inc, make sure the function entity_load is defined in there.
Comment: Thanks Jance, includes/common.inc exists and contains entity_load(). Disabling the Devel module solved the issue. To the moderators: I want to publish the solution that helped me solve this problem for others who might encounter the same issue.


Where I can host my proprietary Maven artifacts?

Question: What are my options to host proprietary (non open-source) Maven artifacts online?
Answer: I like Nexus.  sonatype.org or sonatype.com depending on whether you want the open source repository or commercial.


Aptana will not install on Windows 7 Professional

Question: When I try to install Aptana Studio, I get an error message
Failed to correctly acquire installer_nodejs_windows.msi file: CRC error.
I am then told that Aptana Studio setup ended prematurely bacause of an error. The installer then shuts down without installing the application.
I have installed nodejs, but still get this error.
Doug
Answer: I had the same problem, just go to https://nodejs.org/en/ , download and install node.js. Afterwards the installation of Aptana should work.
Comment: Hi, Thanks for responding. I tried that. I tried both the node-v4.2 and the node-v5.3 versions and neither made it where aptana studio 3 would install. It does not appear to look to see if I already have the software but rather it goes to download it. I think the installer setup is going to the wrong url to download the software (maybe).


Core Image slow rendering

Question: I created test application with ViewController, GLKView and UISlider.
Slider change value in selected filter. Rendering image very slow.
What's wrong with my code?
Test class of GLKview:
import UIKit
import CoreImage
import GLKit

class CustomGLView: GLKView {
    //test filters
    let clampFilter = CIFilter(name: "CIAffineClamp")!
    let blurFilter = CIFilter(name: "CIGaussianBlur")!
    let ciContext:CIContext

    override init(frame: CGRect) {
        let glContext = EAGLContext(api: .openGLES2)
        ciContext = CIContext(
            eaglContext: glContext!,
            options: [
                kCIContextWorkingColorSpace: NSNull()
            ]
        )
        super.init(frame: frame, context: glContext!)
        enableSetNeedsDisplay = true
    }

    required init(coder aDecoder: NSCoder) {
        let glContext = EAGLContext(api: .openGLES2)
        ciContext = CIContext(
            eaglContext: glContext!,
            options: [
                kCIContextWorkingColorSpace: NSNull()
            ]
        )
        super.init(coder: aDecoder)!
        context = glContext!
        enableSetNeedsDisplay = true
    }

      var inputImage: UIImage? {
        didSet {
            inputCIImage = inputImage.map { CIImage(image: $0)! }
        }
    }

     var blurRadius: Float = 0 {
        didSet {
            blurFilter.setValue(blurRadius, forKey: "inputRadius")
            setNeedsDisplay()
        }
    }

    var inputCIImage: CIImage? {
        didSet { setNeedsDisplay() }
    }

    override func draw(_ rect: CGRect) {
        if let inputCIImage = inputCIImage {
            clampFilter.setValue(inputCIImage, forKey: kCIInputImageKey)
            blurFilter.setValue(clampFilter.outputImage!, forKey: kCIInputImageKey)
            let rect = CGRect(x: 0, y: 0, width: drawableWidth, height: drawableHeight)
            ciContext.draw(blurFilter.outputImage!, in: rect, from: inputCIImage.extent)
        }
    }
}

How I change value in CIFilter:
import UIKit
import GLKit
import CoreImage

    class ViewController: UIViewController {
        //image
         let imageOriginal = UIImage(named: "pic_2")
         //my GLKView
        @IBOutlet weak var glView: CustomGLView!

        override func viewDidLoad() {
                super.viewDidLoad()
                //test image
                self.glView.inputImage = self.imageOriginal

            }

        @IBAction func mySlider(_ sender: UISlider) {

                self.glView.blurRadius = sender.value
            }
    }

Comment: Are you testing on device or simulator?
Comment: Device. In simulator always slow.
Comment: yes because device is hardware accelerated, sim no
Comment: Hello @Metman , i have found same issue while using CIFilter , have you solved above issue and how ?
Comment: Hello @GOPAL VASANI. Just resize image for rendering. When rendering will done, apply changes to original image. I used one CIContext for all.
Comment: Hey @Metman even i used only one  CIContext For all Filters , but still it takes time , i want to show you my code , where i can contact you . ?
Comment: I have the same question. The Accelerate framework and vImage is much faster, so I might just rewrite all my apps using vImage. But it doesn't really explain why CoreImage is so slow on M1.
Answer: Creating a CIImage from UIImage may require extra time to copy the image data from memory to GPU memory. Try loading your image into a GPU texture and then creating a CIImage backed by this texture using CIImage(texture:size:flipped:colorSpace:)
Make sure you're only creating the texture once, not at the start of every draw(_:).
You could also try:

Making sure the blur radius isn't too large. A gaussian blur is an expensive operation and it will take longer the greater the blur radius.
Using a smaller image. If you need larger images, you may want to scale the image down first, apply the blur, and then scale back up (see here for an explanation). Halving the width and height will reduce the number of pixels by a factor of 4.
UISlider will change at a rate of 60 per second. Reducing the frame rate to 30 fps will give you double the time to render each image.

Core Image slow rendering


nodegit reset/revert single file

Question: I'm trying to reproduce the checkout file operation using nodegit for reverting current changes of a file.
git checkout -- filename.ext

My first attempt was to use checkoutRef function from Repository object, like this:
nodegit.Repository.open(gitRepo)
  .then(function (repo) {
    repo.checkoutRef('filename.ext',{
      checkoutStrategy: nodegit.Checkout.STRATEGY.FORCE
    }).then(function (data) {
      console.log(data);
    });
});

Answer: Try the following code: ;-)
try {
    const commit = await repository.getBranchCommit("origin/master");
    const tree = await commit.getTree();
    const resCheckout = await Checkout.tree(repository, tree, { checkoutStrategy: Checkout.STRATEGY.FORCE, paths: ["YOUR_FILE_PATH"] });
} catch (err) {
    console.log(err)
}

Answer: I think Reset.default is what you want.

nodegit reset/revert single file