outputting a string to terminal and otherwise in a correct format

Question: I have a string which I would like to output to the terminal and subsequently write to a file. I have managed to do this in my code but I wish to change the format of it.
Normally this is what should happen with any print statement:
 x = scatter
 print (x)

and to the terminal screen it outputs
 scatter

where as my string is of the following format
n = 1
x = 'scatter -n', n

printing this statement to terminal gives....
('scatter -n', 1)

What I would like to do is be able to print a string where it has multiple elements of a string of text, followed by a variable declared earlier in the program like above. I am not sure on how to set the syntax such that the string will appear as follows when I print to terminal:
scatter -n 1

The text provided here is a smaller example of the full string I need to print. In it I have a large number of variables which are defined in my program but for here I will leave them out on this post as it's mainly a syntax issue that I am stuck on. The full string I need to write is as follows:
test = '"scatter -n',n,'-A ',A,' -g ',g,' -t ',stime,' -i "-M',Mbu,' -rm ',rm,' -R ',R,' -v ',vrel,' -t -q',qout,' -a ',aoutu,' -e ',eout,' -r1 ',r1,' -t1 -q ',qin,' -a ',ainu,' -e ',ein,' -r1 ',r1,' -r2 ',r2,'"'

How I have formatted the string here is the only way I managed to get it to work properly in the program in it's current iteration.
Any input will be greatly appreciated.
Comment: Do you search a simple: `' '.join(['a', 'b', 'c'])` ? Or, with your example `' '.join(x)`
Answer: Any reason why you define the sequence as an implicit tuple?
If you want to keep it as a list/tuple/whatever collection, consider this:
' '.join([str(i) for i in test])

Hint: I used str() to account for all non-string values that eventually occur in your list of variables.
Otherwise, you could just use regular string formatting '%s, ...' % (val, ...), if the number of variables is fixed.
Answer: Hi do you mean like this?
test= test.replace(",", " ")

Answer: print(x)
('scatter -n', 1)

So that's expected behavior since it declared as tuple of elements in variable x.
And python prints it as is.
print(', '.join(str(i) for i in x))
scatter -n, 1

You are actually looking for join() method.
Answer: x = 'scatter -n', n

This line in your code is not concatenating, it's packing a tuple. That's why the parentheses are showing up in the output. Besides, you can't concatenate an int type onto a string without casting it first, anyway.
Instead, you can use this format to string cast & concatenate:
x = "scatter"
y = "-n"
z = 1
cmd = "{} {} {}".format(x, y, z)
print cmd

to print
scatter -n 1

Comment: This is the solution that I found worked best for what I needed thank you.


What technical spec should I look for in noise isolating headphones?

Question: I am looking to buy some noise isolating (not noise cancelling) headphones, but I am very confused right now. Initially I thought that impedance was a good measure of the capacity for a pair of headphones to block outside noise, but after reading a review on Amazon to this product I am not convinced because in the description for these headphones an impedance rating of 50 ohms is given and a reviewer has made the following statement:
These headphones are not at all designed to be sound isolating. They are completely open - any other sound in your listening environment will come in, and anyone else around you will be able to hear what you're listening to.
So I ask the following:

What is a good technical spec to judge the ability of a pair of headphones to block outside noise?
What is a good pair of noise isolating over ear headphones?
Comment: Do you need them for something music related? If not, this question may be off topic. Noise isolating headphones are most often used with loud tools like lawn mowers.
Comment: @AudriusMeškauskas They are indeed music related. I have just found a forum relating to the answer I am looking for here: http://www.drummerworld.com/forums/archive/index.php/t-36091.html. Many drummers use noise isolating headphones so they can block out the loud drums and better hear the melody they are playing to.
Answer: This is what the impedance spec refers to:
http://en.wikipedia.org/wiki/Electrical_impedance
It's nothing to do with sound isolation.
I doubt there is any spec that can accurately represent the level of sound isolation.
This is because the level of isolation is almost entirely dependent on the fit; How well they fit to your particular head shape and the pressure applied.
The headphones you link are open backed so will have very little isolation.
http://en.wikipedia.org/wiki/Headphones#Open_or_closed_back
In-ear headphones can achieve reasonable sound isolation as they can form an air tight fit in the ear canal. Over ear (closed back) head phones can't form an air tight fit so can't achieve any where near the level of isolation as in ears. If over ears applied enough pressure to become air tight they'd be so tight it'd be unbearable.
Your need to try on a few different over ears to see which achieve a good fit on your particular head. Be aware that those that provide the best isolation may be tight enough to give you a headache after an hour or two.
Comment: There is a spec for isolation called the NRR or Noise Reduction Rating, but I'm not aware of that being measured or reported for close-backed headphones intended for music listening. It is used often for earplugs and other noise *safety* equipment, including equipment that also functions as headphones designed for voice communications (e.g., for constuction work), as opposed to music listening. As to how accurate NRR specs are, well that's another question. They are kind of like A-weighted SPLs in that they try to deal with safety, primarily.
Answer: ATTENUATION.
This is the technical term for a reduction in signal strength (i.e. a reduction in the volume).
Isolation or cancellation? The other responders seem to miss that many solutions for noise reduction are using active inverse wave cancellation rather than passive isolation--which is what I recommend for maximum hearing protection and listening enjoyment.
Look into Etymotic research headphones, I am a drummer and big fan of their products--even their $60 product is mind-blowingly better than most alternatives and is still compatible with high end custom fit ear protection.
Admittedly these are insert earphones rather than closed-back, over-the-ear headphones, but the attenuation is impressive 35-45 db and relatively flat so things sound better than wearing foam ear plugs with even higher sound attenuation.
EDIT: adding link to head-fi thread:
http://www.head-fi.org/t/658792/headphones-with-best-ambient-noise-attenuation
Comment: Good catch. I didn't notice before but manufacturers of headphones for recording do often list attenuation in dB. Here's an example: http://en-us.sennheiser.com/hd-280-pro
Answer: An effective way to have noise-isolating headphones is to use earphones under industrial muffs. You don't specify whether they are to stop others hearing what you're listening to, or to stop extraneous noise getting to your ears, but this will work either way.Obviously, full size headphones won't do it, but smaller, good quality in-ear phones will. The impedence values will not affect the situation.


Ansible delete stack with termination protection

Question: I am able to create a cloudformation stack with termination protection in ansible by adding termination_protection: yes to the creation part, but when it comes time to delete the task, I am having some trouble.
I've tried two approaches:
- name: "Disable termination protection and delete stack"
  cloudformation:
    stack_name: [STACK NAME]
    termination_protection: no
    state: absent

This tells me that I need to disable termination protection before deleting the stack, which makes sense, however, when I try to do this:
- name: "Disable termination protection"
  cloudformation:
    stack_name: [STACK NAME]
    termination_protection: no
- name: "Delete stack"
  cloudformation:
    stack_name: [STACK NAME]
    state: absent

I am told that I need to pass the parameters to the cloudformation stack.  However, these parameters are defined upon stack creation, and I really shouldn't need to do this to disable termination protection.  Is this a bug in ansible or am I missing something?
Comment: I don't disagree with you.  This is likely a limitation in the Ansible module as it is written currently.  I haven't looked through the code for the module, so I was curious if it was easy enough to work around for the time being.
Comment: Have you tried to pass at least the template when you are trying to turn off `termination_protection`?
Comment: I shouldn't need to pass anything, I am able to use the CLI to turn off termination protection using only the stack name.
Comment: Yes, for now I am just using the shell command to run AWS CLI commands.
Answer: From what I read in the repository, in order to have the termination_protection updated, you need to have the state: present in the task.
See the call to the function update_termination_protection being enclosed in the condition if state == 'present'
So this should be your fix:
- name: "Disable termination protection"
  cloudformation:
    stack_name: [STACK NAME]
    state: present
    termination_protection: no
- name: "Delete stack"
  cloudformation:
    stack_name: [STACK NAME]
    state: absent

Which, in the end, makes sense, since you would not be able to update anything on an absent stack.
Comment: This doesn't work, state has a default value of present.


Calcular o total de pedidos e o total de pedidos do mês atual com MySQL

Question: Tenho essa tabela de pedidos, preciso contar o total de pedidos de cada usuário e o total de pedidos de cada usuário no mês vigente
| id | id_user | name | data_criacao |
| 1  | 10      |Pedro | 2018-05-01   |
| 2  | 10      |Pedro | 2018-05-03   |
| 3  | 15      |Joao  | 2018-05-04   |
| 4  | 10      |Pedro | 2018-05-10   |
| 5  | 18      |Maria | 2018-05-07   |

Fiz esse select que traz o nome e o total de pedidos de cada usuário, porém preciso trazer o total de pedidos de cada usuário no mês vigente, mas não estou conseguindo.
select name, count(*) as total from pedidos  group by id_user;
Answer: Oi @Daywison Ferreira Leal,
vc precisa fazer um BETWEEN no mês atual.
seria algo assim:
$mes_atual = date('m');

select name, count(*) as total from pedidos WHERE mes_vigente BETWEEN $mes_atual AND $mes_atual group by id_user;

Nesse exemplo, falo sobre a possibilidade de vc ter uma coluna chamada mes_vigente. Vc pode utilizar a sua coluna data_criacao e fazer um explode no mes.
Comment: | name | total no mes | total geral |
| Pedro|       2             |    22          |
| Maria |       3             |    10         |

Eu precisava retornar um resultado assim.
Answer: Para trazer o total de pedidos de cada usuário no mês vigente, tente assim:
select name
      ,count(*) as total
  from pedidos
 where Month(data_criacao) = Month(CURRENT_DATE())
   and Year(data_criacao)  = Year(CURRENT_DATE())
 group by id_user;

Adicionei o filtro por ano também, para não aparecer registros de algum outro ano feito no mesmo mês, mas se desejar é só remover.
Editado
Já que quer mais informações tente assim:
select name
      ,count(*) as total_geral
      ,count(CASE WHEN Month(data_criacao) = Month(CURRENT_DATE()) and Year(data_criacao) = Year(CURRENT_DATE()) THEN 1 END) as total_usuario
  from pedidos
 group by id_user;

Obs.: Não esqueça de informar na pergunta quais dados você quer como resultado
Comment: Esse select está parcialmente correto, mas além de trazer o nome, e o total do mês quero trazer o total geral de pedidos desses usuários, como fazer isso ?
Comment: Verifique a edição da minha resposta


mark single form field as cause of error on form validation

Question: I've a custom field, and I'm trying to write the validation for the field values. however when a particular field causes the failure, the whole fielset is marked in red. I only want the specific field element to be highlighted, and in the case of Unlimited I only want the specific entry highlighted.
here is the code I have so far. but the whole fieldset is marked in red when ever a validation fails.
<code>   function prodlist_field_widget_form(&$form, &$form_state, $field, $instance, $langtype, $items, $delta, $element) {
      $base = $element;

      if ($instance['widget']['type'] == 'prodlist_text') {
        $element['#element_validate'] = array('_prodlist_text_validate');

        $element['prod_type'] = array(
          '#type' => 'select',
          '#title' => t('Product Type'),
          '#default_value' => isset($items[$delta]['prod_type']) ? $items[$delta]['prod_type'] : NULL,
          '#options' => type_options(),
          ) + $base;

        $element['prod_description'] = array(
          '#type' => 'select',
          '#title' => t('Description'),
          '#default_value' => isset($items[$delta]['prod_description']) ? $items[$delta]['prod_description'] : NULL,
          '#options' => description_options(),
          ) + $base;

        $element['order_amount'] = array(
          '#type' => 'textfield',
          '#title' => t('Amount'),
          '#default_value' => isset($items[$delta]['order_amount']) ? $items[$delta]['order_amount'] : NULL) + $base;
      }
      return $element;

    }

function _prodlist_text_validate($element, &$form_state) {

  if ($form_state['complete form']['#form_id'] == 'field_ui_field_edit_form') {
    return ;
  }

  $values = $form_state['values'];
  $language = $values['language'];
  $field_name = $element['#field_name'];
  $field_name_error_box = $field_name;

  foreach ($values[$field_name][$language] as $delta => $item) {

    if (isset($item['order_amount'])) {

      if (is_numeric($item['order_amount'])) {
        if($item['prod_description'] != 'no order' && $item['order_amount'] <= 0 ){
          form_set_error($field_name_error_box, t('Order amount has to be more then 0'));
        } else if ($item['prod_description'] == 'no order' && $item['order_amount'] > 0) {
          form_set_error($field_name_error_box, t('You have created an order amount without selecting a product.'));
        }

      } else {
        form_set_error($field_name_error_box, t('Order amount has to be numeric'));
      }
   }

  }

}
</code>
I'm trying to set the variable <code>$field_name_error_box = $field_name;</code> to the correct value but it either lights up the whole form section or nothing at all.
I've tried the following, and lots of other variants without luck.
<code>$field_name_error_box = $field_name . 'order_amount';
</code>
Answer: You must use a field name like this:  'parent][element'
In your case,
<code>$field_name_error_box = $field_name . '][order_amount';
</code>
should work.


What does "I Solisti Veneti" mean?

Question:
What does Vivaldi mean by "I Solisti Veneti"?
What does the title mean?

There doesn't seem to be a translation I could find of.
Comment: A quick search in the Wiktionary seems to indicate it simply means "The Soloists from [Veneto][https://en.wikipedia.org/wiki/Veneto]".
Comment: While this is a well-known ensemble busily playing and recording Vivaldi, I'm not aware of Vivaldi himself using that term - do you have a source?
Comment: Not really certain this is on topic here...
Comment: @guidot there's a contemporary musical ensamble called "[I Solisti Veneti](https://en.wikipedia.org/wiki/I_Solisti_Veneti)", and they play period music. I suppose the score, the youtube video title or whatever the source of this sentence is referencing to the arrangement of this piece used by them, rather than something Vivaldi himself put in writing.
Comment: No, sorry @guidot.
Answer: According to my Italian colleague it means (as Édouard commented):

The (=I) soloists (=solisti, regular  [but somewhat unexpected, since one has to know, that the gender of the word is male] plural from solista) from
  Veneto (i. e. the region, from which Venice is the capital).
Comment: good translation - I'll get rid of my attempt, which I guess was close but no cigar.
Comment: Why "irregular plural"? All derived substantives in -ista (which works for both males and females) naturally go -isti (or -iste when feminine), e.g. il/la violinista - i violinisti / le violiniste, l'apprendista - gli apprendisti / le apprendiste...
Comment: @giobrach: Your examples as well as the sparse profile data let me assume, that Italian is you mother tongue.  Is my edit more correct?
Comment: Yes, that's better!

What does "I Solisti Veneti" mean?


Comparing $f(x)$ and the $f\_approx(x)$ in Matlab, Octave or Mathematica/Wolfram

Question: I have a function $f(x)$ and I wrote the approximation for $f(x)$ as $f\_approx(x)$ which is a simple algebraic formula with sums and products .
I now want to study the 2 functions side by side and see :

how much they differ on average on a given range
if there is a coefficient that multiplied by $f\_approx(x)$ can improve the accuracy of $f\_approx(x)$ itself
if there is a constant difference so I can just add back the gap to $f\_approx(x)$

The main problem is that I haven't really found much in Matlab, Octave and Mathematica that really tackles my problem as I wish this softwares could do and plotting doesn't help much because the current versions of the functions only diverge for some zero-point-zero-something and it's a difference that I can't really appreciate graphically when my Domain is spanning over a couple of integers .
Thanks for your help.
As an example :
$f(x) = sin(x)$
$f\_approx(x) = x-(x^3/3!)$
Answer: Suppose that the function is $f(x)$ and its approximation is $g(x)$ and suppose that you are concerned by a given range $a\leq x \leq b$.
You can define two error functions, for example $$r_1(x)=f(x)-g(x)$$ $$r_2(x)=\frac {f(x)-g(x)}{f(x)}$$ Plotting these functions over the given range would immediately show you the kind of errors (absolute and relative) related to the approximation.
If you want to improve the approximation multiplying $g(x)$ by a constant $A$, you can define $$I=\int_a^b \left(f(x)-Ag(x)\right)^2\,dx$$ and now, compute $\frac{dI}{dA}$ and ask for the solution of $$\frac{dI}{dA}=0$$
If you want to improve the approximation shifting $g(x)$ by a constant $A$, you can define $$I=\int_a^b \left(f(x)-g(x)+A\right)^2\,dx$$ and now, compute $\frac{dI}{dA}$ and ask for the solution of $$\frac{dI}{dA}=0$$ All of this work is doable formally using a CAS.
Let me try with your example using $(a=0,b=1)$. What I should write (hoping thet I properly remember Mathematica syntax) is

f[x_]:=Sin[x]
g[x_]:=x-x^3/6
Int=Integrate[(f[x]-A g[x])^2,{x,0,1}]
Der=D[Int,A]
Solve[Der==0,A]

This should give you $$\text{Int}=\frac{341 A^2}{1260}-3 A \sin (1)+\frac{11}{3} A \cos (1)+\frac{1}{2}-\frac{\sin
   (2)}{4}$$ $$\text{Der}=\frac{341 A}{630}-3 \sin (1)+\frac{11 \cos (1)}{3}$$ $$A=-\frac{210}{341} (11 \cos (1)-9 \sin (1))$$
Comment: thanks for the complete exposition


Vetor gradiente para uso na função optim

Question: Já procurei muito, em diversos fóruns e em muitas páginas sobre estimação de parâmetros via função optim do R e não encontrei nada sobre como acrescentar a função gradiente em um script, de tal forma que as derivadas sejam calculadas via alguma função do R seja, _deriv()_ ou _deriv3()_ ou via pacote _NumDeriv_ ou pacote _Deriv_. Preciso calcular o gradiente com o intuito de tentar melhorar meu processo de estimação e é impossível fazer as derivadas na mão pois minha função log de verossimilhança é muito extensa.
Consigo fazer as derivadas no _Maple 16_, mas gostaria de saber obter o gradiente no _R_ de forma mais automatizada. O código abaixo é um script para estimação de parâmetros da Birnbaum-Saunders univariada com dois parâmetros, caso consiga implementar o gradiente neste script eu conseguiria implementar no meu código mais complicado!
Ao compilar o código abaixo tenho obtido as vezes parâmetros negativos, o que é um absurdo, pois _alpha_, _beta_ e _t_ são positivos. Imagino que com o gradiente isso possa deixar de ocorrer.
library(VGAM)
alpha<-2
beta <-1
truevalue <- c(alpha,beta)
n=1000
N=300
m=matrix(ncol=2,nrow=N)

for (i in 1:N){
x <- rnorm(n,mean = 0,sd=sqrt((alpha^2)/4))
t <- beta*(1+2*x^2+2*x*sqrt(1+x^2)) #t possui distribuição birnbaum-Saunders com parâmetros alpha e beta
#t <- rbisa(n, alpha, beta)
#sum(1*(t<0))

#Função Densidade da distribuição birnbaum-saunders

f <-function(theta){
  alpha <- abs(theta[1])
  beta  <- abs(theta[2])
  d <- (1/(2*alpha*beta*sqrt(2*pi)))*(sqrt(beta/t)+(beta/t)^(3/2))*exp(-    (1/(2*alpha^2))*((t/beta)+(beta/t)-2))
  return(d)
}

#Forma 1 da log verossimilhança

# log.ver <- function(theta){
#   alpha <- abs(theta[1])
#   beta  <- abs(theta[2])
#   l <- sum(log(f(theta)))
#   return(l)
# }

#Forma 2 da log verossimilhança

log.ver <- function(theta){
  alpha <- abs(theta[1])
  beta  <- abs(theta[2])
  l <- sum(log((1/(2*alpha*beta*sqrt(2*pi)))*(sqrt(beta/t)+    (beta/t)^(3/2))*exp(-(1/(2*alpha^2))*((t/beta)+(beta/t)-2))))
  return(l)
}

alpha_0 <- 3
beta_0 <- 4
start <- c(alpha_0,beta_0)
opt <- optim(start,log.ver,method="BFGS",hessian = F,control=list(fnscale=-1))
m[i,]=opt$par
}

#Calculating the average of each column of the array of parameters m
mest=colMeans(m)

#calculating the standard deviation of each column of the array of     parameters m
dest=apply(m,2,sd)

#root mean square error in the calculation of each column of the array of     parameters m in relation to the true value of the parameter
eqm=function(x,opt){
  N=length(x)
  sqrt(sum(((x-opt)^2))/N)}

#Estimated mean squared error of each parameter
eqmest=c(eqm(x=m[,1],opt=alpha),
         eqm(x=m[,2],opt=beta))

# Table with the true values of the parameters and the average
# Standard deviation and mean square error of the estimated parameters
tab=data.frame(truevalue,mean=mest,sd=dest,eqm=eqmest)
tab

Agradeço muito a ajuda!
Answer: Trabalhei sobre o código original da sua resposta e identifiquei dois problemas:

Por padrão, a função optim realiza minimizações, que podem ser convertido em um problema de maximização se você trocar o sinal da função objetivo. Por isso, o ponto que a sua otimização está retornando é um ponto de mínimo. De todo jeito, já vi que você resolveu isso na segunda resposta.
Se o seu estimador de máxima verossimilhança precisar satisfazer condições, você vai ter que usar um algoritmo que faça a otimização levando em conta essas restrições. Fornecer um gradiente não resolverá esse problema diretamente, apenas deixará sua otimização mais rápida e mais precisa. Isso eventualmente pode fazer com que você encontre pontos de ótimo apenas na região que te interessa, mas existem problemas em que a otimização irrestrita mesmo com o gradiente vai te levar a resultados absurdos. Na verdade, eu acho que é uma boa estratégia não implementar gradientes até que se experiencie problemas de convergência ou ineficiência no código. No seu caso, acho que isso ainda não ocorre.

Dito isso, minha solução para o seu problema usa a função constrOptim do pacote stats, que resolve problemas de minimização usando os mesmos algoritmos do optim, mas garante que a otimização será feita com restrições.
O código abaixo ilustra a utilização da função constrOptim no seu problema, onde faço com que alfa e beta sejam positivos através dos parâmetros ui e ci.
library(VGAM)
alpha<-2
beta <-1
truevalue <- c(alpha,beta)
n=1000
N=300
m=matrix(ncol=2,nrow=N)

for (i in 1:N){
  x <- rnorm(n,mean = 0,sd=sqrt((alpha^2)/4))
  t <- beta*(1+2*x^2+2*x*sqrt(1+x^2)) #t possui distribuição birnbaum-Saunders com parâmetros alpha e beta
  #t <- rbisa(n, alpha, beta)
  #sum(1*(t<0))

  #Função Densidade da distribuição birnbaum-saunders

  f <-function(theta){
    alpha <- abs(theta[1])
    beta  <- abs(theta[2])
    d <- (1/(2*alpha*beta*sqrt(2*pi)))*(sqrt(beta/t)+(beta/t)^(3/2))*exp(-    (1/(2*alpha^2))*((t/beta)+(beta/t)-2))
    return(d)
  }

  #Forma 1 da log verossimilhança

  # log.ver <- function(theta){
  #   alpha <- abs(theta[1])
  #   beta  <- abs(theta[2])
  #   l <- sum(log(f(theta)))
  #   return(l)
  # }

  #Forma 2 da log verossimilhança

  log.ver <- function(theta){
    alpha <- abs(theta[1])
    beta  <- abs(theta[2])
    l <- -sum(log((1/(2*alpha*beta*sqrt(2*pi)))*(sqrt(beta/t)+(beta/t)^(3/2))*exp(-(1/(2*alpha^2))*((t/beta)+(beta/t)-2))))
    return(l)
  }

  alpha_0 <- 2
  beta_0 <- 3
  start <- c(alpha_0,beta_0)
  opt <- constrOptim(start, log.ver, grad = NULL, ui = diag(2), ci = rep(0,2), method = 'Nelder-Mead')

  m[i,]=opt$par
}

#Calculating the average of each column of the array of parameters m
mest=colMeans(m)

#calculating the standard deviation of each column of the array of     parameters m
dest=apply(m,2,sd)

#root mean square error in the calculation of each column of the array of     parameters m in relation to the true value of the parameter
eqm=function(x,opt){
  N=length(x)
  sqrt(sum(((x-opt)^2))/N)}

#Estimated mean squared error of each parameter
eqmest=c(eqm(x=m[,1],opt=alpha),
         eqm(x=m[,2],opt=beta))

# Table with the true values of the parameters and the average
# Standard deviation and mean square error of the estimated parameters
tab=data.frame(truevalue,mean=mest,sd=dest,eqm=eqmest)
tab

Comment: Obrigado @FernandoCorrêa, em relação a sua resposta 1, note que em meu código acrescento na função _optim_ o termo _control=list(fnscale=-1)_, isso significa que estou fazendo uma maximização. Em relação a sua resposta 2, concordo plenamente, porém, como pode perceber, após algumas correções que postei em minha resposta o processo de estimação mesmo sem o gradiente não está ruim. Isso não é meu problema, pois esse código é um teste, eu realmente necessito de ajustar o gradiente conforme expliquei na minha pergunta para resolver a estimação em outros modelos. Mais agradeço sua ajuda!
Answer: Consegui uma solução para o gradiente e ainda acrescentei a Hessiana, com as três linhas de código que estão comentadas no meio do script é possível verificar a coerência do código!
    rm(list=ls())
cat("\014")
library(VGAM)
library(Deriv)
n=100
N=300
m=matrix(ncol=2,nrow=N)
f <- quote((log((1/(2*alpha*beta*sqrt(2*pi)))*(sqrt(beta/t)+(beta/t)^(3/2))*exp(-(1/(2*alpha^2))*((t/beta)+(beta/t)-2)))))
fd1 <- Deriv(f,"alpha")
fd2 <- Deriv(f,"beta")

hd11 <- Deriv(fd1,"alpha")
hd12 <- Deriv(fd1,"beta")
hd21 <- Deriv(fd2,"alpha")
hd22 <- Deriv(fd2,"beta")

for (i in 1:N){
  alpha<-2
  beta <-1
x <- rnorm(n,mean = 0,sd=sqrt((alpha^2)/4))
t <- beta*(1+2*x^2+2*x*sqrt(1+x^2)) #t possui distribuição birnbaum-Saunders com parâmetros alpha e beta

rm(alpha,beta)
log.ver <- function(theta){
  alpha <- theta[1]
  beta  <- theta[2]
  l <- sum(log((1/(2*alpha*beta*sqrt(2*pi)))*(sqrt(beta/t)+(beta/t)^(3/2))*exp(-(1/(2*alpha^2))*((t/beta)+(beta/t)-2))))
  return(-l)
}

grad<-function(theta){
  alpha <- theta[1]
  beta  <- theta[2]
  gd <- cbind(eval(fd1),eval(fd2))
  return(-colSums(gd, na.rm = FALSE))
}

Hess<-function(theta){
  alpha <- theta[1]
  beta  <- theta[2]
  matrix(c(-sum(eval(hd11)),-sum(eval(hd12)),
         -sum(eval(hd21)),-sum(eval(hd22))),nrow = 2,ncol = 2)
}

# theta <- c(opt$par[1],opt$par[2])
# Hess(theta)
# opt$hessian

alpha_0 <- 10
beta_0 <- 10
start <- c(alpha_0,beta_0)
opt <- optim(start,log.ver,method="BFGS",gr=grad,hessian = T)
#opt <- optim(start,log.ver,method="BFGS",hessian = F)

m[i,]=opt$par
}
alpha<-2
beta <-1
#Calculating the average of each column of the array of parameters m
mest=colMeans(m)

#calculating the standard deviation of each column of the array of parameters m
dest=apply(m,2,sd)

#root mean square error in the calculation of each column of the array of parameters m in relation to the true value of the parameter
eqm=function(x,opt){
  N=length(x)
  sqrt(sum(((x-opt)^2))/N)}

#Estimated mean squared error of each parameter
eqmest=c(eqm(x=m[,1],opt=alpha),
         eqm(x=m[,2],opt=beta))

# Table with the true values of the parameters and the average
# Standard deviation and mean square error of the estimated parameters
#m
truevalue <- c(alpha,beta)
tab=data.frame(truevalue,mean=mest,sd=dest,eqm=eqmest)
tab


Cannot find name 'BigInt64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later

Question: I have already added all the necessary components and dependencies but when I build the project I get this error projects/fs-lib/node_modules/type-fest/source/typed-array.d.ts:16:4 - error TS2583: Cannot find name 'BigInt64Array'. Do you need to change your target library? Try changing the 'lib' compiler option to 'es2020' or later.
I can't remove this error since yesterday. I lose hope if someone can help me.
I'm trying to create an angular library from a finished project. I have already created a lib and copy and export all the components needed for this. The problem is that I build the lib I still receive this error since yesterday.
I use es2021, I have already reinstalled my dependencies. The project uses Angular 12.2.8 and node version 14.20.1
I am using typescript version 4.3.5.
Here is my global project tsconfig file:
{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "paths": {
      "fslib": [
        "dist/fslib/fslib",
        "dist/fslib"
      ]
    },
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2017",
    "module": "es2020",
    "lib": [
      "es2021",
      "dom"
    ],
    "resolveJsonModule": true,
    "esModuleInterop": true
  },
  "angularCompilerOptions": {
    "enableI18nLegacyMessageIdFormat": false,
    "strictInjectionParameters": true,
    "strictInputAccessModifiers": true,
    "strictTemplates": true,
  }
}

tsconfig of lib
{
    "extends": "../../../tsconfig.json",
      "include": [
        "src/**/*.ts",
        "src/lib/interfaces/interfaces"
      ]
}

my project package.json:
{
  "name": "file-system",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test",
    "lint": "ng lint",
    "build-library": "ng build fs-lib"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~12.2.0",
    "@angular/cdk": "^12.2.13",
    "@angular/common": "~12.2.0",
    "@angular/compiler": "~12.2.0",
    "@angular/core": "~12.2.0",
    "@angular/forms": "~12.2.0",
    "@angular/localize": "~12.2.0",
    "@angular/material": "^12.2.13",
    "@angular/platform-browser": "~12.2.0",
    "@angular/platform-browser-dynamic": "~12.2.0",
    "@angular/router": "~12.2.0",
    "@ng-bootstrap/ng-bootstrap": "^10.0.0",
    "bootstrap": "^4.5.0",
    "ngx-bootstrap": "^10.2.0",
    "ngx-infinite-scroll": "^13.1.0",
    "ngx-toastr": "^14.2.1",
    "rxjs": "~6.6.0",
    "tslib": "^2.3.0",
    "yup": "^1.1.1",
    "yup-locales": "^1.2.12",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~12.2.0",
    "@angular-eslint/builder": "12.7.0",
    "@angular-eslint/eslint-plugin": "12.7.0",
    "@angular-eslint/eslint-plugin-template": "12.7.0",
    "@angular-eslint/schematics": "12.7.0",
    "@angular-eslint/template-parser": "12.7.0",
    "@angular/cli": "~12.2.0",
    "@angular/compiler-cli": "~12.2.0",
    "@types/jasmine": "~3.8.0",
    "@types/node": "^14.14.38",
    "@typescript-eslint/eslint-plugin": "4.28.2",
    "@typescript-eslint/parser": "4.28.2",
    "eslint": "^7.26.0",
    "jasmine-core": "~3.8.0",
    "karma": "~6.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "~1.7.0",
    "ng-circle-progress": "~1.6.0",
    "ng-packagr": "^12.1.1",
    "ngx-file-drop": "^12.0.0",
    "typescript": "4.3.5"
  }
}

package.json from the lib:
{
  "name": "fs-lib",
  "version": "0.0.1",
  "peerDependencies": {
    "@angular/common": "~12.2.0",
    "@angular/core": "~12.2.0"
  },
  "dependencies": {
    "@angular/animations": "~12.2.17",
    "@angular/cdk": "~12.2.13",
    "@angular/common": "~12.2.17",
    "@angular/compiler": "~12.2.17",
    "@angular/core": "~12.2.17",
    "@angular/forms": "~12.2.17",
    "@angular/localize": "~12.2.17",
    "@angular/material": "~12.2.13",
    "@angular/platform-browser": "~12.2.17",
    "@angular/platform-browser-dynamic": "~12.2.17",
    "@ng-bootstrap/ng-bootstrap": "~10.0.0",
    "@popperjs/core": "~2.11.6",
    "ajv": "~6.9.1",
    "bootstrap": "~4.5.0",
    "ngx-infinite-scroll": "13.1.0",
    "ngx-toastr": "~14.2.1",
    "tslib": "~2.3.0",
    "yup": "~1.1.1"
  },
  "devDependencies": {
    "@types/node": "^16.7.13",
    "ng-circle-progress": "~1.6.0",
    "ts-node": "^10.9.1",
    "typescript": "4.3.5"
  }
}

Thanks.
I tried to modify my lib and install the dependencies which should have removed the error but no
Answer: Add "es2020" in the lib section of your tsconfig :
"lib": [
  "es2020",
  "es2021",
  "dom"
],

Comment: I have already tried it does not work.


Ideal action and string gauge for acoustic fingerstyle

Question: I've been playing more and more percussive fingerstyle, and one thing I have trouble with is getting volume when hitting strings with only my left hand, for example like Jon Gomm and others. Especially for the higher strings.
I am currently using light-gauge strings (cycling various brands and types), with a rather low action, on a Taylor 214. Does anyone have any knowledge on this? I suppose that heavier strings would help, but I would like to ask before I get my truss-rod adjusted again as there isn't somewhere conveniently close to where I live.
Answer: It sounds glib - but learn to adjust the guitar yourself! Certainly if there's no-one local to help you. It's not difficult, and with care, not risky. Turn the nut a quarter each time, re-tighten the strings, wait a while, and check.
Heavier gauge strings will be more effective, but will be harder work. You have to be quite brutal with hammer-ons using l.h., and of course pretty accurate where your fingers hit. It's not an easy technique, so loads of practice! But as soon as your fingers start to tell you they've had enough, let them rest.
Comment: You check to see what made the cracking noise... only kidding! Sight along the neck to see how close the strings are to the frets, and if there is still a slight bowing. Play each fret for buzzing, if o.k., turn again, and re-check. It's a methodical job to take time over, don't rush, as the guitar needs to settle after each adjustment.
Comment: I always thought about that, but everywhere (on the internet) I've looked for this, I've usually seen warnings of "unless you know exactly what you're doing, you risk damaging your guitar permanently!"...

So after turning the nut, re-tightening the strings, waiting a while... what do I actually check for?


combine or cumulate many comments into one comment if posted within similar time or same user

Question: Question:  I want cumulate or combine many comments  into one if they are posted in similar time by the same user. What is the best way of approaching this?
Currently: I have DB table that has comments written by each user, structure as follow:
ID, comment, timestamp, userid
Example:  All users have a current status page, here you can view  what they  have been upto. For a example if the user uploads a new photo, comment will appear to show they have uploaded a photo. But if the user uploads many photos at once, let say 10 in the last 30mins, then there will be 10 different comments, but i want to combine or cumulate this into one comment instead of spamming the status page.
Technology used:  MYSQL, PHP
thanks, if more info needed please ask.
Comment: Why don't you check the last comment the user did and see if it was not more than 30 minutes ago. If that evaluates to true just append the comment to the old comment, otherwise create a new comment.
Answer: you should not create multiple comments if it is all the same
make 3 tables:
photos [id, src,  title, date, etc...]
comments [id, comment, timestamp, userid, etc...]
photos_comments [id, photo_id, comment_id]
when you upload multiple comments at once you will create only 1 new record in the comments table, but connect it to multiple photos in the photos_comments table (this is called many to many relationship)
when you want to get all the comments that related to a photo (lets say photo with id=10), you can pull it from the DB with this query:
SELECT * FROM comments WHERE id IN (SELECT comment_id FROM comments_photos WHERE photo_id=10)
or even better, with joins:

SELECT comments.* FROM comments INNER JOIN photos_comments ON photos_comments.comment_id=comments.id WHERE photos_comments.photo_id=10


Integral $\int_0^\infty x^{-\alpha} \sin(x)dx.$

Question: I am trying to understand how to integrate $$\int_0^\infty x^{-\alpha} \sin(x)dx.$$ Mathematica indicates that the integral exists for $0< \alpha < 2$ and gives $$ \dots = \cos(\alpha \pi/2)\Gamma(1-\alpha)$$ where $\Gamma$ is the gamma function. I have tried looking the integral up in Gradshteyn's book but I could not find it. Is there some obvious trick?
Comment: Related: https://math.stackexchange.com/questions/3806166/proof-of-the-identity-int-0-infty-frac-sinxx-alphadx-frac-gamma and https://math.stackexchange.com/questions/382412/mellin-transform-of-sin-x-aka-int-infty-0-xs-1-sin-x-dx?noredirect=1&lq=1
Comment: using Euler's formula to represent $\sin x$ may be helpful
Comment: Consider integrating $z^{-\alpha}e^{iz} dz$ along the spherical lune integral from $0$ to $\infty$ along positive real axis, and coming back along positive imaginary axis.
Answer: Consider the Mellin transform of the sine function:
$$\left\{\mathscr{M} \sin\right\}(s) = \int_{0}^{\infty} x^{s-1} \sin(x) dx $$
We can expand $\sin x$ using the Euler's formula and the de Moivre theorem:
$$
\sin(w) = \frac{e^{ix}-e^{-ix}}{2i} = \sum_{n=0}^{\infty} \frac{(ix)^n}{2in!} -\sum_{n=0}^{\infty} \frac{(-ix)^n}{2in!}=\sum_{n=0}^{\infty} \frac{(-x)^n\left[(-i)^n-(i)^n\right]}{2in!}
$$
By de Moivre's theorem
$$(-i)^{n} =  \cos\left(\frac{n\pi}{2}\right)-i\sin\left(\frac{n\pi}{2}\right)$$
$$i^{n} = \cos\left(\frac{n\pi}{2}\right)+i\sin\left(\frac{n\pi}{2}\right) $$
Therefore
$$\sin x =  \sum_{n=0}^{\infty}\frac{(-x)^n[-\sin\left(\frac{n\pi}{2}\right)]}{n!}dw $$
Applying the Ramanujan's master theorem and using the fact that sine is odd
$$\left\{\mathscr{M} \sin\right\}(s) = \int_{0}^{\infty} x^{s-1} \sin(x) dx = \Gamma(s)\sin\left(\frac{s\pi}{2}\right) $$
If $\displaystyle s = 1-a$ we have
$$\int_{0}^{\infty} x^{-a} \sin(x) dx = \Gamma(1-a)\sin\left(\frac{\pi}{2}-\frac{a\pi}{2}\right) = \Gamma(1-a)\cos\left(\frac{a\pi}{2}\right) $$
Note that $\Gamma(1-a)$ is defined for $a\neq 1$.
Therefore
$$\boxed{\int_{0}^{\infty} x^{-a} \sin(x) dx  = \Gamma(1-a)\cos\left(\frac{a\pi}{2}\right) \quad a\in(0,1)\cup(1,2)} $$
For the case $a=1$ the integral is the usual Dirichlet integral


Is there a technique for solving the integral of the square root of a constant minus the square of the cosecant?

Question: I have to solve this integral:
$$
\frac{1}{\pi}\int_{\theta_1}^{\theta_2}\sqrt{\Gamma^2 - \frac{J^2}{\sin^2(\theta)}}\text{d}\theta,
$$
where $\theta_1$ and $\theta_2$ are the endpoints of one of the intervals where the integrand function is defined, so - for example - $\theta_1 = \arcsin(J/\Gamma)$ and $\theta_2 = \arcsin(-J/\Gamma)+\pi$, if $J > 0$.
$\Gamma$ and $J$ are real values chosen such that the previous expressions are well defined.
The solution should be $\Gamma-|J|$. Is there any change of variable or technique useful in solving it?
Comment: What does $G$ mean? Is it Catalan's Constant?
Comment: @Accelerator No, you just made me realize I made a mistake, it should be $\Gamma$. I correct the question, thank you!
Comment: I'll see if there's a clever way to solve this. Have you come up with other ideas? It seems like the antiderivative will not be pretty.
Comment: @Accelerator Thanks! I tried with some substitutions, like a simple $\sin(\theta) = t$ or $\sin(\theta) = J/\Gamma\sin(t)$ and they didn't seem to be such good ideas, but I've never been good in finding strategies for solving integrals.
Comment: You can rewrite the integrand as $$\dfrac{\sqrt{(\Gamma^2 - J^2) - \Gamma^2\cos^2\theta}}{\sin\theta}$$ A substitution based on $\cos\theta$ would then be helpful.
Answer: Denote $a=(J/\Gamma)^2$, substitute $t=\sin^2\theta$ and use the symmetry w.r.t. $\theta\mapsto\pi-\theta$: $$I=\frac\Gamma\pi\int_a^1\sqrt{\frac{t-a}{1-t}}\frac{dt}{t}.$$
Now try $(t-a)/(1-t)=z$, i.e. $t=(a+z)/(1+z)$. You get $$I=\frac\Gamma\pi\int_0^\infty\frac{(1-a)\sqrt{z}\,dz}{(a+z)(1+z)}=\frac\Gamma\pi\int_0^\infty\left(\frac1{1+z}-\frac{a}{a+z}\right)\frac{dz}{\sqrt{z}}.$$
And now the (elementary) integration is easy: $$I=\frac{2\Gamma}\pi\left(\arctan\sqrt{z}-\sqrt{a}\arctan\sqrt{z/a}\right)_{z=0}^{z=\infty}=(1-\sqrt{a})\Gamma.$$
Which matches your expected result.
Answer: For $J \in [0,\Gamma]$ and $k \in \mathbb{Z}$, we will prove that
$$\frac{1}{\pi}\int_{\arcsin\left(\frac{J}{Γ}\right)+k\pi}^{\arcsin\left(-\frac{J}{Γ}\right)+\left(k+1\right)\pi}\sqrt{Γ^{2}-\frac{J^{2}}{\sin^{2}\theta}}d\theta=Γ-J.$$
Proof. We can rewrite the integral as
$$\frac{2}{\pi}\int_{\arcsin\left(\frac{J}{Γ}\right)+k\pi}^{\frac{\pi k}{2}+\frac{\pi\left(k+1\right)}{2}}\frac{\sqrt{\left(Γ^{2}-J^{2}\right)\sec^{2}\theta-Γ^{2}}}{\sec\left(\theta\right)\left(\sec^{2}\theta-1\right)}\sec\left(\theta\right)\tan\left(\theta\right)d\theta$$
since both $\displaystyle \sqrt{Γ^{2}-\frac{J^{2}}{\sin^{2}\theta}}$ and $\frac{\sqrt{\left(Γ^{2}-J^{2}\right)\sec^{2}\theta-Γ^{2}}}{\sec\left(\theta\right)\left(\sec^{2}\theta-1\right)}\sec\left(\theta\right)\tan\left(\theta\right)$ are equal when $\theta \in \left[\arcsin\left(\frac{J}{g}\right)+k\pi, \frac{\pi k}{2}+\frac{\pi\left(k+1\right)}{2}\right)$, where that upper bound is the halfway point of the original interval. To avoid ugly lower and upper bounds, we can calculate the indefinite integral instead:
$$
\begin{align}
\int\frac{\sqrt{\left(Γ^{2}-J^{2}\right)\sec^{2}\theta-Γ^{2}}}{\sec\theta\left(\sec^{2}\theta-1\right)}\sec\theta\tan\theta d\theta &= \int_{ }^{ }\frac{\sqrt{\left(Γ^{2}-J^{2}\right)u^{2}-Γ^{2}}}{u\left(u^{2}-1\right)}du \tag{1} \\
&= \left(Γ^{2}-J^{2}\right)\int_{ }^{ }\frac{v^{2}}{\left(v^{2}+Γ^{2}\right)\left(v^{2}+J^{2}\right)}dv \tag{2} \\
&= \int_{ }^{ }\left(\frac{Γ^{2}}{v^{2}+Γ^{2}}-\frac{J^{2}}{v^{2}+J^{2}}\right)dv \tag{3} \\
&= Γ\arctan\left(\frac{v}{Γ}\right)-J\arctan\left(\frac{v}{J}\right)+C \\
\end{align}
$$
where in: $(1)$ we used $u=\sec\theta$; $(2)$ we used $v=\sqrt{\left(Γ^{2}-J^{2}\right)u^{2}-Γ^{2}}$; $(3)$ we used partial fractions. Recalling that $v=\sqrt{\left(Γ^{2}-J^{2}\right)\sec^{2}\theta-Γ^{2}}$, we can use FTC as follows:
$$\frac{2}{\pi}\lim_{t \to \frac{\pi k}{2}+\frac{\pi\left(k+1\right)}{2}}\left[Γ\arctan\left(\frac{\sqrt{\left(Γ^{2}-J^{2}\right)\sec^{2}\theta-Γ^{2}}}{Γ}\right)-J\arctan\left(\frac{\sqrt{\left(Γ^{2}-J^{2}\right)\sec^{2}\theta-Γ^{2}}}{J}\right)\right]_{\arcsin\left(\frac{J}{Γ}\right)+k\pi}^{\Large t}.$$
Doing some calculations results in $\Gamma-J$, as desired. Q.E.D.
(A similar proof could be letting $J \in [\Gamma,0]$ and $k\in\mathbb{Z}$ and proving the integral in question equals $J-\Gamma$.)


Convergence of an improper integral involving logarithm

Question: I'm in the first year of a Physics degree. I was solving past paper exams so I came across a problem asking about the values of $\alpha \in \mathbb{R}$ for which the following integral is convergent: $$\int_0^{+\infty} \frac{\ln |1-x^2|}{x^{\alpha}}dx.$$ I thought about splitting the integration interval so I have: $$\int_0^1 \frac{\ln |1-x^2|}{x^{\alpha}}dx + \int_1^{+\infty} \frac{\ln |1-x^2|}{x^{\alpha}}dx.$$ For the second integral I thought this way: $$\frac{\ln |1-x^2|}{x^{\alpha}} \sim_{+\infty}\frac{\ln |-x^2|}{x^{\alpha}}=\frac{\ln(x^2)}{x^{\alpha}}=\frac{2\ln x}{x^{\alpha}}=\frac{2}{x^{\alpha}(\ln x)^{-1}}.$$ So it converges iff $\alpha \le 1$, but I'm not sure if it's the right procedure. For the first integral I really have no idea. Can someone please help me?
[Btw I'm not an English native speaker so forgive me my grammar mistakes.]
Answer: First notice that $$
\frac{\ln{\lvert 1-x^2\rvert}}{x^\alpha} \underset{x\to 1}{\sim} \ln(1+x)+\ln{\lvert 1-x \rvert} \underset{x\to 1}{\sim} \ln{\lvert 1-x\rvert},
$$
so our function is integrable in a neighbourhood of $1$ (i.e. for example $\int_{1/2}^{2} \frac{\ln{\lvert 1-x^2 \rvert}}{x^\alpha} \,\mathrm{d}x$ converges).
We have
$$
\frac{\ln{\lvert 1-x^2\rvert}}{x^\alpha} \underset{x\to 0}{\sim}\frac{-x^2}{x^\alpha}=-x^{2-\alpha},
$$
so the first integral converges iff $2-\alpha>-1$.
The second integral converges iff $\alpha >1$ (you made a mistake here).
Comment: Thanks. But isn't x=1 a problematic point? In its neighbourhood the logarithm goes to infinity.
Comment: @Michele Indeed, I modified my answer. The integral $\int \ln\lvert 1-x \rvert \,\mathrm{d}x$ is convergent in a neighbourhood of $1$ (you can compute its antiderivative explicitely) so $x=1$ is, in fact, not a problematic point.


Form button event not firing

Question: I've got this jQuery event code to handle clicking on the whole document, any link, button and textfield.

and this HTML form code:
        <form action="#" method="get">
            <fieldset>
                <legend>A Form</legend>

                  <input name="button" type="button" id="button" value="A Button" />

                    <input name="textfield" type="text" id="textfield" />

                  <input type="button" id="button" value="Doesn't work"/>

            </fieldset>
        </form>

I cannot understand the part where the user clicks the button and it changes its value. For a single button it works fine, but when I add a second with same ID (#button), it still works only for the first one. I expected this to run with any button which I have assigned that ID. I hope I made myself clear.
Comment: the ID's must be unique.
Comment: And if it is not unique, the subsequent items with the same ID in the DOM's tree will be ignored...
Answer: You cannot have multiple elements with same ID. You can change your code like this,
$('input[type=button]').click(function(){
    $(this).val("Stop it!");
});

This will apply all the input buttons in the page
Comment: But warn him to remove the duplicate ID identifiers from his code.
Comment: Read the first line of the answer :)
Comment: Thanks! I still lear HTML/CSS and JS/JQ, so it wasn't obvious to me.
Comment: I did :). He must remove the duplicate identifiers, than he follows your nice solution. I am trying to prevent him to use your code, and maintain the duplicated identifiers.

Form button event not firing


Product and Sum of Polynomial Roots

Question: The ratio of the sum of the roots of the equation, $8x^3+px^2-2x+1=0 $  to the product of the roots of the equation $5x^3+7x^3-3x+q=0 $ is $3:2$. What is the value $\frac{p-q}{p+q}$?
Well I found out the sum of the roots of 1st equation is $-\frac{p}{8}$ and product of roots of second equation is $-\frac{d}{5}$.
Now what to do further? How to get in terms of $\frac{p-q}{p+q} $ ?
Comment: Please use LateX (directions in the FAQ section) or, at least and to begin with, parentheses: what is $\,p-q/p+q\,$? Did you mean $$\frac{p-q}{p+q}\;,\;\;p-\frac qp+q\;,\;\;p-\frac q{p+q}\ldots ??$$
Comment: oh..yeah...the 1st one
Answer: Using Vieta's Formulas,
the sum of the roots of  $\ 8x^3+px^2-2x+1=0$ is $\frac{-p}8$
and the product of the roots of $\ 5x^3+7x^3-3x+q=0$ is $\frac {-q}5$
So, $$\frac {\frac{-p}8}{\frac {-q}5}=\frac32\implies \frac pq=\frac{3\cdot 8}{2\cdot 5}=\frac{12}5$$
Now, use Componendo and dividendo
or use $$\frac{p-q}{p+q}=\frac{\frac pq-1}{\frac pq+1}=\frac{\frac {12}5-1}{\frac {12}5+1}=\frac{12-5}{12+5}$$
or use  $$\frac p{12}=\frac q5=r(\ne0)\text{(say)}\implies p=12r,q=5r$$
Comment: "Options can't be wrong"?? Like when someone writes down something...he can't be wrong?! You honestly think?
Comment: OH yeah! c & d! well, after this it shud be $$\frac{24-10}{10+10}$$  ...???
Comment: @joeyrohan, no, it should be $$\frac{24-10}{24+10}$$  or we can use $$\frac{p-q}{p+q}=\frac{\frac pq-1}{\frac pq+1}=\frac{\frac {24}{10}-1}{\frac {24}{10}+1}=\frac{24-10}{24+10}$$
Comment: But 7/17 is not in the options.These are : 3/2,2/3,2/5,1/5 !!!
Comment: Then either you miscopied the question or they have a mistake in the options for the answer.
Comment: @joeyrohan, please cross the question & the options. But I believe learning the method is more important than matching the answer(s) supplied
Comment: @DonAntonio I am sure..like 100%..the question is correct..n options can't be wrong !
Comment: @joeyrohan, sounds like an oracle. Could you really follow the method used here? Correct method always leads to the correct answer.
Comment: They are MCA top university papers..well, but the method here is right...so have to accept it :)
Comment: @labbhattacharjee the ques. is from DU MCA 2011...That's why!!
Comment: @joeyrohan, is it available online?
Comment: @labbhattacharjee yup https://docs.google.com/file/d/0B8gUa0bct5D_ZGpBV2owV2ZIdkE/edit?usp=drive_web
Comment: @labbhattacharjee i got it...may the options are wrong!!
Comment: What is MCA, DU MCA...and why being from the latter one "explains" the mistake in the options?
Answer: Hints:
The given ratio is (notice: is $\,q\,$ , not $\,d\,$ )
$$\frac{\frac p8}{\frac q5}=\frac{5p}{8q}$$
Get from here the solution to your question, whatever it is.
Comment: Yeah..this much i solved...$$\frac{5p}{8q}$$ = 3/2 .but what's next?
Comment: $$\frac{5p}{8q}=\frac32\implies 5p=12q\implies q=\frac{5}{12}p\implies$$

$$\frac{p-q}{p+q}=\frac{\frac7{12}p}{\frac{17}{12}p}=\ldots$$

Product and Sum of Polynomial Roots


Finding the Direction Given Rate of Change

Question: I'm working on the problem:
In what direction at the point (2,0) does the function $f(x,y) = xy$ have rate of change of -1? Are there directions in which the rate is -3?
So, we know that the gradient of f(x,y) is = < y, x > (because of the partial derivatives)
Thus, when we plug in our points, we get <0,2>.
So, I then set up the equation of $-1=<0,2>*u$ (since u is the direction vector)
Since we're looking for u, we must determine a situation where 2 can be multiplied by the y-component to equal -1 as desired, which is -1/2.
Thus, I set my answer to be <0,-1/2> and said that a rate of -3 could be achieved similarly with a direction vector of <0,-6/2>.
Now, my issue comes into play here: In the x-component of the direction vector, since the x-component of our gradient is 0, couldn't our x-component for the direction vector be anything from -infinity to +infinity? Me setting it to 0 was just an arbitrary number, but the truth is that we can't actually determine it since we're multiplying by 0. Am I missing something important here?
Any help in the right direction would be greatly appreciated!
Answer: So the directional derivative in any direction would be given by
$$\langle 0, 2\rangle\cdot\langle a,b\rangle=2b$$
Thus we would have a derivative of $-1$ when $b=-\frac{1}{2}$. If $b$ is $-\frac{1}{2}$, then we need $a$ to be $±\frac{\sqrt 3}{2}$ so that the length of the vector is a unit.
That may be the key part you are missing: the direction must be a unit vector. Now can you see why $2b$ can never be $3$?
Comment: Oh, gotcha. That clears it up completely. I wasn't aware that the direction had to be a unit vector, the question itself makes a lot more sense now. Thank you!


What's the best workaround for indeterminate progressbar jumping in ICS?

Question: I have a custom layout that includes a progress bar above the main ListView. When the list is refreshing, I set the progress bar to be indeterminate. On JellyBean and above, this works nicely. However, in IceCream Sandwich, when set to indeterminate it jumps a few pixels above, enough to hide part of it under the ActionBar.
What would be the best way to work around this behaviour?
Have two progress bars with different marginTop values and switch between them by changing the view visibility when changing between determinate and indeterminate modes? Changing the LayoutParams of the progress bar when changing modes? Or some other way?
In both cases I can do selective handling, such that in the first way I would set up different layouts for different API versions and in the second only change the LayoutParams if SDK_INT value is less than 16.
Is there a better way to work around the behaviour? If not, which of them would be "better"? Here better would probably be in terms of less resource usage and/or maintainability, but I'd also be interested in pros and cons of them.
Comment: First thing you shoud try to understand why it jumps. Is it connected to the drawable resources used? If so you can simply provide your own resources
Comment: Spot on. The drawable for the indeterminate progress bar in ICS has a different height than the one for the determinate progress bar, so the view draws them in slightly different vertical offsets. It was fixed in commit `d0f8ea5` in AOSP. I fixed the problem by including the same assets present in that commit and by setting `android:indeterminateDrawable="@drawable/progress_indeterminate_horizontal_holo"`. Thanks for pointing it out!
Answer: Consider setting the progress bar maximum to be the timeout for the refresh. So if you set the timeout to be 60s, use a counter to update the progress bar every second until it times out. Then it will always be a determinant progress bar.


Prove that this inverse trigonometric equation is equal to $\frac{2b}{a}$

Question: Prove that $\tan\bigg[\dfrac{\pi}{4}+\dfrac12 \cos^{-1}\bigg(\dfrac{a}{b}\bigg)\bigg]+\tan\bigg[\dfrac{\pi}{4}-\dfrac12 \cos^{-1}\bigg(\dfrac{a}{b}\bigg)\bigg]=\dfrac{2b}{a}$
I tried substituting $\cos ^{-1}\bigg(\dfrac{a}{b}\bigg)=\theta$ but could not finish it. Please help.
Comment: I guess the $\tan^{-1}$ should be $\tan$. No?
Comment: @velutluna I guess you are right. Should I edit?
Comment: Yes. Please edit it if that's true.
Comment: @velutluna The question in my book is stated this way, however the edit you suggested seems correct.
Comment: Hint: If $\alpha = \dfrac{\pi}{4}+\dfrac12 \cos^{-1}\bigg(\dfrac{a}{b}\bigg)$ then the expression is $\tan \alpha+\cot \alpha = 2 \csc 2 \alpha$
Answer: We have: $$\tan(a +b) +\tan(a-b) = \frac{\tan a + \tan b}{1-\tan a \tan b} + \frac{\tan a - \tan b}{1+\tan a \tan b} = \frac{2\sin 2a}{\cos 2a + \cos 2b}\tag 1$$
With $a = \frac{\pi}{4}, b = \frac12 \arccos \left(\frac{a}{b}\right)$, $(1)$ becomes: $$\begin{align} \tan(\frac{\pi}{4}+\frac12 \arccos \left(\frac{a}{b}\right)) + \tan(\frac{\pi}{4}-\frac12 \arccos \left(\frac{a}{b}\right)) \\ = \frac{2\sin \frac{\pi}{2}}{\cos \frac{\pi}{2} + \cos(\arccos(\frac{a}{b}))} = \frac{2b}{a}\end{align}$$
Comment: Wow, that is a great approach. Thanks!
Answer: Using
$$\tan(A+B)=\frac{\tan A+\tan B}{1-\tan A \tan B}$$
we have
$$\tan\left[\frac{\pi}{4}\pm \frac{1}{2}\cos^{-1}\frac{a}{b}\right]=\frac{1 \pm \tan\frac{1}{2}\cos^{-1}\frac{a}{b}}{1\mp\tan\frac{1}{2}\cos^{-1}\frac{a}{b}}$$
Hence
$$\tan\bigg[\dfrac{\pi}{4}+\dfrac12 \cos^{-1}\bigg(\dfrac{a}{b}\bigg)\bigg]+\tan\bigg[\dfrac{\pi}{4}-\dfrac12 \cos^{-1}\bigg(\dfrac{a}{b}\bigg)\bigg]=2\frac{1+\tan^2\left(\frac{1}{2}\cos^{-1}\frac{a}{b}\right)}{1-\tan^2\left(\frac{1}{2}\cos^{-1}\frac{a}{b}\right)}$$
Then by using half angle formula
$$\cos\alpha=\frac{1-\tan^2 \frac{\alpha}{2}}{1+\tan^2 \frac{\alpha}{2}}$$
we have
$$\tan\bigg[\dfrac{\pi}{4}+\dfrac12 \cos^{-1}\bigg(\dfrac{a}{b}\bigg)\bigg]+\tan\bigg[\dfrac{\pi}{4}-\dfrac12 \cos^{-1}\bigg(\dfrac{a}{b}\bigg)\bigg]=\frac{2}{\cos\cos^{-1}\frac{a}{b}}=\frac{2b}{a}$$
Comment: That's neat. Thanks!
Answer: To simplify notation, I'll make a slightly different substitution of $\theta = \frac12\cos^{-1}\left(\frac{a}{b}\right)$. Then compute:
\begin{align}
  \tan\left(\frac\pi4 + \theta \right) + \tan\left(\frac\pi4 - \theta \right) &= \frac{\sin\left(\frac\pi4 + \theta\right)}{\cos\left(\frac\pi4 + \theta\right)} + \frac{\sin\left(\frac\pi4 - \theta\right)}{\cos\left(\frac\pi4 - \theta\right)}\\
  &= \frac{\sin \frac\pi4\cos\theta + \sin \theta\cos\frac\pi4}{\cos\frac\pi4\cos\theta-\sin\frac\pi4\sin\theta} + \frac{\sin \frac\pi4\cos\theta - \sin \theta\cos\frac\pi4}{\cos\frac\pi4\cos\theta+\sin\frac\pi4\sin\theta}\tag{$*$}\\
  &= \frac{\frac{\sqrt2}{2}\cos \theta + \frac{\sqrt2}{2}\sin \theta}{\frac{\sqrt2}{2}\cos \theta - \frac{\sqrt2}{2}\sin\theta} + \frac{\frac{\sqrt2}{2}\cos\theta - \frac{\sqrt2}{2}\sin\theta}{\frac{\sqrt2}{2}\cos\theta + \frac{\sqrt2}{2}\sin\theta}\\
  &= \frac{\cos\theta + \sin \theta}{\cos\theta - \sin\theta} + \frac{\cos\theta- \sin\theta}{\cos\theta + \sin \theta}\\
  &= \frac{\cos^2\theta + 2\cos\theta\sin\theta + \sin^2\theta + \cos^2\theta - 2\cos\theta\sin\theta + \sin^2\theta}{\cos^2\theta - \sin^2\theta}\\
  &= \frac{2}{\cos2\theta}\\
  &= \frac{2}{\cos\left(\cos^{-1}\left(\frac ab\right) \right)}\\
  &= \frac{2b}{a}.
\end{align}
In $(*)$, I've used the angle sum and difference formulas
\begin{align}
  \sin\left(A \pm B\right) &= \sin A\cos B \pm \sin B \cos A,\\
  \cos\left(A \pm B\right) &= \cos A \cos B \mp \sin A \sin B.
\end{align}
Answer: Like Mathistopheles,
let $2x=\arccos\dfrac ab\implies\cos2x=\dfrac ab$
$$F=\tan\left(\dfrac\pi4-x\right)+\tan\left(\dfrac\pi4+x\right)=\dfrac{\sin\left(\dfrac\pi4-x+\dfrac\pi4+x\right)}{\cos\left(\dfrac\pi4-x\right)\cos\left(\dfrac\pi4+x\right)}$$
Using Prove that $\cos (A + B)\cos (A - B) = {\cos ^2}A - {\sin ^2}B$,
$$F=\dfrac1{\cos^2\dfrac\pi4-\sin^2x}=\dfrac2{1-2\sin^2x}=\dfrac2{\cos2x}=?$$


Size of conjugacy classes

Question: If we are given |$D_{10}$|, why can the conjugacy classes only have size 1,2, or 5? Why not 10?
I know that the size of conjugacy classes divides |$G$|
Answer: The conjugacy classes partition the group, and the identity element is the only member of its conjugacy class. Thus, no conjugacy class can be the whole group: all must be smaller, and size $10$ is therefore impossible.
Comment: @kelly: Because $g1_Gg^{-1}=1_G$ for every $g\in G$: the only thing conjugate to the identity is itself.
Comment: Thanks for your answer @Brian M. Scott
How do we know that the identity element is the only member of its conjugacy class though?

Size of conjugacy classes


Solving system of integer solution

Question: First I want to know what is the logarithm used in the following system of equations.

In the set-up protocol, $r_{0}^{\prime}, \cdots, r_{s}^{\prime}$ are found as a solution of the following system
$$
\left[\begin{array}{c}
R^{\prime} \\
\vdots \\
R^{\prime}
\end{array}\right]=\left[\begin{array}{cc}
r_{0}^{\prime} \cdot r_{1}^{\prime a_{1}} \cdot r_{2}^{\prime a_{1}^{2}} \cdots r_{s}^{a_{1}^{s}} & \bmod n^{2} \\
& \vdots & \\
r_{0}^{\prime} \cdot r_{1}^{\prime a_{s}} \cdot r_{2}^{\prime a_{s}^{2}} \cdots r_{s}^{a_{s}^{s}} & \bmod n^{2}
\end{array}\right]
$$
The above system has $s+1$ unknowns and $s$ equations. Therefore it has one degree of freedom. To avoid the trivial solution $r_{0}^{\prime}=R^{\prime}$ and $r_{1}^{\prime}=\cdots=r_{s}^{\prime}=1$, we choose a random $r_{0}^{\prime}$. Then we divide the system by $r_{0}^{\prime}$ and we take logarithms to get
$$
\left[\begin{array}{c}
\log \left(R^{\prime} / r_{0}^{\prime}\right) \\
\log \left(R^{\prime} / r_{0}^{\prime}\right) \\
\vdots \\
\log \left(R^{\prime} / r_{0}^{\prime}\right)
\end{array}\right] \quad \bmod n=\left[\begin{array}{cccc}
a_{1} & a_{1}^{2} & \cdots & a_{1}^{s} \\
\vdots & \vdots & \vdots & \\
a_{s} & a_{s}^{2} & \cdots & a_{s}^{s}
\end{array}\right] \cdot\left[\begin{array}{c}
\log r_{1}^{\prime} \\
\log r_{2}^{\prime} \\
\vdots \\
\log r_{s}^{\prime}
\end{array}\right] \quad \bmod n
$$
The matrix on the right-hand side of the above system is an $s \times s$ generalized Vandermonde matrix (not quite a Vandermonde matrix). Hence, using the techniques in $[7]$ it can be solved in $O\left(s^{2}\right)$ time for $\log r_{1}^{\prime}, \cdots, \log r_{s}^{\prime} .$ Then $s$ powers modulo $n^{2}$ need to be computed to turn $\log r_{i}^{\prime}$ into $r_{i}^{\prime}$ for $i=0, \cdots, s$.

Second I want to understand how one can obtain integer values $r^\prime_1, r^\prime_2, ..., r^\prime_s$ after using logarithm.
Note: All the other values ($R^\prime,r^\prime_0, a_i;\forall i$) in the system are integers.
This equation is from this article (page 16).
Answer: It is a discrete logarithm with an unspecified base. Because it is a discrete logarithm it gives you integers. Some points follow.
First, you're following the math too linearly; you need to think from an implementation perspective. For example, you do not "obtain integer $(r_0', r_1', \dots r_n')$ after performing a logarithm" on them; instead you have a matrix equation which you are going to solve for integer $(\log r_0', \log r_1', \dots \log r_n').$ The logarithms in this expression are not logarithms that you actually have to take! Instead you simply have to invert them via modular exponentiation, which is much simpler.
That leaves the $r_0', R'$ thing for the only reason you'd like to choose a specific logarithm. I do not know the exact reasoning of the authors of the paper but I can tell you that there is one logarithm in particular which will give these some nice properties, and it is base-$n+1,$ but it is not perfect.
In particular, choose a random $R'$ coprime to $n$ and then choose a random $ 0 < b < n$ so that you choose therefore $r_0' = R' + b n \mod n^2$  from a smaller set of possibilities. This smaller-set-of-possibilities is the "imperfection" I mentioned above. However in the paper they only seem to require that the $r_i'$ be nontrivial -- so probably this is OK?
Then $R' / r_0' \equiv 1 \mod n,$ which means that you can efficiently calculate its base-$n+1$ logarithm in the mod-$n^2$ ring, because $(1 + n)^p = 1 + p n + O(n^2).$ So we compute the inverse element for the $r_0'$ that we've chosen above, and then multiply by $R'$, reduce modulo $n^2$, subtract 1, and divide by $n$. The resulting number is not $0$ so the resulting expression is not trivial.
Also, since multiplying by $(r_0')^{-1}$ was a permutation, I'm pretty sure that uniformly choosing $0 < b < n$ is the same as uniformly choosing $ 0 < p < n $ and working backwards from a known exponent, which is probably how they did this in practice.

Solving system of integer solution


A view inside another View, updated with AJAX

Question: I have a View of taxonomy terms (categories of books). This View lists all of the categories available to the user. Now I would like that, when the user clicks on the Category, a div will appear with a few books (another View, with contextual filter). By clicking on a link, I can go to the full View or to the details of the book, but if I do not click on any link, and go to another section and click on the title, I would like the earlier section to close the div, and another div with new books will appear in this new section.
The schema would be something like this:

Category 1
Category 2
Category 3

When clicking on Category 1, with AJAX there will appear:

Category 1 ---> the next part appears retrieved with AJAX

Book 1
Book 2
Book 3
See more books on Category 1 <--- END of content thrown by AJAX call.

Category 2
Category 3

I have been able to make it work without AJAX, using both modules Views Field View and Views Accordion.
However, I cannot find out how to make it work with AJAX, so no tab content is loaded it will be loaded in AJAX when clicking and opening one tab category, so the browser memory/speed/server requeriment is not impacted if I just want to see books in one category.
Comment: @Cesar bounty is not important for me, I just want help another person use drupal , I love drupal and try to help the others use drupal. i think your case is every custom and there is not way to completely achieve it with modules.
Comment: why you need make it work with ajax? Are you dynamically updating any content in that section?
Comment: It is part of a more advanced feature. I would like to scroll down and make a "infinite scroll page" effect, loading more books. Obviously, I need to do it via AJAX (not from the beginning, but it could be), or I could crash the server loading hundreds of books at once. I will allow for a limit of AJAX calls, but seriously I need the possibility to achieve the effect.
Comment: did u check [Views Dynamic Fields](https://www.drupal.org/project/views_dynamic_fields)?
Comment: in Book view can't we use infinite scroll?
Comment: I do not understand Views Dynamic Fields, in isolation or with those 2 earlier modules? Yes, maybe I will try and install an infinite scroll module, but I though that it may be more simple task just to load with AJAX by now. I have the problem in the first place.  Imagine 30 categories with 10 books and no infinite scroll. With accordion you have 300 items loaded (a lot of resource consuming). With AJAX you only have 10 loaded each time. I have the two problems, so maybe mentioning infinite scroll is misleading, I still would like to load first instances of Accordion items with AJAX.
Comment: Hi @Cesar,  what is deadline for this task?( maybe I can write code for you tomorrow night,) are you a developer ? ( can you implement my solution ? my solution need some develop )
Comment: HI @zhilevan, you have almost 7 days. The bounty is 50 points. I would prefer some solution with no code at all, following this link preferences, but you are welcome if your code is elegant and see no other way of doing it. I am a developer struggling with Drupal. [link](http://drupal.stackexchange.com/questions/210522/if-there-are-so-many-modules-in-drupal-are-the-hard-coded-functions-reserved-on)
Comment: @zhilevan, I see your point. I would tend to agree on your view about custom module. My approach was this (I have not advanced since I wanted to extent all possibilites before that): [link](http://drupal.stackexchange.com/questions/212618/adding-a-jquery-interaction-with-views-accordion) . I tried to intercept the accordion "id" and fill the div with the jQueryAJAX view result, but it seemed too work. I played with QuickTabs but I think it is limited and not what I am searching (I believe it is static rather than dynamic). I do not see why it is so custom, it is almost accordion but with AJAX.
Comment: "I would prefer some solution with no code at all" - highly likely that that will not happen in this case. You want a custom AJAX action to do custom things. You should probably scale back the functionality and look at something like Views Show More, which will do the 'endless scroll' part but not the 'AJAX view within view' part. https://www.drupal.org/project/views_show_more
Answer: Views Megarow sounds like it would be ideal for this situation as it opens up a new "accordion" page in the middle of your view like you desire.
You would need to build a new view page / panel page for the parent terms which list the books. This can be done in many ways but I guess a view for /categories/%tid would be the easiest.
The benefit is that you can really do a lot of stuff inside that page.. Blocks / Comments / Multiple Views etc. along with just listing books. If you already have pages for each category, it would be a case of creating a version suitable for loading inside the megarow.
It doesn't close the last category but I guess you could get past that with some basic jQuery.
Answer: You can try using Module 'Views Ajax Get'
https://www.drupal.org/project/views_ajax_get
Or you can also implement it on your own using below sample code, as Views itself provides callback /views/ajax for getting any view through Ajax -
PHP:
$view = views_get_view('taxonomy_term');
$view->set_display('page');
$view->set_use_ajax(TRUE);
$view->set_arguments(array($tid));
$settings = array(
  'views' => array(
    'ajax_path' => url('views/ajax'),
    'ajaxViews' => array(
      array(
        'view_name' => $view->name,
        'view_display_id' => $view->current_display,
        'view_args' => check_plain(implode('/', $view->args)),
        'view_path' => check_plain($_GET['q']),
        'view_base_path' => $view->get_path(),
        'view_dom_id' => 1,
        'pager_element' => $view->pager['element'],
      ),
    ),
  ),
);
drupal_add_js($settings, 'setting');
views_add_js('ajax_view');

JavaScript:
$.ajax({
  url: Drupal.settings.views.ajax_path,
  type: 'GET',
  data: data,
  success: function(response) {
    var viewDiv = '.view-dom-id-' + data.view_dom_id;
    $('#content > div.limiter').html(response.display);
    // Call all callbacks.
    if (response.__callbacks) {
      $.each(response.__callbacks, function(i, callback) {
        eval(callback)(viewDiv, response);
      });
    }
  },
  error: function(xhr) {
    $('#content > div.limiter').html('
Error text.
');
    $('#block-request-0').hide();
  },
  dataType: 'json'
});

Reference: https://stackoverflow.com/questions/4932523/embed-a-view-using-ajax


asp.net session cookies without the use of session

Question: I am a little bit confused about the use of the ASP.NET_SessionId cookie.
When not using session state in my application I thought that the cookie was
set on every response, just with a new value. In the moment I use sessions in my app, the cookie's value (session-id) would stay the same.
Actually when not using session in my app, the cookie's value is still the same (indicating the same sessionid).
Q1: Why is session-cookie value the same when not using session in app?
Q2: Why is there a session-cookie sent on every response when when not using session in app?
Answer: It depends on how you turn off SessionState - http://support.microsoft.com/kb/306996


What happens if matrix $A^2$ has a zero column?

Question: Let me assume that $A$ is a square matrix and the matrix $A^2$ has a column of zeros. Is it possible for me to prove that A has a column of zeros. I know that the determinants are both zero, however it did not help me. I assumed that jth column is the zero row and had [i,j] term $(a_{i1}*a_{1j}+a_{i2}*a_{2j}+...+a_{ij}*a_{ij}+...+a_{in}*a_{nj}=0)$ equal to zero. I summed it for all $i$ in range 1 and $n$, and tried to prove it. But I was not able to do it. Are there anything I am missing?
Comment: As Misha points out, this claim is not true. It is true, however, that if $A^2$ has a zero column, then $A$ is similar to matrix with a zero column.
Answer: Just because $A^2$ has a column of zeroes, doesn't mean $A$ does. For example, $$\begin{bmatrix}1&-1\\1&-1\end{bmatrix}^2=\begin{bmatrix}0&0\\0&0\end{bmatrix}.$$
Comment: Hi @MishaLavrov, this is unrelated to your answer, hence I would be deleting this comment soonest. Please could you help out with this question https://math.stackexchange.com/q/4441875/585488
Answer: To obtain other similar couterexamples let consider
$$\begin{bmatrix}a&b\\c&d\end{bmatrix}^2=\begin{bmatrix}a^2+bc&ab+cd\\ac+dc&cb+d^2\end{bmatrix}$$
and take for example

$a^2+bc=0 \implies a=i, b=1, c=1$
$ac+dc=0 \implies d=-i$

to obtain
$$\begin{bmatrix}i&1\\1&-i\end{bmatrix}^2=\begin{bmatrix}0&0\\0&0\end{bmatrix}$$


Django REST View FileHandling

Question: Using Django REST, post request to my API View :
def post(self, request, *args, **kwargs):

    serializer = DocumentSerializer(data=request.data)

    try:

        serializer.is_valid(raise_exception=True)
        new_document = Documents.objects.create(
            TipoDoc = serializer.data.get("TipoDoc"),
            DataInsert = serializer.data.get("DataInsert"),
            DataInizio = serializer.data.get("DataInizio"),
            DataFine = serializer.data.get("DataFine"),
            CompanyID = serializer.data.get("CompanyID"),
            Doc = serializer.validated_data.get("Doc").read()
        )

    Except : blablabla

ERROR :
'collections.OrderedDict' object has no attribute 'Doc'
Internal Server Error: /docs/
[27/Feb/2024 07:52:26] "POST /docs/ HTTP/1.1" 500 108
DATA PASSED:
blablabla
'Doc': [<InMemoryUploadedFile: MyTestFile.pdf (application/pdf)>]}>
MODEL :
class Documents(models.Model):
class Meta:
    db_table = "documents"

DocID = models.AutoField(primary_key=True)
TipoDoc = models.TextField()
DataInsert = models.TextField()
DataInizio = models.TextField()
DataFine = models.TextField()
CompanyID = models.TextField()
Doc = models.BinaryField()

Can't understand why gives me this type of error. My PDF file is good, there is maybe some issue with the function create?
Tried to modify how i validated data,
tried to modify the order
tried to set the database exactly as the model
Comment: its better to use Filefield in models
Answer: serializer.validated_data.get("Doc").read()

You have to remove this and explicitly add the line in the object creation, like this
     Cart.objects.create(
       user=serializer.validated_data['user'],
       name=serializer.validated_data['name'],
       price=serializer.validated_data['price'],
       doc=request.data.get('doc').read()
     )

Django REST View FileHandling


Vector Norm on Complex numbers

Question: How can we define a vector norm on $\mathbb{C}^n$ that is not an l$_p$-norm?
I have no idea how to start.
Answer: You can take, for instance, $\bigl\lVert(z_1,z_2,\ldots,z_n)\bigr\rVert=\lvert z_1\rvert+2\lvert z_2\rvert+\cdots+n\lvert z_n\rvert$.
Comment: But isn't norm a function from a vector space V(in this case $\mathbb{C}^n$)  to $\mathbb{R}$. What you have defined will be V*V->$\mathbb{R}$
Comment: I solved your problem in the case in which $n=2$ because I thought that that would be enough to understand how to do it in the general case. I've edited my answer.

Vector Norm on Complex numbers


Fill a polygon with a image opengl

Question: http://coliru.stacked-crooked.com/a/400b648e7442eeb3
You can read a piece of code: the idea is to fullfill a polygon quad with a texture ( the image is repeated inside the quad).
I want that the image would repeat only once: in other words to put the image as background of the polygon. Im in a 800x600 window, and i would like to put a billiards table for example 600x400 ( in a quad defined by the glvertex3i). It could be glvertex2i and implemented in 2D,as is a 2D game.
Any help would be apreciated
Also i have a better code to support any jpg file instead of loadtexture and readjpeg( i think):
GLuint MyLoadTexture(std::string const filename)
{
    GLuint texname = 0;
    /* this is actually tied to the OpenGL context, so this should
    * actually be a map GLcontext -> std::string -> texturename */
    static std::map<std::string, GLuint> loaded_textures;
    if( loaded_textures.find(filename) != loaded_textures.end() ) {
        texname = loaded_textures[filename];
        glBindTexture(GL_TEXTURE_2D, texname);
        return texname;
    }

    int width,height;
    std::vector<uint8_t> image;
    if( ReadJPEG(filename, &image, &width, &height) ) {
        std::cerr
            << "error reading JPEG"
            << std::endl;
        return 0;
    }

    glGenTextures(1, &texname);
    if( !texname ) {
        std::cerr
            << "error generating OpenGL texture name"
            << std::endl;
        return 0;
    }

    glBindTexture(GL_TEXTURE_2D, texname);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
    glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_REPLACE);

   /* glTexImage2D(
        GL_TEXTURE_2D, 0, GL_RGB,
        width, height, 0,
        GL_RGB,
        GL_UNSIGNED_BYTE, buffer );
    */
    glTexImage2D(
           GL_TEXTURE_2D, 0, GL_RGB,
           width, height, 0,
           GL_RGB,
           GL_UNSIGNED_BYTE, &image[0]);

    loaded_textures[filename] = texname;

    return texname;
}

int ReadJPEG(
    std::string const filename,
    std::vector<uint8_t> *image,
    int *width, int *height )
{
     if( !image ) {
            return -1;
        }

        FILE * const infile = fopen(filename.c_str(), "rb");
        if( !infile ) {
            std::cerr
                << "error opening file "
                << filename
                << " : "
                << strerror(errno)
                << std::endl;
            return -2;
        }

        struct jpeg_decompress_struct cinfo;
        struct jpeg_error_mgr jerr;
        cinfo.err = jpeg_std_error(&jerr);

        jpeg_create_decompress(&cinfo);

        jpeg_stdio_src(&cinfo, infile);
        jpeg_read_header(&cinfo, TRUE);
        jpeg_calc_output_dimensions(&cinfo);
        jpeg_start_decompress(&cinfo);

        if( width )  { *width  = cinfo.output_width;  }
        if( height ) { *height = cinfo.output_height; }

        size_t const stride = cinfo.output_width * cinfo.output_components;
        image->resize(cinfo.output_height * stride);

        for(size_t i = 0; i < cinfo.output_height;) {
            uint8_t * const row =  &(*image)[stride * i];
            i += jpeg_read_scanlines(&cinfo, (unsigned char**)&row, 1);
        }
        jpeg_finish_decompress(&cinfo);

        fclose(infile);
        return 0;
    }

Comment: Clamp your texture coordinates to the range 0.0...1.0. Also: you should be conscious that you are using highly obsolete OpenGL 2.0 API. It is a good idea to stop doing this and go for OpenGL 4 immediately.
Comment: Please post the relevant parts of your code. The `ReadJPEG` does not actually help answer this question. Show your drawing code.
Comment: The example code is in coliru.. Is an example of repeating a texture in a quad. Update: Ive update coliru link to the concrete example ( pared.jpg is a n image with the texture, in this case a wall...)
Comment: I think the above code of LoadTexture and readjpeg are better than the ones in coliru ( more flexible). How can i do it ? Im afraid but going for opengl 4 is not an option by now....What advantages would i have if i change ?
Comment: It appears that by your code base you are using OpenGL v1.0. I would suggest scrapping this and start to learn modern OpenGL any version of OpenGL v3.3 or higher! Also reading in a jpeg is not friendly with OpenGL. You are better off using either TGA or preferably PNG, you could use a bmp but it does require a little bit of work.
Comment: A quad has 4 sides. A polygon has any number of sides greater than or equal to 3. So what is a "polygon quad"? Just a quad?
Answer: I noticed you are using a deprecated version of OpenGL. Now as for your situation, It is not obvious to me if you are concerned with alpha values within your textures or not. Also how many bytes does each color channel have? This is important to know.
In this section of your code there are a couple things that I see that should be improved:
glGenTextures(1, &texname);
if( !texname ) {
    std::cerr
        << "error generating OpenGL texture name"
        << std::endl;
    return 0;
}

glBindTexture(GL_TEXTURE_2D, texname);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_REPLACE);

/* glTexImage2D(
    GL_TEXTURE_2D, 0, GL_RGB,
    width, height, 0,
    GL_RGB,
    GL_UNSIGNED_BYTE, buffer );
*/
glTexImage2D(
       GL_TEXTURE_2D, 0, GL_RGB,
       width, height, 0,
       GL_RGB,
       GL_UNSIGNED_BYTE, &image[0]);

loaded_textures[filename] = texname;

Before you call glGenTextures(1, &texname); you should call this first:
glGetError(); // This will clear errors

After your call to glGenTextures(1, &texname);instead of checking texname for errors this method is preferred:
GLenum err = glGetError();
if ( err != GL_NO_ERROR ) {
    // Generate Error Here, either log message to file, console or throw an error
}

Next is your glBindTexture( GL_TEXTURE_2D, texname ); which is good. Now as for OpenGL's functions that generate and bind the textures the second parameter is an unsigned ID that OpenGL generates automatically that associates it with the filename that it is given. It is easier for a machine to read an unsigned value to check for multiple resources than it is to check and verify a string. It is also a performance increase when an application is working 100s, 1000s or even 1,000,000s of resource files.
After this you are now setting up the parameters on how OpenGL will deal with mipmaps. And this section of your code appears to be fine if this is the behavior you want for mipmapping. However the caller to this function for using a texture has no method to set the quality level of a mipmap. What I normally do here is have an enumeration that deals with the different quality levels of mimpmaps here is snippet of how I handle working with mipmaps:
Note: the enum value is not defined or declared within this function it would be a parameter that would be passed to it.
// This enum I usually have it declared or defined in a CommonStructs header.
enum FilterQuality {
    FILTER_NONE = 1,
    FILTER_GOOD,
    FILTER_BETTER,
    FILTER_BEST
 }; // FilterQuality

 // Now as within side of my function for generating texture files I have something like this for mipmaps:
if ( texture.generateMipMap ) {
    switch ( texture.filterQuality ) {
        case TextureInfo::FILTER_NONE : {
            glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
            glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST );
            break;
        }
        case TextureInfo::FILTER_GOOD: {
            glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
            glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR );
            break;
        }
        case TextureInfo::FILTER_BEST: {
            glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
            glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
            break;
        }
        default: {
            glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
            glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST );
        }
    } // Switch

    if ( openglVersion.x < 3 ) {
        // In OpenGL v3 GL_GENERATE_MIPMAP Is Deprecated, And In 3.1+ It Was Removed
        // So For Those Versions We Use glGenerateMipmap below
        static const unsigned int GL_GENERATE_MIPMAP = 0x8191;
        glTexParameteri( GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE );
    }
} else { // No MipMaps
    switch( texture.filterQuality ) {
        case TextureInfo::FILTER_NONE:
        case TextureInfo::FILTER_GOOD: {
            glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
            glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
            break;
        }
        default: {
            glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
            glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
        }
    }
}

The only thing that I see that could be irrelevant is your call to glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_REPLACE); for I have never used it, now this may be some type of behavior that you want and for that I do not know.
After you set up your mimpmapping information this is where you want to set the parameters for clamping or wrap repeat which you are missing from your code to generate a texture. They look like this:
bool wrapRepeat; // This variable would not be here inside of the function,
// but would come from this function's definition so that the caller can
// set this parameter or flag to the behavior they want for each texture in use.

// What these two lines of code will do depending on the state of wrapRepeat
// is they will cause the last parameter to be either WRAP in S & T coordinates or
// to clamp to edge in both S & T coordinates.
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, (wrapRepeat ? GL_REPEAT : GL_CLAMP_TO_EDGE ) );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, (wrapRepeat ? GL_REPEAT : GL_CLAMP_TO_EDGE ) );

Finally you have your code that will load the texture into memory and as a reference this is what I have within my function to generate textures:
// Load Texture Into Video Memory
glPixelStorei( GL_UNPACK_ALIGNMENT, texture.hasAlphaChannel ? 4 : 1 );
glTexImage2D( GL_TEXTURE_2D,
    0,
    ( texture.hasAlphaChannel ? GL_RGBA8 : GL_RGB8 ),
    texture.uWidth,
    texture.uHeight,
    0,
    ( texture.hasAlphaChannel ? GL_RGBA : GL_RGB ),
    GL_UNSIGNED_BYTE,
    &texture.vPixelData[0] );

if ( texture.generateMipMap && openglVersion.x >= 3 ) {
    glGenerateMipmap( GL_TEXTURE_2D );
}

This should help you to resolve your current problem with your textures being wrapped and not clamped.
Now as for my project, I have a derived filehandler class that reads in texture files specifically and it loads in either a TGA or a PNG file and the way that it is designed it can load in any other texture or image file as long as you add a function to that class to parse the file type. My actual image types used in rendering are separate from the file reader. And they are separate from this code here. This code belongs to a class that is an AssetStorage. This class of mine is responsible for storing all assets and managing their memory and that is it. This class does not render anything, but it does load objects into ram and video ram. It is my batch class and batch manager classes that handles all of the rendering of objects. Now my objects are all built off of using GLSL Shaders. But to show you this function in full can be used as a reference into how my framework is designed.
// ----------------------------------------------------------------------------
// add()
// Creates An OpenGL Texture And Returns It's ID Value
// This Can Only Be Called From The Main OpenGL Thread
TextureInfo AssetStorage::add( const Texture& texture, const std::string& strFilename ) {
    if ( INVALID_UNSIGNED != getTextureInfo( strFilename ).uTextureId ) {
        std::ostringstream strStream;
        strStream << __FUNCTION__ << " can not store " << strFilename << " multiple times";
        throw ExceptionHandler( strStream );
    }

    TextureInfo textureInfo;
    textureInfo.hasTransparency = texture.hasAlphaChannel;
    textureInfo.size = glm::uvec2( texture.uWidth, texture.uHeight );

    glGetError(); // Clear Errors

    glGenTextures( 1, &textureInfo.uTextureId );

    GLenum err = glGetError();
    if ( err != GL_NO_ERROR ) {
        std::ostringstream strStream;
        strStream << __FUNCTION__ << " failed glGenTextures with error code 0x" << std::hex << err;
        throw ExceptionHandler( strStream );
    }

    glBindTexture( GL_TEXTURE_2D, textureInfo.uTextureId );

    // Wrap Textures
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, ( texture.wrapRepeat ? GL_REPEAT : GL_CLAMP_TO_EDGE ) );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, ( texture.wrapRepeat ? GL_REPEAT : GL_CLAMP_TO_EDGE ) );

    const glm::uvec2& openglVersion = s_pSettings->getOpenglVersion();

    if ( texture.generateMipMap ) {
        switch ( texture.filterQuality ) {
            case TextureInfo::FILTER_NONE : {
                glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
                glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST );
                break;
            }
            case TextureInfo::FILTER_GOOD: {
                glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
                glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR );
                break;
            }
            case TextureInfo::FILTER_BEST: {
                glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
                glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
                break;
            }
            default: {
                glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
                glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST );
            }
        } // Switch

        if ( openglVersion.x < 3 ) {
            // In OpenGL v3 GL_GENERATE_MIPMAP Is Deprecated, And In 3.1+ It Was Removed
            // So For Those Versions We Use glGenerateMipmap below
            static const unsigned int GL_GENERATE_MIPMAP = 0x8191;
            glTexParameteri( GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE );
        }
    } else { // No MipMaps
        switch( texture.filterQuality ) {
            case TextureInfo::FILTER_NONE:
            case TextureInfo::FILTER_GOOD: {
                glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
                glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
                break;
            }
            default: {
                glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
                glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
            }
        }
    }

    // Load Texture Into Video Memory
    glPixelStorei( GL_UNPACK_ALIGNMENT, texture.hasAlphaChannel ? 4 : 1 );
    glTexImage2D( GL_TEXTURE_2D,
        0,
        ( texture.hasAlphaChannel ? GL_RGBA8 : GL_RGB8 ),
        texture.uWidth,
        texture.uHeight,
        0,
        ( texture.hasAlphaChannel ? GL_RGBA : GL_RGB ),
        GL_UNSIGNED_BYTE,
        &texture.vPixelData[0] );

    if ( texture.generateMipMap && openglVersion.x >= 3 ) {
        glGenerateMipmap( GL_TEXTURE_2D );
    }

    // Store TextureId
    BlockThread blockThread( s_criticalSection );
    m_textureInfos.insert( MapTextureInfos::value_type( strFilename, textureInfo ) );

    if ( s_pSettings->isDebugLoggingEnabled( Settings::DEBUG_MEMORY ) ) {
        Logger::log( std::string( "Created " ) + strFilename );
    }

    return textureInfo;
} // add

Comment: Can you edit it in coliru please ? It would be nice to have an example of use..http://cnilove.com/pool-table-top/perfect-pool-table-top-for-home-decoration-ideas-with-pool-table-top/ as background...an i want to use it in a quad fo width, height dimensions.. I assume you are using the functions ( loadtexture and readjpege) "improved" shown above.. and not the other used in coliru. Thanks for your help. Its not imporant bytes of color or alpha, alpha i use always 0 ( i think)... I only need to show the billiards table inside the quad... Then i have to add the balls etc...
Comment: Also its not necessary to use this method, if theres something easier.. the idea is that in a window for example 800x600 i could add black colour as glClearColor and then put the billards table in for example 400x300 ( letting the borders black). thanks for your help...
Comment: @EduardoGutiérrez There is a difference between applying a material (color) to a polygon as opposed to applying a texture.
Comment: @EduardoGutiérrez Basically you would still want to create triangle strips. You would have to define 2 triangles and have their vertices defined in the right winding order. This would be in your Image2d class.
Comment: @EduardoGutiérrez I'm not at all familiar with coliru. I can suggest a great website that has a few series of video tutorials that deals with OpenGL and 3D Game Engine development. Visit http://www.MarekKnows.com His first series of tutorials OpenGL Game Engine covers OpenGL v1.0 in full detail on how to create different shapes, to apply materials and textures to them, how to define your vertices, indexes, and UV coordinates. It also shows how to create lighting. Then his next series is a combo of OpenGL Tips & Tricks and Physics Engine. Then we use that to make a 3D Game in Ghost Toast...
Comment: @EduardoGutiérrez Finally, his newest series goes into working with Modern OpenGL and that is the Shader Engine.
Comment: @EduardoGutiérrez The code that I provided above only shows you how to load textures into memory, and how you want it configured such as using MipMaps and if you want to WrapRepeat or to Clamp to Edge. The code that applies this pixel color information is not here, it is usually found in your objects that you create to be rendered.
Comment: @EduardoGutiérrez and you should worry about alpha values, let say you have a graphic image and the pool table you want to apply to your rectangle has rounded corners, and on the outside of those corners the image has an alpha channel (transparency). If you don't tell OpenGL to use alpha, then these pixels could render in either black or white, and will not show any color information or background colors (textures) that are behind this image.
Comment: Thanks for your effort.Coliru is just an editor where you can edit and then in terminal compile a program, and then share it like paste bin. I would follow your suggestions and try, but the example was working well. Its good to improve the code. But what im trying is how to put the billieard table ( example the link i pass to you or another) as background in a quad defined. I need to start putting in the balls and the movements, and im stuck on inserting and show the image. As i told you if you know any alternative to achieve this Perhaps we can chat or hangouts. Thanks again
Comment: sorry but you know how to put an image es background in opengl ? Ideally a quad inside a window, but could the whole window also...Thanks

Fill a polygon with a image opengl


How to disable(not remove) a column in celltable of gwt

Question: i am new to GWT.I know tablename.removeColumn(columnname) can be used to remove the column, but instead of removing i want to disable it. Can anybody please help
thnx in advance!
Comment: possible duplicate of [Disable a specific column in GWT Grid](http://stackoverflow.com/questions/14040594/disable-a-specific-column-in-gwt-grid)
Comment: @chad Nouis i want to disable it ..not change the column type
Comment: What do you mean by `disable`. Can you provide an example or some additional clarification?
Comment: @chad Nouis what i mean is the field should be present but the user should not be able to write anything in it.
Comment: Is this column always disabled, for all users? Or depending on some condition the column might be enabled or disabled? The reason I'm asking is because when specifing a column you can specify if it is editable by providing the correct column type (`TextInputCell` is editable, `TextColumn` is disabled/not editable). So if the column is for all purposes disabled then just use TextColumn, if there is a condition though it's a little more complex, and I need the condition in order to provide some code.
Comment: The link provided by @ChadNouis is correct. Your question is solved by that answer. That's the gwt way of disabling a column, by providing the correct column type. So this `i want to disable it ..not change the column type` is incorrect. They are the same thing essentially.
Comment: @alkis i want to disable the column depending upon some condition.Actually i am fetching a url by:

 String url = Window.Location.getHref();
  boolean value = url.contains("xyz");

based on value i want to enable or disable my column.
Comment: not really..i ended creating a new component and calling that based on the url...thanks for the efforts anyways mate (y)
Comment: In order for the thread to be considered closed, you could provide an answer of your own and mark that. This way, the answer you found can be used by others facing the same problem.
Answer: There are some ways to do this, but an easy and clean way to do it is the following :
public static class CustomTextInputCell extends TextInputCell {
    @Override
    public void render(Context context, String value, SafeHtmlBuilder sb) {
        String url = Window.Location.getHref();
        boolean isEditable = url.contains("xyz");

        if (isEditable)  //Condition if editable or not
            super.render(context, value, sb);
        else if (value != null) {
            sb.appendEscaped(value);
        }
    }
}

The render method will be called every time this cell is rendered. So every time it will check if the condition is met to be enabled or not.
This allows you to keep all the functionality of an editable cell but disable it easily when the condition is met.
You use it like this
Column<YOUR_OBJECT_HERE, String> column = new Column<YOUR_OBJECT_HERE, String>(new CustomTextInputCell());
cellTable.addColumn(column , "YOUR_HEADER_HERE");

Answer: I ended up creating a new component that has the columns that i want and called that component based on the url
String url = Window.Location.getHref();
boolean value = url.contains("xyz");
if(value)
{
  component.setEnable(true);
 }
else{
  componentprevious.setEnable(true);
     }

enter code here