classical solutions of PDE with mixed boundary conditions

Question: Nowadays people usually consider PDEs in weak formulations only, so I have a hard time finding statements about the existence of classical solutions of the Poisson equation with mixed Dirichlet-Neumann boundary conditions.
Maybe someone here can help me and point to a book or article where I can find sufficient conditions on the right hand side that guarantee the existence of a $C^2$ solution.
Note that the unique solvability in $H^1(\Omega)$ follows, e.g., from the paper on discrete maximum principles by Karatson and Korotov in Numer. Math. 99 (2005), 669-698. So (a slightly more precise version of) my question boils down to finding conditions such that this solution is actually C^2 in the interior and continuous differentiable at the boundary.
Comment: Have you looked at [Troianiello, *Elliptic Differential Equations and Obstacle Problems*](http://books.google.at/books?id=lGfG5rxGywIC)? Chapter 3 might have something on Hölder regularity, and if I recall correctly, he treats mixed boundary conditions (although only homogeneous ones).
Answer: I believe the papers by Gary Lieberman will answer your question: one is Mixed boundary value problem for elliptic and parabolic differential equations of second order. Another one is Optimal holder regularity for mixed boundary value problems. Thanks
Comment: Thanks. These and especially their reference to Azzam and Kreyszig are very useful!
Answer: From my rather primitive knowledge of PDEs, for a well-posed mixed boundary value problem for Poisson equation, I think the effect of the Neumann boundary condition on the regularity of the solution is equivalent to Dirichlet boundary condition of one less differentiability.
Intuitively speaking(most likely I am wrong here), if the uniqueness of the mixed problem can be established(via maximum principle for example), and enough regularity has been assumed for the $u$ to be well-defined on $\Gamma_N$, then it is same that we have $u = H g_N$ on $\Gamma_N$ where $H$ is the Neumann-to-Dirichlet map. If we know all the Dirichlet and Neumann data, the regularity of the solution depends on the regularity of the boundary like the classical theory states.
For reference, in the book Elliptic Partial Differential Equations of Second Order by Gilbarg and Trudinger, they use an entire chapter six to discuss the classical Schauder estimate for Hölder continuous solutions with various boundary conditions, in Section 6.7 of that book, Lemma 6.27 reads the solution to the Neumann problem of Poisson equation is $C^{2,\alpha}(\bar{\Omega})$-regular if Neumann data $g_N$ is $C^{1,\alpha}$, $f$ is $C^{0,\alpha}$, and the domain is $C^{2,\alpha}$. Now back to the regularity estimate for the Dirichlet problem in Theorem 6.19, if Dirichlet data $g_D$ is $C^{2,\alpha}$, other the conditions are the same, we will get the same $C^{2,\alpha}$-regularity for the solution. Hence I am guessing for mixed boundary problem we should have a similar result that a $C^2(\Omega)\cap C^{1,1}(\bar{\Omega})$ solution should require a $C^2$ domain, $C^1$ Neumann boundary data, and $C^2$ Dirichlet boundary data.
Comment: Thanks. I hadn't realize before that the pure Neumann case is in Gilbarg/Trudinger which I generally know quite well. I still hope to get info on the mixed case from somewhere....


How to know the convergence of $\sum_{n=1}^{\infty} a_n$?

Question:
Let $\sum_{n=1}^{\infty} a_n$ be a series of positive terms. Show that if
$$\lim_{n \to \infty} n \log \left( \frac{a_n}{a_{n+1}} \right) = g > 1$$
then $\sum_{n=1}^{\infty} a_n$ is convergent.

Consider $\lim_{n\to\infty}\left|\frac{a_{n+1}}{a_{n}}\right| =L<1$ convergence:
\begin{align*}
\lim_{n\to\infty}\left|\frac{a_{n+1}}{a_n}\right|& =\lim_{n\to\infty}e^{\log\left|\frac{a_{n+1}}{a_n}\right|}  \\
&=e^{\lim_{n\to\infty}\log\left|\frac{a_{n+1}}{a_n}\right|} \\
&=e^{\lim_{n\to\infty}\frac{\log\left|\frac{a_{n+1}}{a_n}\right|}{1/n}} \\
&=e^{-\lim_{n\to\infty}\frac{\log\left(\frac{a_n}{a_{n+1}}\right)}{1/n}} \\
&=e^{-\frac\theta n} \\
&\approx e^{0} \\
&=1
\end{align*}
and I don't know how to next step.
Comment: You have a number of recent questions, and they generally look like homework questions. Can you let us know what you are working on and why so that we may best help point you in the right direction?
Comment: You should show what you have tried so far.
Comment: Your proof is not correct.
Comment: how to proof is right
Comment: @dream Assuming $g$ finite the given condition implies that the ratio $\frac{a_n}{a_{n+1}}\to 1^+$, form here we can proceed for a proof.
Comment: This is almost unreadable on a smartphone. Put that long sentence out of aligned environment and use $\exp(\cdot)$ function instead of $e^\cdot$.
Answer: We have that for $g\in \left(1,\infty\right)$
$$n \log \left( \frac{a_n}{a_{n+1}} \right) \to g  \implies \frac{a_n}{a_{n+1}}\to 1^+$$
then
$$n \log \left( \frac{a_n}{a_{n+1}} \right)=n \left( \frac{a_n}{a_{n+1}} -1\right)\frac{\log \left( 1+\left( \frac{a_n}{a_{n+1}} -1\right) \right)}{\left( \frac{a_n}{a_{n+1}} -1\right)}\to g$$
which implies
$$n \left( \frac{a_n}{a_{n+1}} -1\right)\to g$$
and for Raabe's test the series converges.
To complete the proof we need to consider the case with $g=\infty$.


Export blocks with features extra

Question: I installed the Features extra module to export custom made blocks in my Drupal 7 environment. But for some reason, it doesn't work...
What I do is the following:

I create a custom block
I give it a machine name, description, title and body, just like it's required.
I go to Structure - features - Create feature
I create my feature by clicking the custom block under FE Block
The fe_block dependencies fills in automatically.
I download the feature and place it in /sites/all/modules/features
In my install profile I add this line: dependencies[] = custom_blocks
I try to reinstall the website and... nothing!

The blocks aren't showing up in my Block-page, but the feature is... What am I doing wrong in this process? Do I need to enable something or install an extra module in order to get my custom blocks exported?
Answer: Alternative:
Use the Panels module to get the ability to create "Mini-panels" which function as equivalents to the standard Drupal block.
I believe there is much better support for exporting mini-panels into Features, since exportability was a key design component for the Panels module.
Personally, I've been successful using Panels, mini-panels, and Features.
Answer: IIRC, you can't put drupal blocks into features without patching it.
Have a look at the Boxes module, this is a replacement for the blocks system and is compatible with features.

Boxes module is a reimplementation of the custom blocks (boxes) that the core block module provides. It is a proof of concept for what a re-worked block module could do.
The module assumes that custom blocks are configuration, and not content. This means that it is a reasonable action to ask for all blocks at one time, this is in fact exactly what the core block module does.
Boxes provides an inline interface for editing blocks, allowing you to change the contents of blocks without going to an admin page.
Boxes provides exportables for its blocks via the (required) Chaos tools module. This allows modules to provide blocks in code that can be overwritten in the UI.
Answer: Try upgrading your Features Extra module. Or try Blockexport module instead.
Answer: I think that you need to enable your features.
Use drush, it's an interesting tools for drupal

drush en your_feature_name.

Export blocks with features extra


C# List property unresponsive to adding new elements

Question: Would you help me understand why before exiting the Main function the repository.Courses is null, even though I had just added a course to the repository by calling  repository.AddCourse(course); before exiting? How would I correct this? I think it may have to do with how the Courses property is defined (getter and setter). In teh getter I want to initialize by an empty list only if it's already null, otherwise I want to return the existing list. In the setter I want to assign a value - this should be correlated with the possibility of adding to list.
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{

    class Repo
    {

        public IList<Course> _courses;

        public IList<Course> Courses
        {
            get
            {
                if (_courses == null)
                    _courses = new List<Course>();
                return new List<Course>(_courses);
            }
            set
            {
                _courses = value;

            }
        }
        public void AddCourse(Course course)
        {
            course.Id = Courses.NextId();
            Courses.Add(course);
        }

        static void Main(string[] args)
        {
            Repo repository = new Repo();
            var path = "C:\\a1\\demos\\demo1-after\\ConsoleApplication1\\json1.json";
            var reader = new StreamReader(path);

            string text = reader.ReadToEnd();
            var course = JsonConvert.DeserializeObject<Course>(text);
            repository.AddCourse(course);

        }
    }

    public class Course : IEntity
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Author { get; set; }
        public Course(string n, string a)
        {
            Name = n;
            Author = a;

        }
    }

    public interface IEntity
    {
        int Id { get; set; }
    }
    public static class Extensions
    {
        public static int NextId<T>(this IList<T> list) where T : IEntity
        {
            return list.Any() ? list.Max(x => x.Id) + 1 : 0;
        }
    }
}

Comment: `return new List(_courses);` in the `get` **always** returns a new list and `Courses.Add` does not call `set`.
Comment: Simpler version: `public IList Courses { get; set; } = new List();` (you then don't need the backing variable, and lazy creation of the empty list does not give you much here).
Comment: You should return the current list (`_courses`) as @crashmstr says instead of a new list.
Answer: The problem here is that your get is always returning a new list, rather than the backing field.
Try this instead:
get
{
    if (_courses == null) _courses = new List<Course>();
    return _courses;
}

Answer: I noticed that the getter of Courses returns a new list rather than a reference to the field. Is that because you don't want anyone from outside the class to be able to add anything to the list except through AddCourse?
In this case the fix I'd recommend is to change AddCourse to address the field directly rather than the property, as currently it's adding the item to the new list created by the getter rather than to the list referenced by your field.


How do I connect to an RD farm using the farm name?

Question: New to RD... I'd think this a very obvious question but my web searches come up dry...
I've got two Server 2012 servers, call them ALPHA and BETA.  ALPHA is an RD Gateway, RD Connection Broker, and RD Session Host.  (I imagine this system doubling as a session host could be trouble under heavy load, but this is only a trial.)  BETA is simply an RD Session Host.
I've got ALPHA and BETA in a collection, we'll call "My Collection".
If I set my RD client to use the gateway, and then enter "ALPHA.domain.com" where it says "Computer:" on the connection dialog, I invariably get a session on ALPHA.
If I enter "BETA.domain.com", one of two things happen.  Either I get a session on BETA, or I get an error saying:

Remote Desktop Connection cannot connect to the remote computer.
The remote computer BETA.domain.com that you are trying to connect to is redirecting you to another remote computer named ALPHA.domain.com.  Remote Desktop Connection cannot verify that the computers belong to the same RD Session Host server farm.  You must use the farm name, not the computer name, when you connect to an RD Session Host server farm.
If you are using an RDP Connection provided to you by your administrator, contact your administrator for assistance.
If you want to connect to a specific farm member to administer it, type "mstsc.exe /admin" at a command prompt.

This message suggests I use the "farm name", but if I try entering "My Collection" as the computer name, it firstly truncates this to "My", and then basically tells me there's no such computer.  There wouldn't be one called "My Collection", either.
(Of course, the Help button is no help.)
Questions:

What am I supposed to do on the client in order to connect to whichever of the two hosts is least busy?
Should the redirect mentioned in the error message have worked, and if so, what things should I look at to explain why it didn't?

Thank you for any insight!
Answer: Kevin, to answer one point you wrote:
"I imagine this system doubling as a session host could be trouble under heavy load, but this is only a trial."
Not at all, the broker service is a very lean service which all it does is poll the various  servers in the farm and maintain who is logged on where in a small database and tell where to go.
There are a few steps in setting up RD Session Farms.
This is the best starting point:
http://technet.microsoft.com/en-us/library/cc753891.aspx
But in essence:
1) Create a round robin dns entry with the farm name which has the IP of all your session host servers.
2) On the broker, add all session host (alpha + beta in your case) to the group Remote Desktop Server (may be slightly different name, I don't have it in front of me).
3) Setup the Remote desktop service telling it that it is part of a farm.
4) Enable the policy of "one session per user" - otherwise you may have a situation where a user has a session on each server.
Then with all that, on the client you just go to the farm name (since it's in DNS).
Your client will be directed to one of the entry in the round robin dns. They will get a logon prompt. The server they got will then check with the broker to see whether they should let the user on or redirect him to a different server and proceed.
If you are using pre-win7 clients, then they will get a repeated login screen if they get redirected. A bit annoying my users are saying! But on win7+ clients then it does not do that.
Comment: Thank you for the rundown.  I'll give this a try.  I notice the link you mention is for 2008 R2.  Have you tried this on Server 2012?  I think I read somewhere there were some significant changes to load balancing in 2012.  As for sharing the roles, the broker probably is pretty lightweight but I'd be a bit more worried about the gateway.  If my understanding is correct, it carries and encrypts traffic for all the hosts (for clients which need to connect through a gateway, which in our case is most of them).
Comment: Good point on the gateway - that is something I did not try (don't use it as I don't need it accessible through web based protocol).


Parameters for the SPJobDefintion constructor

Question: What are parameters for the SPJobDefintion constructor?
Answer: There is no better answer to this question than the original MSDN documentation: SPJobDefinition Constructor


O que é o meta charset no HTML?

Question: Alguém me pode explicar este código de HTML5?
<meta charset="utf-8">

Para que é que serve e por que é que é utilizada esta norma?
Comment: ["O Mínimo Absoluto Que Todo Desenvolvedor De Software Absolutamente, Positivamente Precisa Saber Sobre Unicode E Conjuntos de Caracteres (Sem Desculpas!)"](http://local.joelonsoftware.com/wiki/O_M%C3%ADnimo_Absoluto_Que_Todo_Desenvolvedor_De_Software_Absolutamente,_Positivamente_Precisa_Saber_Sobre_Unicode_E_Conjuntos_de_Caracteres_%28Sem_Desculpas!%29) ;)
Comment: Todo arquivo de texto possui um código de caracter, o mais conhecido é o ASCII e nada mais é um indicador de qual foi a logica binária utilizada para armazenar as letras e numeros em bits. Se voce usar uma logica CHARCODE diferente para gravar do que o que é utilizado para Exibir, começam a dar aqueles caracteres ilegíveis.
Answer: Segundo a especificação do HTML, o elemento <meta>, que deve sempre estar no , "representa vários tipos de metadados que não podem ser representados com os elementos title, base, link, style ou script" tradução livre. Exemplos desses metadados são resumo do conteúdo, palavras-chaves, indicações a robôs de busca, entre outras.
Ele pode ter um atributo content, e deve ter um atributo name, http-equiv ou charset (e nunca mais de um entre esses três). No caso de haver um charset, ele é usado para indicar o formato de codificação de caracteres usado no documento.
Para além dos 128 caracteres básicos do ASCII, um mesmo símbolo gráfico pode ser codificado internamente de maneiras diferentes. Isso vale, por exemplo, para todos os caracteres acentuados do português. Se um arquivo HTML é salvo com a codificação Latin 1 (ISO 8859-1, ou Windows 1252, que é similar), o caractere ã utiliza apenas um byte para ser armazenado. Já em UTF-8, o mesmo caractere utiliza 2 bytes, com valores diferentes do byte usado em Latin 1. Por isso, se você mandar o browser exibir com uma codificação e o documento estiver sendo servido com outra, os caracteres especiais quebram.
É importante lembrar que o elemento <meta> não deve ser o principal método a ser usado para indicar ao browser qual o charset utilizado. O método preferencial é que o servidor envie um cabeçalho HTTP com essa informação. O uso de <meta> é uma segunda linha de defesa contra problemas de encoding – altamente recomendada, não deixe seu HTML sem isso (veja por exemplo o caso mencionado pelo Miguel Angelo: um HTML pode ser aberto diretamente, e não enviado por um servidor, e nesse caso não haveria cabeçalho com indicação do charset usado, não fosse a presença desse elemento do HTML).
Comment: @Tiago: Você pode usar o [fiddle](http://www.telerik.com/download/fiddler), que é um programa para visualizar as requisições feitas, o que permite ver os headers.
Comment: @Tiago Depende do browser. No Chrome, nas ferramentas de desenvolvedor, aba "Network", você pode ver a lista de todas as requisições, e para cada um pode ver os cabeçalhos de requisição e resposta.
Comment: +1 por indicar que essa não deve ser usada como a principal forma de indicar a codificação, apesar de eu achar que sempre deve estar presente por motivo de manter a codificação ao salvar o arquivo por exemplo.
Comment: Incluí outra frase no final reforçando que o uso do meta charset também é recomendado.
Comment: @bfavaretto, como posso visualizar o cabeçalho HTTP enviado pelo servidor ao meu browser?
Answer: Isso serve para indicar qual é a codificação do arquivo html servido.
Neste caso está indicando a codificação utf-8, que é um padrão definido pelo Unicode:
Unicode UTF-8
O unicode UTF-8 é um formato de codificação que tem um tamanho variável de caractere, podendo ter de 1 até 4 bytes. Os caracteres mais comuns são mapeados para códigos de 1 byte, outros menos comuns, como a maioria dos caracteres acentuados, possuem 2 bytes.

Wikipedia: Sobre o UTF-8
Wikipedia: sobre o unicode

Tag Meta
A tag meta do HTML, permite indicar metainformações, ou seja, informações sobre o próprio documento.
Como funciona o mata charset?
Essa tag, usada com charset serve para indicar a codificação do próprio documento. Note que há uma certa incoerência nessa afirmação, então vem a pergunta: Como poderia ser possível ler a codificação do documento, de dentro do próprio documento? Afinal, conhecer a codificação do documento de antemão é o que permite ler o arquivo.
Resposta: A maioria das codificações são muito parecidas para os caracteres principais, então em grande parte das codificações é possível ler partes do arquivo, considerando a codificação ASCII. É assim que o browser consegue ler, até encontrar a tag <meta charset="utf-8">... quando isso acontece, ele recomeça a leitura do arquivo, considerando a codificação que acabou de encontrar dentro do próprio HTML.
Duas formas de indicar charset em forma de metadados
Existem duas formas de indicar o charset do documento HTML, com meta-informação:
Forma recomendada pelo padrão HTML5:
<meta charset="utf-8">

ou assim:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

Essas duas formas são equivalentes. Em ambos os casos essas tags devem aparecer dentro da tag head do documento HTML... e quanto antes, melhor, pois quando a tag for encontrada, a leitura do arquivo terá de ser reiniciada.
Referência

<meta charset='utf-8'> vs <meta http-equiv='Content-Type'>
How is it possible to specify the encoding of a document inside the document?
<meta charset="utf-8"> declares encoding of own file?

Por que isso existe?
Por que existe essa forma de indicar a codificação do documento HTML? Já não existe, no protocolo HTTP, uma forma de indicar o charset usando um header na resposta?
Isso não é apenas por garantia. Acontece que um documento HTML servido através do protocolo HTTP poderia ser salvo pelo receptor, de forma independente dos headers com que o arquivo foi servido.
Não existe no HTML nenhuma restrição quanto ao protocolo que deve ser usado para servir o documento, portanto a tag meta com charset, para mim é quase que uma obrigação: ela permite que o documento continue coerente, mesmo que o protocolo/storage não suportem indicar o charset do arquivo.
Comment: Se não me engano, das duas formas que você indicou, a primeira é a recomendada em HTML5.
Comment: @bfavaretto: Obrigado, vou deixar isso claro na minha resposta de forma a não induzir a práticas não recomendadas.
Answer: Esta Tag  meta charset="utf-8" é usada  para poder mostrar ao navegador o tipo de codificação que sera utilizada  em seu site
Answer: -meta charset= utf-8 é uma metatag responsável por chavear qual
tabela de caractéres a página está utilizando.
-As tags meta são muito utilizadas porque são elementos capazes de definir qualquer tipo de informação em HTML.
-Logo após o atributo meta, temos o atributo charset: é ele quem define que a informação a ser comunicada pelo atributo meta é um formato de codificação.

Ao utilizar a tag meta charset="UTF-8", estamos informando ao navegador a informação de que a codificação daquela página é a UTF-8, o padrão de codificação mais utilizado, também chamado de Unicode — ou Conjunto de Caracteres Codificados Universal.Esse padrão uniformiza as informações ao redor do mundo fazendo com que os navegadores renderem todos os conteúdos a partir das regras estabelecidas pelo UTF-8.
Answer: A meta charset="utf-8" é uma metatag responsável por chavear qual
tabela de caractéres a página está utilizando.
A Web é acessada por pessoas do mundo inteiro. Ter um sistema
ou um site que limite o acesso e pessoas de outros países é algo que
vai contra a tradição e os ideais da internet. Por isso, foi criado uma
tabela que suprisse essas necessidades, essa tabela se chama
Unicode. A tabela Unicode suporta algo em torno de um milhão de
caracteres.

O que é o meta charset no HTML?


MATLAB interpretation of Xcorr2 - Cross Correlation function

Question: I have two vectors of matching lengths. They are readings from two different sensors (one is from a smartphone and the other is from a wiimote) of the same hand movement. I am trying to find the time offset between them to synchronise the readings for further processing. The readings I get are of the format (Time(ms) Value) for accelerations in the X,Y and Z direction.
For the synchronization, I plotted the cross-correlation function xcorr2() between the two sets. I am getting the same graph (a weird triangle peak and a straight line at the bottom) for Accelerations along the x, y and z directions (which I guess is good) but I don't know how to interpret it. What do the axes in the graph represent?
Can anyone explain to me what xcorr2() means in a qualitative sense. From the correlation function, how do I determine the offset (i.e. how many seconds is sensor1 behind sensor2)?
Thanks!
Imelza
Comment: Wouldn't this be more appropriate for http://math.stackexchange.com?
Comment: You will probably get a better answer from http://stats.stackexchange.com/
Answer: The peak of the triangle represents your offset.  If the two vectors were identical, the peak would appear exactly in the center.  If they are offset from each other, the peak will occur offset from the center.
I'd do an experiment and correlate a vector with itself.  Then use a function like argmax() to find the index of the maximum position.  It should be len(vector)/2 plus or minus 1.  Then do the correlation of the two different signals, and do argmax on that.  Subtract the value you just found for identical vectors, and you will have your offset.  If you reverse the order of the signals, the offset will be negative.
Remember that there are different implementations of correlation, like a circular cross-correlation, where the signals are wrapped around.  You don't want that.  If the Matlab function is a circular cross-correlation (FFT-enhanced), then you need to zero pad first.  Read into the different implementations and options of xcorr2.
Here's a simple example in Python.
Comment: I like the simplicity of the results from `rxy = real(irfft(rfft(x, K) * conj(rfft(y, K))))`, where x is length L, y is length M, and K is L+M-1 rounded to the next even number (due to using rfft). The L non-negative lags are at rxy[:L], and the M-1 negative lags are at rxy[:-M:-1]. For example, the 1st positive lag is at rxy[1], and the 1st negative lag is at rxy[-1], and the 0 lag is at rxy[0].
Comment: (Meta: I can't say that I like this font, though. Maybe it's an issue with my browser, Chrome, but it looks squished, and the number 0 looks like the letter o.)
Comment: Also, using numpy.fft.rfft is about 3 times faster than scipy.signal.fftconvolve. I wouldn't use numpy.correlate or scipy.signal.correlate on arrays longer than about 2**15 -- it's way too slow. Likewise,  matplotlib.pyplot.xcorr uses numpy.correlate.
Comment: @eryksun: Does your version include this change? http://projects.scipy.org/scipy/browser/trunk/scipy/signal/signaltools.py?rev=5968 http://projects.scipy.org/numpy/ticket/1260
Comment: @endolith: Yes, it does. But fftconvolve is using scipy.fftpack.fftn, which computes the negative frequencies. numpy.fft.rfft only computes the non-negative frequencies, returning an array sized N/2+1.
Comment: @endolith: As to the NumPy ticket, it doesn't look like any progress was made on the proposal, and it was unscheduled. cdavid mentions adding an FFT-based version to NumPy, but I suppose they decided that scipy.signal.fftconvolve based on fftpack's fftn is sufficient.
Comment: Hi, thanks for the reply. I just did the correlation of one vector with itself.. and my maximum is NOT length(vector)/2 .. its about 200 samples off.. do you know why that could happen? One important (and possibly extremely stupid) question is that the vector is a single row vector of values (I store time in a different vector) The sampling is not uniformly spaced, so how do I account for this?
Comment: @Imelza I don't know how to do correlations with non-uniformly sampled data.  See Graham's answer about interpolation.
Comment: Yes, I resampled it to be uniform and your method works now. Thanks a lot!!
Answer: @Imelza If the data is not uniformly sampled in time, xcorr will not work correctly (and shifting it by samples will not give the right correspondence.) You could use interp1 to resample it uniformly first.
Comment: Thanks! I resampled the data uniformly and it pretty much worked. Thanks very much!
Comment: also, you may be getting 200 samples off because the default lags are bipolar--they start from negative lags. You can get the lags xcorr is using with
    [c,lags] = xcorr(a,b);


Persisting related entity

Question: Using FOSUserBundle, I'm trying to persist related entities. I extended User with a new entity called UserInfo. When persisting using cascade function:
user_id column in the related userinfo entity is not being filled with the value of id from user entity upon registration:
User entity:
/**
* @ORM\Entity
* @ORM\Table(name="re_user")
*/
class User extends BaseUser
{
...

    /**
     * @ORM\OneToOne(targetEntity="UserInfo", mappedBy="user", cascade={"persist", "remove"})
     */
    protected $userinfo;

User
class UserInfo
{
...

/**
 * @ORM\OneToOne(targetEntity="User", inversedBy="userinfo")
 * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
 */
protected $user;

...
}

What id the correct way to persist related FOSUserBundle entities.
I hope I've explained it well, please let me know if I can clarify further.
Comment: Related question: http://stackoverflow.com/questions/8009406/the-good-way-to-persist-a-fosuser-entity-in-cascade
Comment: Have you made any assignment to UserInfo::$user in your code?
Comment: I'm not sure what you mean by assignment but I've included part of my userinfo entity above where JoinColumn is with user_id referencing id from the User entity.
Answer: Without seeing your setter method for $userinfo I can only guess, but I had a similar problem. In my situation the problem was that I did not set the related mappedBy property in the setter for the inversedBy property.
Try the following:
<?php
// ...
class User extends BaseUser {
  // ...
  public function setUserinfo(UserInfo $userinfo) {
    $userinfo->setUser($this);
    $this->userinfo = $userinfo;
  }
}

Persisting related entity


How to display a view on a customize way?

Question: I've searched similar questions but I'm not sure to have understood how to do it. I would like to create a page for the team of my website. I have several blocs: administrators, moderators, etc.
I'd like to display in a left column the member avatar and on the right, I want to display all the rest of the data such as the nickname, a short description, etc.
If you have any tips on how to search on Stack Exchange, I'd gladly accept the information.
Comment: I found [Panels](https://www.drupal.org/project/panels) but I don't know if it's the thing I'm searching for.
Answer: Yes, Panels is what you're looking for. Panels, in a gist, is similar to how the core Structure -> Block Layout works, except it's more powerful. You use it in conjunction with Page Manager, a submodule of Ctools (if I remember correctly) which lets you create one-off pages as well as override how core pages render. This post will explain what which does.
In summary, the workflow would be like this:

Create a content type for your members. Populate it with fields for the data.
Enable both Panels and Page Manager
Go to Structure -> Pages and enable the Node View page (the one with the <code>/node/%</code> path)
Edit the Node View page and add a variant - a config for what to render where, when and how when on the page's path.
Configure the variant to render when viewing the content type. I think that's under Selection, then add a Type criteria matching the content type.
Configure the layout of the variant. By default, there's a 1-column layout available. You can use Display Suite to provide more layouts or you can write your own.
Configure the contents of the variant. Here's where the magic happens. You can virtually add anything to the layout. Views, blocks, fields, nodes, entire pages, anything. In this case, position the fields of the content type into where you want them.

That's a quick rundown of how to use Panels. And all of this happens with minimal to no coding at all (except if you create your own layout and/or add a sprinkle of CSS so things don't look very Drupal-y).
Comment: First of all, thanks for your answer! You mentionned the Blocks Layout but I never understood how this works. Is it possible to do the same thing without using Panels or is it a "obliged" modules on most Drupal projects?
Comment: @Helmasaur The other way to do it is via template overrides, which can get ugly fast. Also, if you simply want to provide a layout for content type fields, Display Suite or Field Groups (with Bootstrap Field Groups for grids) could do that. But Panels is a handy module to learn if you want greater flexibility. Once you get the hang of it, you will never look back.
Comment: I'm a bit scared to use modules because if it's not updated, I would get stuck with my data. I'm new with a CMS and I'm used to develop my website myself and deciding how to display pages the way I want. The most difficult thing in my opinion is to get to what you want from a "limited" tool. When I say limited, it's that you can't do it the way you want or think but do it with the possibilities that the CMS gives. I need to learn more!
Comment: It's extremely easy to use Views or Paragraphs.


Integration against multivariable gaussian reduce to single variable gaussian

Question: Given the logistic function $f(x) = \frac{1}{1+e^{-x}}, w, \phi\in\mathbb{R}^n$ and $q\sim \mathcal{N(\mu, \Sigma)}$(i.e. normally distributed, with mean $\mu\in\mathbb{R}^n$ and covariance matrix $\Sigma\in\mathbb{R}^{n\times n}$), how can I show that $$\int f(w^T\phi)q(w)dw =\int f(a)p(a)da$$ with $p\sim \mathcal{N}(\hat{\mu}, \hat{\sigma}^2)$ and find $\hat{\mu}\in\mathbb{R}$ and $\hat{\sigma}\in\mathbb{R}$? I am stuck and don't know where to start.
Comment: @sudeep5221, Okay, I understand your comment I think, I turned it into an answer.
Comment: If $\phi \sim \mathcal{N}(\mu, \Sigma)$, then $w^{\top} \phi \sim \mathcal{N}( \hat{\mu}, \hat{\sigma}^2)$, where $\hat{\mu} = w^{\top} \mu$ and $\hat{\sigma}^2 = w^{\top} \Sigma w$. The result immediately follows after this. This result is also a direct consequence of the definition of mean and covariance.
Answer: Write $X=\mu+\sqrt{\Sigma}Z$ where $Z\sim N(0,I_n)$ denote $A=e^{-\langle\phi,\mu\rangle }$ and $B=\sqrt{\Sigma}\phi.$ For computing $$I=E\left(\frac{1}{1+Ae^{-\langle B,Z\rangle }}\right)$$ you have to compute the distribution of $Y=\langle B,Z\rangle $ that you can obtain from the integral $$E\left(e^{s\langle B,Z\rangle }\right)=e^{
\frac{s^2\|B\|^2}{2}}$$ saying that $Y\sim N(0,\|B\|^2)$ or $Y\sim \|B\|Z_1$ where $Z_1\sim N(0,1).$ Finally $$I=\int_{R}\frac{1}{1+Ae^{-\|B\|z}}e^{-z^2/2}\frac{dz}{\sqrt{2\pi}}$$ which is not computable by the elementary means. Note that $\|B\|^2=\phi^T\Sigma \phi:$ you do not need to compute $\sqrt{\Sigma}.$
Comment: thank you, let me try to reproduce the computations
Answer: Define the random vector $W\sim q\sim\mathcal{N}(\mu,\Sigma)$. Then by the law of the unconscious statistician we have $$\int f(w^T\phi)q(w)dw = \mathbb{E}[f(W^T\phi)].$$ However, $A:=W^T \phi$ is a linear transformation of a gaussian random vector and so it is gaussian as well and $A\sim\mathcal{N}(\phi^T\mu, \phi^T\Sigma\phi)$ which density we call $p$. Then $$\int f(w^T\phi)q(w)dw=\mathbb{E}[f(W^T\phi)]=\mathbb{E}[f(A)]=\int f(a)p(a)da.$$ where $p\sim\mathcal{N}(\underbrace{\phi^T\mu}_{\hat{\mu}}, \underbrace{\phi^T\Sigma\phi}_{\hat{\sigma}})$.


Worn saddles on Floyd-Rose bridge break my strings

Question: I have two Cort guitars with the same type of Floyd Rose bridge. One is about 5 years older than another. Each of them has the same problem. The saddles are worn due to friction with the strings. It makes them serrated like a saw. Then it breaks the string frequently and throws the remaining strings out of tune.
I go to a luthier and he strips smooth again, but it never lasts long and the problem returns. I use tape between the string and the saddle to improve the durability.
My question is, there's a way to fix it without throwing them away and buying some new ones ?
Answer: Broken strings are a known risk with Floyd Rose tremolos. It doesn't seem to be particularly related to a worn saddle though.
The standard solutions seem to be:

taking care when tightening the screws
oiling the saddle
changing strings frequently

There are a couple of products designed to address the problem. "Saddle Singers" are inserts that sit between the string and the saddle. "String Savers" are replacement saddles.
Comment: I change my strings once each month and I use 11 gauge, it's a hard string. But I think that Saddle Singers is what I'm searching for. Thank you!


COM object management in C++

Question: Suppose you created COM object that represents all DVD drives in Windows system. You retrieved all necessary information from it and showed it to user. If there is "refresh" button somewhere (in case if some drives are added to the system) what is correct strategy to manage COM object?
1) Create class that manages DVD drive info. You create instance of this class when DVD Info window is created (with "refresh" button) and destroy it when window is destroyed. COM object is created in constructor and live until class instance is destroyed.
2) Create function (may be method of more general class) that creates COM object, retrieve all information and destroys it. It is called when DVD Info window is created and when user hits "refresh" button.
The bottom line is whether you should keep COM object if it is used frequently or "just in case"?. What is costly, keep COM object alive OR create and destroy it each time? If answer is quite deterministic, is it true for all Windows object? If no, how to know in which case which strategy is more appropriate? Thanks.
Answer: There is no rule for this.
It's not very correct, but COM object for C++ is just an instance of a class. There is different ways how this objects are creating. It's more extensible operation in case of COM. But in case of CLSCTX_INPROC_SERVER there is no very big costs for object creating if we are comparing with object creating with new in C++. So, i think that the answer for your question is the same as answer for question: If i don't know how long constructor of some class will be running too much, can i create the instances of such a class too frequently times?
But, again, If you think that call to CoGetClassObject() (CoCreateInstance()) is too expensive for you then try to save reference to newly created object as long as possible

COM object management in C++


Testing for normality in non-normal distributions with zero skewness and zero excess kurtosis

Question: [This question was formerly called "On Non-normal distributions with zero skewness and zero excess kurtosis" and relabeled to better reflect its focus.]
I am trying to write a little simulation using @Glen_b's very nice answer in this post: Non-normal distributions with zero skewness and zero excess kurtosis?
In particular, I want to show that (what is known in econometrics as) the Jarque-Bera test (which was actually considered earlier in for example Bowman and Shenton (1975). "Omnibus contours for departures from normality based on √b1 and b2". Biometrika 62 (2): 243–250, see @Glen_b's comment) lacks power against non-normal but symmetric distributions without excess kurtosis. The figure shows the distribution of the p-values of the simulation.

For his uniform (left panel) and Poisson (right panel) example I do get a distribution of the p-values that leads to no power beyond size/a conservative test (depending on whether you call JB a test of normality or a test of the two moments), but in the gamma example (middle panel) there does even seem to be some power.
In neither case do I get a uniform distribution of the p-values though, although I (believe to) simulate data under (what I think is) the null - symmetry and no excess kurtosis.
Thoughts on how/why that happens?
CODE:
library(tseries)
library(MASS)

n <- 1e5
a <- sqrt(5+sqrt(24))
b <- (sqrt(13)+1)/2
lambda <- .5

reps <- 1000
JBpval <- matrix(rep(NA,3*reps),ncol=3)

for (i in 1:reps) {
#(a)
u1a <- runif(n/2,-1,1)
u2a <- runif(n/2,-a,a)

#(b)
u1b <- rgamma(n/2,shape = b, scale = 1)
u2b <- -rgamma(n/2,shape = b, scale = 1)

#(c)
u1c <- sqrt(rpois(n/2,lambda = lambda))
u2c <- -sqrt(rpois(n/2,lambda = lambda))

ua <- c(u1a,u2a)
ub <- c(u1b,u2b)
uc <- c(u1c,u2c)

JBpval[i,1] <- jarque.bera.test(ua)$p.value
JBpval[i,2] <- jarque.bera.test(ub)$p.value
JBpval[i,3] <- jarque.bera.test(uc)$p.value
}

par(mfrow=c(1,3))
truehist(JBpval[,1])
truehist(JBpval[,2])
truehist(JBpval[,3])

Comment: That argument might have merit. But notice that the J-B statistic involves up to the *eighth* moment of the sample (it includes the square of the sample kurtosis).  Such moments cannot be expected to stabilize until sample sizes are enormous.  $10^5$ is likely far too small.  This is one reason the J-B test performs so poorly in the first place.
Comment: I don't see anything in your code that would correspond to simulating data according to the null hypothesis of a Normal distribution. Could you show us where that would be?
Comment: I now provide a more complete analysis of this point in my answer below.
Comment: @ChristophHanck, did you see my answer to a related question here? http://stats.stackexchange.com/questions/90697/is-shapiro-wilk-the-best-normality-test-why-might-it-be-better-than-other-tests one of the references has a power comparison for many different alternatives, this may help you design your simulation
Comment: @Aksakal, no, I hadn't seen that yet. Very useful, thanks!
Comment: In the link, @Glen_b shows that the distributions I am sampling from (f.ex. (a), a 50-50 mixture of $U[-1,1]$ and $U[-a,a]$) are symmetric distributions with excess kurtosis 0, s.th. I believe the data to come from a distribution satisfying the *actual* null hypothesis of the JB test, viz. symmetry and zero excess kurtosis. Hence, I expect the p-values of the JB test to be $U[0,1]$.
Comment: The p-value for the JB test is computed assuming the underlying distribution is *Normal*. No p-value can be computed for the *nonparametric* assumption of zero skewness and zero excess kurtosis, because under that assumption the statistic has no definite distribution.
Comment: My understanding is that the $\chi^2$ limiting distribution is a consequence of a CLT, CMT and delta method applied to sample skewness and kurtosis. As such, the distribution of the data in the population should, provided the CLT works, not matter. I am struggling to find a reference for my claim, though.
Comment: Another mistake in my reasoning appears to be that the test exploits expressions for the asymptotic distribution of the sample moments which only hold for normal populations. See http://www.bje.uni-bonn.de/download-the-latest-issue-1/volume-1/foerster-testing-normality, for example.
Comment: In the gamma and sqrt-poisson cases you have generated exactly half of each sample to be negative; that's not quite right. Each observation should have a 50-50 chance to be negative. You did something similar to the uniform-based one. (This may not make all that much difference to the results though.)
Answer: Let my try to answer my own question:
If $X\sim\mathcal{N}\left(0,\sigma^2\right)$ (zero mean is w.l.o.g.). Define the centered moment $\mu_k=E\left(X-E X\right)^k$ and its empirical counterpart $m_k=\frac{1}{n}\sum_{i=1}^{n}\bigl(X_i-\overline{X}\bigr)^k$.
Analyze the two (method of moments) estimators
$$
 b_1=\frac{m_3}{m_2^{3/2}}\qquad\text{and}\qquad b_2=\frac{m_4}{m_2^2},
$$
for the skewness $\beta_1(X)=E(X-E(X))^3/\left[E(X-E(X))^{2}\right]^{3/2}$ and for the kurtosis $\beta_2(X)=E(X-E(X))^4/\left[E(X-E(X))^2\right]^2$. A CLT will ensure that
$$
\sqrt{n}\left(\begin{pmatrix}m_2\\m_3\\m_4\end{pmatrix}-\begin{pmatrix}\mu_2\\ \mu_3\\ \mu_4\end{pmatrix}\right)
$$
converges in distribution to a centered multivariate normal with covariance matrix $\Sigma$.
Now, we want to show that, when $X$ is normal,
$$
\sqrt{n}\left(\begin{pmatrix}b_1\\b_2\end{pmatrix}-\begin{pmatrix}\beta_1\\ \beta_2\end{pmatrix}\right)\to_d\mathcal{N}\left(\begin{pmatrix}0\\0\end{pmatrix},\begin{pmatrix}6 & 0\\0 & 24\end{pmatrix}\right).
$$
The follow result is helpful (see, e.g., Rao C.R., Linear Statistical Inference and its applications (1972), Section 6h2): $$\text{Acov}(\sqrt{n}m_j,\sqrt{n}m_k)=\mu_{j+k}-\mu_j\mu_k+jk\mu_2\mu_{j-1}\mu_{k-1}-j\mu_{j-1}\mu_{k+1}-k\mu_{k-1}\mu_{j+1},$$ For the normal distribution,
        $$
   \mu_{2k}=\sigma^{2k}\frac{(2k)!}{k!2^k},\qquad\mu_{2k+1}=0,\qquad k=0,1,\ldots.
  $$
Thus, $\mu_2=\sigma^2$, $\mu_3=0$, $\mu_4=3\sigma^4$, $\mu_5=0$, $\mu_6=15\sigma^6$ and so forth.
The limiting distribution of $(b_1,b_2)$ then is an application of the multivariate delta method.
The $(2\times3)$ matrix of derivatives of $b_1$ and $b_2$ w.r.t. $m_2$, $m_3$, $m_4$, evaluated at the population moments is
$$
J=\begin{pmatrix}0&\sigma^{-3}&0\\-6\sigma^{-2}&0&\sigma^{-4}\end{pmatrix}
$$
Also,
$$
\Sigma=\begin{pmatrix}2\sigma^4&*&15\sigma^6-\sigma^23\sigma^4\\*&6\sigma^6&*\\15\sigma^6-\sigma^23\sigma^4&*&105\sigma^8-(3\sigma^4)^2\end{pmatrix},
$$
where $*$ omits terms not needed (because they will be multiplied with zeros in $J$ when evaluating the $(2\times 2)$ variance matrix of interest $J\Sigma J'$).
The variance-covariance matrix of the delta method then gives
$$
J\Sigma J'=\begin{pmatrix}6 & 0\\0 & 24\end{pmatrix},
$$
as desired.
Thus, the limiting null distribution of the Jarque-Bera test
$$
JB=n\left(\frac{b_1^2}{6}+\frac{(b_2-3)^2}{24}\right)
$$
follows directly because, under the null of normality, $\sqrt{n}(b_1/\sqrt{6})\to_d N(0,1)$ and $\sqrt{n}((b_2-3)/\sqrt{24})\to_d N(0,1)$ such that $n(b_1^2/6)\to_d \chi^2_1$ and $n(b_2-3)^2/24\to_d\chi^2_1$. By asymptotic independence,
$$
JB\to_d\chi^2_2
$$
But, and that was the point of the original post, these arguments inherently required normality for the limiting distribution to obtain.
Hence, even if distributions share the skewness and kurtosis of the normal, there is no reason to believe that the JB test will be $\chi^2_2$, and thus, no reason to believe that the $p$-values will be uniform. So, my intuition was false.
(As also mentioned by @whuber in the comments, what would be required would be a distribution that shares the first eight moments with the normal, as $\text{Acov}(\sqrt{n}m_4,\sqrt{n}m_4)$ contains $\mu_{8}$. I am not aware of such a distribution though - examples would be appreciated, if existent!)
Comment: Even when the Jarque Bera test is applied to the normal, the asymptotic distribution doesn't really "kick in" until sample sizes are very large.  My own simulations of the bivariate distribution showed its quite clearly not bivariate normal until $n$ is well over 500, and I'd hesitate to use the resulting univariate statistic until $n$ is at least 300. Bowman and Shenton's 1975 paper ( "Omnibus contours for departures from normality based on √b1 and b2". Biometrika 62 (2): 243–250. ) -- *five years before Jarque and Bera* -- discuss the problem with the (widely misnamed) statistic and ... ctd
Comment: ctd ... describe small sample improvements. However, Fig 1  in their paper suggests either their approximation goes the wrong way (the contours of the approximation are a worse fit than the asymptotic ones) -- or perhaps an error was made in drawing the figure. In any case, the dot diagram itself (easily simulated) shows the characteristic "smile" shape of a sample (skewness,kurtosis) plot seen for many of the common symmetric distributions. The asymptotic test itself was widely known before Bowman and Shenton's paper, so it's odd that it's named after authors of a paper published much later.
Answer: It's not so much that the test would be without any power, but you might find it interesting to see what happens to the relative power as $n$ increases when you compare the "Jarque-Bera" with (say) Shapiro-Wilk. Actually, here you go:

The light grey line marks the type I error rate; below that (with a false null) we have a biased test (biased tests are common with goodness of fit).
[Note to self: I should make a beta example that does the same trick as the gamma one. That should make for a more spectacular comparison.]
R code, if anyone cares to have it --
library(tseries)
f <- function(x) mean(x<.05)

reps <- 5000
b <- (sqrt(13)+1)/2

nseq <- c(16,25,64,100,225,400,625)
nres <- matrix(rep(NA,length(nseq)*2),nc=2)

for (i in seq_along(nseq)){
 res <- replicate(reps,{
     g1 <- rgamma(nseq[i],b)*sign(runif(nseq[i])-.5)
     c(jarque.bera.test(g1)$p.value,shapiro.test(g1)$p.value)
   })
 nres[i,] <- apply(res,1,f)
}

and code to do the plot:
plot(qnorm(nres[,1])~sqrt(nseq),ylim=c(qnorm(.02),qnorm(.997)),
         type="o",col=4,ylab="zscore of power",xlab="sqrt(n)")
points(qnorm(nres[,2])~sqrt(nseq),type="o",col="orange3")
abline(h=qnorm(0.05),col=8)


how to let user whatever number of images they want to upload. so it can be optional to upload from 1 to 5 images based on their need

Question: how to let user whatever number of images they want to upload. so it can be optional to upload from 1 to 5 images based on their need. in here everything works well if the user upload all 5 images, but if you upload less than 5 images it freezes and give this error,

i dont even know what the existsSync is and where it came from, nothing on internet about it too.
and this is how the submitting page looks like so you dont ask why there are 5 functions to upload images.

<code>import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/rendering.dart';
import 'dart:io';
import 'package:path/path.dart' as path;
import 'package:image_picker/image_picker.dart';

class ItemInput extends StatefulWidget {
  @override
  _ItemInputState createState() => _ItemInputState();
}

class _ItemInputState extends State<ItemInput> {
  final Firestore database = Firestore.instance;
  //CollectionReference products = Firestore.instance.collection('products');

  TextEditingController nameText = TextEditingController();
  TextEditingController priceText = TextEditingController();
  TextEditingController cellNoText = TextEditingController();
  TextEditingController addText = TextEditingController();
  TextEditingController detailText = TextEditingController();
  TextEditingController pic = TextEditingController();
  final _formKey = GlobalKey<FormState>();
  File _image1;
  File _image2;
  File _image3;
  File _image4;
  File _image5;
  //String nall;

  static const menuItems = <String>[
    'Car/موتر',
    'motorcycle/ موترسایکل',
    'electronics/الکترونیک',
    'house/ خانه',
    'household/لوازم خانه',
    'mobile/موبایل',
    'Sellect Category/انتخاب بخش',
  ];

  final List<DropdownMenuItem<String>> _dropDownMenuItems = menuItems
      .map((String value) => DropdownMenuItem<String>(
            value: value,
            child: Text(value),
          ))
      .toList();

  String _btnselected = "Sellect Category/انتخاب بخش";

  Future getImage1() async {
    var firstImage = await ImagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      _image1 = firstImage;
    });
  }

  Future getImage2() async {
    var secondImage = await ImagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      _image2 = secondImage;
    });
  }

  Future getImage3() async {
    var thirdImage = await ImagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      _image3 = thirdImage;
    });
  }

  Future getImage4() async {
    var forthImage = await ImagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      _image4 = forthImage;
    });
  }

  Future getImage5() async {
    var fifthImage = await ImagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      _image5 = fifthImage;
    });
  }

  var imageUrl1;
  var imageUrl2;
  var imageUrl3;
  var imageUrl4;
  var imageUrl5;

  FirebaseStorage storage = FirebaseStorage.instance;

  uploadPic() async {
    //String fileName = path.basename(_image1.path);
    StorageReference reference = storage.ref().child("images");
    StorageUploadTask uploadTask = reference.putFile(_image1);
    StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
    String url = await taskSnapshot.ref.getDownloadURL();
    imageUrl1 = url;
    return url;
  }

  /////2
  uploadPic2() async {
    //String fileName = path.basename(_image2.path);
    StorageReference reference = storage.ref().child("images");
    StorageUploadTask uploadTask = reference.putFile(_image2);
    StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
    String url = await taskSnapshot.ref.getDownloadURL();
    imageUrl2 = url;
    return url;
  }

  ////3
  uploadPic3() async {
    //String fileName = path.basename(_image3.path);
    StorageReference reference = storage.ref().child("images");
    StorageUploadTask uploadTask = reference.putFile(_image3);
    StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
    String url = await taskSnapshot.ref.getDownloadURL();
    imageUrl3 = url;
    return url;
  }

  ///4
  uploadPic4() async {
    //  String fileName = path.basename(_image4.path);
    StorageReference reference = storage.ref().child("images");
    StorageUploadTask uploadTask = reference.putFile(_image4);
    StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
    String url = await taskSnapshot.ref.getDownloadURL();
    imageUrl4 = url;
    return url;
  }

  ///5
  uploadPic5() async {
    //String fileName = path.basename(_image5.path);
    StorageReference reference = storage.ref().child("images");
    StorageUploadTask uploadTask = reference.putFile(_image5);
    StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
    String url = await taskSnapshot.ref.getDownloadURL();
    imageUrl5 = url;
    return url;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Put AD'),
          centerTitle: true,
        ),
        body: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.all(5.0),
            child: Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Form(
                  key: _formKey,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      TextFormField(
                        controller: nameText,
                        decoration: const InputDecoration(
                          icon: const Icon(Icons.directions_car),
                          hintText: 'Corolla, Mercedes...',
                          labelText: 'Item Name - نام جنس',
                        ),
                      ),
                      SizedBox(height: 10),
                      TextFormField(
                        controller: detailText,
                        decoration: const InputDecoration(
                          icon: const Icon(Icons.description),
                          hintText: 'Description - مشخصات',
                          labelText: 'Description - مشخصات',
                        ),
                      ),
                      SizedBox(height: 10),
                      TextFormField(
                        controller: priceText,
                        decoration: const InputDecoration(
                          icon: const Icon(Icons.attach_money),
                          hintText: 'Enter your item\'s price',
                          labelText: 'Price - قیمت',
                        ),
                      ),
                      SizedBox(height: 10),
                      TextFormField(
                        controller: cellNoText,
                        decoration: const InputDecoration(
                          icon: const Icon(Icons.call),
                          hintText: '0700-000-000',
                          labelText: 'Mobile Number -  شماره تماس',
                        ),
                      ),
                      SizedBox(height: 10),
                      TextFormField(
                        controller: addText,
                        decoration: const InputDecoration(
                          icon: const Icon(Icons.location_city),
                          hintText: 'Enter Your Address',
                          labelText: 'Address - آدرس',
                        ),
                      ),
                      SizedBox(height: 30),
                      Padding(
                        padding: const EdgeInsets.all(5.0),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                          children: <Widget>[
                            //////// dropdown start //////////
                            DropdownButton(
                              hint: Text('Sellect Category'),
                              value: _btnselected,
                              items: this._dropDownMenuItems,
                              onChanged: (String newvalue) {
                                setState(() {
                                  _btnselected = newvalue;
                                });
                              },
                            ),
                            ///////  dropdown end  //////
                            Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: <Widget>[
                                InkWell(
                                  onTap: () async {
                                    //image.getImage(source: ImageSource.gallery);
                                    await getImage1();
                                  },
                                  child: Container(
                                      decoration: BoxDecoration(
                                          color: Colors.black26,
                                          borderRadius:
                                              BorderRadius.circular(10)),
                                      height: 60,
                                      width: 60,
                                      child: (_image1 == null)
                                          ? Icon(Icons.add_a_photo, size: 30)
                                          : Image.file(
                                              _image1,
                                              fit: BoxFit.cover,
                                            )

                                      // : Icon(Icons.add_a_photo, size: 30),
                                      ),
                                ),
                                SizedBox(width: 5),
                                InkWell(
                                  onTap: () async {
                                    // image.getImage(source: ImageSource.gallery);
                                    await getImage2();
                                  },
                                  child: Container(
                                      height: 60,
                                      width: 60,
                                      decoration: BoxDecoration(
                                          color: Colors.black26,
                                          borderRadius:
                                              BorderRadius.circular(10)),
                                      child: (_image2 == null)
                                          ? Icon(Icons.add_a_photo, size: 30)
                                          : Image.file(
                                              _image2,
                                              fit: BoxFit.fill,
                                            )),
                                ),
                                SizedBox(width: 5),
                                InkWell(
                                  onTap: () async {
                                    // image.getImage(source: ImageSource.gallery);
                                    await getImage3();
                                  },
                                  child: Container(
                                      height: 60,
                                      width: 60,
                                      decoration: BoxDecoration(
                                          color: Colors.black26,
                                          borderRadius:
                                              BorderRadius.circular(10)),
                                      child: (_image3 == null)
                                          ? Icon(Icons.add_a_photo, size: 30)
                                          : Image.file(
                                              _image3,
                                              fit: BoxFit.fill,
                                            )),
                                ),
                                SizedBox(width: 5),
                                InkWell(
                                  onTap: () async {
                                    // image.getImage(source: ImageSource.gallery);
                                    await getImage4();
                                  },
                                  child: Container(
                                      height: 60,
                                      width: 60,
                                      decoration: BoxDecoration(
                                          color: Colors.black26,
                                          borderRadius:
                                              BorderRadius.circular(10)),
                                      child: (_image4 == null)
                                          ? Icon(Icons.add_a_photo, size: 30)
                                          : Image.file(
                                              _image4,
                                              fit: BoxFit.fill,
                                            )),
                                ),
                                SizedBox(width: 5),
                                InkWell(
                                  onTap: () async {
                                    // image.getImage(source: ImageSource.gallery);
                                    await getImage5();
                                  },
                                  child: Container(
                                      height: 60,
                                      width: 60,
                                      decoration: BoxDecoration(
                                          color: Colors.black26,
                                          borderRadius:
                                              BorderRadius.circular(10)),
                                      child: (_image5 == null)
                                          ? Icon(Icons.add_a_photo, size: 30)
                                          : Image.file(
                                              _image5,
                                              fit: BoxFit.fill,
                                            )),
                                ),
                                SizedBox(width: 5),
                              ],
                            ),

                            SizedBox(
                              height: 10,
                            ),
                            RaisedButton.icon(
                                color: Colors.teal,
                                onPressed: () async {
                                  Navigator.pop(
                                    context,
                                  );
                                  switch (_btnselected) {
                                    case 'Car/موتر':
                                      database.collection("car").add({
                                        "item Name": nameText.text,
                                        "item Desc": detailText.text,
                                        "item Price": priceText.text,
                                        "seller Number": cellNoText.text,
                                        "seller add": addText.text,
                                        "image 1 Url":
                                            (await uploadPic() != null)
                                                ? await uploadPic()
                                                : null,
                                        "image 2 Url":
                                            (await uploadPic2() != null)
                                                ? await uploadPic2()
                                                : null,
                                        "image 3 Url":
                                            (await uploadPic3() != null)
                                                ? await uploadPic3()
                                                : null,
                                        "image 4 Url":
                                            (await uploadPic4() != null)
                                                ? await uploadPic4()
                                                : null,
                                        "image 5 Url":
                                            (await uploadPic5() != null)
                                                ? await uploadPic5()
                                                : null,
                                      });

                                      break;
                                    case 'motorcycle/ موترسایکل':
                                      database.collection("motorcycle").add({
                                        "item Name": nameText.text,
                                        "item Desc": detailText.text,
                                        "item Price": priceText.text,
                                        "seller Number": cellNoText.text,
                                        "seller add": addText.text,
                                        "image 1 Url": _image1.path,
                                        "image 2 Url": _image2.path,
                                        "image 3 Url": _image3.path,
                                        "image 4 Url": _image4.path,
                                        "image 5 Url": _image5.path,
                                      });
                                      break;

                                    case 'electronics/الکترونیک':
                                      database.collection("electronics").add({
                                        "item Name": nameText.text,
                                        "item Desc": detailText.text,
                                        "item Price": priceText.text,
                                        "seller Number": cellNoText.text,
                                        "seller add": addText.text,
                                        "image 1 Url": _image1.path,
                                        "image 2 Url": _image2.path,
                                        "image 3 Url": _image3.path,
                                        "image 4 Url": _image4.path,
                                        "image 5 Url": _image5.path,
                                      });
                                      break;

                                    case 'house/ خانه':
                                      database.collection("house").add({
                                        "item Name": nameText.text,
                                        "item Desc": detailText.text,
                                        "item Price": priceText.text,
                                        "seller Number": cellNoText.text,
                                        "seller add": addText.text,
                                        "image 1 Url": _image1.path,
                                        "image 2 Url": _image2.path,
                                        "image 3 Url": _image3.path,
                                        "image 4 Url": _image4.path,
                                        "image 5 Url": _image5.path,
                                      });
                                      break;

                                    case 'household/لوازم خانه':
                                      database.collection("household").add({
                                        "item Name": nameText.text,
                                        "item Desc": detailText.text,
                                        "item Price": priceText.text,
                                        "seller Number": cellNoText.text,
                                        "seller add": addText.text,
                                        "image 1 Url": _image1.path,
                                        "image 2 Url": _image2.path,
                                        "image 3 Url": _image3.path,
                                        "image 4 Url": _image4.path,
                                        "image 5 Url": _image5.path,
                                      });
                                      break;

                                    case 'mobile/موبایل':
                                      database.collection("mobile").add({
                                        "item Name": nameText.text,
                                        "item Desc": detailText.text,
                                        "item Price": priceText.text,
                                        "seller Number": cellNoText.text,
                                        "seller add": addText.text,
                                        "image 1 Url": _image1.path,
                                        "image 2 Url": _image2.path,
                                        "image 3 Url": _image3.path,
                                        "image 4 Url": _image4.path,
                                        "image 5 Url": _image5.path,
                                      });
                                      break;
                                  }
                                  uploadPic().then((value) {
                                    DocumentReference docRef = Firestore
                                        .instance
                                        .collection("carPics")
                                        .document();
                                    docRef.setData({"image 1 Url": value},
                                        merge: true);
                                  });

                                  //2
                                  uploadPic2().then((value) {
                                    DocumentReference docRef = Firestore
                                        .instance
                                        .collection("carPics")
                                        .document();
                                    docRef.setData({"image 2 Url": value},
                                        merge: true);
                                  });

                                  ///3
                                  uploadPic3().then((value) {
                                    DocumentReference docRef = Firestore
                                        .instance
                                        .collection("carPics")
                                        .document();
                                    docRef.setData({"image 3 Url": value},
                                        merge: true);
                                  });

                                  ///4
                                  uploadPic4().then((value) {
                                    DocumentReference docRef = Firestore
                                        .instance
                                        .collection("carPics")
                                        .document();
                                    docRef.setData({"image 4 Url": value},
                                        merge: true);
                                  });

                                  ///5
                                  uploadPic5().then((value) {
                                    DocumentReference docRef = Firestore
                                        .instance
                                        .collection("carPics")
                                        .document();
                                    docRef.setData({"image 5 Url": value},
                                        merge: true);
                                  });
                                },
                                icon: Icon(
                                  Icons.send,
                                  size: 25,
                                  color: Colors.white,
                                ),
                                label: Text(
                                  'Submit  - برو',
                                  style: TextStyle(
                                      fontSize: 20,
                                      color: Colors.white,
                                      fontWeight: FontWeight.bold),
                                ))
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ));
  }
}
</code>
Comment: Does this answer your question? [How do I optionally upload images to my database/storage?](https://stackoverflow.com/questions/62847303/how-do-i-optionally-upload-images-to-my-database-storage)
Answer: Try this,
<code>import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/rendering.dart';
import 'dart:io';
import 'package:path/path.dart' as path;
import 'package:image_picker/image_picker.dart';

class ItemInput extends StatefulWidget {
  @override
  _ItemInputState createState() => _ItemInputState();
}

class _ItemInputState extends State<ItemInput> {
  final Firestore database = Firestore.instance;
  //CollectionReference products = Firestore.instance.collection('products');

  TextEditingController nameText = TextEditingController();
  TextEditingController priceText = TextEditingController();
  TextEditingController cellNoText = TextEditingController();
  TextEditingController addText = TextEditingController();
  TextEditingController detailText = TextEditingController();
  TextEditingController pic = TextEditingController();
  final _formKey = GlobalKey<FormState>();
  File _image1;
  File _image2;
  File _image3;
  File _image4;
  File _image5;
  //String nall;

  static const menuItems = <String>[
    'Car/موتر',
    'motorcycle/ موترسایکل',
    'electronics/الکترونیک',
    'house/ خانه',
    'household/لوازم خانه',
    'mobile/موبایل',
    'Sellect Category/انتخاب بخش',
  ];

  final List<DropdownMenuItem<String>> _dropDownMenuItems = menuItems
      .map((String value) => DropdownMenuItem<String>(
    value: value,
    child: Text(value),
  ))
      .toList();

  String _btnselected = "Sellect Category/انتخاب بخش";

  Future getImage1() async {
    var firstImage = await ImagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      _image1 = firstImage;
    });
  }

  Future getImage2() async {
    var secondImage = await ImagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      _image2 = secondImage;
    });
  }

  Future getImage3() async {
    var thirdImage = await ImagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      _image3 = thirdImage;
    });
  }

  Future getImage4() async {
    var forthImage = await ImagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      _image4 = forthImage;
    });
  }

  Future getImage5() async {
    var fifthImage = await ImagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      _image5 = fifthImage;
    });
  }

  String imageUrl1;
  String imageUrl2;
  String imageUrl3;
  String imageUrl4;
  String imageUrl5;

  FirebaseStorage storage = FirebaseStorage.instance;

  uploadPic() async {
    //String fileName = path.basename(_image1.path);
    StorageReference reference = storage.ref().child("images");
    StorageUploadTask uploadTask = reference.putFile(_image1);
    StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
    String url = await taskSnapshot.ref.getDownloadURL();
    imageUrl1 = url;
    return url;
  }

  /////2
  uploadPic2() async {
    //String fileName = path.basename(_image2.path);
    StorageReference reference = storage.ref().child("images");
    StorageUploadTask uploadTask = reference.putFile(_image2);
    StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
    String url = await taskSnapshot.ref.getDownloadURL();
    imageUrl2 = url;
    return url;
  }

  ////3
  uploadPic3() async {
    //String fileName = path.basename(_image3.path);
    StorageReference reference = storage.ref().child("images");
    StorageUploadTask uploadTask = reference.putFile(_image3);
    StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
    String url = await taskSnapshot.ref.getDownloadURL();
    imageUrl3 = url;
    return url;
  }

  ///4
  uploadPic4() async {
    //  String fileName = path.basename(_image4.path);
    StorageReference reference = storage.ref().child("images");
    StorageUploadTask uploadTask = reference.putFile(_image4);
    StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
    String url = await taskSnapshot.ref.getDownloadURL();
    imageUrl4 = url;
    return url;
  }

  ///5
  uploadPic5() async {
    //String fileName = path.basename(_image5.path);
    StorageReference reference = storage.ref().child("images");
    StorageUploadTask uploadTask = reference.putFile(_image5);
    StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
    String url = await taskSnapshot.ref.getDownloadURL();
    imageUrl5 = url;
    return url;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Put AD'),
          centerTitle: true,
        ),
        body: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.all(5.0),
            child: Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Form(
                  key: _formKey,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      TextFormField(
                        controller: nameText,
                        decoration: const InputDecoration(
                          icon: const Icon(Icons.directions_car),
                          hintText: 'Corolla, Mercedes...',
                          labelText: 'Item Name - نام جنس',
                        ),
                      ),
                      SizedBox(height: 10),
                      TextFormField(
                        controller: detailText,
                        decoration: const InputDecoration(
                          icon: const Icon(Icons.description),
                          hintText: 'Description - مشخصات',
                          labelText: 'Description - مشخصات',
                        ),
                      ),
                      SizedBox(height: 10),
                      TextFormField(
                        controller: priceText,
                        decoration: const InputDecoration(
                          icon: const Icon(Icons.attach_money),
                          hintText: 'Enter your item\'s price',
                          labelText: 'Price - قیمت',
                        ),
                      ),
                      SizedBox(height: 10),
                      TextFormField(
                        controller: cellNoText,
                        decoration: const InputDecoration(
                          icon: const Icon(Icons.call),
                          hintText: '0700-000-000',
                          labelText: 'Mobile Number -  شماره تماس',
                        ),
                      ),
                      SizedBox(height: 10),
                      TextFormField(
                        controller: addText,
                        decoration: const InputDecoration(
                          icon: const Icon(Icons.location_city),
                          hintText: 'Enter Your Address',
                          labelText: 'Address - آدرس',
                        ),
                      ),
                      SizedBox(height: 30),
                      Padding(
                        padding: const EdgeInsets.all(5.0),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                          children: <Widget>[
                            //////// dropdown start //////////
                            DropdownButton(
                              hint: Text('Sellect Category'),
                              value: _btnselected,
                              items: this._dropDownMenuItems,
                              onChanged: (String newvalue) {
                                setState(() {
                                  _btnselected = newvalue;
                                });
                              },
                            ),
                            ///////  dropdown end  //////
                            Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: <Widget>[
                                InkWell(
                                  onTap: () async {
                                    //image.getImage(source: ImageSource.gallery);
                                    await getImage1();
                                  },
                                  child: Container(
                                      decoration: BoxDecoration(
                                          color: Colors.black26,
                                          borderRadius:
                                          BorderRadius.circular(10)),
                                      height: 60,
                                      width: 60,
                                      child: (_image1 == null)
                                          ? Icon(Icons.add_a_photo, size: 30)
                                          : Image.file(
                                        _image1,
                                        fit: BoxFit.cover,
                                      )

                                    // : Icon(Icons.add_a_photo, size: 30),
                                  ),
                                ),
                                SizedBox(width: 5),
                                InkWell(
                                  onTap: () async {
                                    // image.getImage(source: ImageSource.gallery);
                                    await getImage2();
                                  },
                                  child: Container(
                                      height: 60,
                                      width: 60,
                                      decoration: BoxDecoration(
                                          color: Colors.black26,
                                          borderRadius:
                                          BorderRadius.circular(10)),
                                      child: (_image2 == null)
                                          ? Icon(Icons.add_a_photo, size: 30)
                                          : Image.file(
                                        _image2,
                                        fit: BoxFit.fill,
                                      )),
                                ),
                                SizedBox(width: 5),
                                InkWell(
                                  onTap: () async {
                                    // image.getImage(source: ImageSource.gallery);
                                    await getImage3();
                                  },
                                  child: Container(
                                      height: 60,
                                      width: 60,
                                      decoration: BoxDecoration(
                                          color: Colors.black26,
                                          borderRadius:
                                          BorderRadius.circular(10)),
                                      child: (_image3 == null)
                                          ? Icon(Icons.add_a_photo, size: 30)
                                          : Image.file(
                                        _image3,
                                        fit: BoxFit.fill,
                                      )),
                                ),
                                SizedBox(width: 5),
                                InkWell(
                                  onTap: () async {
                                    // image.getImage(source: ImageSource.gallery);
                                    await getImage4();
                                  },
                                  child: Container(
                                      height: 60,
                                      width: 60,
                                      decoration: BoxDecoration(
                                          color: Colors.black26,
                                          borderRadius:
                                          BorderRadius.circular(10)),
                                      child: (_image4 == null)
                                          ? Icon(Icons.add_a_photo, size: 30)
                                          : Image.file(
                                        _image4,
                                        fit: BoxFit.fill,
                                      )),
                                ),
                                SizedBox(width: 5),
                                InkWell(
                                  onTap: () async {
                                    // image.getImage(source: ImageSource.gallery);
                                    await getImage5();
                                  },
                                  child: Container(
                                      height: 60,
                                      width: 60,
                                      decoration: BoxDecoration(
                                          color: Colors.black26,
                                          borderRadius:
                                          BorderRadius.circular(10)),
                                      child: (_image5 == null)
                                          ? Icon(Icons.add_a_photo, size: 30)
                                          : Image.file(
                                        _image5,
                                        fit: BoxFit.fill,
                                      )),
                                ),
                                SizedBox(width: 5),
                              ],
                            ),

                            SizedBox(
                              height: 10,
                            ),
                            RaisedButton.icon(
                                color: Colors.teal,
                                onPressed: () async {
                                  Navigator.pop(
                                    context,
                                  );
                                  switch (_btnselected) {
                                    case 'Car/موتر':
                                      database.collection("car").add({
                                        "item Name": nameText.text,
                                        "item Desc": detailText.text,
                                        "item Price": priceText.text,
                                        "seller Number": cellNoText.text,
                                        "seller add": addText.text,
                                        "image 1 Url":
                                        (_image1 != null)
                                            ? await uploadPic()
                                            : null,
                                        "image 2 Url":
                                        (_image2 != null)
                                            ? await uploadPic2()
                                            : null,
                                        "image 3 Url":
                                        (_image3 != null)
                                            ? await uploadPic3()
                                            : null,
                                        "image 4 Url":
                                        (_image4 != null)
                                            ? await uploadPic4()
                                            : null,
                                        "image 5 Url":
                                        (_image5 != null)
                                            ? await uploadPic5()
                                            : null,
                                      });

                                      break;
                                    case 'motorcycle/ موترسایکل':
                                      database.collection("motorcycle").add({
                                        "item Name": nameText.text,
                                        "item Desc": detailText.text,
                                        "item Price": priceText.text,
                                        "seller Number": cellNoText.text,
                                        "seller add": addText.text,
                                        "image 1 Url": _image1 != null ? _image1.path : null,
                                        "image 2 Url": _image2 != null ? _image2.path : null,
                                        "image 3 Url": _image3 != null ? _image3.path : null,
                                        "image 4 Url": _image4 != null ? _image4.path : null,
                                        "image 5 Url": _image5 != null ? _image5.path : null,
                                      });
                                      break;

                                    case 'electronics/الکترونیک':
                                      database.collection("electronics").add({
                                        "item Name": nameText.text,
                                        "item Desc": detailText.text,
                                        "item Price": priceText.text,
                                        "seller Number": cellNoText.text,
                                        "seller add": addText.text,
                                        "image 1 Url": _image1 != null ? _image1.path : null,
                                        "image 2 Url": _image2 != null ? _image2.path : null,
                                        "image 3 Url": _image3 != null ? _image3.path : null,
                                        "image 4 Url": _image4 != null ? _image4.path : null,
                                        "image 5 Url": _image5 != null ? _image5.path : null,
                                      });
                                      break;

                                    case 'house/ خانه':
                                      database.collection("house").add({
                                        "item Name": nameText.text,
                                        "item Desc": detailText.text,
                                        "item Price": priceText.text,
                                        "seller Number": cellNoText.text,
                                        "seller add": addText.text,
                                        "image 1 Url": _image1 != null ? _image1.path : null,
                                        "image 2 Url": _image2 != null ? _image2.path : null,
                                        "image 3 Url": _image3 != null ? _image3.path : null,
                                        "image 4 Url": _image4 != null ? _image4.path : null,
                                        "image 5 Url": _image5 != null ? _image5.path : null,
                                      });
                                      break;

                                    case 'household/لوازم خانه':
                                      database.collection("household").add({
                                        "item Name": nameText.text,
                                        "item Desc": detailText.text,
                                        "item Price": priceText.text,
                                        "seller Number": cellNoText.text,
                                        "seller add": addText.text,
                                        "image 1 Url": _image1 != null ? _image1.path : null,
                                        "image 2 Url": _image2 != null ? _image2.path : null,
                                        "image 3 Url": _image3 != null ? _image3.path : null,
                                        "image 4 Url": _image4 != null ? _image4.path : null,
                                        "image 5 Url": _image5 != null ? _image5.path : null,
                                      });
                                      break;

                                    case 'mobile/موبایل':
                                      database.collection("mobile").add({
                                        "item Name": nameText.text,
                                        "item Desc": detailText.text,
                                        "item Price": priceText.text,
                                        "seller Number": cellNoText.text,
                                        "seller add": addText.text,
                                        "image 1 Url": _image1 != null ? _image1.path : null,
                                        "image 2 Url": _image2 != null ? _image2.path : null,
                                        "image 3 Url": _image3 != null ? _image3.path : null,
                                        "image 4 Url": _image4 != null ? _image4.path : null,
                                        "image 5 Url": _image5 != null ? _image5.path : null,
                                      });
                                      break;
                                  }
                                  if(_image1 != null)
                                  uploadPic().then((value) {
                                    DocumentReference docRef = Firestore
                                        .instance
                                        .collection("carPics")
                                        .document();
                                    docRef.setData({"image 1 Url": value},
                                        merge: true);
                                  });

                                  //2
                                  if(_image2 != null)
                                  uploadPic2().then((value) {
                                    DocumentReference docRef = Firestore
                                        .instance
                                        .collection("carPics")
                                        .document();
                                    docRef.setData({"image 2 Url": value},
                                        merge: true);
                                  });

                                  //3
                                  if(_image3 != null)
                                  uploadPic3().then((value) {
                                    DocumentReference docRef = Firestore
                                        .instance
                                        .collection("carPics")
                                        .document();
                                    docRef.setData({"image 3 Url": value},
                                        merge: true);
                                  });

                                  //4
                                  if(_image4 != null)
                                  uploadPic4().then((value) {
                                    DocumentReference docRef = Firestore
                                        .instance
                                        .collection("carPics")
                                        .document();
                                    docRef.setData({"image 4 Url": value},
                                        merge: true);
                                  });

                                  //5
                                  if(_image5 != null)
                                  uploadPic5().then((value) {
                                    DocumentReference docRef = Firestore
                                        .instance
                                        .collection("carPics")
                                        .document();
                                    docRef.setData({"image 5 Url": value},
                                        merge: true);
                                  });
                                },
                                icon: Icon(
                                  Icons.send,
                                  size: 25,
                                  color: Colors.white,
                                ),
                                label: Text(
                                  'Submit  - برو',
                                  style: TextStyle(
                                      fontSize: 20,
                                      color: Colors.white,
                                      fontWeight: FontWeight.bold),
                                ))
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ));
  }
}
</code>
Comment: thanks @Niteesh . i was stuck in there for a couple of days.