An adjoint-based formalism for optimal design of time-delay systems and uncertainty quantification in stochastic systems