Proving OLS unbiasedness without conditional zero error expectation?

Question: The OLS estimate $b$ is equal to $(X^TX)^{-1}X^Ty$ for the linear regression model. If we assume that $E(\epsilon|X)=0$ then it is easy to prove simply by taking the conditional expectation, of $b$ substituting in the expression for $y$ and simplifying.
But how do we prove it if we only know that $E(X^T\epsilon)=0$? $E(\epsilon|X)=0$ implies $E(X^T\epsilon)=0$, but not the other way around.
EDIT: Can I just get an answer, just to be sure, that even if the $u_i$'s are i.i.d., that $E(x_iu_i)=0$ does not imply unbiasedness?
So just to be absolutely clear: If $u_i$ is i.i.d., and we know that $E(x_iu_i)=0$ holds, but we don't know whether $E(u_i|x_i)=0$ holds, then OLS may be biased?
Comment: I think you mean identification not unbiasedness.
Comment: No I meant unbiasedness.
Answer: For this question we can make use of a simple decomposition of the OLS estimator:
$$\begin{equation} \begin{aligned}
\hat{\boldsymbol{\beta}} = (\mathbf{X}^\text{T} \mathbf{X})^{-1} \mathbf{X}^\text{T} \mathbf{Y}
&= (\mathbf{X}^\text{T} \mathbf{X})^{-1} \mathbf{X}^\text{T} (\mathbf{X} \boldsymbol{\beta} + \mathbf{\epsilon}) \\[6pt]
&= \boldsymbol{\beta} + (\mathbf{X}^\text{T} \mathbf{X})^{-1} \mathbf{X}^\text{T} \mathbf{\epsilon}. \\[6pt]
\end{aligned} \end{equation}$$
This useful decomposition follows directly from the form of the OLS estimator and the underlying regression equation, so it is not dependent on any assumptions about the behaviour of the error terms.  From this decomposition, the conditional bias (taking the regressors as fixed) is:
$$\text{Bias}(\hat{\boldsymbol{\beta}}|\mathbf{x}) = \mathbb{E}(\hat{\boldsymbol{\beta}} | \mathbf{x}) - \boldsymbol{\beta} = (\mathbf{x}^\text{T} \mathbf{x})^{-1} \mathbf{x}^\text{T} \mathbb{E}(\mathbf{\epsilon}| \mathbf{x}).$$
The unconditional (marginal) bias (taking the regressors as random variables) is:
$$\text{Bias}(\hat{\boldsymbol{\beta}}) = \mathbb{E}(\hat{\boldsymbol{\beta}}) - \boldsymbol{\beta} = \mathbb{E}((\mathbf{X}^\text{T} \mathbf{X})^{-1} \mathbf{X}^\text{T} \mathbf{\epsilon}).$$
In both cases, the condition $\mathbb{E}(\mathbf{\epsilon}| \mathbf{x}) = \mathbf{0}$ is sufficient for unbiasedness, but in the latter case, the weaker condition $\mathbb{E}((\mathbf{X}^\text{T} \mathbf{X})^{-1} \mathbf{X}^\text{T} \mathbf{\epsilon}) = \mathbf{0}$ is sufficient.  The condition $\mathbb{E}( \mathbf{X}^\text{T} \mathbf{\epsilon}) = \mathbf{0}$  is not sufficient for unbiasedness in either case.
Comment: I think you mean "in the former case" for your last four words...
Comment: Actually, I think it is both cases.  Edited.
Answer: You can't, because the statement is not true under the weaker assumption.
Consider for example the autoregressive model
\begin{equation*}
y_{t}=\beta y_{t-1}+\epsilon _{t},
\end{equation*}
in which the strict exogeneity $E(\epsilon|X)$ is violated even under the assumption $E(\epsilon_{t}y_{t-1})=0$:
we have that
\begin{equation*}
E(\epsilon_ty_{t})=E(\epsilon_t(\beta y_{t-1}+\epsilon _{t}))=E(\epsilon_{t}^{2})\neq 0.
\end{equation*}
But, as $y_{t+1}=\beta y_{t}+\epsilon_{t+1}$, $y_t$ is also a regressor for $y_{t+1}$ and hence, it is impossible in this model that the error term is also uncorrelated with future regressors.
Now, it is also well-known that OLS is biased for the coefficient of an AR(1)-model, see Why is OLS estimator of AR(1) coefficient biased?
Comment: So this problem would go away if we instead required that $E(x_i\epsilon_j)=0$ for all i and j?
Comment: What if we require that $E(x^T\epsilon)=0$
Comment: In my example, you cannot require the idea from the first comment, as I demonstrate. The second is the same as what you already state in your question, it seems.
Comment: @Programmer2134 you are thinking about identification, which renders OLS consistent, but not necessarily unbiased in finite samples in statistical terms (you should take a look here https://stats.stackexchange.com/questions/303403/the-role-of-invoking-unconfoundedness-in-the-rubin-causal-model-treatment-estima/303414#303414). OLS is still consistent,  as $n$ grows the estimator  converges to the parameter, the bias we are talking about is a finite sample property of the estimator, in the sense that the expected value of the estimator is not the parameter.


Qual a vantagem de usar function(window, document, undefined)

Question: Notei a um bom tempo que muitas bibliotecas estão a usar algo como:
(function(window, document, undefined){
    //exemplo de script
    console.log(window, document);
})(window, document);

ou
(function(window, document, undefined){
    console.log(window, document);
}(window, document));

Isto realmente traz vantagem ao desenvolver algo como:
(function(){
    console.log(window, document);
})();

Note: Se undefined é uma variável a normal e pode ser alterada undefined = "new value"; o que impossibilitaria a comparação com var a; if (a === undefined) { ... }
Answer: De um modo geral usa-se funções IIFE desta maneira para salvaguardar que variáveis caiam no escopo global.
Uma IIFE é uma função que se auto-executa, e gera um novo escopo dentro dela própria.
Passar como parâmetro da função window e document não tem grande utilidade, mas tem uma função que é facilitar/optimizar na compressão do código.
Se houver muitas vezes no código dentro dessa função as variáveis window ou document então um compressor de JavaScript como o Uglify vai encurtar e dar uma letra a essas variáveis, dessa maneira minimizando o tamanho do ficheiro.
O caso do undefined é mais interessante.
Por vezes comete-se o erro de sobre-escrever essa variável. Ou seja é possível (em alguns Browsers) fazer undefined = 20. Nesse caso todas as linhas de código que usem undefined para verificar se uma variável está definida vão dar valores inesperados. Criando uma função com 3 parâmetros mas só chamar/usar 2  faz com que o terceiro receba o valor real de undefined. Assim, para browsers que permitem re-escrever undefined este truque re-estabelece o seu valor original.
A outra vantagem e razão para o undefined aí estar é o mesmo que em cima: para compressores de código poderem transformar n vezes a palavra de 9 caracteres "undefined" numa letra só.
Comment: Na verdade a informação sobre o IIFE está fora do escopo da minha questão, mas a sua informação sobre a parte de "comprimir de código" era a resposta ao qual eu necessitava saber. +1
Answer: Sei que a pergunta é antiga, mas já que você linkou a mesma em uma resposta, vale adicionar alguns detalhes.

é util passar os objetos desta forma para realizar testes.
quando se está desenvolvendo em node, a variável window não existe. Neste caso é possível fazer algo assim:
(function(window) {
    window.sayHello = function() {};
})(typeof window !== 'undefined' ? window : this);

Obs: este é o processo que o jquery utiliza.
A questão sobre o undefined serve para garantir que a variável representa realmente o valor undefined já que a mesma pode ser sobrescrita.
Comment: Obrigado, uma boa informação +1
Answer: Eles usam mais pelo undefined mesmo, as vezes pode estar definida de alguma maneira e pode  atrapalhar o código.
Exemplo
undefined = 'foo';
var bar;
bar === undefined; // FALSE

(function (undefined) {
    var bar;
    bar === undefined; // TRUE
})();


Blackberry background image?

Question: I have searched but haven't find out any solution, i have but its creating problems. when I insert this it says illegal argument and doesn't start.
Bitmap bitmap = Bitmap.getBitmapResource("Background.png");

 this.getMainManager().setBackground(

             BackgroundFactory.createBitmapBackground(bitmap)
         );

It doesn't work.
Thanks for helping! Its working. Just a typo error of my path
Comment: you want to add fields to this image ?
Comment: No I just want to set a background
Comment: I mean yes there will be labels and some fields infront of this background.
Answer: tyy this -
final Bitmap top = Bitmap.getBitmapResource("your background image.png");
final VerticalFieldManager top_ = new VerticalFieldManager(Manager.NO_HORIZONTAL_SCROLL | Manager.NO_HORIZONTAL_SCROLLBAR | Manager.VERTICAL_SCROLL | Manager.VERTICAL_SCROLLBAR | Field.USE_ALL_WIDTH){

        public void paint(Graphics graphics) {
            graphics.drawBitmap(0, 0, top.getWidth(),
                    top.getHeight(), top, 0, 0);
            super.paint(graphics);
        }

    };

Now you add all your fields to this top_. then add the top_ to your screen. If there is no fields, it will not display the background image. so Dont forget to add some fields.
Comment: either use Field.USE_ALL_WIDTH and Field.USE_ALL_HEIGHT or set margin.
Comment: I have now many fields with different layouts in it. Can't it can be done in another way? because Im using 2 or 3 vertical and horizontal managers. :S And I already have made 16 classes. I though to add the background at the end. Any idea how to resolve this now?
Comment: add all your items to this VerticalFieldManager .Then add it to your screen.
Comment: Yes its working but its filled half. How can I get it to 100% width and 100% height?

Blackberry background image?


Problemas com consulta Lambda e DateTime

Question: Ola tenho o seguinte código ActionResult da minha controller abaixo:
[HttpPost]
[AuthorizedUser]
public ActionResult Load(DateTime DataInicial, DateTime DataFinal)
{
    var AcessoDominio = new SmartAdmin.Domain.Acesso();
    var Collection = new List<AcessoDto>();

    Collection = AcessoDominio.GetList(_ => _.DTH_ACESSO >= DataInicial &&
                                                _.DTH_ACESSO <= DataFinal)
                                                 .OrderByDescending(_ => _.DTH_ACESSO)
    .ToList();

    ViewBag.DataInicial = DataInicial;
    ViewBag.DataFinal = DataFinal;

    return View("Index", Collection.ToPagedList(1, PageSize));
}

Quando do um submit na pagina de duas datas por exemplo 22/09/2015 e 22/09/2015
respectivas Data Inicial e Data Final minha consulta não retorna nada e quando
mudo a consulta para  22/09/2015 e 23/09/2015 retorna somente itens do dia 22.
O que eu precisaria é consultar é as data no between e tambem por hora a query que é gerada pelo Entity é a seguinte :
SELECT
`Extent1`.`COD_ACESSO`,
`Extent1`.`COD_USUARIO`,
`Extent1`.`TIPO_USUARIO`,
`Extent1`.`IP`,
`Extent1`.`BROWSER`,
`Extent1`.`PLATAFORMA`,
`Extent1`.`RESOLUCAO`,
`Extent1`.`DTH_ACESSO`,
`Extent1`.`DIA`,
`Extent1`.`MES`,
`Extent1`.`ANO`,
`Extent1`.`HORA`,
`Extent1`.`URL_ACESSO`,
`Extent1`.`DISPOSITIVO`,
`Extent1`.`DOMINIO`,
`Extent1`.`SUPORTA_ACTIVEX`,
`Extent1`.`SUPORTA_COOKIES`,
`Extent1`.`SUPORTA_JAVA_APPLET`,
`Extent1`.`COORD_LATITUDE`,
`Extent1`.`COORD_LONGITUDE`,
`Extent1`.`CIDADE`
FROM `ACESSO` AS `Extent1`
 WHERE (`Extent1`.`DTH_ACESSO` >= @p__linq__0) AND (`Extent1`.`DTH_ACESSO` <= @p__linq__1

Não sei como proceder para retornar por exemplo itens do mesmo dia entre a horas 22/09/2015 00:00:00 e 22/09/2015 23:59:59
Detalhes: Meu campo já esta como DateTime '_.DTH_ACESSO' nao sei como prosseguir!
Comment: você quer pegar independente da hora ?
Comment: Então, quero pegar data e hora. se alguem acessou o sistema ou melhor fez login as 22/09/2015 as 23:58:00 esse dado tem que retornar. quando fizer a consulta 22/09/2015 00:00:00 e 22/09/2015 23:59:59 mas na View tenho campos com DatePicker que so preenchem dia mes e ano entende;
Comment: Faça o teste com a minha resposta `DbFunctions` e me fala se deu certo!
Answer: Use DbFunctions, com o método TruncateTime:
Independentemente da Hora você quer pegar todos as datas diante o período informado e deve informar ao Entity Framework que você só quer pela data (eu vi pela lógica sua que a hora nessa consulta não precisa)
Exemplo
DateTime dataInicial = DateTime.Parse("22/09/2015");
DateTime dataFinal = DateTime.Parse("22/09/2015");

myDataBaseEntities db = new myDataBaseEntities();

IList<Datas> datas = db.Datas
    .Where(x => DbFunctions.TruncateTime(x.Data) >= dataInicial
             && DbFunctions.TruncateTime(x.Data) <= dataFinal)
    .ToList();

SQL gerada por causa do DbFunctions.TruncateTime:
SELECT
    [Extent1].[Id] AS [Id],
    [Extent1].[DataJulia] AS [DataJulia],
    [Extent1].[Data] AS [Data]
    FROM [dbo].[Datas] AS [Extent1]
    WHERE ((convert (datetime2, convert(varchar(255), [Extent1].[Data], 102) ,  102)) >=
    @p__linq__0)
   AND ((convert (datetime2, convert(varchar(255), [Extent1].[Data], 102) ,  102))
   <= @p__linq__1)

Observação: Se você mudar a sua regra aonde a data virá completa e você quer pegar pela hora também a sua tela deve ser alterada para aceitar a digitação da hora junto com a data e ai não precisa colocar o DbFunctions.TruncateTime. Essa observação é mediante o relato nos comentários.


How do I get the entity ID when inserting a new node?

Question: How do I get the ID of the inserted entity?
I am trying to use hook_ENTITY_TYPE_presave() and hook_ENTITY_TYPE_insert(), but in neither of those I can get the entity ID.
In hook_ENTITY_TYPE_presave(), I used the following code.
 if ($entity->isNew()) {
    print $entity->id();
 }

Comment: Is this a duplicate of https://drupal.stackexchange.com/questions/188667/how-can-i-alter-the-title-of-a-node-upon-save? If not, can you provide more details?
Comment: Updated my question.
Comment: Why not use Pathauto?
Comment: Please don't change a question to ask something else once it's been answered. If you have another question, just ask a new question
Comment: im having same issue.. did u fix it ?
Answer: The ID isn't available in hook_ENTITY_TYPE_presave() (pre meaning before, as in not saved so the database hasn't assigned it an ID yet), but is definitely available in hook_ENTITY_TYPE_insert().
This will work, for example:
function MODULE_node_insert(NodeInterface $node) {
  // No need to check `isNew()`; if it's in an insert hook, it's new.
  $nid = $node->id();
}

Comment: This hook is not working in my module. Unable to found the issue. Even I put die() as well.
function hook_node_insert(NodeInterface $node) {
   print $nid = $node->id(); die('---------------');
}
Comment: You've spelled it wrong then, or not enabled the module, something other than what the docs say to do. This definitely answers your question _How to get nid while inserting new node drupal 8_. Look at the example for the hook itself: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_ENTITY_TYPE_insert/8.2.x. It uses `$entity->id()`. I know from experience that those docs are correct
Comment: ok, need to do more debugging then. Thanks for your reply.
Comment: Don't use `die`. Use a debugger like xdebug.
Comment: this hook is not triggered for me.. any idea?
Answer: I needed to do something similar - this worked for me:
function your_module_node_insert($node) {
  if ($node->getType() == 'your_node') {
        $node->setTitle('New entity ' . $node->id()); // to update title with node id
        $node->field_test = 'Id' . $node->id();  // or, to update a text field with node id
        $node->save();
  }
}


How to find which variable impacts the answer the most in this equation?

Question: In this equation, if two of the variables are held constant, which variable will bring out the maximum positive change in the answer? I tried doing this in excel, but I'm having trouble figuring out if I'm on the right track. I got 27 different scenarios in the excel sheet and sorted by the highest value. Instinct tells me this is not the correct way to determine this.
$$S = \frac{AB}{1+C-B}$$
Comment: Touchè, did the OP mean this:
$S = {{A\times}B\over1+C} - B$ or this:
$S = {{A\times}B\over1+C - B}$?
Comment: @Morgormir All right, you got me!
Comment: I've edited your question, is this what you meant? Or did you mean: $S = {{A\times}B\over1+C - B}$?
Comment: @Morgormir OP can't see your edit yet. ... And I suspect s/he meant what you wrote in the comment, since dividing by one wouldn't make much sense.
Comment: Eeek, sorry to edit over you, morgor. I didn't check the comments' timestamps before I reviewed it :/
Comment: @EricStucky No problem
Comment: I'm interested in knowing whether or not my answer was useful to you or not, as I suspect you might not have experience with calculus? If you'd like I'd be happy to make some plots that visualize what's going on, so you don't have to rely so much on the formulas?
Comment: All right, I went ahead and did it either way! If the math is too much, go to the very bottom of my answer, and I have some conclusions for you... but really, all the fun is in the exploration that leads up to those :)
Answer: I've renamed your variables so as to be more familiar looking:
$$f(x,y,z) = \frac{xy}{1+z-y}$$
In multivariable calculus, there's something called the gradient of a function $f$ in a point $a$, which is $$\nabla f(a) = \left. \pmatrix{\partial_xf\\\partial_yf\\\partial_zf} \right|_a$$ which means that the 1st/2nd/3rd entry in the vector is the derivative of $f$ with respect to $x$/$y$/$z$, respectively, evaluated in the point $a$.
All right, how do we use it? Well, there's a theorem that states that when you take $f$ in some point $a$, the direction in which $f$ grows the most from there is the direction of the gradient in that same point.
In your case, the gradient is $$\nabla f(x,y,z)=\pmatrix{\frac{y}{1+z-y} \\ \frac{x(1+z)}{(1+z-y)^2} \\\frac{-xy}{(1+z-y)^2}} = \frac{x}{(1+z-y)^2}\pmatrix{\frac{y}{x}(1+z-y) \\ 1+z \\-y}$$
So if you take any point $(x,y,z)$ and plug it into that gradient, whichever of the three is bigger is the one that will bring the maximum change. For instance, if it was the first that was the biggest, then you know that you should be going in the $x$-direction to get the biggest change.
Try playing around with it and - if you have the possibility - make some contour plots... it's fun, I promise!

EDIT: Visualization time!
This would be so easy if only had two variables. With three variables, however, we need three axis ($x,y,z$) and one axis for the value of $f(x,y,z)$ - that's one too many!
Still, there are a couple of methods that can aid with the visualization. The one I'll choose here is one where you only look at one value of $f$ at a time. If we call this value $c$, we can write $$f(x,y,z)=c=\frac{xy}{1+z-y} \leftrightarrow xy = c(1+z-y) \leftrightarrow z=\frac{xy}{c}+y-1$$
Now we have a function $z(x,y)$ of only two variables, and this can be plotted, here for $c=1$ (note that $c$ doesn't change the shape of the surface, only how steep it is):

So how to interpret this? In relation to $f$ this is, admittedly, a bit hard. What we can say is that, for a constant value of $f$, $x$ and $y$ influences $z$ equally.
Let's try something more powerful: Plotting the gradient! Since the gradient in a point is a vector (an arrow, with a magnitude and a direction), its generalization to any point is a vector field. I've plotted it here:

The $x,y$-axis lies closest to the screen ($y$ is up, $x$ is to the left (notice the axis-values!)) and the $z$-axis is going into the screen.
The way to read this is as follows: Pick a point $(x,y,z)$ and look at the arrow coming out of this point. The direction the arrow is pointed is the direction you'd want to take a step in to make the value of $f$ bigger. The magnitude of the arrow indicates how big a change a single step results in (so big arrow $\rightarrow$ big effect, and vice versa). Neat, right?
Since the directions can be hard to see, I've the same thing, but seen from the left instead of from the right:

Note that I've chosen to plot in the interval $[0,5]$ for all three variables. However, the behavior of the vector field seems to scale without changing when looking at larger intervals, so I think it is fair to assume the analysis below is valid for larger values as well.
As you can see, the gradients all seem to point in pretty much the same direction, namely in the direction of lower $z$ and higher $y$. $x$ only seem to vary the magnitude of the gradient, i.e., how big an effect taking a step has.
Let's take a look at a specific point, say $(4,4,4)$. Then $$\nabla f(4,4,4) = 4\pmatrix{1 \\ 5 \\ -4} \rightarrow r_{4,4,4} = \frac{1}{\sqrt{42}}\pmatrix{1 \\ 5 \\ -4}$$
where $r_{x,y,z}$ is just the unit vector pointing in the direction of $\nabla f(x,y,z)$.
Let's compare this with the gradient of another point $(4,3,2)$. Then $$r_{4,3,2} =\frac{1}{\sqrt{2}}\pmatrix{0 \\ 1 \\ 1}$$
It is clear that these do not point in the same direction. From this can be concluded that what direction you should go in to make $f$ bigger depends on where you're standing. But in general, from our purely visual analysis regarding the general direction of the field of the gradient, we can say:

In general, if you want to maximize $f$, go in the direction of higher $y$'s and lower $z$'s. To get a bigger overall effect of your steps, increase $x$.

And to make the conclusion complete:

But really, which way you should go depends on the specific values of $(x,y,z)$.
Comment: +1 I hope the OP can understand this thoughtful complete answer. S/he should at least appreciate it.
Comment: @EthanBolker Thank you very much! Well, either way, it was fun to write, and I've been training myself to focus on that aspect of answering questions, instead of the reputation/recognition aspect; I have caught myself getting bitter because OP didn't respond to a (I think) good answer of mine, because I didn't get any rep. out of it, but that situation is not desirable. Of course, getting the human response that ones work is appreciated is wonderful (and your comment certainly had that effect!), but really, I do this because I think it is fun... or because I'm trying to escape doing chores :P


What is the best built-in optimizer in Matlab for this problem?

Question: I need to optimize
$$\sum_{j=1}^p\frac{\sigma^2 \alpha_j^2}{\sigma^2+\delta_j^2\alpha_j^2}-\frac{\left(\displaystyle\sum_{j=1}^p \displaystyle\frac{\sigma^2 ( \delta_j^2 \alpha^2 - \theta\alpha_j)}{\sigma^2+\delta_j^2\alpha_j^2}\right)^2}{(p^2\sigma^2+p \theta^2) - \displaystyle\sum_{j=1}^p \frac{(\sigma^2+\theta \delta_j\alpha_j)^2}{\sigma^2+\delta_j^2\alpha_j^2}}$$
it terms of $\alpha$ where

$\alpha$ is a vector of four parameters,
$\sigma$ is a constant,
$\delta$ is the product of $\alpha$ and another vector which is fixed in value, and
$\theta$ is the sum of the $\delta$'s.

I think fminunc would be most suitable given the problem in non-linear, and I don't want to use any constraints (unless I have to).
Just wondered if fminunc is indeed most suited to my problem?
In the Matlab documentation, you are invited to use a table to choose the best solver (link); it seems to suggest quadprog but doesn't even mention fminunc?
Thanks
Answer: For this problem you are interested in unconstrained optimization and you have a smooth nonlinear problem objective (assuming that the denominator does not blow up). From the table in the Matlab documentation, you have two choices: either fminunc or fminsearch are appropriate. (Also, the table indicates that quadprog is appropriate but only for a quadratic objective.)


Using activities from library

Question: I'm creating my first library to use in some future projects, on it I'm creating some Activities that are the same on every project.
Right now I'm working with a test project and on my library I have this LoginActivity. It has it's own layout and works fine.
How can I make my test app LoginActivity be the one from the library? At the moment I'm extending my LoginActivity from the library into my activity on the project. Is this the right way of doing it considering that all the code logic happens on the Library activity?
Library LoginActivity
public class LoginActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        // Some useless code...

    }
}

Project Login Activity
public class MainActivity extends LoginActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Nothing happens in this class... really...

    }

}

Comment: Presumably you will have other activities that extend LoginActivity. What common functionality will be needed such that the subclasses need to have LoginActivity as a parent class?
Comment: Mostly it's because I'll use it in two different projects, It will handle the authentication process with the online server, so instead of having it and another classes that will be identical on multiple projects, I'm trying to create a library with them.
Comment: So then, why not use LoginActivity directly? Since you are setting the layout in the parent class, the layout is the same regardless of the project. I guess I'm hesitant to have an activity like that in a library. It sounds like you could create a utility class library that handles the authentication process.
Comment: Yes, the layout is the same, but I don't know how to use the Activity from the Library directly. How can I do this?
Comment: I wouldn't have the activity in the library. In each project have `public class MainActivity extends AppCompatActivity`. Then have a library project, call it `LoginUtilities` maybe and have a  method `public static boolean authenticate(...)` and each project's `MainActivity` calls this method.
Comment: If you're intent (ha!) on having a library with an Activity, I would read [these SO questions](https://www.google.com/webhp?source=search_app#q=android+activity+in+library+project).
Answer: Add login activity into AndroidManifest.xml in library or application.
<application>
        <activity
            android:name="com.mypackage.LoginActivity" />

</application>

Answer: Make sure that Activity that is inside of the library project is declared inside of the library's manifest file. Then start the activity how you normally would start any other activity. If you want the activity to be the first activity when the app launches (launcher activity), you need to declare it explicitly inside of your manifest and add an intent-filter tag element as a child, that indicates it should be the launcher activity. View this post.. Another way to roughly achieve the same effect would be to create a blank activity that is declared in the app manifest file as the launcher activity and inside of the onCreate method launch the library activity. Make sure you clear any and all activity transitions so that the switch to the library activity is seamless. The benefit to this approach is that you can perform a check before launching the library activity.
Ex. checking if the login activity needs to be displayed or if the screen can be by-passed and the app can be entered immediately.

Using activities from library


jQuery - how to use the "on()" method instead of "live()"?

Question: I have the following code (which I've simplified for this) which worked fine alongside jquery-1.7.

Like 1

Like 2

Like 3

<input type="text" /> Save 1

<input type="text" /> Save 2

<input type="text" /> Save 3

JQuery
$(document).find("div[id^='sublike-']").live('click', function(){
    var num = this.id.split('-')[1];
    $('#sublike-form-' + num).toggle();
});

I'm trying to upgrade my code though so I can upgrade my jQuery pack version so I've changed it to onclick.
This doesn't do anything though. It doesn't throw any errors either so I can't see where the problem is.
 $(document).find("button[class^='sub-']").on('click','a', function(){
           alert('hi');
        });

Any ideas?
Update
This is my button
 <button type="button"  id="sub-'+o.id+'"  class="select_address btn btn-
     primary icon  pull-right">Select</button>

Comment: Yo are trying to assign click event handler to a `a` tag within `button`...
Comment: I don't see any elements matching the selector `button[class^='sub-']`
Comment: still there is no class in the button type.and also you don't have any a tag inside the button
Comment: @Kate Fernando i don't know how to write it please help me because i am new to web development(learner)
Answer: $(document).find("button").on('click','a', function(){..});

You are applying the "click" event to an a element within the button - that does not match your html (and would also be invalid html - links are not valid children of buttons)
You need
$("button").on('click',function(){ ... });

or
$(document).on('click','button', function(){ ... });

Note that I took the attribute part out of your selector - it was wrong, but you can target the right button exactly as you would any other selector in jQuery.
Answer: In the following code what you are doing is find the button with the class that has 'sub'. And then inside that should be a tag and by clicking that you have to alert 'hi'.
Following is the html that can map with your jquery code.
<button type="button"  class="sub-'+o.id+'">Select</button>

$(document).find("button[class^='sub-']").on('click','a', function(){
               alert('hi');
            });

But remember don't use the above scenario since we are creating separate class for each element. This should not happen. you should use id to create separate ids.
Otherwise you have to change your jquery code with relevant to your html code as below.
$(document).find("button[id^='sub-']").on('click', function(){
                   alert('hi');
                });

Please let me know if you have any further issues.
Thanks

jQuery - how to use the “on()” method instead of “live()”?


Should HEAD's response status code be the same as GET's status code?

Question: As I know, HEAD is the same as GET, but without response body. If I request resource that doesn't exist, GET will response with 404 Not Found. What status code should return HEAD request in this case? 200 OK or 404 Not Found?
Comment: You get a `status` response from the `http` request, and not from the method ! So for sure it will be 404 ! https://developer.mozilla.org/pt-BR/docs/Web/HTTP/Status
Answer: As you said yourself, the response should be the same except there is no body.
This means that both the status and headers need to be the same as they would be for a GET request.


como fazer curl -X POST -d em PHP

Question: Estou fazendo um integração com uma api que traz imóveis
Na documentação, está assim:
curl -X POST -d "client_id=1234&client_secret=abcd&grant_type=client_credentials" \
https://www.linkapi.com.br/oauth/token

Porém não sei como fazer em PHP, fiz da maneira abaixo, mas retornou em branco({}bool(true)):
$client_id="1234";
$client_secret="abcd";
$url ="https://www.linkapi.com.br/oauth/token";

$process = curl_init($url);
$data = json_encode(array('grant_type' => 'client_credentials', 'client_id' => $client_id, 'client_secret' => $client_secret));
curl_setopt($process, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
curl_setopt($process, CURLOPT_POST, true);
curl_setopt($process, CURLOPT_POSTFIELDS, $data);
$resp = curl_exec($process);

Answer: O dado está em x-www-form-urlencoded, e não em JSON.
-d "client_id=1234&client_secret=abcd&grant_type=client_credentials"

Isto é um urlencoded, e não um JSON.

Para ter exatamente o mesmo efeito, teria que utilizar:
$data = http_build_query(['grant_type' => 'client_credentials', 'client_id' => $client_id, 'client_secret' => $client_secret]);

$process = curl_init($url);
curl_setopt($process, CURLOPT_HTTPHEADER, ["Content-Type: application/x-www-form-urlencoded"]); // O -d utiliza `application/x-www-form-urlencoded` por padrão.
curl_setopt($process, CURLOPT_POST, true);
curl_setopt($process, CURLOPT_POSTFIELDS, $data);
curl_setopt($process, CURLOPT_RETURNTRANSFER, true); // Para "salvar" a resposta no curl_exec (o $resp).
$resp = curl_exec($process);

A única diferença é a remoção do json e o uso do http_build_query.
Comment: perfeito, deu certinho, obrigado! só pra eu aprender o urlencoded é por causa do -X?
Comment: e outra coisa, ele printou na tela {"access_token":"q95b","token_type":"Bearer","expires_in":31535701,"scope":"basic_info building_list building_details feedback","created_at":1586782560} como pego o acess_token?
Comment: @LeandroTeraoka Isso é por causa do `-d`, e devido ao tipo de dado que está sendo enviado. É uma serie de fatores. Se estivesse como `-d '{"client_id": 1234, "client_secret": abc}'` seria um JSON, você reconhece que isso é JSON. Enquanto que um `client_id=1234&client_secret=abcd` é um urlencoded, se fosse utilizasse o `-F` seria um `multipart/form-data`. Mas, especificamente sobre o JSON, provavelmente também usaria o `-H "Content-Type: application/json"` para sobrescrever o `Content-Type`.
Comment: @LeandroTeraoka Você deve usar o `CURLOPT_RETURNTRANSFER` para que o `$resp` tenha o valor da resposta. Isso é, `curl_setopt($process, CURLOPT_RETURNTRANSFER, true);`, editei a resposta para incluir isto.
Comment: deu certinho, muito obrigado!

como fazer curl -X POST -d em PHP


How to remove special characters?

Question: How to remove special characters?
foreach ($login_and_logout_list['rval'] as $k => $v) {
  $login_time[] = $v['login_time'];
  $logout_time[] = $v['logout_time'];
  $create_time[] = $v['create_time'];
  $i++;
}
var_dump($login_time);

What i am getting in var_dump
array (size=3)
  0 => string '{09:46},{09:48}'
  1 => string '{05:04},{07:04},{08:40},{08:54}'
  2 => string '{05:20}'

What i want in var_dump is
array (size=3)
  0 => string '09:46 | 09:48'
  1 => string '05:04 | 07:04 | 08:40 | 08:54'
  2 => string '05:20'

Comment: Possible duplicate of [Remove all special characters except space from a string using JavaScript](https://stackoverflow.com/questions/6555182/remove-all-special-characters-except-space-from-a-string-using-javascript)
Comment: You can str_replace on php.. Since your code is on php and not javascript.
Answer: I assume you want to port your code from PHP to JavaScript.

var a = ['{09:46},{09:48}', '{05:04},{07:04},{08:40},{08:54}', '{05:20}']

a = a.map(o => {
   return o.replace(/(}\,{)/mg, ' | ').replace(/(}|{)/mg, '');
})

console.log(a);

Here's the PHP solution:
<?php

$a = ['{09:46},{09:48}', '{05:04},{07:04},{08:40},{08:54}', '{05:20}'];

$a = array_map( function($o){

    $o = preg_replace('/(}\,{)/m', ' | ', $o);

    $o = preg_replace('/(}|{)/m', '', $o);

    return $o;

}, $a);

var_dump($a);

// output
// array(3) {
//      [0]=> string(13) "09:46 | 09:48"
//      [1]=> string(29) "05:04 | 07:04 | 08:40 | 08:54"
//      [2]=> string(5) "05:20"
// }

Comment: @PrabhudevVatnal, the code I posted works perfectly if the environment is JavaScript. I can post a PHP solution as well.
Comment: Please try that above problem

How to remove special characters?


polar coordinates and derivatives

Question: Using the standard notation $(x,y)$ for cartesian coordinates, and $(r, \theta)$ for polar coordinates, it is true that $$ x = r \cos \theta$$ and so we can infer that
$$ \frac{\partial x}{\partial r} = \cos \theta.$$ This means that if we perturb $r$ to $r+\Delta r$, $x$ gets perturbed to approximately $x+ \cos(\theta) \Delta r$. This is equivalent to saying that if we perturb $x$ to $x+\Delta x$, then we perturb $r$ to approximately $r+ (1/\cos \theta) \Delta x$. Correspondingly, we expect that $$ \frac{\partial r}{\partial x} = \frac{1}{\cos \theta}.$$ In fact,
$$ \frac{ \partial r}{\partial x} = \frac{\partial}{\partial x} \sqrt{x^2+y^2}= \frac{2x}{2 \sqrt{x^2+y^2}} = \frac{x}{r} = \cos \theta.$$ What gives?
Comment: If you are in the $(r,\theta)$ plane, a change in $r$ does not affect $\theta$; the change in $x$ is proportional to the change in $r$, with the constant of proportionality given by $\cos\theta$, which is constant because $\theta$ is not changing. But if you are in $(x,y)$-plane, a change in $x$ affects *both* $r$ and $\theta$, so you cannot consider $\cos\theta$ a fixed quantity; this means that the claim that perturbing $x$ by $\Delta x$ corresponds to perturbing $r$ by $\frac{1}{\cos\theta}\Delta x$ is unjustified and unclear: *which* $\theta$? $\theta$ changes!
Comment: Good question. I had the same questions when I first learnt partial derivatives. My teachers did not emphasize what we were doing and used to simply write out the answer using the appropriate expressions.
Answer: When you take partial derivatives, what you are doing is to hold the other variable fixed. So for instance if $f$ is a function of $n$ variables, $f(x_1,x_2,\ldots,x_n)$, $\frac{\partial f}{\partial x_i}$ means you hold all the other $x_j$'s constant except $x_i$ and vary $x_i$ by $\delta x_i$ and find out what happens to $\delta f$.
We have
$x= r \cos(\theta)$,$y= r \sin(\theta)$, $r^2= x^2 + y^2$ and $\tan(\theta) = \frac{y}{x}$.
We are transforming from the $(x,y)$ space to $(r,\theta)$ space.
In the $(x,y)$ space, $x$ and $y$ are independent variables and In the $(r,\theta)$ space, $r$ and $\theta$ are independent variables.
$\frac{\partial x}{\partial r}$ means you are fixing $\theta$ and finding out how changing $r$ affects $x$.
So $\frac{\partial x}{\partial r} = \cos(\theta)$ since $\theta$ is fixed.
$\frac{\partial r}{\partial x}$ means you are fixing $y$ and finding out how changing $x$ affects $r$.
So $\frac{\partial r}{\partial x} = \frac{x}{\sqrt{x^2+y^2}}$ since $y$ is fixed.
When you do $r = \frac{x}{\cos(\theta)}$ and argue that $\frac{\partial r}{\partial x} = \frac{1}{\cos (\theta)}$ you are not holding $y$ constant.
If you were to hold $y$ constant, then $\theta$ would change as well.
EDIT:
I am adding this in the hope that this will make it a bit more clear. If you want to use $r = \frac{x}{\cos(\theta)}$ and still derive it, you need to do as follows:
$r = \frac{x}{\cos(\theta)}$, $\delta r = \frac{\delta x}{\cos(\theta)} + \frac{-x}{\cos^2(\theta)} (-\sin(\theta)) \delta \theta$.
$\tan(\theta) = \frac{y}{x} \Rightarrow x \tan(\theta) = y$
$\delta x \tan(\theta) + x \sec^2(\theta) \delta \theta = 0$ (Since $y$ is held constant)
$x \delta \theta = - \frac{\delta x \tan(\theta)}{\sec^2{\theta}} = - \sin(\theta) \cos(\theta) \delta x$.
Plugging the above in the previous expression, we get
$\delta r = \frac{\delta x}{\cos(\theta)} + \frac{\sin(\theta)}{\cos^2(\theta)} (-\sin(\theta) \cos(\theta) \delta x) = \frac{1-\sin^2(\theta)}{\cos(\theta)} \delta x = \cos(\theta) \delta x$ and hence we get
$\frac{\partial r}{\partial x} = \cos(\theta) = \frac{x}{\sqrt{x^2+y^2}}$
Comment: Or, alternatively to "not holding $y$ constant", one is not applying the chain rule properly, since $\theta$ *also* changes with $x$.
Comment: @Arturo: Right. I was adding that when you made this comment.
Comment: I would only add a reference to the inverse function theorem: http://en.wikipedia.org/wiki/Derivative_rule_for_inverses#Statement_of_the_theorem

polar coordinates and derivatives


Query com ForEach e Subquery Node JS e MSSQL

Question: Estou com um problema que não achei solução ainda, tenho um select em uma procedure, que faço um forEach no resultado, dentro desse forEach faço outro select em outra procedure utilizando os Ids conforme código abaixo.
Funciona o problema é que na hora de fazer o bulk no mongo db por algum motivo a function done() esta chamando o bulk mais de uma vez, em algum momento o done() esta sendo chamado mais de uma vez.

var consultaSQL = function(){

  console.time('sql');
  sequelize.query('PRS_MONGO_PRODUTO;', { type: sequelize.QueryTypes.SELECT }).then(function(result){
    console.log(result.length);
    console.timeEnd('sql');

    done = _.after(result.length, function () {
      if(result.length > 0) {
        var i = 1;
        var bulk = Detalhe.collection.initializeOrderedBulkOp();
        console.time('bulk');
        result.forEach(function(p){
          bulk.find({ produtoId: p.produtoId, clienteId: p.clienteId }).upsert().replaceOne(p);
        });
        console.timeEnd('bulk');

        console.log('Quantidade Exec: ' + result.length);
        console.time('exec');

        bulk.execute(function (err, result) {
          if(err) console.error(err);
          console.timeEnd('exec');
          console.log('##################### Inicia em 5 Segundos! #####################');
          var teste =  setTimeout(function () {
            consultaSQL();
          }, 5000);
        });
      }
      else {
        console.log('##################### Sem registros! #####################');
        setTimeout(function () {
          consultaSQL();
        }, 30000);
      }
    });
    if(result.length == 0) done();
    result.forEach(function(p){
      p.skus = [];
      sequelize.query('PRS_PESQ_PRODUTO_INDEXACAO_MONGO ' + p.clienteId + ', ' + p.produtoId, { type: sequelize.QueryTypes.SELECT }).then(function(resultA){
        done2 = _.after(resultA.length, function () {
          done();
        });

        if(resultA.length == 0) done2();

        resultA.forEach(function(s){
          sequelize.query('select caminho as imagem from produtoSkuImagem where produtoSkuId = ' + s.produtoSkuId, { type: sequelize.QueryTypes.SELECT }).then(function(resultB){

            done3 = _.after(resultB.length, function () {
              done2();
            });
            s.imagens = [];
            s.imagens.push(resultB)
            p.skus.push(s);
            done3();
          });

        });

      });
    });
  }).catch(function(err){
    console.error(err);
    process.exit();
  });
}

O resultado que ele tem que gerar é esse abaixo:
{
"_id" : ObjectId("573b202f6d16e35c707c3119"),
"clienteId" : 1,
"produtoId" : 3948,
"parceiroId" : 1,
"codigoProduto" : "2014526",
"nome" : "Armário Blumenau Branco - Politorno",
"descricao" : "Armário para Forno Microondas, com duas portas.Fabricado em chapas de 15mm. Limpeza do móvel deve ser feita com um pano umedecido com água.",
"codigoMarca" : 3150,
"marca" : "Politorno",
"produtoSkuId" : 4424,
"peso" : 23250,
"altura" : 11,
"comprimento" : 109,
"estoque" : 1,
"preco" : 185.31,
"precoDe" : 285,
"pontos" : 195,
"parcelamento" : 1,
"imagem" : "https://static.wmobjects.com.br/imgres/arquivos/ids/2509026",
"ativo" : 1,
"dataCadastro" : ISODate("2016-03-21T11:10:53.620Z"),
"dataAtualizacao" : ISODate("2016-05-17T10:29:27.590Z"),
"skus" : [
    {
        "clienteId" : 1,
        "produtoId" : 3948,
        "parceiroId" : 1,
        "codigoProduto" : "2014526",
        "nome" : "Armário Blumenau Branco - Politorno",
        "descricao" : "Armário para Forno Microondas, com duas portas.Fabricado em chapas de 15mm. Limpeza do móvel deve ser feita com um pano umedecido com água.",
        "codigoMarca" : 3150,
        "marca" : "Politorno",
        "produtoSkuId" : 4424,
        "peso" : 23250,
        "altura" : 11,
        "comprimento" : 109,
        "estoque" : 1,
        "preco" : 185.31,
        "precoDe" : 285,
        "pontos" : 195,
        "parcelamento" : 1,
        "imagem" : "https://static.wmobjects.com.br/imgres/arquivos/ids/2509026",
        "ativo" : 1,
        "dataCadastro" : ISODate("2016-03-21T11:10:53.620Z"),
        "dataAtualizacao" : ISODate("2016-05-17T10:29:27.590Z"),
        "imagens" : [
            [
                {
                    "imagem" : "https://static.wmobjects.com.br/imgres/arquivos/ids/2514797"
                },
                {
                    "imagem" : "https://static.wmobjects.com.br/imgres/arquivos/ids/2514804"
                },
                {
                    "imagem" : "https://static.wmobjects.com.br/imgres/arquivos/ids/2514811"
                }
            ]
        ]
    }
]

}
Esse código funciono o problema é que ele chama o bulk mais de uma vez sendo assim ele inseri mais de uma vez, então o resultado fica demorado. Preciso que o done() seja chamado somente uma vez e do modo certo.
Answer: O ideal é que você transforme sua query em apenas uma, trazendo todos os produtos e relacionando já com todos os skus e imagens. Fica muito mais performático do que fazer outras queries dentro de um loop.
Os registros vindo duplicados vc trata isso no código.
Fiz uma função de exemplo pra facilitar:

// Esse é o resultado da sua query com todos os joins
var resultset = [
 {prod: 1, prod_nome: 'prod_1', sku: 51, sku_nome: 'a', img: '1.jpg'},
 {prod: 1, prod_nome: 'prod_1', sku: 51, sku_nome: 'a', img: '2.jpg'},
 {prod: 1, prod_nome: 'prod_1', sku: 51, sku_nome: 'a', img: '3.jpg'},
 {prod: 1, prod_nome: 'prod_1', sku: 52, sku_nome: 'b', img: '1.gif'},
 {prod: 1, prod_nome: 'prod_1', sku: 52, sku_nome: 'b', img: '2.gif'},
 {prod: 1, prod_nome: 'prod_1', sku: 52, sku_nome: 'b', img: '3.gif'},
 {prod: 2, prod_nome: 'prod_2', sku: 53, sku_nome: 'c', img: 'c1.jpg'},
 {prod: 2, prod_nome: 'prod_2', sku: 53, sku_nome: 'c', img: 'c2.jpg'},
 {prod: 2, prod_nome: 'prod_2', sku: 54, sku_nome: 'd', img: 'd.jpg'}
];

function Resultset(rs){
 var o = this;
 o.reader = rs;
 o.idx = -1;
 o.len = rs.length;
 o.current = null;
 o.fieldKeys = {}
 o.lastFKeyIteration = null;
 o.end = false;
}
Resultset.prototype.get = function(field) {
 return this.current[field];
}
Resultset.prototype.next = function(fieldKey) {
 var o = this;
 var rs = o.reader;
 fieldKey = fieldKey || null;
 var nextFK = fieldKey != o.lastFKeyIteration && o.lastFKeyIteration != null;
 if(!nextFK)
  o.idx++;

 o.lastFKeyIteration = fieldKey;
 if(fieldKey != null && typeof o.fieldKeys[fieldKey] == 'undefined')
    o.fieldKeys[fieldKey] = null;

 if(!o.end){
  if((fieldKey != null && nextFK) || o.idx < o.len) {
   if(fieldKey != null) {
    for(var fk in o.fieldKeys) {
     var _v = rs[o.idx][fk];
     if(_v != o.fieldKeys[fk] && fk != fieldKey)
      return false;

     if(fk == fieldKey) {
      o.fieldKeys[fieldKey] = _v;
      break;
     }
    }
   }

   o.current = rs[o.idx];
   return true;
  }
  o.end = true;
  return false;
 }
 return false;
}

// Para utilizar ficaria algo do tipo:
var rs = new Resultset(resultset);

var data = [];
if(rs.next('prod')){
  do{
    var prod = {
      id: rs.get('prod'),
      nome: rs.get('prod_nome'),
    };
    var skus = [];
    while(rs.next('sku')){
      var sku = {
        id: rs.get('sku'),
        nome: rs.get('sku_nome')
      };
      var imgs = [];
      while(rs.next('img')){
        imgs.push(
          rs.get('img')
        );
      }
      sku.imagens = imgs;
      skus.push(sku);
    }
    prod.skus = skus;
    data.push(prod);
  }
  while(rs.next('prod'));

  console.log(data);
}
else{
  console.log('Nenhum registro');
}
Comment: Cara muito obrigado, funcionou perfeitamente, agora vou implementar mais alguns campos que tenho e já era. TKS!


Macro Do Until Loop in SAS

Question: My loop is only making 1 iteration. I am supposed to create three macro variables: var1 = Month1, var2 = Month2, and var3 = Month3 if qtr = qtr1.  My loop is only creating var1 = Month1 and I = 1 when I checked it with a Put statement. It is only making one iteration, so I'm not sure what I am doing wrong.
%Let qtr = qtr1;

%Macro Firstqtr(qtr);

%Let I = 1;

%If &qtr = qtr1 %then %do %until (&I > 3);

%Let var&I = Month&I;

%let I = %eval(&I + 1);

%end;

%Mend Firstqtr;

%Firstqtr(qtr);

Comment: Your posted program will never run the %DO loop because the condition in the %IF statement will be FALSE.
Answer: The issue is one of macro variable scope.  qtr is defined both globally (line1) and locally (as a macro parameter) so the local (empty) one is used instead.
Try passing it through in your parameter as follows:
%Let qtr = qtr1;

%Macro Firstqtr(qtr);
  %Let I = 1;
  %If &qtr = qtr1 %then %do %until (&I > 3);
    %global var&i;
    %Let var&I = Month&I;
    %put var&i=&&var&i;
    %let I = %eval(&I + 1);
  %end;
%mend Firstqtr;

%Firstqtr(&qtr);

Be aware that the variables you are creating would have local scope - to make them global, you declare them as such (%global statement).
Comment: What can I do to make them exist outside the macro?
Comment: Got it now! Thanks!
Comment: Sorry, got it now, I think!
Answer: Your %DO loop will never run given the input you made for the QTR parameter to your macro.  You can turn on MLOGIC to see this.
1228  options mlogic;
1229  %Firstqtr(qtr);
MLOGIC(FIRSTQTR):  Beginning execution.
MLOGIC(FIRSTQTR):  Parameter QTR has value qtr
MLOGIC(FIRSTQTR):  %LET (variable name is I)
MLOGIC(FIRSTQTR):  %IF condition &qtr = qtr1 is FALSE
MLOGIC(FIRSTQTR):  Ending execution.

If you want to pass in qtr1 as the value either hard code it in the macro call.
%Firstqtr(qtr1);

Or you could make your call pass in the macro variable you defined earlier.
%let qtr=qtr1;
%Firstqtr(&qtr);

It might make this distinction between the parameter's value and the value of an external macro variable with the same name clearer if you call the macro using named parameters. Note: you can use parameter names in the macro call even for parameters that were defined as positional in the macro definition.
%Firstqtr(qtr=&qtr);

Comment: great tip, didn't realise that about positional parameters!
Answer: option mprint;
%global qtr;
%Let qtr = qtr1;

%Macro Firstqtr(qtr);

%Let I = 1;

%If &qtr = &qtr  %then %do %until (&I > 3);

%Let var&I = Month&I;

%let I = %eval(&I + 1);

%end;
%put &var1 &var2 &var3;

%Mend Firstqtr;

%Firstqtr(qtr);

You have to declare qtr as Global variable then only the if condition will be pass.

Macro Do Until Loop in SAS


How I get notified every time their is an *new* update and not every day for the sames updates?

Question: The update module can send you email when a new release is available for a module you installed. The problem is I get a email everyday. Some security update are very minor and unreachable for an attacker, I don't want to update the website and so I don't want future notification about this update.
I would like to be notified every time their is an new update, not every day for the sames updates.
Comment: This looks to me more of a feature request for the core update module, than a question. This should be discussed on a issue queue on drupal.org and not here.
Comment: That'll need a core patch (to `update_requirements()` and `_update_cron_notify()` at least by the looks of things). It would be much easier to ignore the emails and check the site manually on a schedule that suits your workflow
Comment: Gmail is pretty good at hiding duplicated content in conversation, so I'm getting mails but see immediately if there's something new or not. On the other side, I don't ignore updates (I have the luxury of applying them as they go), so haven't tested with this particular mailing.
Answer: I can use hook_mail_alter to cancel the sending of the mail. I can simply store a md5 of the mail's body every time the mail is send and compare it with the "new" email, if it's the same I don't send it.
Comment: I'm not sure about the MD5 of the emails, but instead of using hook_form_alter, I'd suggest you to use the `hook_mail_alter()`, instead. you can do the check in that function and then set the argument of the function `$message['send']` to `FALSE` to stop the mail from being sent, based on the condition (MD5).
Comment: I said hook_mail_alter... edited my message to make a proper link.
Comment: Oh, my bad! Slip of sight I suppose ;-)


chern character of wedge product of bundles

Question: It is well known that the, for Chern character of vector bundles,
$$ ch (E \otimes F)= ch(E) \wedge ch(F)$$
holds true.
What about $E \wedge E$ when $E$ is holomorphic vector bundle?
Comment: What does $E\wedge F$ mean for vector bundles (or just vector spaces)?
Comment: right, it was just my fantasy
Answer: It's easy to get it via the splitting principle. Supposing $E=L_1\oplus L_2\oplus\dots\oplus L_n$, where $L_k$'s are line bundles, $ch(L_k)=e^{x_k}$ ($x_k$ the 1st Chern class of $L_k$) we get $ch(E\wedge E)=\sum_{i<j}e^{x_i+x_j}=\bigl((\sum_{k}e^{x_k})^2-\sum_{k}e^{2x_k}\bigr)/2$, hence
$$ch(E\wedge E)=\bigl((ch(E))^2-r_2\cdot ch(E)\bigr)/2$$
where $r_2$ acts on $H^{2k}$ by multiplying by $2^k$.
Comment: Could I ask what happens here if $ch(E)$ has odd rank, i.e. odd $ch_0(E)$? Because then $ch_0(E \wedge E) \in \frac{1}{2} \mathbb{Z}$, and I thought $ch_0$ should always be integral?
Comment: Are you sure it is always possible to write a holomorphic vector bundle $E$ as sum of line bundles?
Comment: OK, I think this http://en.wikipedia.org/wiki/Splitting_principle answers my question
Comment: @mathphys thanks, there was a mistake (now corrected)
Comment: @user8268 Thanks!


How to setup a CNAME entry

Question: A third party has asked me to setup a new subdomain and point it too sub.theirdomain.com.  Apparently I can do this with a single CNAME record.  Although I set it up over 24 hours ago, it doesn't seem to be resolving.  Here's the entry I made:
sub.mydomain.com. IN CNAME sub.theirdomain.com.

Does that look OK?
The host is Webmasters, and I asked their helpdesk who thought it was fine.
The only way I know that it isn't resolving is that when I surf to sub.mydomain.com I get a server not found error.  What tools should I be using to diagnose further?
Any you can see, I'm no DNS expert, so any assistance is much appreciated!
Comment: Did you update the serial number and, if this is using BIND, did you reload the file after making changes?
Answer: An HTTP server not found error doesn't mean that the DNS is not working. Try doing the following and see if it resolves correctly. It should say sub.mydomain.com cnames to sub.theirdomain.com
nslookup sub.mydomain.com

If it resolves then telnet to port 80 to see if its open.
telnet sub.mydomain.com 80

Comment: Thanks.  The nslookup says it can't find sub.mydomain.com.  Next step?
Comment: Check your zone file. You can check the zone file is error free using named-checkzone command which is included with Bind.
Comment: Also ensure that you have updated the zone serial (as John suggested in his comment above) and look at your named logs to see if there were any errors reloading the zone.
Comment: Thanks All, particularly @Sameer.  Turns out that it was just a propogation delay.  I did learn a lot by asking the question, though.
Answer: The format of the CNAME itself looks fine.
Depending on what kind of checking the input on your zone editor does, it's possible that the problem is some added nesting. Do you get the CNAME result for 'sub.mydomain.com.mydomain.com'?
Usually the best way to check DNS issues is with tools like 'dig' (typically on *nix systems) or 'nslookup' (built into Windows).
Comment: nslookup is available on *nix too.
Comment: *nix may have replaced nslookup with host.

How to setup a CNAME entry


Criar um objeto a partir de outra classe

Question: Possuo a classe Endereco e a classe Cliente, construi 2 construtores para a Cliente, e em um deles é pra ser inserido o nome do cliente e um objeto do tipo Endereco, o que funciona perfeitamente, mas no outro construtor é pra ser inserido o nome do Cliente e criar um objeto do tipo Endereco junto, o problema é que após digitar os dados do Endereco, dou inspect e Endereco é considerado null.
Parte essencial(2 construtores) da classe Endereco:
public class Endereco{
    private String logradouro;
    private String numero;
    private String complemento;
    private String telefone;
    private String celular;
    private String email;

    public Endereco(String log, String num, String comp, String tel, String cel, String mail){
        logradouro = log;
        numero = num;
        complemento = comp;
        telefone = tel;
        celular = cel;
        email = mail;
    }
    public Endereco(){
        Teclado t = new Teclado();
        logradouro = t.leString("Informe o logradouro: ");
        numero = t.leString("Informe o numero: ");
        complemento = t.leString("Informe o complemento: ");
        telefone = t.leString("Informe o telefone: ");
        celular = t.leString("Informe o celular: ");
        email = t.leString("Informe o e-mail: ");
    }
}

Parte essencial da classe Cliente:
public class Cliente{

    private String nome;
    private Endereco endereco;
    private int pontos;

    public Cliente(String nm, Endereco ed){
        nome = nm;
        endereco = ed;
        pontos = 0;
    }
    public Cliente(String nm){
        nome = nm;
        Endereco e = new Endereco();
    }
}

Comment: Coloque em `Endereco e`, troque por `this.endereco` = `new Endereco()`, porque se ta criando um outro `objeto` da da `classe` **Endereco**, que não condiz com o private criado dentro da classe Cliente ...
Answer: Em vez disso:
Endereco e = new Endereco();

Faça isso
this.endereco = new Endereco();

Você esqueceu de atribuir a nova instância ao atributo da classe.
Comment: valeu meu, um erro bobo e simples mesmo mas que eu nunca iria me ligar hahaha
Answer: Julgo que o problema está na forma como você declara o Endereço no segundo construtor você deve usar a variável privada endereco e não declarar outra.
private String nome;
private Endereco endereco;
private int pontos;

public Cliente(String nm, Endereco ed){
    nome = nm;
    endereco = ed;
    pontos = 0;
}
public Cliente(String nm){
    nome = nm;
    endereco = new Endereco(); // use a variável privada
}

Answer: Basta Instanciar o objeto dando um new no Endereço dentro co construtor sem parâmetro, ele ficou nulo pois o mesmo não foi instanciado
this.endereco = new  Endereco();


The directory tmp does not exist and could not be created

Question: I keep getting this error since updating to Drupal 7.5.8 and cannot get rid of it regardless of trying all I know. Even adding it / copying-pasting the previous tmp dir or changing the tmp file name (eg tmp3) doesn't solve it.  Any files placed in the directory are writable unless I need to add a new Drupal 'group' in security.
Any one know how to solve this update issue?
Answer: You didn't mention the actual (complete) value for the path of the "Temporary directory" you want to use. But something that should work, pretty sure, is like so:

Navigate (in your web browser) to relative path admin/config/media/file-system.
Copy the value you have entered for "Public file system path", assume it's some/path/files.
Paste the copied value (like some/path/files) in the field "Temporary directory", and append to that value something like /temp, so that it becomes something like  some/path/files/temp/
Hit the Save configuration button and you should be good to go (Drupal will, automagically, take care of the rest).
Comment: I know what you mean, but you might want to make it more clear that "navigate to relative path" refers to navigation in the web browser, rather than `cd` in a terminal. (It's only confusing because we are dealing explicitly with file system paths here.)
Comment: @hotwebmatter merci for the feedback. If you want, please go ahead to integrate your comment in my answer. Pretty sure I'll approve it.
Answer: Please update the file size first in php.ini file. Then check again.
upload_max_filesize = 1024M

post_max_size = 1024M


A matrix $Q$ has orthonormal columns, but $QQ^T \neq I$

Question: I have to find an example of a matrix $Q$ that has orthonormal columns, but $QQ^T \neq I$.
If a matrix has orthonormal columns, it does not imply that the matrix is orthogonal, so that it is a square matrix. Therefore, I could simply give a matrix with unit vectors that is not a square matrix, since the $QQ^T$ would not be a identity, right?
Comment: A matrix of the form $AA^T$ is always square.
Answer: Your idea is right, although you would still need to have some verification that $QQ^T$ is not, in fact, the identity. It's certainly conceivable (without some theorem to back you up…) that you could get unlucky and choose a non-square $Q$ for which $QQ^T$ was still the identity matrix.
Answer: Yes, any $Q$ which is a thin matrix will work, i.e., $Q \in \mathbb{R}^{m \times n}$, with $m > n$. This is because $\text{rank}(QQ^T) = n$, where $QQ^T \in \mathbb{R}^{m \times m}$, whereas $I \in \mathbb{R}^{m \times m}$ has rank $m$.


Centered DIV (exactly 900px), with divs (with opacity) on each side filling up the rest of the page

Question: I have a centered DIV, which is exactly (never more or less) 900px. I want it to always be centered and have the two filler divs to fill up the rest of the page on each side...
giving the content under (using z-index) a highlighted type effect...(that's the use of the filler divs...to show there is other content on each side of "SPOTLIGHT" content, but it's not under the "SPOTLIGHT".

THIS CODE BELOW DOESN'T WORK...BUT IT GIVES YOU A FEELING OF WHAT I'M ATTEMPTING TO DO

CSS:
/* DIV I WANT TO BE CENTERED, SURROUNDED BY 50% OPACITY DIVS FILLING REST OF PAGE */
.shadercentered {
width:950px;
margin-left:auto;
margin-right:auto;
position:relative;
background-color:green;
height:73px;
float:left;
top:-28px
}

/* DIVS THAT FILL THE REST OF THE PAGE ON EACH SIDE OF 900px CENTERED DIV */
.shaderblindsleft {
background-color:black;
opacity:0.5;
width:fill;;
height:73px;
float:left;
position:relative;
top:-28px;
}
.shaderblindsright {
background-color:black;
opacity:0.5;
width:fill;;
height:73px;
float:right;
position:relative;
top:-44px;
}

HTML:

Comment: is this what you are up to http://jsfiddle.net/gErXe/
Answer: You get it with controlling what happens in shaderdiv with getting its children out of the flow, with position absolute.
You put shadercenter in the middle with hooking it at left: 50%, then offseting it to the left with a negative margin-left of half its size.
For the surrounding, you use the capabilities of constraints to define the width. For the left one, you hook it to left:0 (because it's the left one), and then you define its right side to be where shadercenter is hooked... so it would be right: 50%. Then, you add a margin-right of half the size of shadercenter so it will be constrainted to be smaller. Use the same technic "reversed" for the right one

.shaderdiv
{
  position: relative;
  width: 90%;
  height: 73px;
  border: 1px solid yellow; /* debug stuff */
  box-sizing: border-box; /* debug stuff */
}

.shaderdiv > div { opacity:0.5 }

.shadercenter
{
  position: absolute;
  left: 50%;
  margin-left: -125px; /* minus half size of width */
  width:250px; /* fixed width */
  height:100%;
  background:green;
}

.shaderblinds
{
  position: absolute;
  height: 100%;
}

.left
{
  left: 0;
  right:50%;
  margin-right: 125px; /* half size of width */
  background:red;
}

.right
{
  right: 0;
  left: 50%;
  margin-left: 125px; /* half size of width */
  background:blue;
}

Example here : http://jsfiddle.net/5kDjw/2/
You can play with the size of shaderdiv to see that it's fully liquid, shadercenter is always fixed width, always centered, with no overlapping


Live feeds via Atom protocol

Question: I have to create a consumer that consumes feeds from an Atom service. The feeds should be consumed as and when anything is published on the atom server.
Currently I am using camel-atom protocol which polls the atom server every 60 seconds by default (this polling time can be reduced). Is any way (using any API) that I can just subscribe to the atom server and receive updates whenever they are posted?
Answer: Atom servers are not pushing changes to subscribers. Published feeds (RSS and Atom) are a way to enable clients to automatically check for updates.
There is no option to configure camel-atom other than consumer.delay, which sets the polling interval.
Answer: As Cringe says, Atom itself is "just" a data format... not a protocol to distribute/consume data. There are several protocols which have been built around distrubuting and consuming Atom, starting with Atompub. However, the most popular these days is clearly PubSubHubbub (supported by Wordpress, Blogger, Medium, Feedburner, Feedpress, Etsy... as well as many smaller/indie CMSes).
Check out Superfeedr too (which I created!) which can help you turn any RSS/Atom feed into a stream to consume.

Live feeds via Atom protocol


Monotonicity of function averages

Question: Please let me know if you know an answer to this problem. May be you could provide a reference to some publication on this topic?
Let $f(x)$ be a real-valued  strictly convex function on $[0, 1]$. For any integer $k$ between $0$ and some positive integer $n$ let $x_k =k/n$. Consider the average value function $g(n)= \sum_{k=0}^{n}f(x_k)/(n+1) $. Is it true that $g(n)$ is decreasing?
Thank you!
Comment: Good question, and I believe the answer is yes after toying around with some numerical examples to build intuition.  I'm trying to find a proof.
Comment: Idea for an argument: look at the partitions as used to  approximate the Riemann integral from $0$ to $1$.
Comment: Isn't this just weighted jensens?
Comment: I don't know about weighted Jensens, @CalvinLin, maybe you could elaborate in an answer?  One intuition here is that the sum is (up to an additive constant independent of $ n $) the result of the trapezoid rule for approximating the Riemann integral.  This intuition suggests an affirmative answer to the question, though I still can't pin down why the trapezoid rule should converge monotonically for a concave function.
Answer: $g(n-1) \geq g(n) \Leftrightarrow (n+1) \sum f( \frac{i}{n-1}) \leq n \sum f( \frac{i}{n})$.
This follows by summing up the following inequlities:
$\begin{array} { l l l l l l l }
& & n \times f(0) & = & n \times f(0) &=& n \times f(0), \\
1 \times f(\frac{0}{n-1}) &+& (n-1) \times f( \frac{1}{n-1} ) & \geq & n \times f( \frac{\frac{0}{n-1} + \frac{n-1}{n-1}}{n}) &=& n f(\frac{1}{n}), \\
2 \times f( \frac{1}{n-1}) &+& (n-2) \times f( \frac{2}{n-1}) &\geq& n \times f ( \frac{\frac{ 2}{n-1} + \frac{2n-4}{n-1}}{n}) &=& n f(\frac{2}{n}), \\
\vdots      \\
i \times f( \frac{i-1}{n-1}) & + & (n-i) \times f( \frac{i}{n-1}) & \geq & n \times f( \frac{\frac{ i^2 - i}{n-1} + \frac{ni - i^2}{n-1} } { n } ) & = & n f(\frac{i}{n}), \\
(n-1) \times f( \frac{n-2}{n-1} ) &+&  1 \times f( \frac{n-1}{n-1}) &\geq& n \times f(\frac{ \frac{ n^2-3n+2}{n-1} + \frac{n-1}{n-1} }{n}) &=& n f(\frac{n-1}{n}) \\
n \times f(1) & & &=& n \times f(1)&=& n \times f(1) \\
\end{array}$

Note: Strict convexity gives strict inequalities, so the function is strictly decreasing.
Comment: Nice, essentially performing Jensen's inequality for each new point as a convex combination of the two nearest old points
Comment: Thank you, Calvin, for providing this elegant proof!
Answer: The following related monotonicity facts are also true: If, in addition, $f(x)$ is decreasing, then the sequence $u(n)= \sum_{k=0}^{n-1}f(x_k)/n$ is decreasing and the sequence $v(n)= \sum_{k=1}^{n}f(x_k)/n$ is increasing.
For the affirmative answer to the original problem this additional assumption about  $f(x)$  is not needed.

Monotonicity of function averages


Onchange Selectbox and php

Question: I'm using a selectbox with onchange = "this.form.submit()" and a table with php that shows data according to the selection, well, it works fine, but when I select an option and the page refresh, selectbox always shows as value the first element. I want that it shows the element that I've selected. This is the code
<form action="#" >
<select name="proyect" id="proyect" onchange = "this.form.submit()">
<?php
$SQL = "SELECT id  FROM categories ORDER BY nomCategories ASC";
            $result = mysql_query($SQL);

while ($row = mysql_fetch_array($result)) {
?>

<option value="<?php echo $row["id"];?>"><?php echo $row["nomCategories"];?></option>
<?php
}
?>

Thanks!
Comment: your question is not bad, but you didn't provided any code? how people can help you?
Answer: You should do same as viewstate in ASP.NET. For this you should send the selected index to the server. There is some ways like:
Create a <input type='hidden' ... /> and set the selected index to property value of this hidden input (Note that this element must be created into the form element)
At this stage you can retrieve the index by $_GET or $_POST
And while the page is rendering you can set this index to the select box
UPDATE(detailed)
Change your HTML&PHP code to this:
<form action="yourpage.php" method="POST" >
    <input type="hidden" name="pindex" value="" />
    <select name="proyect" id="proyect" onchange = "mysubmit(this.parentNode)">
    <?php
    $SQL = "SELECT id  FROM categories ORDER BY nomCategories ASC";
                $result = mysql_query($SQL);

    while ($row = mysql_fetch_array($result)) {
    ?>

    <option value="<?php echo $row["id"];?>"><?php echo $row["nomCategories"];?> </option>
    <?php
    }
    ?>
    </select>
</form>

Comment: @user2553299: In the first time page load the PHP echos `0`, But when an user select an item in select box, the PHP echos `$_POST['pindex']`

Onchange Selectbox and php


Which instrument is used in beginning of Make you mine (by Public)

Question: In the very beginning of sound I hear piano and hi hat probably, but there is still a 3rd humming kind of sound which follows the chords I think what is it?
I'm trying to make cover for the song and I  need to know what kind of instrument it is, or atleast I need to know how to and where to look if I want to understand about various instrument sounds in music I hear. Because I cannot recognise instruments many times.
I'm new for this site, apologies if I have framed my question poorly.
:)
I play guitar and classical piano but am very new to digital piano and yet can't recognise if this sound was actually made using synthetic piano.
Comment: It's a fine question, it's just that Stack Overflow isn't the place for it. I'd suggest asking in other music-oriented communities (Reddit? Maybe real-life friends?). Meanwhile, 1) Don't worry, as you get more experience you'll get better at analyzing what you hear, and 2) As DataProcessing mentions, a cover doesn't have to be *exactly* the same as the original. If you want to include these sounds in your version, try various instruments and see what you think sounds good.
Comment: I'm voting to close this question because it belongs on MusicFans. The post has been flagged so that the mods can migrate it.
Comment: @Aaron identification questions are now all off-topic on music fans.
Comment: @Dom Oh, cool. I thought they were just being more sharply restricted.
Comment: Welcome to this site. If you read the Help Centre, it'll give you better guidance for posing questions.
Comment: Then how shall I approach these areas of music as I'm still learning music but I'd like to explore and kmow more about music already made
Answer: Electric guitar, but you don't need to precisely copy the original arrangement in order to do a cover.  Some of the best known cover songs don't try to stick close to what the original artist did.  Of course if you're new and just trying to learn music arrangement and pop song construction, then it can be very instructive to figure out what all the parts are and what they're doing.  But eventually you'll want to do it your own way.
Comment: I believe the OP refers to that "humming" as the "wobbling" sound other than the guitar. It *might* be a guitar effect, but it's probably a synth with an LFO linked to the volume.


A problem with build task and sourceCompatibility = 1.7, gradle 5.3

Question: I use sourceCompatibility = 1.7 in gradle.properties, Gradle JVM(Settings, Gradle, Intellij IDEA) is 1.8.0_171 and
wrapper {
    gradleVersion = '5.3'
    distributionType = 'ALL'
}

in build.gradle.
When I run build task(Tasks->build->build Intellij IDEA) I get "error: incompatible types: inferred type does not conform to equality constraint(s)" during compileJava task.
If I set up Gradle JVM is 1.7.0_80 and
wrapper {
    gradleVersion = '4.3'
    distributionType = 'ALL'
}

build is fine.
What I'm doing wrong? How can I build JAVA 7 project using gradle 5.3?
Comment: Only to a certain degree.  A Java 8 compiler running with `--source 1.7` is still a Java 8 compiler under the hood.  It is just that certain new language features are turned off.
Comment: It is probably caused by a change in the type-checking rules for generics between Java 7 & Java 8; see https://stackoverflow.com/questions/32384531/why-does-this-program-compile-with-java-7-but-not-java-8
Comment: @StephenC I thought sourceCompatibility = 1.7 will set up java 7 for compile *.java.
Comment: How can I build JAVA 7 project using gradle 5.3?
Answer: This is probably caused by a subtle change in the type-checking rules for generics between Java 7 & Java 8 as described in Why does this program compile with Java 7 but not Java 8?
So what is the solution?
I doubt you will find a magic compiler switch or something to just make it work.  Realistically, I think that your choices are:

You could just compile on a Java 7 platform as you did to start with.   But this is not a good long-term solution.
If this is a supported product, lodge a support request.
If this is an open source product, check the product's issue checker to see if someone has already reported the problem.  They may have reported a fix as well.
Look at the source code that you are trying to compile, identify the cause of the compilation error and fix it.  If this is an open source product, submit your fix as a patch.

Note that it is possible that these compilation errors are reporting a latent bug that could under some circumstances lead to unexpected runtime exceptions.

You said:

I thought sourceCompatibility = 1.7 will set up java 7 for compile *.java.

It does.  However, there are degrees of compatibility.
When you run a Java 8 compiler with -source 1.7 you are actually just turning off support for new language features.  Under the hood, the compiler is still a Java 8 compiler.  If there have been subtle changes in (for example) the type checker, it is plausible that the Java engineers did not implement a backwards compatibility mode for the old behavior.
(The extra mode may make an already complex piece of software too difficult to maintain.  Type checking and type inference is one of the more difficult aspects of  compiler implementation.)


Augmented coalgebras

Question: Let $C, \Delta$ be a coalgebra. Assume that it is coaugmented with coaugmentation $u\: : \: k\to C$ and co unit $\epsilon\: : \ C\to k$. Since $\epsilon\circ u=id $ we get
$$
C=\text{Kern}(\epsilon )\oplus k
$$
Set $\bar{C}:=\text{Kern}(\epsilon )$. Then $\bar{C}$ equipped with the reduced coproduct $\bar{\Delta}(x):=\Delta(x)-1\otimes x-x\otimes 1$ is a (non-coaugmented) coalgebra. Then we have a functor between the category of augmented coalgebras into the category of coalgebras.
Does this functor defines an equivalences of categories?
I ask this because a similar thing is true in the contest of algebras and aumented algebras. The idea is starting from a generaleal coalgebra $C',\Delta'$ choose a symbol 1 and define $C:=C'\oplus 1 k$, then define
$$
\Delta(x):=\Delta'(x)+1\otimes x+x\otimes 1
$$
Do you know some reference about that?
Does this process works in the contest of differential graded coalgebras?
Comment: I don't know a reference off the top of my head, but what you've written is true, you get an equivalence of categories between {coaugmented coalgebras (with counit)} and {coalgebras (without counit)}, exactly for the same reasons as in the case of algebras, and it does work for dg-coalgebras. The two functors you've written down are indeed the two parts of an equivalence.
Comment: Thanks. the proof is just testing the coassociativity for $\Delta$ which folows after a short calculation.
Answer: Actually it's simpler (to follow the duality with the case of algebras) to consider the cokernel of the coaugmentation, instead of the kernel of the augmentation. More precisely define an equivalence:
$$F : \{ \text{coaugmented counital dg-coalgebras} \} \leftrightarrows \{ \text{coalgebras (without counit)} \} : G$$
as follows. Let $(C,\Delta,\varepsilon,d,u)$ be a coaugmented dg-coalgebra (with the obvious notations, $\varepsilon$ the counit and $u$ the coaugmentation). Then $F(C,\Delta,\varepsilon,d,u) = (C', \Delta', d')$ where:

$C' = \operatorname{coker}(u) = C / \operatorname{im}(u)$;
since the coaugmentation is a morphism of coalgebras and $\Delta(1_k) = 1_k \otimes 1_k$, it follows that $\Delta(1) = 1 \otimes 1$ (where $1 = u(1_k)$), thus $\Delta : C \to C \otimes C$ induces a map on the quotient $\Delta' : C' \to C' \otimes C'$, which is again coassociative;
similarly $d(1_k) = 0$ thus $d(1) = 0$ and so $d$ induces a map $d' : C' \to C'$, which is a coderivation that squares to zero (because $d$ was).

Conversely let $(C',\Delta',d')$ be a coalgebra (without counit), then you can define a coaugmented counital coalgebra $G(C',\Delta',d') = (C, \Delta, \varepsilon, d, u)$ by:

$C = C' \oplus k1$ (where $1$ is some symbol);
$\Delta(x) = \Delta'(x) + x \otimes 1 + 1 \otimes x$ for $x \in C$ and $\Delta(1) = 1 \otimes 1$, extended linearly;
$\varepsilon(x) = 0$ for $x \in C'$ and $\varepsilon(1) = 1$;
$d(x) = d'(x)$ for $x \in C'$ and $d(1) = 0$;
$u(1_k) = 1$.

You get a coaugmented counital dg-coalgebra this way. Skip the next paragraph if you don't need convincing.

Most axioms are easy to check, the most troublesome one (in terms of lines of computation needed) is perhaps coassociativity. Let me write down $\Delta'(x) = x_{(1)} \otimes x_{(2)}$ using Sweedler notation. By coassociativity of $\Delta'$ we know that $(\Delta' \otimes \operatorname{id}) \Delta'(x) = x_{(1)} \otimes x_{(2)} \otimes x_{(3)} = (\operatorname{id} \otimes \Delta') \Delta'(x)$. Then:
$$\begin{align}
(\Delta \otimes \operatorname{id}) (\Delta(x))
& = (\Delta \otimes \operatorname{id}) \bigl( x_{(1)} \otimes x_{(2)} + x \otimes 1 + 1 \otimes x \bigr) \\
& =  \Delta(x_{(1)}) \otimes x_{(2)} + \Delta(x) \otimes 1 + \Delta(1) \otimes x \\
& = \bigl( \Delta'(x_{(1)}) \otimes x_{(2)} + x_{(1)} \otimes 1 \otimes x_{(2)} + 1 \otimes x_{(1)} \otimes x_{(2)} \bigr) \\
& + \bigl( \Delta'(x) \otimes 1 + x \otimes 1 \otimes 1 + 1 \otimes x \otimes 1 \bigr) + 1 \otimes 1 \otimes x \\
& = x_{(1)} \otimes x_{(2)} \otimes x_{(3)} + x_{(1)} \otimes 1 \otimes x_{(2)} + 1 \otimes x_{(1)} \otimes x_{(2)} \\
& + x_{(1)} \otimes x_{(2)} \otimes 1 + x \otimes 1 \otimes 1 + 1 \otimes x \otimes 1 + 1 \otimes 1 \otimes x
\end{align}$$
and now clearly you can rearrange the terms in that last expression to get back to $(\operatorname{id} \otimes \Delta)\Delta(x)$ (whew! it took me some time to get it right).

Now you need to prove that $F$ and $G$ are inverse equivalences. This comes from the fact that if $C$ is a coaugmented dg-coalgebra, the exact sequence
$$0 \to k \xrightarrow{u} C \to \operatorname{coker}(u) \to 0$$
is split by the counit: $\varepsilon(u(1_k)) = 1_k$. So $C$ is isomorphic as a chain complex to $\operatorname{coker}(u) \oplus k$, which you can check is exactly $G(F(C))$. The converse $F(G(C')) \cong C'$ is almost immediate by definition. (All that's left is checking naturality of everything, which is a completely mechanical exercise.)
Comment: Of course this approach is more-or-less equivalent to the one in your question.

Augmented coalgebras


Problem about tangent vector and the inclusion map of the unit circle.

Question:
It is so complecated for me. Please can you show how to solve. Thank you.
Answer: We have
$$i_*\left(\frac{\partial}{\partial \bar{x}}\right)(x) = \frac{\partial}{\partial \bar{x}}(i^*x)$$
and likewise
$$i_*\left(\frac{\partial}{\partial \bar{x}}\right)(y) = \frac{\partial}{\partial \bar{x}}(i^*y).$$
Given that the text defines $\bar{x}=i^*x$ and $\bar{y}=i^*y$, can you solve it from here?
The complete solution for $x$:
$$i_*\left(\frac{\partial}{\partial\bar{x}}\right)(x) = \frac{\partial}{\partial\bar{x}}(i^*x) = \frac{\partial}{\partial\bar{x}}(\bar{x})=1$$
Comment: Please can you solve this only for $x$ from here. I Will be able to do the solution for $y$ by myself if you Will show. By the way, for part-b, how do I follow a way to prove?
Comment: Thank you for completeding of the question :)
Comment: By the way, is that all? It is so esay but i look difficult. Well, for the part-b, how do I express these in general?
Comment: That's all. It's really not that hard. I don't really see the point of part b) to be honest, since exactly the same calculation applies. These things are local after all.
Comment: Okay that is not difficult really. Thank you for help:)


using embedded Foreach loops to cross-reference arrays in PHP

Question: I'm trying to take two lists (arrays) of numbers, and use Foreach loops in PHP to create a third array containing all the common numbers. Feel like I have hit a roadblock as far as understanding the logic, can anyone out there make sense of what I've got and what is wrong?
<code><?php
$cardOutcome = array();

$explodeCalled = explode(",", $card_detail['calledNumbers']);
$explodeCard = explode(",", $card_detail['cardNumbers']);

foreach($explodeCard as $card)
{
    foreach($explodeCalled as $called)
    {
        if($called == $card)
        {
            $cardOutcome[] = $called;
        }
    }
}

print_r($cardOutcome);
?>
</code>
The array values and outcome of the print_r are below
<code>$explodeCard = 2, 5, 1, 11, 4, 25, 19, 28, 21, 18, 32, 37, 38, 41, 40, 50, 55, 49, 56, 57, 75, 73, 61, 72, 74

$explodeCalled = 3, 70, 39, 6, 45, 43, 9, 48, 54, 51, 49, 33, 21, 1, 65, 71, 75, 15, 50, 36, 55, 14, 13, 7, 4, 67, 74, 26, 8, 32, 22, 28, 62, 57, 56, 38, 12, 2, 59, 40, 27, 69, 18, 20, 42, 44, 37, 46, 72, 60, 11, 58, 66, 29, 30, 35, 52, 25, 47, 10, 61, 5, 23, 73, 53, 34, 41,

$cardOutcome = Array ( [0] => 2 [1] => 5 [2] => 1 [3] => 11 [4] => 4 [5] => 25 [6] => 28 [7] => 21 [8] => 18 [9] => 32 [10] => 37 [11] => 38 [12] => 41 [13] => 40 [14] => 50 [15] => 55 [16] => 49 [17] => 56 [18] => 57 [19] => 75 [20] => 73 [21] => 61 [22] => 72 [23] => 74 )
</code>
The $outcome array seems to simple be printing the "card" values. I feel like I have made a blatant logical misstep. And ideas??
Answer: Try array_intersect (http://php.net/manual/en/function.array-intersect.php)
<code>$explodeCalled = explode(",", $card_detail['calledNumbers']);
$explodeCard = explode(",", $card_detail['cardNumbers']);
$cardOutcome = array_intersect($explodeCalled,$explodeCard);
</code>


Procedural functions vs Static methods. Which is better or avoid both?

Question: I am just looking through some core files of Codeigniter and I see that it uses some what you might call procedural functions scattered all over the place like to get the instance of the config class somewhere in a core class instead of injecting it into the object it just does
$config =& get_config();

I'm no expert but isn't that bad to do? To me it seems like making the application have unnecessary global state.
As far as I can see it is nearly the exact same as doing something like
$config = App::loadClass('config');

Is doing it the second way worse than the first? I'm thinking it might be because when calling it the second way the App class needs to exist (and be located) and doing it the first way no specific class must exist and the class file does not need to be included so less requirements.
I am making my own framework and have avoided using any static stuff so far but when I look into the code of the leading frameworks for ideas or help I see static stuff all over the place and I wonder why?
You would think that the leading frameworks would be coded a bit better or maybe using global methods is not as harmful as many people make them out to be what do you think?
In my framework I have to inject this $config object into lots of classes and a $logger object and a $messages/$language and a few more. I use a Dependency Injection container and factories but it's still a bit of a pain compared to just doing
$config = App::loadClass('config');
$someSetting = $config->setting('some.setting');
Logger::write('debug', 'some message');

If I'm going to use static methods should I use the procedural ones(Codeigniter example) or the ones embedded in classes? or do you strongly advise to never use them?
Any opinions would be great thanks.
Comment: Your question is if they are bad from a high-level code design perspective / platitude. What you actually should be asking if either is unsuitable for maintainability, obscures behaviour or obstructs debugging / testability. Most importantly you however ought to consider code readability first. (Which btw, is the whole raison d'etre of OOP.)
Answer:
I'm no expert but isn't that bad to do? To me it seems like making the application have unnecessary global state.

Correct. This should be avoided. Not only does it introduce global state, but it also spits out a strict warning:

Strict Standards: Only variables should be assigned by reference in ...

 Is doing it the second way worse than the first?

Don't think it is worse, because at least you don't get the `Strict Standards` warning. But still you would really want to avoid this.

> I am making my own framework and have avoided using any static stuff so far but when I look into the code of the leading frameworks for ideas or help I see static stuff all over the place and I wonder why?

This is because of the fact that most popular frameworks out there are terrible. Not only do they introduce bad coding practice, but often they also will also tell you it is using a MVC structure (which most are clearly not).

> You would think that the leading frameworks would be coded a bit better or maybe using global methods is not as harmful as many people make them out to be what do you think?

Again those frameworks are full of WTF's. If you really think you want to look into one of the popular frameworks you should look into Symfony 2 or Zend FW 2. Not because they do everything the correct way, but because they are the best (of the popular ones) imho.

> In my framework I have to inject this $config object into lots of classes and a $logger object and a $messages/$language and a few more.

Dependency injection is the correct way to solve this (at least if you are going for an OOP approach). However if you classes have a lot of dependencies you might have to stop for a moment and think about the fact the perhaps your classes are doing too much. A.k.a they have [too many responsibilities](http://en.wikipedia.org/wiki/Single_responsibility_principle).

> If I'm going to use static methods should I use the procedural ones(Codeigniter example) or the ones embedded in classes? or do you strongly advise to never use them?

Strongly advice against both. As you already stated in introduces global state. Make testing a pain. And has more to do with procedural programming than OOP.

*P.S. I have giving you the two best FW's in my opinion. If you want to know CodeIgniter and Cake are the worst.*

To finish this post a somewhat related message from [the PHP chatroom](https://chat.stackoverflow.com/transcript/11?m=6055399#6055399) by [Lusitanian](https://chat.stackoverflow.com/users/1477526/lusitanian):

> *Microframework* (n): A small amount of crap. See also *Framework* (n): A large amount of crap.
Answer: In my opinion CodeIgniter is a low quality PHP framework, much under Zend Framework or Symfony for example. Also i think that static functions has their specific role in OOP, for example can be used when implement registry pattern, for logs and so on. Regarding procedural functions i strongly recommend to not use them in a OOP application.
Comment: Thanks for the reply. Yeah after a few hours of looking through some CodeIgniter files for some ideas on how to implement stuff I have decided it is coded too badly even for my standards. I am going to download Zend now and look under the hood to see how they do it and pick up some good techniques and ideas.
Comment: Agreed with the fact the CI is pretty bad. However I really don't agree with your statement about `static` functions playing a role in OOP. It's the exact opposite of OOP.
Comment: Yeah I know they are bad in my framework I have stayed away from using them so far but what I'm saying is its a bit of a pain injecting the $config, $logger, $lang objects etc into the classes that use them even with a DI Container but if it's the best thing to do I will keep injecting them instead of using static methods.
Comment: A static registry is just a glorified array of singletons. I do not see how it would be considered even remotely "good".
Comment: Maybe my expression was no so good but pure OOP may not cover all needs, without risk to have duplicate objects which are resource expensive, or duplicate pieces of code and so on. So i think that in big projects at least, static functions can not be avoided completely. Also another example where i think that a static function is needed is singleton pattern. I waiting and other opinions how my examples can be implemented without using static functions and without reinventing the OOP wheel. I also agree that static functions need be be avoided as much is possible.
Comment: Can you give a single concrete example where you **need** to use global state in mostly-OO code? Because that's what static registries and singletons are - just a form of globals state. You could as well just use `global` variables. It would have all the same impact on your codebase. In OOP we have this magical approach - called "dependency injection". Learn about it.
Comment: @tereško Let not deviate from the topic, from what you say, in order to resume, i could understand that every scenario where may need static functions, can be avoided by using "dependency injection". I still not agree with that but is your opinion and i respect that.
Comment: http://www.youtube.com/watch?v=-FRm3VPhseI&feature=channel


RoR plugin for inviting friends

Question: could u suggest some socialnetworking plugins for inviting and adding friends,
for both registerd and unregistered users in website.
thanks
Answer: Check this website http://jimneath.org/2008/04/25/building-a-social-network-site-in-rails/ for building a social networking site in rails using some plugins.
and check the stackoverflow question for some more information.
Best Ruby on Rails social networking framework

RoR plugin for inviting friends


Countable Complete Orthonormal Set implies countable dense subet

Question: Let $\mathcal H$ be a Hilbert Space, let $B = \{u_j\}_{j=1}^{\infty}$ be a countable orthonormal basis. So we know that if a set is a complete orthonormal basis, the set of all finite linear combinations is dense in $\mathcal H$. Define the set
$$S := \{\sum_{j=1}^{n} (q_j+ir_j)u_j \, : \, n \in \mathbb{N}, q_j,r_j \in \mathbb{Q} \},$$ which is countable since it can be injected into $\mathbb{Q} \times \mathbb{Q} \times \mathbb{N}$. Now, since the set of all finite linear combinations is dense let $x \in \mathcal H$, we have
$$\|x-\sum_{j=1}^{m(x)} \langle x,u_j \rangle u_j \| < \frac{\epsilon}{2}$$ for some $m(x)$ depending only on $x$. Note then that (this is where I'm unsure if this is logically sound)
$$\|\sum_{j=1}^{m(x)}  \langle x,u_j \rangle u_j\| \leq m(x)|\langle x,u'_j \rangle|$$ where $|\langle x,u'_j \rangle| := \max \limits_{j=1,\ldots, m(x)} \{|\langle x,u_j \rangle| \}$. Ergo, given $x \in \mathcal H$, if we choose $q_j,r_j$ such that $$|\langle x,u_j \rangle - q_j+ir_j| \leq \epsilon (2m(x)|\langle x,u'_j \rangle|)^{-1},$$
we find that $$\|x-\sum_{j=1}^{m(x)} (q_j+ir_j)u_j\| < \epsilon$$ by the triangle inequality.
Does this suffice? Is there a logical issue with choosing epsilon in this manner?
Comment: What do you want to prove?
Comment: @sinbadh  Countable complete orthonormal set implies countable dense subset, as in the title..
Answer: You are confused:

Let $H$ be a Hilbert Space, let $B=\{u_j\}_{j=1}^\infty$ be a countable
  orthonormal basis. So we know that if a set is a complete orthonormal
  basis, the set of all finite linear combinations is dense in $H$.

It is true.

Now, since the set of all finite linear combinations is dense let
  $x\in H$, we have
$\|x−∑_{j=1}^{m(x)}⟨x,uj⟩uj\|<\epsilon/2...(*)$

No. It doesn't mean that the set of all finite linear combination is dense. It is a consequence of countable orthonormality of $B$. The fact that all the finite linear combanations is dense in $H$ is that for each $\epsilon>0$, there are $n(x)\in\mathbb{N}$, scalars $a_1,...,a_{n(x)}$ and elements $u_{j_1},...,u_{j_{n(x)}}\in B$ such that $\|x-\sum_{k=1}^{n(x)}a_ku_{j_k}\|<\epsilon$.
Please, note the differences between tha last expression and $(*)$ (principal difference is that could it be $a_k\neq\langle x,u_{j_k}$).
Now, since $\epsilon$ is fixed, then the $a_k$ and the $u_{j_k}$ are fixed. Let us approximate each scalar $a_i$ with a rational scalar:
Let $\epsilon>0$. Then, there are $n(x)\in\mathbb{N}$, scalars $a_1,...,a_{n(x)}$ and elements $u_{j_1},...,u_{j_{n(x)}}\in B$ such that $\|x-\sum_{k=1}^{n(x)}a_ku_{j_k}\|<\frac{\epsilon}{2}$.
Now, for $\frac{\epsilon}{2n(x)}$ and fixed $k$, there are a complex $q_k$ with rational real and complex parts such that $|a_k-q_k|<\frac{\epsilon}{2n(x)}$
Then
$\begin{eqnarray}
\|x-\sum_{k=1}^{n(x)}q_ku_{j_k}\|&=&\|x-\sum_{k=1}^{n(x)}(q_k-a_k+a_k)u_{j_k}\|\\
&=&\|x-\sum_{k=1}^{n(x)}a_ku_{j_k}+\sum_{k=1}^{n(x)}(a_k-q_k)u_{j_k}\|\\
&\le&\|x-\sum_{k=1}^{n(x)}a_ku_{j_k}\|+\|\sum_{k=1}^{n(x)}(a_k-q_k)u_{j_k}\|\\
&<&\dfrac{\epsilon}{2}+\sum_{k=1}^{n(x)}|a_k-q_k|\\
&<&\dfrac{\epsilon}{2}+\dfrac{n(x)\epsilon}{2n(x)}\\
&=&\epsilon
\end{eqnarray}$
The desired result follows.
Comment: A simple comment could have cleared the confusion; the one difference here is that you're telling me the coefficients are *not necessarily* the fourier coefficients...other than that, this is the same proof,

thanks all the same


How can I set a DateTimePicker value as today's date+1

Question: How can I set a DateTimePicker value as today's date+1 in code?
Comment: Please mark the correct answer when you get the answer, so that when other users visit this answer then can easily find the answer. Till now you haven't mark any answer as correct.
Comment: Plus 1 what? day? hour? minute? second?
Comment: if date in 18/02/2011,i want to set the date in datetimepicker as 19/02/2011
Answer: Can you pass the binding/context/value as  : DateTime.Now.AddDays(1);
Answer: Try this
this.dateTimePicker1.Value = DateTime.Now.AddDays(1);
Answer: var myDate = DateTime.Now.AddDays(1);

should do it
Answer: set it's selected date to a Datetime.Now.AddDays(1);
Answer: you can say like DateTime.Today.AddDays(1)


Jordan form step by step general algorithm

Question: So I am trying to compile a summary of the procedure one should follow to find the Jordan basis and the Jordan form of a matrix, and I am on the lookout for free resources online where the algorithm to be followed is clearly explained in an amenable way.
I have found some interesting youtube videos but what I am on the lookout for is a written thing.
Alternatively, if you are so kind as to flesh out the procedure I would be happy to accept that as an answer.
Comment: Abstract Algebra, 3rd Edition by Dummit and. Foote, http://mathcs.holycross.edu/~spl/old_courses/304_fall_2008/handouts/jordan.pdf and algorithm: http://math.rice.edu/~friedl/math355_fall04/Jordan.pdf
Comment: I suppose you could also look at: https://math.berkeley.edu/~wilken/papers/Achain.pdf and http://math.cts.nthu.edu.tw/Mathematics/RANMEP%20Slides/Zhonggang%20Zeng.pdf
Comment: See also [Jordan Canonical Form: Theory and Practice](http://www.morganclaypool.com/doi/abs/10.2200/S00218ED1V01Y200908MAS006)
Comment: Neither of the links above works for me ... can somebody fix them please?
Answer:
Find all the eigenvalues of $T$.

For each eigenvalue $\lambda$:

Let $N = T-\lambda I$.

Compute $N^2, N^3, \dots, N^n$.

Find the generalized eigenspace $G=G(\lambda,T)$ of solutions $u$ to $N^n u = 0$.

Find a temporary basis for $G$.

Let $U_0 = G$, $U_n = \{0\}$ and $B_n = \emptyset$.

For $k=n-1,\dots,1,0$:

Find $U_k = $range$ (N_{|_G})^k$ by applying $N^k$ to the temporary basis of $G$.

From the previous step we have a Jordan basis $B_{k+1}$ to $T_{|_{U_{k+1}}}$ given by
$N^{d_1}v_1,\dots,N^2 v_1, N v_1, v_1, \dots, N^{d_m}v_m,\dots,N^2 v_m, N v_m, v_m$, with the property that $N^{d_j+1} v_j = 0$ for all $j$.

For $j=1,\dots,m$, find one $u_j$ such that $N u_j = v_j$.

Let $\tilde B_k = N^{d_1}v_1,\dots,N^2 v_1, N v_1, v_1, u_1 \dots, N^{d_m}v_m,\dots,N^2 v_m, N v_m, v_m, u_m$. Then $\tilde B_k$ is a Jordan basis for $T$ restricted to its span.

Find $A_k$ such that $\tilde B_k \cup A_k$ is a basis for $U_k$.

For each $w\in A_k$:

Find $x \in {\sf span} \tilde B_k$ such that $Nx = Nw$.

Let $u=w-x$, so $Nu=0$.

Let $\tilde A_k$ be the set of vectors obtained above.

Let $B_k = \tilde B_k \cup \tilde A_k$. Then $B_k$ is a Jordan basis for $T_{|_{U_k}}$.

In the end, $B_0$ is a Jordan basis for $T_{|_G}$.

Recollecting all Jordan bases for each $T_{|_{G(\lambda,T)}}$ produces a Jordan basis for $T$.

I found this method myself by digging into the proof in Axler's Done Right book. I hope it is correct.
Comment: On the third to the last bullet point, I think you meant $\tilde{A_k}$.
Comment: @SungjinKim Thanks! I edited it just now. Is that what you meant?
Comment: Thank you. Yes, that was it.


Enviar e-mail após o upload estar concluído?

Question: Tenho a seguinte função para envio de e-mails utilizando o nodemailer e um servidor HapiJS:
let data = request.payload;
    if (data.file) {
        let name = data.file.hapi.filename;
        let caminho = __dirname + "/uploads/" + name;
        let file = fs.createWriteStream(caminho);

        file.on('error', function (err) {
            console.error(err)
        });

        data.file.pipe(file);

        data.file.on('end', function (err) {
            mailOptios.attachments.push({
                filename: name,
                path: caminho //push nos anexos quando o upload está concluido
            });
            reply('Upload Concluído');
        });
    }

    let destinatario = 'firstname.lastname@example.com';
    let ass = 'teste com anexo';
    let email = 'Teste com anexo';
    let mailOptios = {
        from: usuario, //usuário está definido mais acima no código
        to: destinatario, //não incluí usuário aqui por questões de privacidade
        subject: ass,
        text: email,
        attachments: [
        ]
    };

    console.log(mailOptios);
    transporter.sendMail(mailOptios, function (err, info) {
        if (err){
            console.log(err)
        } else {
            console.log('Enviado! ' + info.response);
            return reply.response('Enviou')
        }
    })

Porém, o processo está ocorrendo de forma assíncrona e o email está sendo enviado antes de ocorrer o upload completo do anexo.
Como deixar essa função síncrona ou garantir que o anexo esteja pronto antes de enviar o email?
Comment: Não podes jogar a função "transporter.sendMail(...);" depois de "reply('Upload Concluído');", simplesmente ?
Comment: Após pequenos teste e adaptações funcionou perfeitamente, por favor adicione uma resposta para que eu possa aceitá-la e possivelmente ajudar à outras pessoas que possam ter essa dúvida...
Answer: Você tem que colocar todo esse código aqui:
let destinatario = 'firstname.lastname@example.com';
let ass = 'teste com anexo';
let email = 'Teste com anexo';
let mailOptios = {
    from: usuario, //usuário está definido mais acima no código
    to: destinatario, //não incluí usuário aqui por questões de privacidade
    subject: ass,
    text: email,
    attachments: [
    ]
};

console.log(mailOptios);
transporter.sendMail(mailOptios, function (err, info) {
    if (err){
        console.log(err)
    } else {
        console.log('Enviado! ' + info.response);
        return reply.response('Enviou')
    }
})

Dentro do data.file.on('end'), isto porque o on é um evento, de forma que ele está enviando uma mensagem dizendo que o upload terminou. Eu aconselho você transformar isso tudo em uma função sendMail e mandar os parâmetros necessários dentro do evento end