Using the BIC to select a model

Question: I have a data set (with $n$ points) and there are two models which I think will fit the data well. The first model is a simple power law and the second model is a power law plus a linear term and an intercept;
\begin{eqnarray}
y&=&ax^b\\
y&=&ax^b+cx+d.
\end{eqnarray}
I would like to use the Bayesian Information Criterion (BIC) to see if using the second model is really worth it. My question is, what exactly is the likelihood $L$ for both of these models? How exactly do I compute $L$ so that I can estimate the BIC?
Comment: @jbowman I would like to know this in general, for any error distribution. I do have software black-boxes that compute BIC's but my goal is to understand what the calculations really are. How would I do this manually step-by-step? For specificity, for this example my errors are normally distributed with mean zero and variance $\sigma^2$. My data is of the same order of magnitude so normal-error assumption is perfectly valid despite me trying to fit a power-law.
Comment: You are guessing well. With RSS in hand, one can compute $\text{BIC} = k \ln(n) + n \ln\left( \frac{2\pi \sum_i^nu_i^2}{n}\right) + n$.
G. Schwarz. 1978. Estimating the dimension of a model. The Annals of Statistics, pages 461-464. I fully agree with your willing to open black boxes.
Comment: Is your model linear in (all) its parameters ? I mean, is $b$ knowledge-driven or is it a parameter to estimate ?
Comment: The likelihood depends on what distribution you assume the errors follow.  If you are using a standard software package, often BIC will be calculated for you (perhaps optionally) on the basis of some distributional assumption, e.g., Normally-distributed errors or Poisson regression.
Comment: @Kanak Both models are nonlinear. I need to estimate $b$ in both cases. Does it matter if my problem is linear or nonlinear?
Comment: Yes it (weakly) mattered at first, since depending on the estimation method, you either work with residual sum of squares (RSS) or with the maximized log-likelihood. This affects the explanations, even if admittedly, RSS are involved in both cases.
Comment: @Kanak For this particular problem I am using nonlinear least squares for both models. But could you please include an explanation for both. The goal here is to understand the entire computation process. Which fitting methods require working with RSS and which fitting methods require maximizing the log-likelihood? I am guessing LS necessitates RSS?
Answer: Actually, a term is missing in your (two) models: the error term. Let's play with the first one:
$y_i = ax_i^b + u_i$ for $i=1,...,n$
The (distribution-specific) likelihood function used in the Bayesian Information Criterion (BIC) is that of $\boldsymbol{u}$ (of the residual vector $\boldsymbol{y} - \widehat{a}\boldsymbol{x}^\widehat{b}=\widehat{\boldsymbol{u}}$ in practice).
This means that you first need to assume a probability density function for $\boldsymbol{u}$, say, $f(\boldsymbol{u},(a,b))$.
Then you can compute -- not to say maximize -- the corresponding log-likelihood function, $\ln(\widehat{L})=\sum_{i=1}^n\ln(f(\widehat{u_i},(\widehat{a},\widehat{b})))$.
Finally, $\text{BIC} = k \ln(n) -2 \ln(\widehat{L})$.

In the (first model) case you describe, $k=2$ and the sensible part is about specifying the probability density function. With your normally distributed residuals, one has
$f(\widehat{u_i},(\widehat{a},\widehat{b})) = (\widehat{\sigma}^22\pi)^{-.5} e^{-.5\widehat{u_i}/\widehat{\sigma}}$
Comment: The L used in the BIC is that of the residuals, derived from the errors' distribution. This, this was the missing connection. Wikipedia talks about the distribution of the *data* and I took it to mean the distribution of the (measured) data itself. Now it makes much more sense. +1 and accepted!
Comment: I see the full expression (with the $2\pi$) and the approximation for large $n$ (without the $2\pi$) on wikipedia. Are they both correct? And how large should $n$ be typically before I can use the approximation for large $n$? And these BIC expressions are only valid if the error distributions are from an exponential family? What to do if the error distribution is not from an exponential family?
Comment: @FixedPoint. Relatively to the approximation for large $n$, I am not sure to understand what the authors are explaining. So, the most honest answer I can give you on this, is *I do not know*. But, for having already re-engineered many statistical packages, I only saw the first expression in use. Your last question is more related to the history of statistics than about statistics themselves, but commonly $30$ is considered as large enough, e.g. see [this](https://www.researchgate.net/post/What_is_the_rationale_behind_the_magic_number_30_in_statistics).

Using the BIC to select a model


Comparação de char em C

Question: Preciso descobrir se cada elemento de uma lista encadeada é ou não uma vogal.
Como posso corrigir meu código?
int BuscaNv(LISTA* resp){
   NO* atual = resp->inicio;

   while(atual){
    if(atual->letra == 'a' || 'e' || 'i' || 'o' || 'u'){
      printf("É vogal\n");
      atual = atual->prox;
    }
    else{
      printf("Não é vogal\n");
      atual = atual->prox;
    }
   }
   return 0;
}

Typedefs:
typedef struct estr {
    char letra;
    struct estr *prox;
} NO;

typedef struct {
    NO *inicio;
} LISTA;

Comment: Por que não está conseguindo?
Comment: Código devolve "é vogal" para todos os caracteres
Comment: Estes `||` estão errados.
Comment: Veja, [esta publicação](https://pt.stackoverflow.com/a/230333/18246). O problema é o mesmo que o seu, o que muda é a sintaxe da linguagem.
Answer: Essa sintaxe está completamente errada, tem que comparar a variável contra o caractere individualmente.
if (atual->letra == 'a' || atual->letra == 'e' || atual->letra == 'i' || atual->letra == 'o' || atual->letra <= 'u')

Coloquei no GitHub para referência futura.
Estava comparando a primeira expressão booleana contra caracteres. Um caractere que não é nulo é um valor diferente de 0, e no lógica booleana 0 é falso e todos os outros valore são verdadeiros, então já na segunda expressão depois do || sempre dará verdadeiro, que não é o desejado.
Answer: Que tal utilizar uma função para verificar se a letra é uma vogal:
int eh_vogal( char c )
{
    int i = 0;
    static const char v[] = "aeiouAEIOU";

    while( v[i] )
        if( v[i++] == c )
            return 1;

    return 0;
}

Com isso, seu código ficaria assim:
int BuscaNv(LISTA* resp){
    NO* atual = resp->inicio;

    while(atual){
        if(eh_vogal(atual->letra)){
            printf("É vogal\n");
            atual = atual->prox;
        }
        else{
            printf("Não é vogal\n");
            atual = atual->prox;
        }
    }
    return 0;
}

Answer: Se voce fizer esse teu if assim funciona?
    if(atual->letra == 'a' ||
       atual->letra == 'e' ||
       atual->letra == 'i' ||
       atual->letra == 'o' ||
       atual->letra == 'u'){
    ...
    ...
    ...
    }

Comment: A resposta do @bigown esta mais completa.

Comparação de char em C


d3 - return only data without header

Question: I have a csv data.
DATA :

Time,Count
1377973800,293
1377975600,212
1377977400,129
1377979200,89
1377981000,54
1377982800,21
1377984600,15

I want to return the data in this format.

{
"946705035":4,
"946706692":4,
"946707210":0,
"946709243":2,
"946710714":5,
"946712907":3,
"946713183":4,
"946719001":0
}

I do not want the header Time and Count to be appeared in the json format.
Tried using d3.nest() but the result I got like it starts with key variable which i don't want.
Someone please help me in getting the data in that format.
Answer: I believe a code similar to this would do the job:
d3.csv("data.csv", function(error, data) {
    var myObject = {};
    for (var i=0; i < data.length; i++)
        myObject[data[i].Time] = data[i].Count;
};

This gives you data about counts as strings, and if you want numbers, you can just add a "+", which will trigger conversion from string to number:
        myObject[data[i].Time] = +data[i].Count;

EDIT: Here is related question on creating object properties dynamically, maybe you can find something useful there too.

d3 - return only data without header


How do I find the third of the chord?

Question:
This is the exercise I'm trying to figure out. I don't really understand how to do this.
Answer: A chord is typically defined by intervals of thirds, minor or major. Intervals are the distance between two notes - if a note is three half steps apart, it is a minor third. If it is four, it is a major.  Here is a little visual representation of intervals on a piano in the key of C. Not sure what those numbers on the right are...
A typical chord is typically the 1 (root) - 3 - 5 - 7 intervals, the numbers are coming each note's interval from the root. So as we see here, the third is the second note in the chord. This is generally how they are set up.
So for example, A major chord is 1 - Major3 - 5. The third is the second note of the chord, and is a major 3rd away from the root. This is the note we're looking for.
The staff shows B, G#, E#, and C#. This chord is inverted, meaning the root of the chord is not the bass note, so we'll have to arrange it. This takes a little trial and error, testing to see which chords make the most sense with the note combination, but what stands out to me is that B would be the minor 7th of C#, so C# can be the root here.
If C# is the root, then E# is the third. It is a major third away from the root of the note. This makes G# a perfect 5th and B a minor 7th. This gives us a Dominant 7th chord, where the third is E# and B is in the bass. This is written as C#7/B.
Comment: The numbers on the right look like frequency ratios related to the base tone (http://en.wikipedia.org/wiki/Just_intonation).
Answer: You have the notes B, G#, E#, C#. Chords are built in 3rds so you need to arrange the chords until the are in 3rds. Thirds in general are when you skip a letter name. So all the possible thirds are A - C - E - G - B - D - F - A. Only the letter name matters not the quality i.e. if it is flat, sharp or natural.
In this case you would rearrange them to C#, E#, G#, and B so the 3rd would be E#. They follow the pattern above just there are added accidentals.
Answer: Chord is C#7/B. As in it's C#maj., with the B as a bass b7th under.The leading note would be B#, so to flatten it would be B natural. As such, the major third is going to be the E#.

How do I find the third of the chord?


Why doesn't "dig gmail.com mx" return the domain "smtp.gmail.com"?

Question: dig gmail.com returns this:
;; ANSWER SECTION:
gmail.com.              3600    IN      MX      40 alt4.gmail-smtp-in.l.google.com.
gmail.com.              3600    IN      MX      30 alt3.gmail-smtp-in.l.google.com.
gmail.com.              3600    IN      MX      20 alt2.gmail-smtp-in.l.google.com.
gmail.com.              3600    IN      MX      5 gmail-smtp-in.l.google.com.
gmail.com.              3600    IN      MX      10 alt1.gmail-smtp-in.l.google.com.

How about the smtp.gmail.com, why isn't it included? Is there a way to find it through some utility? Or is it what can found in the documentation of gmail only?
The same question goes for other email services out there.
My initial goal is find all smtp servers of an email provider.
Comment: Then you should accept Wesley's answer.
Comment: II think there's a lot of back and forth going on here because we aren't sure what you're looking for exactly. Are you looking for where to route mail to users of gmail.com? Or are you looking for the servers that users of gmail.com should use in order to send e-mail to any domain on the internet? If the former, you should not use `smtp.gmail.com`, and should use the servers listed in the `MX` record. If the latter, it's appropriate to use `smtp.google.com`, and you learn of that record's existence through the `_submission._tcp.gmail.com` query.
Comment: @AndrewB, don't be thinking too much. My question isn't about gmail in particular.
Comment: gmail isn't the focus of that question at all. I give up.
Comment: @AndrewB, you said - use stmp.gmail.com. I said -- my question isn't about gmail in particular. It's about any email service provider. Namely, "smtp.some_domain.com" won't work in 100% of the cases.
Answer:
How about the smtp.gmail.com, why isn't it included?

Because smtp.gmail.com doesn't receive email for the gmail.com domain. You asked for the MX record for gmail.com. The answer you got was exactly that. The MX record designates which host(s) receives email for a given domain. The MX record tells you nothing about client submission SMTP servers, etc.  A host named smtp.example.com need not be the host that receives email for said domain. A host that receives email for a domain could literally be named anything.
If you want to know what host(s) receives email for a given domain then perform an MX record lookup just as you did. If you want to know what host a client of a specific email provider should use to send email, consult the email hoster's documentation.
Comment: I don't know what? I don't know what you're after? You're right. You haven't sufficiently explained the context of your quest to "find an SMTP server." Are you looking for the SMTP server that accepts email for a given domain? Are you trying to find the client submission SMTP server for email clients? We don't know and we've tried to figure that out by asking you a number of questions, but you've gone and turned into a jerk and have taken a rude turn with your comments. Good luck in your quest to "find the SMTP server."
Comment: **Is there a way to find it through some utility?**
Comment: What are you trying to find exactly? If you're trying to find the hosts(s) that receive email for a given domain then you've already done that. That's what the MX record is for.
Comment: I've said: is there a way to find "smtp.gmail.com" via "dig" or an analogue?
Comment: All that's going to do is find the host (if it exists) named smtp.gmail.com. That tells you nothing about what that host is or what services it may or may not offer. What are you trying to find out? Are you trying to find the host that receives email for a domain?
Comment: is there a way to find "smtp.gmail.com" via "dig" or an analogue?
Comment: `What are you trying to find out?` -- an smtp server.
Comment: `find an smtp server.` - A server that accepts email for a given domain (as designated via the MX record) is an SMTP server. A server that accepts client connections for email submission is an SMTP server. But they're not necessarily the same server. I don't understand what you're trying to accomplish by "finding" an SMTP server. You need to be more specific. Are you trying to find the SMTP server that accepts email for a given domain or are you trying to find the SMTP server used for client submission?
Comment: Okay, how can I find the 1st one and 2nd one?
Comment: You don't know, and it's what you should've pointed out from the beginning.
Comment: `Okay, how can I find the 1st one and 2nd one?`
Comment: `Good luck in your quest to "find the SMTP server."` -- thank you! I'll need luck.
Answer: As joeqwerty rightly points out, it doesn't show smtp.google.com because a MX record indicates where mail servers should send messages destined for that domain. This is not the same as the servers that should be used by an end-user's e-mail client to transmit outgoing messages to arbitrary destinations.
RFC 6186 describes a method for automatically detecting a SMTP server with SRV records. The problem is that for the majority of the internet's life, SMTP server settings have been conveyed through documentation and not through DNS. You can't rely on this information being present. Modern e-mail clients will attempt to automatically detect the SMTP server settings based on the domain suffix you provided, but if that fails the user has to rely on that company's documentation as usual. This information is not otherwise available, electronically or otherwise.

submission:  Identifies an MSA using [RFC4409].  Note that this
covers connections both with and without Transport Layer Security
(TLS) [RFC5246] as defined for SMTP in [RFC3207].
Example: service record
   _submission._tcp     SRV 0 1 587 mail.example.com.

In this particular case, the query you needed was _submission._tcp.gmail.com with a type of SRV.
$ dig _submission._tcp.gmail.com SRV

; <<>> DiG 9.9.5-9+deb8u10-Debian <<>> _submission._tcp.gmail.com SRV
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 8996
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;_submission._tcp.gmail.com.    IN      SRV

;; ANSWER SECTION:
_submission._tcp.gmail.com. 86400 IN    SRV     5 0 587 smtp.gmail.com.

;; Query time: 9 msec
;; SERVER: 22.214.171.124#53(184.108.40.206)
;; WHEN: Sun Jul 02 03:17:11 UTC 2017
;; MSG SIZE  rcvd: 89

Comment: I applied the logic described by the RFC. Read [section 3.1](https://tools.ietf.org/html/rfc6186#section-3.1), followed by [section 4](https://tools.ietf.org/html/rfc6186#section-4). `_submission._tcp` is the prefix applied to the domain.
Comment: where did you get `_submission._tcp.gmail.com`?
Comment: It's happened to be correct, yes. But I mean, given a domain name -- gmail.com --- how one can find out what its SRV record(s) is? Without having to check out their website and documentation.
Comment: If the question is "how can I get a complete list of all SRV records defined by this domain?", the answer is that you can't get such a list. You simply have to ask for them and see if they exist. RFC 6186 describes the standard for how to name the SRV record intended for this specific purpose. It's up to the domain owners to decide whether or not they want to put it into practice.
Answer:
My initial goal is find all smtp servers of an email provider.

You can't.


How to integrate $\frac{1+e^{x^{1/2}}}{1+e^{x}}dx$?

Question: How to integrate $$\int \frac{1+e^{x^{1/2}}}{1+e^{x}}dx?$$
I am trying this question by writing the above expression as $$\int \frac{1}{1+e^{x}}dx + \int \frac{e^{x^{1/2}}}{1+e^{x}}dx.$$
Now I can easily integrate $$\int \frac{1}{1+e^{x}}dx$$ but I am facing problem to integrate $$\int \frac{e^{x^{1/2}}}{1+e^{x}}dx.$$
Please help me out with the proper solution.
Comment: From where you got this? I think I can do this if we have $e^{x/2}$ in $N^r$ instead of $e^{\sqrt{x}}$.
Comment: [I'm not sure there is a closed form, unfortunately.](https://www.wolframalpha.com/input?i=integral+%281%2Be%5E%28sqrt%28x%29%29%29%2F%281%2Be%5Ex%29)
Comment: @LuckyChouhan. Have fun ! It is a nice problem
Comment: As @LuckyChouhan pointed in comments (had it been $e^{\frac{x}{2}}$);

$$I=\int \frac{e^{\frac{x}{2}}}{1+e^x}\,dx$$

Put $e^\frac{x}{2}=t$,

$$I=\int \frac{2}{1+t^2}\,dt=2arctan(t)+c \implies I=2arctan(e^\frac{x}{2})+c$$
Answer: For the second integral $$I=\int \frac{e^{\sqrt{x}}}{1+e^x} \, dx$$ write it as
$$I=\int \Big(\sum_{n=0}^\infty (-1)^n e^{-(n+1) x+\sqrt{x}}\Big)\,dx$$
$$J_n=\int  e^{-(n+1) x+\sqrt{x}}\,dx=2\int t\,e^{-(1+n)t^2 +t}\,dt$$ One integration by parts and completing the square
$$J_n=\frac{\sqrt{\pi }\, e^{\frac{1}{4 n+4}}}{2 (n+1)^{3/2}}\,\text{erf}\left(\frac{2 (n+1) t-1}{2 \sqrt{n+1}}\right)-\frac{e^{-(1+n)t^2 +t}}{n+1}$$
I do not see any way to go further.
If we consider
$$K_n=\int_0^\infty  e^{-(n+1) x+\sqrt{x}}\,dx$$
$$K_n=\frac 1{n+1}+\frac{\sqrt{\pi } e^{\frac{1}{4 n+4}}
   }{2 (n+1)^{3/2}}\left(1+\text{erf}\left(\frac{1}{2
   \sqrt{n+1}}\right)\right)$$
$$\sum_{n=0}^\infty (-1)^n\,K_n=\log(2)+\frac{\sqrt \pi}2\sum_{n=0}^\infty (-1)^n\,\frac{ e^{\frac{1}{4 n+4}}
   }{ (n+1)^{3/2}}\left(1+\text{erf}\left(\frac{1}{2
   \sqrt{n+1}}\right)\right)$$
The convergence will be rather slow since
$$\left| \frac{a_{n+1}}{a_n}\right|=1-\frac{3}{2 n}+O\left(\frac{1}{n^{3/2}}\right)$$
Now, if you want to know how many terms have to be added, write
$$\sum_{n=0}^\infty (-1)^n\,K_n=\sum_{n=0}^p (-1)^n\,K_n+\sum_{n=p+1}^\infty (-1)^n\,K_n$$ and if you want
$$R_p \leq 10^{-k}\implies p\sim \sqrt[3]{ \frac{\pi}{4}   10^{2 k}}$$ that is to say $9227$ terms for $k=6$.
All of that to obtain the value of $2.08630$ given by numerical integration.


How can I override the field in my view?

Question: I have a view for a content type with a number of fields. For one of the fields (List, text) (node_field_type) I would like to override the output result. It can be either type_1 or type_2 . In the database the type is stored in node_field_type table in field_type_value column.
So in the settings of the field under "Rewrite results" tab I picked "Override the output of this field with custom text"

But it doesnt assign any class to html tag.
Could you please help me?
Answer: You need to have the field field_node_type called somewhere in your view to use it as a token in rewrite results for a field. Value that you're trying to use in rewrite results should be available within replacement patterns for the field you're trying to configure.


Note and dotted note on the same line - Lilypond

Question: I have a note here:

What do these notes (a quarter note and dotted quarter note on the same line) mean?
It's note a, in LilyPond, bottom of the bass clef.
How is this coded in LilyPond?
Full measure score here:
Comment: @Aaron The Heart Asks Pleasure First- (The Piano) -Michael Nyman https://musescore.com/johnny-piano/scores/3509146
Comment: Related [question](https://music.stackexchange.com/q/79420/2600) concerning the general notation problem
Comment: Is that Brahms?
Comment: No, not Brahms. Schumann Aufschwung?
Answer: It means there are two "voices": one of them "sings" a dotted quarter note on a certain pitch, the other sings a series of sixteenth notes beginning on that same pitch.
More commonly, you would see this written with a double stem, as in the upper staff. However, in this case, because of the "dot", it must be written as a double note. If not, it would seem as though the upper voice of the two was responsible for a dotted sixteenth note.
This is not a LilyPond issue; it's a standard notational convention.
For instructions on coding this in LilyPond, see the Collision resolution section of the LilyPond documentation.
Here is a code snippet based on the documentation.

\score{
<<
  {
    d'16
  } \\ {
    d'4.
  }
>>
}

...which produces
Answer: In addition to Aaron's answer, you can also overlap these two noteheads if you like by introducing the <code>\mergeDifferentlyDottedOn</code> command:

The code to create this is:
<code>\version "2.20.0"

global = {
  \key c \major
  \time 6/8
}

music = \relative c {
  \global
  \mergeDifferentlyDottedOn
  <<
    {
      a16\( e' a e a e\)
    }
    \\
    {
      a,4.\sustainOn
    }
  >>
}

\score {
  \new Staff { \clef bass \music }
  \layout { }
}
</code>
Comment: I would argue this version is more ambiguous than the one in the question about whether the upper voice's first note should be extended.  It's not completely ambiguous because of the time signature constraint, but the version in the question seems cleaner.


Obter dados de um relacionamento ManyToMany com Doctrine2

Question: Tenho o seguinte relacionamento N:N entre as tabelas professores e turmas, onde existe uma terceira tabela professores_turma.
Quero que ao listar os professores me traga todas as turmas que este professor leciona (que está relacionado), porém quando retorno a consulta dos professores, $professor->getTurma() vem vazio.
Segue meu código:
Controller Professor:
namespace App\Controllers;

class ProfessorController extends Controller
{
    public function index()
    {
        $this->professores = $this->model->getRepository()->findAll();
        // Traz todos os professores, porém não traz suas turmas
        // com $professor->getTurmas()
        foreach ($this->professores as $professor) {
            var_dump($professor->getTurmas()); die();
        }
    }
}

Entidade Professor:
namespace App\Entities;

use Doctrine\Common\Collections\ArrayCollection as ArrayCollection;

/**
 * @Entity
 * @Table(name="professores")
 */
class Professor
{
    /**
     * @Id @Column(type="integer")
     * @GeneratedValue(strategy="AUTO")
     **/
    private $id;

    /**
     * @ManyToMany(targetEntity="Turma", mappedBy="professores")
     **/
    private $turmas;

    public function __construct()
    {
        $this->turmas = new ArrayCollection();
    }

    public function setTurmas($turmas)
    {
        $this->turmas = $turmas;
    }

    public function getTurmas()
    {
        return $this->turmas;
    }
}

Entidade Turma:
namespace App\Entities;

use Doctrine\Common\Collections\ArrayCollection as ArrayCollection;

/**
 * @Entity
 * @Table(name="turmas")
 */
class Turma
{
    /**
     * @Id @Column(type="integer")
     * @GeneratedValue(strategy="AUTO")
     **/
    private $id;

    /**
     * @ManyToMany(targetEntity="Professor")
     * @JoinTable(name="professores_turma",
     * joinColumns={@JoinColumn(name="id_turma",referencedColumnName="id")},
     * inverseJoinColumns={@JoinColumn(name="id_professor", referencedColumnName="id")}
     * )
     **/
    private $professores;

    public function __construct()
    {
        $this->professores = new ArrayCollection();
    }

    public function setProfessores($professores)
    {
        $this->professores = $professores;
    }

    public function getProfessores()
    {
        return $this->professores;
    }
}

Comment: Eu havia respondido que o problema era a falta do parâmetro `inversedBy` no atributo `$professores` da classe `Turma`, mas testei aqui e não é isso. Inseri algumas linhas no banco de dados, tanto na tabela `professores` quanto na tabela `turmas` e na tabela relacional,  e consegui retornar as linhas normalmente. Você tentou fazer isso?
Comment: isso! reproduzi dentro de um projeto Symfony2, mas o processo é basicamente o mesmo. Vou colocar no Github pra vc.
Comment: Segue: https://github.com/rodrigorigotti/lala.git
Comment: Não precisa. Se você achar necessário, adicione uma resposta explicando o que você fez de errado e valide sua resposta depois de alguns dias. :)
Comment: Opa +Rodrigo Rigotti, desculpa a demora de responder... Como você conseguiu? Voçê pegou por getRepository->findAll() todos professores com as turmas relacionadas para o atributo $this->turmas da Entidade Professor e tendo acesso a essas turmas a partir do método getTurmas() da Entidade Professor??? Como voçê fez? Tem como passar o código?
Comment: O problema não era nem minhas entidades, mas sim a forma que estava tentando imprimir, assim: **`$professor->getTurmas()->getNome()`**. Ao invés de fazer um `foreach` em **`$professor->getTurmas()`**. Muito obrigado.
Comment: Como aprovar sua ajuda?
Comment: Blz. Obrigado Mais uma vez!
Answer: O problema não era nem minhas Entidades, nem nas Annotations e nem no relacionamento. Mas sim a forma que estava tentando imprimir, assim:
$professor->getTurmas()->getNome()

Tava errado, ao invés disso, tive de fazer um foreach em $professor->getTurmas(), ficou da seguinte forma no Controller de Professor:
namespace App\Controllers;

class ProfessorController extends Controller
{
    public function index()
    {
        $this->professores = $this->model->getRepository()->findAll();

        foreach ($this->professores as $professor)
            if ($professor->getTurmas()->count() > 0)
                foreach ($professor->getTurmas() as $turma)
                     echo 'TurmaId: ' . $turma->getId() . ' -> TurmaNome: ' . $turma->getNome() . '
';
    }

    /* ... */

}


tr:nth-child css zebra striping after xml jquery parsing

Question: How do I apply styling to a table after parsing XML data into the table?
In the code below I Created the first three rows of a table using html, then the additional rows were created by parsing XML. however the Zebra stripe styling was not applied to the table after the jquery call. I've tried my best to find the problem with my code but I'm stumped.
Here's a code sample of my html:

    <title>Football Players</title>

        Name
        Club
        Number
        Country

        Lionel Messi
        Barcelona
        10
        Argentina

        Juan Mata
        Manchester United
        8
        Spain

And the following is a snippet of my JQuery:
    $(document).ready(function () {
  $.ajax({
    type: "GET",
    url: "football_player.xml",
    dataType: "xml",
    success: processXML

  });

  function processXML(xml) {
    $(xml).find("football_player").each(function () {
      $("table tbody").append("
");
      $("table tbody").append("" + $(this).find("name").text() + "	");
      $("table tbody").append("" + $(this).find("club").text() + "	");
      $("table tbody").append("" + $(this).find("number").text() + "	");
      $("table tbody").append("" + $(this).find("country").text() + "	");
      $("table tbody").append("
");
    });//close processXML

    $("table tbody tr:nth-child(odd)").css("background-color", "#dddddd");
  }
});//close document.ready()

And lastly the XML file:
    <football_players>
  <football_player>
    <name>Cristiano Ronaldo</name>
    <club>Real Madrid</club>
    <number>7</number>
    <country>Portugal </country>
  </football_player>

  <football_player>
    <name>Fernando Torres </name>
    <club>Chelsea </club>
    <number>9</number>
    <country>Spain</country>
  </football_player>

  <football_player>
    <name>Iker Casillas</name>
    <club>Real Madrid </club>
    <number>1</number>
    <country>Spain</country>
  </football_player>

  <football_player>
    <name>David Beckham</name>
    <club>Los Angeles Galaxy</club>
    <number>23</number>
    <country>England</country>
  </football_player>
</football_players>

Answer: Checking the console is always a good idea,The problem in your code probably is in the function processXML(xml).This is beacause your
 were closed before adding .Hence it was not applying the color.
Change it to..
     function processXML(xml) {
        $(xml).find("football_player").each(function () {
           $("table tbody").append("
"+"" +
$(this).find("name").text() + "	"+"" + $(this).find("club").text() + "	"+"" + $(this).find("number").text() + "	"+"" + $(this).find("country").text() + "	"+"
");
        });//close processXML

 $("table tbody tr:nth-child(odd)").css("background-color", "#dddddd");
  }

Comment: Thanks Varun! Copy and paste of your code didn't work but I edited my code using your guideline and it worked! here it is:
Comment: PS this is my first ever question on Stack Overflow and I look forward to more great experiences like this!
Answer: Thanks to Varun I came up with the following which worked:
function processXML(xml) {
    $(xml).find("football_player").each(function () {
      $("table tbody").append("
" + $(this).find("name").text() + "	" + $(this).find("club").text() + "	" + $(this).find("number").text() + "	" + $(this).find("country").text() + "
");
    });

    $("table tbody tr:nth-child(odd)").css("background-color", "#dddddd");
  }


How long to wait to play guitar again?

Question: When playing guitar the other night, I was having some pain going on. I pushed through it because I was playing with someone else, but I had to stop because it eventually turned into a shooting pain when I would try to grab a chord - like the shooting pain that goes from your wrist into your thumb and hurts when you try to squeeze the neck of the guitar. I feel like I did some damage.
I mostly play the drums, but I've been super into guitar lately and it eventually turned into me playing every day 4 hours for 2 weeks. The last day of that two weeks this started to happen. How long should I just stop playing guitar? Can I still play drums? I've taken a couple days off and it feels much better but still there.
Not asking for medical advice, just what has worked from seasoned guitarists. I don't think it is serious so I'm not going to a doctor unless it persists.
Comment: When I had trouble like this I took two months off. It was a very long two months.
Answer: You should make sure you stretch before and after playing both drums and guitar.  You could have just over-extended a joint and you'll feel it for a while.  If you have the luxury of a doctor, go to one and get checked out.  It's not going to make it any worse if you really have a concern about it.
The reason you're experiencing pain, assuming you're otherwise healthy, is probably because of the 4 hours a day for two weeks for someone who normally doesn't play guitar.  That's a bit hard and fast at first, anyway.
If there was pain in your arm/wrist I'd probably say it had to do with the angle at which you were holding the guitar.  Did it feel comfortable before you started to feel pain?  A major break in angle can really mess up the joints for long periods of time.  Comfort over coolness, always.  Listen to your body, and take a break.  It knows what's best for itself, always.
Comment: "Did it feel comfortable before you started to feel pain?" - my hand would get tired from holding barre chords but it never was the shooting pain I described above.
Answer: What you are experiencing could be what I would call an overuse injury caused by repetitive stress to muscles, tendons and joints without adequate rest for recovery.
Many athletes experience this type of injury and it is often exacerbated by using improper form.  But even if using proper form, continual stress without adequate recovery time can lead to a repetitive stress/over use injury.
I have seen these type injuries occur with experienced professional guitarist who book too many gigs in a short period of time and they end up with a similar issue.  Even though they may have been playing regularly for many years without injury.  It's when they over do it without adequate recovery time and rest between gigs that the injuries show up.
Your best bet is to rest for an extended period.  Similar to when the doctor orders bed rest, you may need to lay off any unnecessary use of your hands for as long as a few weeks (or more) to allow for full recovery.  As disconcerting as this may sound, this means no drumming either.  While playing drums stresses different muscles, joints and tendons than playing guitar, there will be some overlap.
When you resume playing, always start with at least ten minutes of warm up and stretching exercises.  Try to avoid playing more than one hour at a time without a ten minute break and try not to play any more than 4 hours a day total.  It's best if you can space out your practice sessions throughout the day.  Say an hour in the morning, an hour at lunch and an hour in the evening instead of 3 hours in the morning.
Here is an article about the importance of warming up prior to playing guitar including some suggested "exercises".  Guitar World Article on Warm Up Routine
Here is a good YouTube video that shows how to do some stretching exercises for guitarist.  YouTube Video showing stretching routine
I know it's hard to stay away from your instrument, but trust me, it is best to allow your body (hands) to fully recover before resuming.  Otherwise you start chipping away at an "open wound" so to speak - and will likely end up right back where you are now.
I wish you the best.
Comment: I'll take your advice. Probably two weeks off and I'll just try to study theory or maybe try to mix some recordings I have better. Thank you for the advice!
Answer: What to do while you're not playing
I agree with the other answers that you should probably rest your hands for at least 2 weeks, then take it slow. 15 min first day, 30 min second day, no more than an hour for the first week or so of playing. If there's no pain, then you can relax these restraints.
But this doesn't mean you should stop practicing! Now is the perfect time to study theory, sight-singing, writing music, and very importantly visualizing music on the guitar.
Theory includes scales and chord-building.
If you can sing solfage ("Doe, a deer ..."), then you can learn to sing any sheet music given a reference pitch (starting note, or often more usefully, the tonic or root note of the key).
That awesome riff you came up with the other day, write it down. The sight-singing skill will help a lot with this.
The last vital part of mental practice is visualizing. Now that you can sight-sing and you can almost hear the notes in your head, you can start to imagine where on the guitar those notes should be played. Which string to use for that little melody? What frets are the notes at? Which fingers would work best? The more you can do without the guitar, the more versatile you'll become with the guitar.
Comment: That's a good answer. I've actually been mixing and thinking about singing over a song I wrote

How long to wait to play guitar again?


Going from non-linear root-finding to multi-objective optimization

Question: To simplify, let's say I can describe a system with
variables x1 and x2,
parameters p1 and p2, and
constraints f(x, p) = 0 and g(x, p) = 0:
For example:
f(x1, x2, p1, p2) = x1^2 * p1 + x1^2 * p2 + x2 = 0
g(x1, x2, p1, p2) = x2^2 * p2 + x1 * p1 = 0
Now, let's say that given the true value of parameters p1 and p2, the root(s) exist(s).
However, in my case, the parameters are determined in an imperfect way and a non-linear root-finder like scipy.optimize's fsolve is unsuccessful. One could feed in the parameters as variables and try to find the roots, but increase the variables and the parameters by an order of magnitude, like in my actual system, and the constraints become very difficult to respect.
Therefore, I've been looking at optimization packages in python that could "solve" my set of non-linear equations. And this is where my lack of understanding of optimization presents a roadblock.
If I understand correctly, as posited, my equations are constraints, meaning that they must be respected for my design to be successful. However, I've realized that given the imperfect nature of the parameters (or the large number of possible variables), I need to have one (or several) objective functions to minimize as opposed to constraints.
All the equations that describe my system have equal validity, so I don't think I can simply choose one or several equations to be objective functions and the rest remain as constraints. It looks like I need to have all my equations as objective functions.
I therefore have two questions:

Is my logic to have all my equations as objective functions valid, and
What python package would allow me to minimize these objective functions?

I have looked at cyipopt, casadi, pyomo, and DEAP, but I am a bit lost. I think once my model of my system is better defined, I will know exactly what to look for. However, if code for my simple example can be provided, I would really appreciate it.
P.S: My model as it stands now has 11 variables and 11*5 parameters (five coefficients representing a 4th degree polynomial for each variable). I can also add constraints to the variables if necessary in the optimization package.
Comment: I would formulate a least-squares problem: minimize the sum of squares of the deviations (a.k.a. slacks) of the equations. If the optimal objective is close to zero, you should declare victory. Also, non-convexity can be an issue. Try some different starting points to make sure you are not in some local optimum.
Comment: This is a very small problem, so any unconstrained NLP solver will do.
Comment: Thanks a lot for the suggestion Erwin. Do you have any recommendations for a python package that can do this? Or is any optimizer that can minimize an objective function suitable?
Answer: With equations:
e1 = x1**2 * p1 + x1**2 * p2 + x2
e2 = x2**2 * p2 + x1 * p1

it is possible to solve the system of equations as hard constraints (equality form):
m.Equation(e1==0)
m.Equation(e2==0)

or as soft constraints (minimize objective):
m.Minimize(e1**2)
m.Minimize(e2**2)

This approach works in Pyomo, CasADi, and Gekko. Here is a Gekko example that uses both approaches:
from gekko import GEKKO
import numpy as np
m = GEKKO()
x = m.Array(m.Var,2,value=2)
x1,x2 = x
p = m.Array(m.Param,2,value=1)
p1,p2 = p
e1 = x1**2 * p1 + x1**2 * p2 + x2
e2 = x2**2 * p2 + x1 * p1

# approach #1
m.Equation(e1==0)
m.Equation(e2==0)

# approach #2
m.Minimize(e1**2)
m.Minimize(e2**2)

m.options.SOLVER=1
m.solve()
print('x: ', x)
print('Objective: ',m.options.OBJFCNVAL)

In this case, the solutions are the same by using one or the other (or both). If it is a large-scale optimization problem, the solver may not reduce e1 or e2 to zero with soft constraints. Sometimes including both can help the solver find a solution.
Comment: I have one final question: is it doable to have many, many soft/hard constraints? I would like to use this approach to optimize several datasets that share variables, which, traditionally, could be solved individually with multiple linear regression. Now instead, I combine all the datasets together and have one global optimization problem where each soft/hard constraint is a different row in the global Y=Xβ+ϵ dataset.
Comment: Please see my StackExchange question as motivation for this global optimization approach: https://math.stackexchange.com/questions/4265365/estimating-coefficients-through-multiple-linear-regression-from-several-data-set
Comment: That is certainly possible. For very large datasets, you may need to use a specialized QP solver because of the `m.Minimize(e**2)` terms. If you can make it linear then there are even more efficient Linear Programming or explicit solutions to linear regression that just rely on matrix manipulations.
Comment: Thank you for your response. The only terms that are non-linear in my problem at the moment are interactive terms. For example `x1*x3*p1 + x2*x3*p2 + x1*p3 + x2*p4 = y`. Do you know if and how it is possible to linearize the interactive, multiplicative terms? If I am able to have a completely linear problem, could you explain (or point me to resources that explain) how I could use linear programming or solve explicitly with matrix manipulations? Thank you.
Comment: I'd recommend that you stay with a nonlinear or quadratic programming solver for that problem. Gekko can solve nonlinear programming problems. There is information here on linearization if that is your only option: https://apmonitor.com/pdc/index.php/Main/ModelLinearization
Comment: One equation applied to multiple data rows is best done with `IMODE=2`. Here is an example: https://apmonitor.com/wiki/index.php/Main/ParameterFit
Comment: I've implemented your example for **multiple** equations applied to multiple data rows; however, I'm getting the error `'Data arrays must have the same length, and match time discretization in dynamic problems'`. You probably know the easy fix; however, in the case that it is a limitation of gekko, here is some info: on line 159 of the file gk_write_files.py, `length =np.size(np.array(vp.value).flatten())` does not update with the first GKParameter of the second equation, since `first_array == True`, thereby raising the Exception.
Comment: I just created a new questions explaining my problem: https://stackoverflow.com/questions/73112525/multiple-equations-minimized-in-regression-imode-of-gekko. Thanks again for all the help!
Comment: Thanks again for your help. I only have on the order of 10 equations, which can be inputted manually, but those equations are equal (hard) or approaching (soft) on the order of 10,000 values. My approach would be to flip the problem on its head and have the corresponding `values` vector as a parameter in each equation: `y = m.Param(value=values)` and then subtract it from the corresponding equation `e1 = x1*x3*p1 + x2*x3*p2 + x1*p3 + x2*p4 - y`. Finally, if I am not mistaken, for each equation, I would only have one constraint (*e.g.*, `m.Equation(e1==0)`) instead of ~10,000! Would this work?
Comment: Check the list that is fed into .value as discussed here: https://stackoverflow.com/questions/71302626/gekko-arx-model-forecasting-data-arrays-must-have-the-same-length  If this doesn't help then please create a new question with minimal code that reproduces the error.


Hypothesis testing for apriori market basket analysis

Question: I'm wondering if there is a possibility to perform hypothesis tests to show that the resulting rules from an apriori market basket analysis are statistically significant?
Maybe I'm missing the forest through the trees so any kind of help or hint is highly appreciated.
Comment: Statistical significance and correctness are completely different things: could you clarify what you are trying to accomplish?
Comment: Thank you for pointing this out. I'd like to show thr statistical significance of the results.
Answer: The problem with Frequent Pattern Mining is that, in practice, one is likely to discover a titanic number of patterns with many redundancies. Many researchers have devoted substantial effort to come up with clever ways to improve the quality of pattern discovery, i.e. bring forth the most interesting patterns and bring down redundancy.
The word 'interesting' can be formalised in more than one way depending on the problem but a high-level example of a formalisation could be to take the word 'interesting' to qualify a pattern that strongly deviates on its expected support under some user-defined distributional null hypothesis.
The Independence Model is the simplest distributional model : one assumes that all individual items appear independently. So, the expected frequency of a pattern $X=\{x_1,...,x_n\}$ equals $\prod_{i=1}^{n} fr(x_i)$, where the frequencies $fr(x_i)$ are simply computed from the historical data.
Presently, we can calculate both $fr(X)$, the observed frequency, and the expected frequency $ind(X)$ of the independence model. The ratio $$ \frac{fr(X)}{ind(X)}$$ is called the lift of $X$. Suppose we consider patterns that have a high lift to be interesting.
Now, suppose our dataset contains $N$ transactions and the transactions are independent.

According to the independence model, the probability of generating a transaction that contains a pattern $X$ equals $fr(X)$;
The probability $$ P(X\hspace{1mm}occurs\hspace{1mm}in\hspace{1mm}M\hspace{1mm}transactions) = {N\choose M} q^M (1-q)^{N-M},$$ where $q=ind(X)$.

Let $Z_X$ be the binomial random variable that counts the support of $X$ under the independence model.
Now, one can perform a one-sided statistical test by calculating $P(Z_X \geq Nfr(X))$.
Because $M$ is large, one can approximate the binomial by the normal distribution $$\mathcal{N}(\mu=Nq, \sigma^2=Nq(1-q)),$$ and ultimately obtain a good approximation of the p-value of the null hypothesis of the one-sided test by calculating the probability mass of the tail of a Gaussian distribution provided that the number of transactions is very large. The most interesting patterns would be the ones that lead to the lowest p-values.
Other relevant approaches are dealt with in Chapter $5$ of Frequent Pattern Mining.
Comment: Thank you for your detailed answer.
Comment: You are most welcome.


jquery get the height of the submenu

Question: I have the
 tag as below. When clicked on the anchor link it should display a div with the ul list items underneath. On the click function of anchor tag, I need to get the complete height of the div (in fact the height of the ul with li items), the submenu

The html code is as below:

    @{
        var i = 1; //Used for submenu ID
    }
    @foreach (var menuItem in Model.Header.TopLevelNavigation)
    {
        if (i < 6)
        {

 Model.MenuMidPoint ? "class=\"sub-menu-nudge-left\"" : "")>
                @if (menuItem.ContentLink.HasChildPages())
                {

                        @menuItem.Name

                        @Html.DisplayEnumerableIContent("
{0}
", "
{0}
", "menu-link", menuItem.ContentLink.GetChildPages(true, true))

                }

        }
        i++;
    }

I tried the jquery function as below:
I tried as below, but I am unable to get the height of the submenu. It never gets into the foreach loop at all. Could anyone please help
$(".menu-link").click(function () {
var $subnavdev = $(this).parent().sublings('sub-menu').siblings('level-2 plain')
 var totalHeight = 0;
    $subnavdev.find('li').each(function() {
      totalHeight += $(this).outerHeight(true);
    });
    alert(totalHeight);
});

Comment: There is a typo: `sublings()` - Is this in your code, or a copy/paste artefact?
Comment: Also, you may want to refer to the class name? Use a `.` prefix: e.g. `.siblings('.sub-menu')...`
Answer: Some of your class selectors were not specified correctly, plus there was a typographical error (all on Line 2).
Update - It also seems the siblings() methods may not be behaving as you intend them to...  - And I got the .level-2 selector wrong still - since you need another . before plain. (See below example)
By using the closest() method you can go up to the nearest parent (for example,
), then use find() to pick out all .level-2.plain items nested within that parent.
Remember that your $(this) inside the handler function refers to the handled element, (in this case the .menu-link item being clicked.
$(".menu-link").click(function () {
   var $subnavdev = $(this).closest('li').find('.level-2.plain');
   // ...
});

Comment: I tried your code. It does not get into the for each loop at all.

jquery get the height of the submenu


Finding the coefficient of $x^{10}$ in $(1+x^2-x^3)^8$

Question: The coefficient of $x^{10}$ in $(1+x^2-x^3)^8$. I tried to factor it into two binomials but it became way to long to solve by hand.
Comment: How can you write $10$ as a sum of $2$s and $3$s? There aren't too many ways
Comment: Answer: 476. :)
Comment: ^^ How did you found that out so quickly
Comment: https://www.wolframalpha.com/input/?i=(1%2Bx%5E2%E2%88%92x%5E3)%5E8
Comment: If you do the expansion as a binomial of $(1+f(x))^{n}$ then look at the $f(x)^{k}$ terms and consider which of them contains an $x^{10}$ term; it's only the k=4 and k=5 cases. Before that $(x^{2}-x^{3})^{3}$ only goes to $x^{9}$ and $(x^{2}-x^{3})^{6})$ starts at $x^{12}$. Then just work out the two coefficients.
Comment: There must be some another way as this question is from a 30min test
Answer: $10=2\cdot 5$ or $2\cdot 3+2\cdot 2$. Hence
$$
\binom{8}{5}+\binom{8}{2}\binom{6}{2}=476.
$$
Answer: More generally, the coefficient of  $x^{n}$ is given by
$$[x^{n}](1+x^2(1-x))^8=[x^{n}]\sum_{k=0}^8\binom{8}{k}x^{2k}(1-x)^k
=(-1)^n\sum_{n/3\leq k\leq \min(n/2,8)}\binom{8}{k}\binom{k}{n-2k}.$$
For $n=10$ we get
$$\sum_{4\leq k\leq 5}\binom{8}{k}\binom{k}{10-2k}=\binom{8}{4}\binom{4}{2}+\binom{8}{5}\binom{5}{0}=476.$$
Answer: The pertinent part of the polynomial expansion can be done by hand without too much fuss:
$$\begin{align}
(1+x^2-x^3)^8&=(1+x^2)^8-8x^3(1+x^2)^7+{8\choose2}x^6(1+x^2)^6-{8\choose3}x^9(1+x^2)^5+\cdots\\
&=(1+x^2)^5((1+x^2)^3-8x^3(1+x^2)^2+28x^6(1+x^2)-56x^9)+\cdots\\
&=(1+x^2)^5((1+3x^2+3x^4+x^6)-8x^3(1+2x^2+x^4)+28x^6(1+x^2)-56x^9)+\cdots\\
&=(1+5x^2+10x^4+10x^6+5x^8+x^{10})(1+3x^2-8x^3+3x^4-16x^5+29x^6-8x^7+28x^8-56x^9)+\cdots\\
&=\cdots+(5\cdot28+10\cdot29+10\cdot3+5\cdot3+1\cdot1)x^{10}+\cdots\\
&=\cdots+(140+290+30+15+1)x^{10}+\cdots\\
&=\cdots+476x^{10}+\cdots
\end{align}$$


Shadows around dark places after HDR conversion

Question: I have converted photo of local castle to HDR with Luminance HDR on Linux,
but it made shadows around towers of castle.

I tried dodge & burn tool in gimp, but it does not made smooth edges.. Is there any way, how to easily remove these shadows with gimp? Or any other tool on linux?
Thank you for all your advices..
Comment: I don't have a solution for you using GIMP / Photoshop, but consider transforming the image into HSV and thresholding the hue.  Take a look at this SO post by Rafael Monteiro to help you out: http://stackoverflow.com/questions/23252114/object-detecting-using-thresholding/23252800#23252800
Answer: It looks like an error in placing the images on top of each other.
It might also be a halo resulted by a spatially invariant filtering.


Django: can't add image from site, but it works from Django Administration page

Question: I try add image from form, on site. My forms work trough, django administration site perfectly. But on site, when I press submit button, page are reload, and I get the information that I need to add image again. All informations, after I reload page,  stay as the was, but added image disappear.
models.py
class UrlUpload(models.Model):
    """docstring for """
    title = models.CharField(max_length=255)
    photo = models.ImageField(upload_to='/home/mariusz/web/moje/moje/static/covers/')
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    description = models.TextField()
    category = models.CharField(max_length=100)

    def __unicode__(self):
        return self.title

forms.py
from django import forms

from .models import UrlUpload
class UrlUploadForm(forms.ModelForm):
    class Meta:
        model = UrlUpload
        fields = ['title', 'description', 'category','photo']

views.py
@login_required
def profile(request):
    if request.method == 'POST':
        form = UrlUploadForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_files(request.FILES['/covers/'])
            return HttpResponseRedirect('profile.html') #dodac potem strone potwierdzjaca wyslanie
    else:
        form = UrlUploadForm()
    return render_to_response('profile.html', {'form': form}, RequestContext(request))

profile.html

Dodaj Informacje

                            <form  method="POST" action="">{% csrf_token %}
                            {{ form|crispy}}
                            <input class="btn btn-success" type='submit' value="Dodaj" />
                            </form>

Comment: Try adding `enctype="multipart/form-data"` to your ``.
Comment: I just add this a second a go. But still is not working.
Comment: are you getting any sort of response from the server? I'm wondering if this is related to folder permission problem.
Answer: I change my views.py to
    @login_required
def profile(request):
    form = UrlUploadForm(request.POST, request.FILES)
    queryset = UrlUpload.objects.all()
    if form.is_valid():
        instance = form.save(commit=False)
        instance.save()
        print instance
    context = {
        "form" : form,
        "queryset": queryset

    }
    return render(request, "profile.html", context)

And it works right now.
Comment: it's a form to create an object or to update object already set?


Features - branch 2.x results in large info files that exceed the 'info' column limit in the 'system' table

Question: Original thread on DO (will keep it up to date)
Hello. I am currently developing a mid-to-large project. As i've done before, but using the 1.x branch, I use Features to track all structural and functional components of my site in order to be able to transfer them from my local installation, to the staging server, to the production server etc, while also having svn capabilities and tracking.
The current project consists of 45 Content Types with an average of 15 fields each. There are also ~15 vocabularies, ~10 fieldgroups, and a couple of tons of views.
The problem occurs when trying to track all this stuff with Features. It produces a large (initially, just alpha versions of the Content Types) .info file ( > 100K) which results in the following error:
PDOException: SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column 'info' at row 1: UPDATE {system} SET info=:db_update_placeholder_0 WHERE
// yada yada yada serialized array of the .info file
Which is totally natural seeing that the collumn is declared as a BLOB.
My question, is how should one go about to manage such a problem?
1) perform a ALTER TABLE system CHANGE info info LONGBLOB /* or MEDIUMBLOB */ NULL DEFAULT NULL? (Ouch)
2) Use branch 1.x instead which is less verbose in the .info file declarations?
3) Break down the project and track it in multiple features? (I'd avoid this cause it will make reverting those features a hellish job since one would depend on the other and vice versa)
4) ...?
I'd appreciate any input on the matter
Answer: The way I see it, you have options:
Features
Break your Features down into smaller Features.  Yes, this might make the dependencies a little more effort to manage, but a Feature containing that many content types, as well as other config does seem a little extreme.
If you do break them up, and are worried about dependencies, create a controller module to deal with them.  Every time you add/break down a Feature, add it as a dependency to this controller module, then make your new Feature depend on the controller module.
This means that all other dependencies will be inherited by the Feature, but you've only had to declare it in one place. When you then disable any part of your Feature, everything will get disabled - which is the same behaviour as having one monolithic Feature.
As an added bonus, if you perform updates to your Features that require hook_install or hook_update_N, they can go in the controller module.
Configuration Management
If the idea of breaking down your Features really sends shivers down your spine, then check out Configuration Management, which can do what you want (track EVERYTHING), and if pretty easily extensible if you are happy writing your own code. This is also the route Drupal 8 is taking/has taken with configuration management, so with this method you'll be future-proofing your own knowledge.
My personal preference is Features, but if you are looking for something that wouldn't involve you breaking down a huge Feature into smaller ones, then Configuration Management is a solid option.
Comment: Regarding your features break-down approach. My problem is pretty much the *order* in which i'll have to run the reverts on the new environment, not the dependencies per say. I mean if Feature A contains vocabularies that are used by fields declared in Feature B and C, and you revert B first, you might mess everything up. The "sub" features will need to be constructed in a way that will allow for a specific revert order, right?
Comment: Also, do you reckon option 1 could break anything in the process? Is there any drawback on having the `info` collumn with increased size?
Comment: It *shouldn't* matter.  If something gets reverted that depends on something else, it should move to "Needs Review" in the Feature UI.  Before you get a chance to notice this, the other Features should have also reverted and everything should be fine. I've used this approach before (broken down Feature that has managed to creep up in size), and the reverts were always fine. Any that weren't usually just needed another revert to prod it in the right direction.
Comment: I would be super wary changing things in the `system` table.  In fact, changing stuff like that on any contrib/core module table seems dodgy to me.  Say the next update to core changes that table in some way...your change will be lost, and your site will break.
Comment: Yeah I know the practice, I'd avoid it as well. I am only proposing since it seems like a small change that *should* not break anything or get reverted with any update. Anyway, thanks for your information, I'll spend the rest of the day testing tracking methods it seems. Configuration Management scares me a bit due to low installations and alpha versions but I'll give it a shot.
Comment: My system.info is already a LONGBLOB and I'm encountering this. It's probably my MySQL `max_packet_size` I guess?
Answer: The error happens, because info column is not long enough to serialize data from .info file of the module.
The solution includes:

breaking down your Feature module into smaller pieces (e.g. by separating components by type, or by base definition and its instances),
increasing size of info column.

If you decide to increase info column, you've the following possibilities:

apply simple Drupal core patch from: Increase size of info column in system table (and re-install Drupal),
run the following one-time off SQL query:
ALTER TABLE `system` CHANGE `info` `info` LONGBLOB /* or MEDIUMBLOB */ NULL DEFAULT NULL

more Drupal way is to change the field by using: db_change_field:

as one-time run, either from the code (e.g. as hook_update_X):
db_change_field("system", "info", "info", array('type' => 'blob', "size" => "big"));

check some field change examples in system_update_7055(),
or using drush:
drush ev 'db_change_field("system", "info", "info", array('type' => 'blob', "size" => "big"));'

or using appropriate hook (e.g. hook_system_info_alter) which could not work properly for system table,
on Drupal install, some example with profile install:
/**
 * Custom callback to recreate system table.
 *
 * This fixes Drupal issue when data is too long for column 'info'.
 * This happens for large feature modules.
 * @see: https://www.drupal.org/node/2580473
 */
function myprofile_install_system() {
  try {
    drupal_install_system();
  } catch (PDOException $e) {
    // This catches: SQLSTATE[22001]: Data too long for column 'info'.
    // Then we alter info column in order to resize it.
    db_change_field("system", "info", "info", array('type' => 'blob', "size" => "big"));
  }
  // Rebuild, save, and return data about all currently available modules again.
  system_rebuild_module_data();
}

myprofile_install_system();

however this could have some side effects.


Limit of measures, two questions on limits of integrals

Question: Suppose $\mu_n$ is a sequence of measures on $(X, \mathcal{A})$ such that $\mu_n(X) = 1$ for all $n$ and $\mu_n(A)$ converges as $n \to \infty$ for each $A \in \mathcal{A}$. Call the limit $\mu(A)$. I can show that $\mu$ is a measure. I have two questions.
First question. Do we have necessarily have that $\int f\,d\mu_n \to \int f\,d\mu$ whenever $f$ is bounded and measurable?
Second question. Do we have necessarily have that$$\int f\,d\mu \le \liminf_{n \to \infty} \int f\,d\mu_n$$whenever $f$ is nonnegative and measurable?
Thanks in advance!
Answer: First question is yes.
Given $|f|\leq M$ is bounded, we can approximate it uniformly using simple functions by cutting $[-M, M]$ into finitely many intervals $I_n$ with length $\epsilon$  and defining $\phi_n (x) =\sum_n \inf\{ I_n\}   \chi_{f^{-1}(I_n)}(x) $ . We would have $\|f - \phi_n\|_\infty \leq \epsilon$.
$$\lim_m\int f d\mu_m = \lim_m \lim_n \int \phi_n d\mu_m$$
since the limit in $n$ is uniform, which I mean for each $\epsilon > 0$ if we choose $n$ large enough and independent of $m$, we have
$$\bigg|\int_X fd\mu_m - \int_X \phi_n d\mu_m \bigg|\leq \int_X |f-\phi_n| d\mu_m \leq \|f-\phi_n\|_\infty \mu_m(X) \leq \|f-\phi_n\|_\infty \leq \epsilon,$$
by Moore-Osgood theorem, we can switch the two limits and we would have
 $$\lim_n \lim_m \int \phi_n d\mu_m = \int f d\mu.$$
The second question is also yes.
For each simple function less than $f$
we have
$$\int \phi d\mu_n \leq \int f d\mu_n$$
take the $\liminf$ we have
$$\int \phi d\mu \leq \liminf_n \int f d\mu_n$$
then take the $\sup$ over all simple functions less than $f$. By definition of Lebesgue integral, we have
$$\int f d\mu \leq \liminf_n \int f d\mu_n.$$
Comment: The phrasing of this is hard to follow. Could you clean it up a bit? Sorry.
Comment: the first part is using the idea that given $\lim_n \mu_n(A) = \mu(A)$ for all measurable sets, then we have $\lim_n \int_X \phi d\mu_n= \int_X \phi d\mu$ for all simple functions $\phi$ (can you show this?). And which part is hard to follow?


Bulk action on views only works for the administrator role?

Question: I have a view with a VBO field to execute a bulk operation over nodes.
The bulk operation for this VBO field is a rule component (which I have created) Get Voucher
This component execute some actions.
Now in the view I can execute the VBO only if I'm logged as a administrator. But not with any other role.
I make sure that the permission of all action are enabled. But the action for the component Get Voucher is not listed here.
The button for the bulk operation is shown but when I click it nothing happens.
Which other permission do I need to enable?
UPDATE 1: I know that the problem is related to the actions executed in the compoment. Here is the exported component
UPDATE 2: trying with a more simple component (just one action to show a message)
<code>{ "rules_test_registered_user" : {
    "LABEL" : "test registered user",
    "PLUGIN" : "rule set",
    "REQUIRES" : [ "rules" ],
    "ACCESS_EXPOSED" : "1",
    "USES VARIABLES" : { "node" : { "label" : "Node", "type" : "node" } },
    "RULES" : [
      { "RULE" : {
          "DO" : [ { "drupal_message" : { "message" : " Hello" } } ],
          "LABEL" : "first rule"
        }
      }
    ]
  }
}
</code>
Answer: If using Action Permissions, under Admin > People > Permissions, double check the "Execute action name" permission is enabled for the role(s).
It may also be that the user role needs permission to eval that php code in the Rule as well as possibly a userpoints grant points permission required.
Lastly, check the Rules module user permissions and also in edit form for the actions on the rule itself.
Comment: I've made sure all those permissions are enabled. But not working.
Answer: Solved but with some implications.
The problem was that I have to enable the permission to Edit the nodes listed in the view (vouchers content type).
I did that, but now this role will have permission to edit this type of node and this is not what I need.
I understand that vbo needs this permission because it assumes that the user will execute action in the node, but this not my situation, I need the action to just read a value of the node (labpoints field) and then execute an action in the user informations (deduct)(user userpoints). So I don't need that the user has the permission to edit the node at all.
I guess I'll use the field permission module to narrow the permissions for this content type.


Why is Darren Lehmann called 'Boof'

Question: Darren Lehmann has been named the new Australia cricket coach and lots of articles, including Wikipedia, refer to his nickname as 'Boof'.  However, I can't seem to find any reason for this nickname or any relation to Boof in cricketing jargon.  Is this a sporting or cricket reference or is this a none sport related nickname.
Comment: http://m.dailytelegraph.com.au/sport/cricket/how-aussie-cricket-coach-darren-lehmann-became-known-as-boof/story-fni2fnmo-1226774535793 Link above to an article explains it all.
Answer: It's nothing to do with cricket, in Australian slang 'boof' means head, typically used to refer to someone with a big head. Sometimes the term 'boofhead' is used, referring to someone big, burly and maybe a little bit stupid (or at least simple minded). To an Aussie, 'boof' is a natural nickname for someone like Darren Lehmann, who has a large bald head, is a tall man who always carried a bit of extra weight around the gut and who had a reputation as an aggressive, physical player both on and off the field.
When exactly Lehmann began being called Boof I do not know. It's possible that it was his nickname long before he became a successful cricketer. It is normal among groups of male friends in Australia for everyone to have a nickname that gets used far more than their real name. This is why all players in the Australian team always get a nickname, it's simply part of Australian culture.
Answer: Boof Lehmann was nicknamed by a schoolmate, John Giannotti, when he was 13. It was because he had a big head  and thus his mate called him "Boofhead" a common term in Australia for someone with a large head. In Boof's case, Boofhead soon became Boof. The nickname went from the schoolyard to the schoolroom and into general use very quickly.
His other cricket nickname was Shreck for obvious reasons.
Comment: Good answer, but do you have a source for this info?
Answer: According to this link here. It states-

Other Darren Lehmann facts include that he once did some racism and that his nickname is 'Boof'. If you're wondering as to the origins of this nickname, it's due to his uncanny resemblance to cult actress and Nineties video game TV programme presenter, Emily 'Bouff' Booth.
Comment: Interesting. Initially I thought this couldn't be right, since Emily Booth is unknown in Australia, however Lehmann was playing for Surrey around the same time Emily Booth was rising to fame in the UK (at least according to wikipedia). He might have got the name in England and then it stuck in Australia since it seemed appropriate for the reasons I mentioned. It's hard to know for sure, since the link you posted doesn't itself reference anything so it could just be someone else speculating on the internet. It is at least plausible anyway.

Why is Darren Lehmann called 'Boof'


$ f: X \rightarrow R^n$ continuous then the set $M=\{x\in X:f(x) \ne 0\} $ is an open set.

Question: Let $ f: X \rightarrow R^n$ continuous, where $ (X, d) $ is an arbitrary metric space. Prove or give a counterexample for the assertion that the set $M=\{x\in X:f(x) \ne 0\} $ is an open set.
I'm thinking this might be fake. In the discret metric it seems true. So I'm thinking of an any metric $d$ and for the special case with $ X = \mathbb {R} $ and $ n = 1 $.
I thought for the following functions:
1) $ f (x) = x \Longrightarrow M = (- \infty, 0) \cup (0, \infty) $. This set is opened.
2) $ f (x) = x ^ 2 \Longrightarrow M $ is an open set.
So I conclude that if the roots of $ f $ is a finite quantity, we have that $ M $ is open. Now if it is an infinite contable quantity, for example for $ f (x) = \sin x $, we have that $ M $ will be open.
So I thought of the following function
$$
f (x) = x \sin \left(\dfrac {1} {x}  \right), x \neq 0 \; \mbox {and} \; \;
f(x)=0, x = 0.
$$
The roots of this function get closer and closer to zero because the roots $ x \neq 0 $ are of the form $ x = \dfrac {1} {2k}$ with $ k \in \mathbb {Z} $.
I thought I would have a counterexample here because I know I have points of $ M $ and points of $ \mathbb{R} \backslash M $ each time closer to each other. But I have not been able to conclude that this is indeed a counterexample.
Comment: Did you know that if $f : Y \to Z$ is a continuous function and if $B$ is any open subset of $Z$, then $f^{-1}(B)$ is an open subset of $Y$ (this is taken as the definition of continuity in abstract topology, and is easy to prove using the metric definition of continuity). Now take $B = R^n \setminus \{0\}$.
Comment: @Rob Arthan I got it. Thanks too much!!! Then this result is true and I understand the proof. I was thinking this is not true and and my attention was only on that. So, thanks too much!!
Answer: $$M = f^{-1} \left( \mathbb{R}^n \setminus \lbrace 0 \rbrace \right)$$
is open as the preimage of the open set $\mathbb{R}^n \setminus \lbrace 0 \rbrace$ by the continuous application $f$.


Cyclic class initialization

Question: In java a class is loaded just before an object of the class is created.And a class is loaded only once during the entire duration of the program.
When this happens , statics are initialized and static blocks are executed.
This can be cyclic ; before a class is fully initialized , I created an object of the class in the class iteself.
For eg:
public class MyTestClass{

public static MyTestClass myTest= new MyTestClass();

}

public class Beginner{

public static void main(String[] args){
System.out.println(MyTestClass.myTest==null);
}
}

When I call MyTestClass.myTest in the main() for the very first time ; MyTestClass will be in the process of loading and I try to create an object of MyTestClass while it's being loaded ; should that not create a cyclic class loading and this can be infinite?
How does this get handled in java?
Comment: That code doesn't compile. Please post real code with your question.
Comment: Do you mean `public class Beginner {` instead of `public void Beginner {`?
Comment: i think he mean it that way :-)
Answer: The sequence of events is like this:

The class is loaded and validated, all static memebers are set to null or 0
The static initializers and blocks of the class are executed (in lexical order)
The code that needed the class proceeds

The execution of initializers in your case includes
public static MyTestClass myTest= new MyTestClass();

That means the code in the main will see MyTestClass.myTest that is not null.
The only time you'll see MyTestClass.myTest that is null is in the constructor of the the MyTestClass instance that is created in the static initializer.

Cyclic class initialization


Exception Handling in HttpHandler ASHX file

Question: I'm using ASHX file to creating images in a dynamic way.
 I added a line of code to throw an exception in my ashx file. if I browse to ashx file directly, my application_error in global.asax is working fine to handle the error.
my problem is application_Error is not working when I use this handler in another page. like in show.aspx if I put:

there would be no errors, just a blank image.
I even tried a custom httpmodule to handle errors, but no luck.
so how can I catch errors in ashx file?
Update: to make things more clear, for exception catching I have 2 options in mind.
first is to redirect user to another page if for ANY reason, image generation goes wrong.
second is to replace the image with my static png file again if ANY reason caused some errors in ashx file.
that's why I thought using httpapplication.error would help. my httpmodule is like:
Public Sub Init(ByVal context As System.Web.HttpApplication) Implements system.Web.IHttpModule.Init
    AddHandler context.Error, AddressOf OnError
End Sub

Private Sub OnError(ByVal sender As Object, ByVal e As EventArgs)
    Dim app As HttpApplication = CType(sender, HttpApplication)
End Sub

So how can I achieve these in OnError ?
Comment: this seems to be a misunderstanding of html?
Comment: what is your desired behavior when an error occurs?
Comment: @zac redirect to another page
Answer: I believe the exception is being thrown as expected. However, now the exception details are serving as the data for your , which will display a 'broken' image.  I would suggest serving up a different, static image if there's an error in the handler and log the error in an external text file or some other data source.
Comment: what if I want to use redirect ?
Comment: Hmm, ideally, how would you like it to work? If the generated image throws an error, redirect the user?
Answer: You can add a catch block as normal, and in the event of an error, you could display another default image.
Comment: I used several external APIs and a bunch of classes to generate this image. I dont like to have tens of try-catch blocks


How to access the bookmark panel using javascript in firefox?

Question: I am developing a firefox addon and I have to access the bookmark panel (to see it go to View->Sidebar->Bookmarks) and add a menu item to its context menu and when the menu item is clicked, get the item it was clicked on.
Por example:
You open the bookmark panel and right click on Most Visited item and click on my menu item, then I want to know that the Most Visited item was clicked.
I tried the following code but with no success:
var bookmarkMenu = document.getElementById('menu_bookmarksSidebar');
var observer = document.createElement('observes'); //Observe when the bookmark panel shows
observer.setAttribute('element','viewBookmarksSidebar');
observer.setAttribute('attribute','checked');
observer.addEventListener('broadcast',function(event){
console.log("Bookmark panel showing " + event.target);

var sidebarWindow = document.getElementById("sidebar").contentWindow;//Try to get the sidebar window
if(sidebarWindow == null){
console.log("NULL");
}
var bar = sidebarWindow.getElementById("placesContext");
if (bar == null){
console.log("NO Sidebar window");
 }

});
bookmarkMenu.appendChild(observer);

I know how to access the browser window but I am unable to access the sidebar window.
According to bookmarkPanel.xul, the id of context menu of that panel is "placeContext" but I can't access it. How I can I access the right-clicked bookmark/element?
event.target always gives me [object xulElement], how can I see what element it is?
I tried this:
var sXML = new XMLSerializer().serializeToString(event.target);

But doesn't seem to work
Thanks
Comment: Need to do with javascript; it's an addon. Thanks
Comment: Can teh solution be based on using xul overlay? or you need to do it with js?
Answer: I think changing
var bar = sidebarWindow.getElementById("placesContext");

to
var bar = sidebarWindow.document.getElementById("placesContext");

will make a difference :-)
Comment: Hello, i will try it but I also tried with  var sidebarWindow=document.getElementById("sidebar").contentDocument; And it doesn't work. Thanks


How is content published from Author to publish Environment in CQ5?

Question: I have installed two instances of CQ5-quickstart.jar . One as Author and one as Publish.
I have a very basic query. If I publish/edit some content in the Author Environment, HOW will it be visible in my Publish environment ?
I mean, is the flow of code/data between these two instances mentioned somewhere that I've missed ?
Answer: You'll need to 'Activate' the page first. Only then it will be available on the Publish environment. Read this page please .
http://dev.day.com/docs/en/cq/current/wcm/page_publish.html
Answer: Hi you could also check on configuring replication agents
http://dev.day.com/docs/en/cq/current/deploying/configuring_cq.html#Replicating from Author to Publish
Answer: First check the publish environment in Replication properly and test connection is established or not.If it is success than activate content.While activating un check those two options and click activate than the changes are can see in publish.
If any modified jsp code need to build in package and push to live.
Thanks
Ramesh v


What is a parallel mode?

Question: What is a parallel mode? How are the parallel modes used in composition and/or improvisation?
Answer: Two modes are parallel if they share the same tonic. That is, D Major, D Minor, D Dorian, and D Mixolydian are all parallel modes. Using a parallel mode will cause a chromatic alteration to your usual key signature. For example, Dorian uses #6 and Phrygian uses b2 (when compared to a minor key or Aeolian mode), while Mixolydian uses b7 and Lydian uses #4 (compared to a major key, or Ionian mode).
By way of contrast, two modes are relative if they share the same key signature. D Major, B Minor, A Mixolydian, and E Dorian are all relative modes. Using a relative mode will not generally cause chromatic alterations, but will cause the tonic to shift to a different note.
In composition (or improvisation) parallel modes allow the use of borrowed chords, via modal mixture, to add color to piece. One example would be the use of the minor iv chord in place of IV, in the major key. Another example might be bIII, bVI, and bVII chords which are common in certain styles of rock.
The most common form of parallel modes is between parallel major and minor keys. Some pieces  in a minor key will borrow the parallel major I chord at the very end, a technique known as a Picardy Third. In some minor key symphonies, its possible to find the entire final movement is in the parallel major (such as Beethoven's 5th). Some Baroque composers such as Vivaldi would occasionally repeat a major theme in a parallel minor to give it a new dimension. Even the ascending melodic minor scale can be thought of as a form of modal mixture, borrowing its notes from the parallel major.
In short, they give you new harmonic "colors" to use, without forcing you to change your tonic.
Comment: hey, its not a #6, its a ♮6
Answer: To expand a little on Caleb's great answer, let's take C major. No key signature, as all notes are 'white' - no # or b. Parallels are - C minor with 3 b. C Dorian with 2 b.C Phrygian with 4b, C Lydian with 1 #, C Mixolydian with 1b, C Aeolian with 3b (as minor), C Locrian with 5b. This example is the 'ordinary' modes, showing that home or the root of C can involve loads of other notes which can manifest themselves when the tune moves to a parallel mode, still 'at home' in C something.
Answer: Same roots but different notes. C Ionian, C Dorian, C Phrygian,  etc
Comment: I sense a potential for this answer to be expanded.

What is a parallel mode?


Create proof of purchase codes

Question: I've made an Ubercart store for our schoolwear. We can't do online purchasing because we're not set up for it.
What happens right now is that when someone buys something from the catalog, they have to go to the office to pay for it. Then, the receipts get sent to the class running the store as proof the order has been paid for.
Here's what I'd like to do with our ubercart:

I create random codes somehow for proof of purchase in the ubercart system. Print them out, and give to the office.
Customer pays at the office for their item (e.g. a sweatshirt) and receives a random code from the office after purchase.
Customer goes to the online catalog and places their order (e.g. sweatshirt size, color, etc).
Customer goes to cart checkout and cannot complete checkout until they type in the random code they got from the office.
The class running the store gets the order through ubercart, and sees the random code as proof that the order has been paid.

I know it's a dumb system, but it's all we have. Is there a way to generate these random codes and have the customer put theirs in at the checkout?
Answer: You can create a new node type "vouchers" and use UUID module to add uuids to these nodes. When the office creates a new voucher it will automatically be assigned a uuid which you can then use as your code to give the student.
When the student shows the store their code the store can lookup that voucher in a Vouchers view using the uuid filter. Then the store can mark the voucher with a boolean "Used" custom field to show they are redeemed.
Comment: Longboardnode, I really appreciate your answer; however, I am not a hardcore Drupal user, and after reading the page for the UUID module, I have no clue how to use it. If it helps: I experimented with [Webform Invitation](https://www.drupal.org/project/webform_invitation) with a webform acting as the product page, and that worked beautifully. If you have any other suggestions, I'm all ears. Thanks.
Comment: If webform invitation worked for you, great!! Re UUID, once you install and enable the module, UUIDs will be automatically added to all nodes, you don't have to do anything to make that happen.
Comment: Okay, I didn't realize that's what UUID did. I'll have to play with it to see what it can do for us. Thanks for the info! Yes, the Webform Invitation worked well, but I was hoping for a similar module for Ubercart. Thanks again for your help!
Comment: For anyone else in this boat, I found a workaround. I installed the balance_tracker module and the e-balance module. In Ubercart, I enabled only the e-balance payment method. Students go to the office, the secretary logs onto our website, takes payment (cash or cheque), and adds the payment in the student's balance tracker account as a credit. Student returns to the site, places order, and now has sufficient 'credit' to place the order. Hope this helps someone else out.

Create proof of purchase codes


Counting number of 11 digit numbers

Question: How many even 11-digit numbers (no leading zeros) have at least three 3's?
First I tried to find the total number of 11-digit even numbers, then I have subtracted number of 11-digit numbers which have at most two 3's.
But this process looks lengthy. If there is an alternative, let me know.
Comment: @abhishekchaudhary 24 looks too less..!!!!
Comment: @abhishekchaudhary Can you please elaborate the solution?
Comment: Your approach is correct and its the easiest try using permutations and you should get your answer
Comment: I hope you subtracted the number of $11$-digit _even_ numbers with at most two $3$'s.  Note that "at most two" is $0$, $1$ or $2$.
Comment: Also, you'll probably want to look separately at the cases where the first digit is or is not $3$.
Comment: @abhishekchaudhary your "solution" in your initial comment (*even if replacing C's with P's*) is very incorrect.  I recommend deleting your comment to avoid confusing more people.  You seem to have completely ignored that we are working in base ten and that we are looking for even numbers specifically.
Comment: @JMoravitz ok sir
Answer: Your idea is a good one and is the one that I would recommend.
Let us look at the sub-problem of counting how many even 11-digit have exactly two $3$'s:
Break into cases based on whether the leading digit is a $3$ or if it is a non-$3$

Case 1: The leading digit is a $3$

Set the first digit as a $3$ (One option)
Choose the final digit, it must be even (five options)
Choose the location of the remaining $3$ (nine options)
From left-to-right, choose the value of each remaining non-3 digit (nine options each)

Case 2: The leading digit is not a $3$

Choose the first digit remembering it can't be $3$ and it can't be $0$ (eight options)
Choose the final digit, it must be even (five options)
Choose the location of the two threes (nine choose two options)
From left-to-right, choose the value of each remaining non-3 non-leading digit (nine options each)

 $5\cdot 9^{9}+8\cdot 5\cdot \binom{9}{2}\cdot 9^7$

Apply multiplication principle and addition principle to arrive at the total number of even 11-digit numbers containing exactly two threes.  Do so similarly for the other subproblems of having exactly one three or exactly zero threes.

Counting number of 11 digit numbers


Get fields to appear in fields list, arguments list and filters list in view

Question: I am using hook_form_alter and adding a extra form field to drupal node form. All works fine, but in view this field is not show up. How do i add this field?
Answer: Instead of adding form element using hook_form_alter use CCK field. View will not understand your custom field but a CCK fields are integrated in views.
EDIT
Please check for Tag User module.
Comment: But i am adding a user autocomplete or say tagging thing while adding a node. this is totally customized. So i need to add it using alter functions.
Answer: To make you understand the difference between a form field and a CCK field in a Node form relationship:
Formfield
You could add a formfield to a node form, but this would only add a <input> field to your form. After adding this field, you could use Drupal's Form API (Drupal.org Form API quickstart guide) to for example validate the fields, or process them in any way you see fit. To be clear, without any validation, post-processing, etc. your field will not be used in any way.
That being said, a form field is only interesting when you make a custom module, which needs some additional information about a node which will be created / editted.
CCK field (Simply: Fields in Drupal 7)
You have numerous types of fields (eg. Text, number, references, file, etc...) which you can assign to different node types. For example, you could add a imagefield field to a node-type "Employee" to make it possible to add a picture of a employee.
I hope this clears it up a bit for you.
edit
I noticed you where trying to add a "user autocomplete" field? Try out the CCK User reference field, it's in the base module if you're using Drupal 6. If you're using Drupal 7 you'll need a separate module: References.
Comment: I gave both, **CCK** for D6, **Fields** for D7
Comment: He needs solution for D6


How to remove needless quotes on AgensGraph?

Question: There is quotes on result of AgensGraph.
I don't want ne
agens=# match (n) return n.value;
 value
--------
 "test"
(1 row)

I expect function or procedure for trimming quotes.
Comment: Found a duplicate here: https://stackoverflow.com/questions/54884620/what-is-the-casting-in-agensgraph-ver-1-3-double-quote but unfortunately, even that is unanswered. Maybe you can put a comment there to find out if OP has found some solution!
Answer: You can use function "btrim" for removing needless quotes.
agens=# select btrim( n.value::text, '"' ) from ( match (n) return n.value ) as n;
 btrim
-------
 test
(1 row)

You must use trim on SQL part of quires for removing quotes.


My table half-exists. Can't drop it

Question: I have a table that is taking up quite a bit of space even though it has no rows. I also dropped it a while ago. When I try to drop it now, it says the table doesn't exist.
It shows up in user_tables. Also, all of its partitions and indexes show up in user_objects.
It's not in the recycle bin either.
What's going on here?
EDIT:
Here is the result of user_tables:
TABLE_NAME  TABLESPACE_NAME CLUSTER_NAME    IOT_NAME    STATUS  PCT_FREE PCT_USED   INI_TRANS   MAX_TRANS   INITIAL_EXTENT  NEXT_EXTENT MIN_EXTENTS MAX_EXTENTS PCT_INCREASE    FREELISTS   FREELIST_GROUPS LOGGING BACKED_UP   NUM_ROWS    BLOCKS  EMPTY_BLOCKS    AVG_SPACE   CHAIN_CNT   AVG_ROW_LEN AVG_SPACE_FREELIST_BLOCKS   NUM_FREELIST_BLOCKS DEGREE  INSTANCES   CACHE   TABLE_LOCK  SAMPLE_SIZE LAST_ANALYZED   PARTITIONED IOT_TYPE    TEMPORARY   SECONDARY   NESTED  BUFFER_POOL ROW_MOVEMENT    GLOBAL_STATS    USER_STATS  DURATION    SKIP_CORRUPT    MONITORING  CLUSTER_OWNER   DEPENDENCIES    COMPRESSION COMPRESS_FOR    DROPPED READ_ONLY
jeremy_ALLK             VALID                                                   N                                            8           1      N   ENABLED         YES     N   N   NO      ENABLED NO  NO      DISABLED    YES     DISABLED            NO  NO

When I do: "drop table jeremy_ALLK", I get:
Error starting at line 7 in command:
drop table jeremy_ALLK
Error report:
SQL Error: ORA-00942: table or view does not exist
00942. 00000 -  "table or view does not exist"
*Cause:
*Action:

Comment: Can you cut and paste from SQL*Plus where you are querying `user_tables` to see the table and then then attempting to drop the table causing the error?  Are you sure that you're trying to drop the same table that is in `user_tables` (particularly if you used a case-sensitive table name)?  Are you using the fully qualified table name in your `DROP` statement?  What you're describing doesn't make sense unless your database is pretty seriously corrupted.
Answer: You're getting caught with the case sensitivity of the table name. In Oracle, all of these commands are exactly the same:
drop table jeremy_ALLK
drop table Jeremy_ALLK
drop table JEREMY_ALLK
drop table "JEREMY_ALLK"

That is to say, the table name is by default "lifted" to upper case. Since you have lower-case letters in your table name you'll have to specify the drop statement like this:
drop table "jeremy_ALLK"

The double-quotes are used whenever you have a database object named with lower-case letters or spaces(!).
Answer: OK.  The problem appears to be that you created the table with a case-sensitive table name (note that the table_name in user_tables is in mixed case).  If you do that (and I would strongly suggest not doing that in the future), you need to use the case-sensitive table name everywhere.  So your DROP TABLE statement would need to be
DROP TABLE "jeremy_ALLK";

My table half-exists. Can't drop it