Compute $\int\frac{1}{1+x^4}dx$

Question: I was given the following hint and I can solve the problem by using the following equation. But I'm curious about how one can get the equation. Can someone give me some wikipedia links about it or hints to manipulate the equation?$$\frac{1}{1+x^4}=\frac{x-\sqrt{2}}{2\sqrt{2}(-x^2+\sqrt{2}x-1)}+\frac{x+\sqrt{2}}{2\sqrt{2}(x^2+\sqrt{2}x+1)}$$
BTW, are there any easier method to solve this integral? As seen on the answer, it seems not very possible. ;)
Comment: Check this out: https://www.physicsforums.com/threads/integral-1-x-4-1.531460/
Comment: @imranfat I was not able to visit this link.Maybe I need a VPN to visit it;(
Answer: To find this decomposition, we have to factorize $x^4 + 1$. As $x^4 + 1$ does not have real roots, it does not have real linear factors. This gives the ansatz
$$ x^4 + 1 = (x^2 + ax + b)(x^2 + cx + d) $$
We have
$$
  (x^2 + ax + b)(x^2 + cx + d) = x^4 + (a+c)x^3 + (b + d + ac)x^2 + (bc + ad)x + bd $$
Comparing the coefficients with $x^4+ 1$, we have
\begin{align}
  a + c &= 0\tag 1\\
 b + d + ac &= 0\tag 2\\
  bc + ad &= 0\tag 3\\
   bd &= 1\tag 4
\end{align}
Now $a = -c$ from (1), this gives
\begin{align}
  a &= -c\\
 b + d - a^2 &= 0\tag 2\\
  a(d - b) &= 0\tag 3\\
   bd &= 1\tag 4
\end{align}
As $a = 0$ is impossible, as then (2) would give $b = -d$, which contradicts (4), we must have $a \ne 0$ and hence $d = b$ from (3), this leaves us with
\begin{align}
  a &= -c\\
 2b - a^2 &= 0\tag 2\\
   d &= b\\
   b^2 &= 1\tag 4
\end{align}
By (2), $b$ is positive, hence $b = 1$ by (4). This gives $d = 1$, and hence $a = \pm \sqrt 2$. Due to symmetry in $a$ and $c$, we may let $a = \sqrt 2$, giving
$$ x^4 + 1 = (x^2 + \sqrt 2 x + 1)(x^2 - \sqrt 2 x + 1) $$
Now we use partial fraction decomposition, starting with the ansatz
$$ \frac 1{x^4 + 1} = \frac{\alpha x + \beta}{x^2 + \sqrt 2 x + 1} + \frac{\gamma x + \delta}{x^2 - \sqrt 2 x + 1} $$
Clearing denominators gives
\begin{align*}
  1 &= (\alpha x + \beta)(x^2 - \sqrt 2 x + 1) + (\gamma x + \delta)(x^2 + \sqrt 2 x + 1)\\
    &= (\alpha + \gamma)x^3 + (\beta -\sqrt 2 \alpha + \delta + \sqrt 2 \gamma)x^2 + (\alpha + \gamma - \sqrt 2\beta + \sqrt 2 \delta)x + \beta + \delta
\end{align*}
Comparing coefficients gives
\begin{align*}
    \alpha + \gamma &= 0\\
    \beta + \delta + \sqrt 2(\gamma - \alpha) &= 0\\
   \alpha + \gamma + \sqrt 2(\delta - \beta) &= 0\\
   \beta + \delta &= 1
\end{align*}
From the first, the third equation and the forth equation we have $\beta = \delta = \frac 12$, the second one gives $\gamma - \alpha = \frac 1{\sqrt 2}$, as $\alpha = -\gamma$ by the first equation $\gamma = \frac 1{2\sqrt 2}$, $\alpha = - \frac 1{2\sqrt 2}$, giving
$$ \frac 1{x^4 + 1} = \frac{- x + \sqrt 2}{2\sqrt 2(x^2 + \sqrt 2 x + 1)} + \frac{x + \sqrt 2}{2\sqrt 2(x^2 - \sqrt 2 x + 1)}
$$
Comment: It is faster to factorize $x^4+1$ by noting:
$x^4+1=x^4+1+2x^2-2x^2=(x^2+1)^2-\left(\sqrt{2}x\right)^2=\left(x^2+\sqrt{2}x+1\right)\left(x^2-\sqrt{2}x+1\right)$.
Comment: I was scared in doing calculations like this, and you just inspire me to do this on my own! Thanks a lot.
Answer: I am giving a hint.
$$\int \frac {dx}{1+x^4}=\frac 12\left(\int\frac {1+x^2}{1+x^4}dx-\int\frac {x^2-1}{1+x^4}dx\right)\\=\frac 12\left(\int\frac {1+\frac 1{x^2}}{x^2+\frac 1{x^2}}dx-\int\frac {1-\frac 1{x^2}}{x^2+\frac 1{x^2}}dx\right)$$
Now, write $x^2+\frac 1{x^2}=\left(x-\frac 1x\right)^2+2$ and $x^2+\frac 1{x^2}=\left(x+\frac 1x\right)^2-2$, for the respective integrals, substitute for $x+\frac 1x=z$ and $x-\frac 1x=u$.
Now, you have $\left(1-\frac 1{x^2}\right)dx=dz$ and $\left(1+\frac 1{x^2}\right)dx=du$
Now,proceed from here, it is easy for you now.
Answer: Notice, $$\int\frac{dx}{1+x^4}=\int\frac{dx}{x^2\left(\frac{1}{x^2}+x^2\right)}$$
$$=\int\frac{\frac{1}{x^2}}{\frac{1}{x^2}+x^2}dx=\frac{1}{2}\int\frac{\frac{2}{x^2}}{x^2+\frac{1}{x^2}}dx$$
$$=\frac{1}{2}\int\frac{\left(1+\frac{1}{x^2}\right)-\left(1-\frac{1}{x^2}\right)}{x^2+\frac{1}{x^2}}dx$$
$$=\frac{1}{2}\int\frac{1+\frac{1}{x^2}}{x^2+\frac{1}{x^2}}dx-\frac{1}{2}\int\frac{1-\frac{1}{x^2}}{x^2+\frac{1}{x^2}}dx$$
$$=\frac{1}{2}\int\frac{1+\frac{1}{x^2}}{\left(x-\frac{1}{x}\right)^2+(\sqrt2)^2}dx-\frac{1}{2}\int\frac{1-\frac{1}{x^2}}{\left(x+\frac{1}{x}\right)^2-(\sqrt2)^2}dx$$
$$=\frac{1}{2}\int\frac{d\left(x-\frac{1}{x}\right)}{\left(x-\frac{1}{x}\right)^2+(\sqrt2)^2}dx-\frac{1}{2}\int\frac{d\left(x+\frac{1}{x}\right)}{\left(x+\frac{1}{x}\right)^2-(\sqrt2)^2}dx$$
$$=\frac{1}{2\sqrt 2}\tan^{-1}\left(\frac{x-\frac{1}{x}}{\sqrt 2}\right)-\frac{1}{4\sqrt 2}\ln\left|\frac{x+\frac{1}{x}-\sqrt 2}{x+\frac{1}{x}+\sqrt 2}\right|+C$$

Compute $\int\frac{1}{1+x^4}dx$


How can I match quoted text excluding leading and trailing whitespaces?

Question: I.e. the match of
<code> He said, "For my part, it was Greek to me. "
</code>
should be
<code>For my part, it was Greek to me.
</code>
Without the trailing space.
I've tried
<code>\"\s*([^\"]*)\s*\"
</code>
but it's always matching trailing whitespaces in the group.
Answer: try:
<code>\"\s*([^\"]*?)\s*\"
</code>
But be careful, this version is contingent upon the closing quotation mark (because it's lazy).  When you add the lazy operator here, it grabs the smallest possible string it can.  If there are no closing quotes, this regular expression will fail
If you're sure there's no empty strings, you can use:
<code>\"\s*([^\"]*[^\"\s])\s*\"
</code>
The main problem with this version is that you are now pushing for a minimum of one character.
Honestly, looking at it twice, I'd use the first pattern.  You're looking for the closing quote and not escaping any quotes.  It'll work 100% of the time for your current needs.
Comment: This could do with a better explanation. I also think your reservations about empty strings is wrong - the first regex should still pull an empty string out of "  " or "". However, I think this is the correct answer.
Answer: Wouldn't it be easier to just trim the blanks afterwards using simple string functions? This would also simplify the regular expression.
Comment: While many people over-code with regular expressions, the flipside of the argument is that regular expressions do exactly one thing, which is robust string pattern-matching.  It's a waste to keep a couple characters out of a regex for simplicity, to add another cleanup step.
Comment: I would argue that the string functions are more efficient than a more complicated regex. And it makes the code more readable when you just trim the blanks by conventional means.
Comment: Agree. This is the first thing I thought of. Of course, there's nothing wrong with the fully functional regex except for the arguable readability issue.
Answer: What about if you force it to have the final character be non-white space? Something like this:
<code>\"\s*([^\"]*[^\s])\s*\"
</code>


my existing code is javascript and i want to convert these in jquery?

Question: how can i convert this to jQuery?
openDish("balkandish1")
function openDish(dishName) {
    var i;
    var x = document.getElementsByClassName("city");
    for (i = 0; i < x.length; i++) {
        x[i].style.display = "none";
    }
    document.getElementById(dishName).style.display = "block";
}

Comment: I didn't know why anyone didn't ask you, what have you tried and just spoon fed you the codes :) please make an attempt and then come for help in future
Answer: You just need to call hide() and show() on the relevant selectors, like this:
openDish("balkandish1")

function openDish(dishName) {
    $(".city").hide()
    $('#' + dishName).show();
}

Answer: jQuery offers .show() and .hide() function that can be used to hide and show DOM elements.
openDish("balkandish1");

function openDish(dishName) {
    $(".city").hide();
    $('#'+ dishName).show();
}

Answer: Use show() and hide() methods.
openDish("balkandish1");

function openDish(dishName) {
   // get all elements using class selector
   // hide them using `hide()` method
   $(".city").hide();
   // get the element using `id` selector
   // make it visible using `show()` method
   $('#' + dishName).show();
}

openDish("balkandish1");

function openDish(dishName) {
  $(".city").hide();
  $('#' + dishName).show();
}

1

2

3

4

5

6


How to distinguish between permutation and combination questions?

Question: You own 5 songs by Adele, 4 by Lady Gaga, and 3 by Katie Perry. How many
playlists (ordered list of songs) can be formed that consist of 3 Adele, 2 Gaga, and 2 Perry songs if:
(a) Repetitions are allowed?
(b) Repetitions are not allowed?
I am struggling on what questions I should ask myself when approaching a problem like this? Is this a permutation, or a combination? Or neither?
Comment: "*Is this a permutation, a combination, or neither?*"  Neither, but it can use both permutations and combinations as substeps in the larger problem.
Comment: Possible duplicate of [Probabilities and sets](https://math.stackexchange.com/questions/2990233/probabilities-and-sets)
Comment: @lulu ironically, although older and an exact duplicate, the answer there is incorrect.  See my comment on user's deleted answer below.
Comment: @JMoravitz  That's funny!  I was struck by the exactness of the duplicate and did not look further.  I'll retract my close vote accordingly.
Answer: Pick which positions will be occupied by songs by Adele.
Among the remaining positions, pick which positions will be occupied by songs by Gaga.  The final remaining positions will be occupied by songs by Perry.
Now, among the positions designated to be occupied by Adele, pick which song occupies the first of those positions.  Then pick which song occupies the second of those positions (noting that in the case of repetition not allowed, we have one fewer option).
Continue in this manner until all is sorted out, giving final answers of $\binom{7}{3}\binom{4}{2}5^3\cdot 4^2\cdot 3^2$ for repetition allowed and $\binom{7}{3}\binom{4}{2}(5\cdot 4\cdot 3)\cdot (4\cdot 3)\cdot (3\cdot 2)$ for repetition not allowed.


What's the relation between Canonical Correlation Analysis (CCA) and Regression?

Question: I'm wondering if CCA is just a feature transformation method. Can I use it for predicting continuous variables like in regression methods?
What I'm doing is to use CCA to transform my training and test matrices, and then use the transformed matrices as features to do regression (e.g., linear regression and decision tree regression). But I'm not sure if it helps or CCA and regression are basically the same thing?
Comment: As explained [here](http://stats.stackexchange.com/q/65692/3277) CCA can be seen as multivariate multiple linear regression. Unlike PCA, it is not just "transformation" of data to summarize it, because, as in regression, there is an external data to predict.
Comment: How many response variables do you have?
Answer: I am not an expert on this subject.
But I guess you can follow procedure similar to the PLS regression.
I mean:

Find the first CCA components of X (feature variables) and Y (target variables).  Name them as t and u, respectively (although u is not used afterwards). Store the weight w and the loading vector p.
Deflate X so that it has no correlation with t :  X  ->  X-(1/t^T t)tt^T X
Perform linear regression of Y on t.  Take the residual (estimation error) of this linear regression as the new, deflated Y :  Y  ->  Y-(1/t^T t)tt^T Y
Take the deflated X and Y as new X and Y, and go back to 1.
Iterate the steps from 1 to 4 as many as you like.  Then you get the final linear estimation :   Y_{estimate} =  X_{test}R where R = W(P^TW)^{-1}. Here, W=(w_1, w_2,...) and P=(p_1, p_2, ...) where w_k and p_k are the k-th weight and loading vector.

Both X and Y are assumed to be centered (their sample means are zero). In practice, you should add or subtract the means of the train data when predicting.
Note that the "k-th CCA component" above is generally not the same as that obtained by the usual CCA decomposition, where you obtain CCA components theoretically at once by solving only one eigenvalue equation without performing any deflation. (I am not familiar enough on this point.)
For your information, the procedure of the PLS regression will be most concisely understandable by the Scikit-learn implementation:
https://github.com/scikit-learn/scikit-learn/blob/7e85a6d1f/sklearn/cross_decomposition/_pls.py#L137


Why did Perl say() not append newline in FCGI mode?

Question: I have a strange behaviour with Perl's say function in FCGI mode. Newlines won't be append. Why does this happen?
Sample code:
#!/usr/bin/perl -wT
use strict;
use warnings;
use utf8;
use feature qw( say );
use FCGI ();
use CGI qw( header );
my $cnt = 0;
my $req = FCGI::Request();
while ( $req->Accept() >= 0 ) {
    $cnt++;
    print header( -type => 'text/plain', -charset => 'utf-8' );
    say "Hello, world #$cnt";
    print "\n";
    print "$$\n"
    print 'Test 1234';
}

Expected result (and actual result via console):
Content-Type: text/plain; charset=utf-8

Hello, world. #1

6712
Test 1234

Actual result via Apache/FCGI:
Content-Type: text/plain; charset=utf-8

Hello, world. #3
6709
Test 1234

Some software info...

Debian Wheezy x86_64
  Apache/2.2.22-11
  mod_fcgid/1:2.3.6-1.1
  Perl/5.14.2-12
  FCGI.pm/0.75-1+b1
Answer: Unfortunately the implementation of the say() function requires the filehandle to support the $\ variable. Basically say is equivalent to writing:
{ local $\ = "\n"; print LIST }

Using FCGI, your STDOUT is replaced by a tied filehandle, which doesn't support $\. This means that say() doesn't work as intended.  Whether this is a bug in FCGI or in say() seems to be debatable.
Comment: A simple workaround would be to re-implement `say`: `use subs qw/say/; sub say { print @_, "\n" };`
Comment: As for a solution I think it is easiest just to say "Don't do that then". The alternative is to get FCGI fixed. Adding `unshift @_, $\ if defined $\\` after [line 264 of FCGI.PL](https://metacpan.org/source/FLORA/FCGI-0.74/FCGI.PL#L265) might do the trick. But there is a chance that it will break a lot of code depending on FCGI not respecting $\.
Comment: @IlmariKaronen Correct. Good catch.


angular 5 routing from auxiliary children route to parent gives match error

Question: I have added a second router outlet for 'reports' and this router outlet is in the "layout" component for reports. All three children routes are linked to in a 'sub menu' component and my issue arises when I go back to the 'start route' (assignment list), thats where i get

Error: Cannot match any routes. URL Segment: 'SE_556354-3353/%2Freports'
  Error

How do I get back to the "root"/parent (assignmentlist) ? Basically, just how can I jump between these links?
Here is the relevant code.
app.module
const routes = [
{ path: ':orgNoParam/organizational-unit/:unitIdParam/employments', component: EmployeeComponent },
 {
    path: ':orgNoParam/reports', component: ReportsComponent, children: [
        { path: '', component: AssignmentListComponent, outlet: 'content' },
        { path: 'managers', component: AssignmentCompactManagersComponent, outlet: 'content' },
        { path: 'employments', component: AssignmentCompactEmployeesComponent, outlet: 'content' }
    ]
 }
];

reportsComponent (aka "the layout")

<assignment-submenu></assignment-submenu>

    <error-message *ngIf="errorList?.length" [errorList]="errorList"></error-message>

<router-outlet name="content"></router-outlet>

Submenu.html (this is where the links are)

    <ng-container *ngIf="translation.link=='reports'">
        {{ translation.name }}
    </ng-container>

    <ng-container *ngIf="translation.link=='managers' || translation.link=='employments'">
        {{ translation.name }}
    </ng-container>

Submenu.ts
goToRoot() {
    this.router.navigate([this.orgNoParam, '/reports']);
}

Answer: I solved itby setting the routerlink to 'routerLink="{{translation.link}}"' for the "root"-child, and then setting the path of the "root"-child (it has the path '') to '../reports' and voila.


Add items to layout in dynamic way

Question: I want to add buttons to layout from code, but in specific way. All buttons should be added in horizontal orientation in one line, but when last button is too long, should be put in next line. How can I do that? There is any custom control to do that?
Comment: you can make use of gridview. and add/remove items whenever u want by just calling notifydatasetchanged method from its adapter.
Answer: You can give a certain width to your button and calculate every time if there is enough space to add a new one, the container could be a RelativeLayout, use the relative position to control the new line issue.
Answer:    LinearLayout my_root = (LinearLayout) findViewById(R.id.my_root);
    LinearLayout A = new LinearLayout(this);
    A.setOrientation(LinearLayout.HORIZONTAL);
    A.addView(view1);
    A.addView(view2);
    A.addView(view3);
    my_root.addView(A);

view1,view2,view3 are your textviews.. easily created programmatically
Hope above code will help you.
Let me know if you need more help in same.

Add items to layout in dynamic way


What's the difference between the two arpeggio symbols (default and upwards)?

Question:
What is the difference between the symbol in the upper-left corner (with no arrow) and the one next to it (with an upwards arrow)? Aren't the two the same?
Comment: That diagram looks like it came right out of Musescore.
Comment: That could be possible. That was one of the first images I saw on google.
Answer: The first two both mean to roll upwards. The third means roll downwards. The second is often used when the third is used to make it direction clear.
Comment: I really like the terminology you used, "to ROLL upwards/downwards". Sounds very majestic!


Interpolating between points of known uncertainty

Question: I have a large but finite set of objects (phylogenetic trees), each of which is assigned an integer value 0 ≤ v ≤ x.  x varies from set to set, but is small (≪ 100).
For a given set,
I wish to estimate p(v ≤ n) for each n in 0 → x.
p(v = 0) can be calculated exactly.  Because p(v = n) is close to 1/n when n ~ x, I'm able to obtain good estimates by sampling many (a million, say) objects; the standard error can be calculated using the binomial distribution.  But p(v = n) is very small when n is small: even a large sample may contain zero objects with n = 1 or n = 2.
I wish to interpolate between my precise estimates for large n and the exact value known for p(n = 0) in order to obtain estimates for p(n ≤ 1, 2, …) in a way that reflects the increasing trend in p as n increases, and to calculate the uncertainty associated with these estimates.
My approach so far has been to attempt a non-linear regression, but I've not found a way to conduct this or other interpolation techniques that I've encountered in a manner that expressly accounts for the known uncertainty of the estimated values.
Answer: My understanding from what you wrote is that you want to adjust the estimates for v=1 or 2 because you observed 0 of them in the simulation and you know the probability has to be greater than 0.
When v=1 or 2 and you observe 0 of those out of 1 million, you can be pretty confident that the probability mass function at those two points is less than $3 \times 10^{-6}$ (3 out of a million). That's a 95% upper confidence limit for the probability mass at those points. If you know the true probability cannot be 0 and you want to force it to be something other than 0, you could replace it be something positive and less than $3 \times 10^{-6}$. If $P[v=0]$ is known exactly and you are estimating all the rest by simulation, you can do that and then re-weight the estimates for those $v$ greater than 0 so that all the mass adds to 1.
If you want to do something more sophisticated that allows you to use prior knowledge and the uncertainty from the simulated values directly, then you could try a Bayesian approach to density estimation. That's going to be alot of work and not worth the effort in my opinion. One other option using a Bayesian idea is to use Laplace rule of succession. If you have a uniform prior on P[v=1] and then you observed 0 occurrences of v=1 out of 1 million simulated objects, the posterior mean estimate of P[v=1] is 1/(1,000,002). You clearly cannot have Uniform(0,1) priors for all values of v so this approach doesn't really hold water without some modification, but this is just some idea of another estimate you could use instead of 0.
Comment: Thanks for these suggestions.  I am hoping for an approach that assigns a higher probability to higher values of _v_.  I need to approximate log(p(n <= 1)) - log(p(n = 0)) and log(p(n <= 2)) - log(p(n <= 1)), so the extra precision that a Bayesian approach might provide would be useful.


Duplicate entry for key 'group_key'

Question: I'm running a query in MySQL where I'm grouping by four columns and selecting a lot of things, including the four values I'm grouping by. But I get this error when I run the query:
Duplicate entry '92-0-10-7' for key 'group_key'

The 92, 0, 10, and 7 are all values of the four grouped-by columns for a particular row (actually, I checked, and there are 63 rows that fit those parameters). But I have no idea what that means, or how to run my query properly.
My query:
Create table table2 as
Select round(x, 0) as x, round(a, 0) as a, round(b, 0) as b, c, d, e, f
from table1
group by round(x, 0), round(a, 0), round(b, 0), c

The 92 would fit x, the 0 a, the 10 b, and the 7 c.
I have no indices on this table.
Thanks!
Comment: `GROUP BY` does not make sense in this query.  There is no aggregate function, here... `ROUND()` is not an aggregate function.  The values for d, e, and f cannot be properly determined.  Do you really mean `SELECT DISTINCT`?  Otherwise, is the purpose of the grouping?
Comment: May be a MySQL bug: http://bugs.mysql.com/bug.php?id=62755
Comment: Your query is `SELECT` whereas that error message may only occur for DML (`UPDATE` or `INSERT`). So, the error message is caused by another query.
Comment: What do you mean another query? I'm only running this query and it still gives me that message. Also, FWIW, the actual query is a create table command, but the only difference is there is a "create table table2 as" in front of the select.
Comment: @zerkms I did try running the same query without the create table part and nothing changed, so I don't really think it matters.
Comment: well, `SELECT` query cannot cause that error
Answer: Your issue seems like a MySQL bug. I was reviewing the logs for our production server the other day and the error logs were filled with this error. I used the workaround below and the errors are gone.

SET SESSION max_heap_table_size=536870912;
SET SESSION tmp_table_size=536870912;

Source: http://bugs.mysql.com/bug.php?id=58081
Comment: worked for me too. mysql  5.6.33. Added these settings to my.cnf.
Comment: I can't really describe my table structure here, but using 5.6.35 and this didn't fix my error
Comment: You saved my bacon. Thank you.
Answer: This is usually disk space issue. Specially temporary space (in linux /tmp). Check you database server Disk space.
Comment: Changing MySQL's `tmpdir` to a folder with more free space solved this problem for me. Thanks!
Answer: You should put the alias names in the GROUP BY like this:
CREATE TABLE table2 AS
SELECT ROUND(x, 0) AS x, ROUND(a, 0) AS a, ROUND(b, 0) AS b, c, d, e, f
FROM table1
GROUP BY x, a, b, c;

Duplicate entry for key 'group_key'


É errado eu usar um método estático para retonar uma coleção de objetos?

Question: Antes de tudo, sei que não devo sair fazendo classes com vários métodos estáticos mas nesse caso que trago aqui, não entendo por que pode ser considerado má prática.
Digamos que eu tenha uma estrutura MVC, no meu model, eu tenho todos os respectivos métodos do meu CRUD, criar, ler, atualizar e deletar. Porem, eu sempre faço um método estático chamado listar, esse por sua vez, pode retornar uma collection (array mesmo no caso no php) com vários objetos do model especifico e ai, para cada objeto, eu tenho os seus métodos do CRUD. Não vejo problema no listar ser estático, uma vez que ele não vai interagir diretamente com nada mais da minha classe.
Pesquisei bastante sobre o assunto e não achei nada que me fizesse mudar de ideia, por isso, queria trazer essa discussão aqui.
Comment: A não ser que tenha entendido errado... Qual motivo de o método listar retornar vários objetos? Qual aplicação que você faz disso?
Comment: Por exemplo, eu tenho uma Classe Pessoa. Eu posso nela, inserir, ler, atualizar e deletar. Mas e quando eu quero listar  por exemplo, todas as Pessoas que tenho. Apresentar uma lista para o usuário. Nesse caso, eu tenho a prática de usar um método estático, pois não vou interagir diretamente com outros métodos ou atributos da classe Pessoa, mas ainda sim, estou fazendo algo relacionado a Pessoa, logo, Por que não, usar um método estático, esse, instanciando uma pessoa para cada linha que minha query retornar e eu retorno essa lista
Comment: Relacionado: [Qual a função de um método estático?](https://pt.stackoverflow.com/questions/54012/qual-a-fun%C3%A7%C3%A3o-de-um-m%C3%A9todo-est%C3%A1tico)
Comment: Não vi problema nessa abordagem, pode inclusive ser prático. Posso até está enganado, mas o framework Laravel (laravel.com) faz algo parecido para alguns métodos.
Comment: Ao pensarmos que um método estático seria um "método da classe" e que seria executado sem precisar de uma instância dela para se listar objetos, acho que não vejo nenhum problema nessa abordagem. Inclusive faz um certo sentido pra mim analisando pelos conceitos em si. Só surgiu uma dúvida que é relativa a conexão com o Banco de Dados nesse método estático: como é feita esta conexão? Toda programada no método estático? Imagino que sim por ser estático.
Comment: Acredito que não há erro em usar métodos estáticos para isso, porém me parece que sua classe está com mais responsabilidades do que simplesmente um model. Isso é comum quando se usa algum ORM do tipo ActiveRecord como o Eloquent do Laravel. Para fugir desse tipo de abordagem, é comum a implementação do pattern Repository, e desacoplar o modelo da integração com o BD.
Answer: Supondo que, seu motivo seja controlar vários cadastros em instancias diferentes, isso faz sentido, que inclusive é aplicado no Laravel com o método Route , que é usado para receber instancias de outras classes, e pode ter várias responsabilidades, como neste exemplo:
Caminho: http://127.0.0.1:8000/api/produtos/1
Route::get('produtos/{id}/', function (Request $request, Produtos $produtos) {
   //
});

No exemplo o método Route chama de forma estática ou método Get, manipulando as instancias de Request e de Produtos, essas classes poderiam possuir diversas outras responsabilidades dentro delas como os proprios Controllers do padrão MVC, mas isso se mal aplicado, pode acarretar num problema que é o encapsulamento do seu código, fazendo com que a manutenção fique custosa.
Prosseguindo na resposta ainda usando o Laravel como exemplo, nesse caso ele se encaixa no padrão de projeto 'Fachada'  (Facade), onde uma 'fachada' (a Route) é responsável por toda cadeia de subclasses posteriores.
Referencias:
Laravel Facades
Laravel Routing
Padrão Facade
Relacionado:
Answer: Hoje o desenvolvimento se baseia em vários padrões de projetos, e alguns desses padrões(ou todos, não sei) utiliza-se injeções de dependência ou seja, injetar uma classe.
Sugiro também implementar interfaces em suas aplicações pois ajudam a melhorar o código e juntando tudo fica mais fácil uma possível manutenção depois.
Recomendo você dar uma estudada sobre design Patterns vai ajudar você a evoluir muito como desenvolvedor.


LME residual plot returns a huge linear block of residual points

Question: The publicly available data I used
https://content.sph.harvard.edu/fitzmaur/ala2e/cd4.txt
I addressed the unbalanced followup visits by transforming the visit time to the nearest multiple of 8 then de-duplicated visit times.
I then used last observation carried forward to impute missing log CD4 values. Then ran two linear mixed intercept models (log CD4 ~ time) on the raw data and on the imputed data. I checked the residual plots and I got these.
Raw model residuals

Imputed model residuals

So I see that my imputation method has made some of the residuals more normal, but why is there that huge group of fitted values around 3? How would I be able to address that?
The models I fit:
<code>raw_3_model <- lme(log_CD4_1 ~ Time, random = ~Time|ID,
                   data = raw_data, method = "REML",
                   na.action = na.exclude)

treatment_3_model <- lme(measurements ~ time, random = ~time|ID,
                         data = final_3, method = "REML",
                         na.action = na.exclude)
</code>
Comment: Could you post the models you fit?
Comment: @user158565 I just added them in!
Comment: I did not get the results like you did.
Comment: @user158565 Would there be a way I could see what your residuals look like? Was it of the raw data?
Comment: "transforming the visit time to the nearest multiple of 8 then de-duplicated visit times." In fact, I think I misunderstood this sentence. What exactly did you do on time variable?
Comment: @user158565 Participants were asked to come in for followup every 8 weeks (until the 5th visit at week 40) and from what I saw, people often had sporadic visit patterns/unbalanced so I rounded their visits to the nearest 8th week (i.e. 7.2 to 8) but if there were two visits that got rounded to same value (i.e. 7.2 and 12.1 to 8), it would appear as if they came in for a visit twice in the same week - so I deleted one of those observations
Answer: A couple of points:

Mixed models work with unbalanced data. Hence, you do not need to transform the visit times to be balanced nor to delete any measurements. Actually, if you are interested in the longitudinal evolution it is better not to have balanced data.
Mixed models will provide you with valid inferences under the missing at random missing data mechanism. Hence, you do not need to impute any missing data. Moreover, the last observation carried forward is a terrible method of imputation that does not even provide correct inferences under the missing completely at random mechanism.
In the residuals plots you see two things: (1) the vertical lines around 3 come from the baseline measurement because all subjects were measured at 0; (2) the diagonal lines on the bottom left come from the bounded nature of the CD4 cell count outcome (i.e., it is greater or equal than zero and you have measurements at and close to this boundary).
Comment: That's really helpful! Thank you Dimitris!
Should I impute missing baseline information then? And keep the followup data missing as is?
Comment: You mean imputing the baseline value of the outcome CD4 cell count or baseline covariates? Regarding the former, if you do not include the baseline CD4 cell count measurement as a baseline covariate in the model, you do not need to impute it. Regarding the latter, you could consider imputing covariates with missing data.


Function of the surface obtained by rotating the graph of $\frac{1}{|x|}$

Question: What is the function of the 3 dimensional plane created when the graph of 1/abs(x) is rotated in the z-axis around the origin?
I'm sorry for bad formatting and if this is a duplicate.
Comment: "The graph of 1/abs(x)" What does that mean? Do you mean the SURFACE $z = 1/|x|$ or the plane curve $y = 1/|x|$? And rotating about the z-axis and the origin are very different things
Comment: If you have trouble formatting, you could see http://meta.math.stackexchange.com/questions/1773/do-we-have-an-equation-editing-howto
Answer: I'm not sure I understand your phrasing, but I assume that you are looking for the equation of the surface obtained by taking the graph of $z=\dfrac{1}{|x|}$ in the $xz$-plane:

and rotating it about the $z$-axis to produce a surface:

If that is the case, then the equation for the above surface is
$$z=\frac{1}{\sqrt{x^2+y^2}}$$
Comment: As a note: parametric equations make the construction of a surface of revolution much easier. If you have some function $z=f(x)$ (i.e. your function is embedded in the $x$-$z$ coordinate plane), and you wanted to rotate about the $z$-axis, then the parametric equations are $$\begin{align*}x&=u\cos\,\theta\\y&=u\sin\,\theta\\z&=f(u)\end{align*}$$
Answer: Hint:  First, what is the other side of the equation you are graphing?  I would guess $y=\frac 1{|x|}$.  Second, can you convince yourself that the absolute value doesn't matter?  If you have a point $(x,y,z)$, isn't $(-x,y,z)$ a rotated version?


Subdomains for different applications on Windows Server 2008 R2 with Apache and IIS 7 installed

Question: I have a home server, on which I have installed Apache, and several other applications that have a Web GUI (JDownloader, Free Download Manager).
In order to access each of these apps (whether be it from the local network or the Internet), I have to enter a different port, e.g.,

http://server:8085 or http://xxxx.dyndns.org:8085 for Apache
http://server:90   or http://xxxx.dyndns.org:90   for FDM
http://server:8081 or http://xxxx.dyndns.org:8081 for JDownloader

I would like to be able to access them using sub-domains, e.g,

http://apache.server      or http://apache.xxxx.dyndns.org      for Apache,
http://fdm.server         or http://fdm.xxxx.dyndns.org         for FDM,
http://jdownloader.server or http://jdownloader.xxxx.dyndns.org for JDownloader

First of all, would it be possible like I want it, i.e., both from LAN and Internet, and if yes, how? Even if it's possible only for Internet, I would like to know how to do it, if there's a way.
Answer: Possible, yes, but I don't know if you'll find a free solution on Windows.  You'd want to install a reverse proxy server which would listen on port 80 for incoming connections.  It would look for requests to the appropriate hostname and then forward those connections internally to the appropriate local IP/port combination (for example, apache.xxxx.dyndns.org -> localhost:8085).
Comment: Ah, thank you very much Justin, I'll try investigating that solution.
Comment: @Yusuf: nginx can act as a reverse proxy, and runs on Windows. As far as I know stackoverflow/serverfault/etc. uses it as part of their stack... http://nginx.org/
Comment: Thanks Matt, I'll try that as soon as I have some time; I hope there's nothing like conflicts with IIS7 or Apache, since it is also an HTTP server?


can we pass null in the url parameter?

Question: I have a Asp.Net webApi controller as below:
[RoutePrefix("business/api/v1")]
public class BusinessController : ApiController
{

    [Route("GetDetails/{id}")]
    public HttpResponseMessage Get(string id)
    {
        // get business details code.
      }
  }

Is there anyway that client can hit this api with id null??
Answer: It depends on your configuration of Web API routes in App_Start/WebApiConfig.cs.
If route is something like:
  config.Routes.MapHttpRoute(
       name: "DefaultApi",
       routeTemplate: "business/api/v1/GetDetails/{id}",
       defaults: new { id = RouteParameter.Optional }
  );

then user can reach resource use http://localhost.business/api/v1/GetDetails or http://localhost.business/api/v1/GetDetails/1.
When you remove defaults: new { id = RouteParameter.Optional } then user have to pass an id otherwise, it will return 404
Comment: no the id parameter is not optional.. I am using attribute routing.. how to see if I have made it as optional in attribute routing?
Comment: Do you want to make `id` optional or not? See http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#optional
Comment: So, if you do not have this line: `defaults: new { id = RouteParameter.Optional }` then user have to always pass `id`. When they pass nothing(null) then it will return 404
Answer: Please try:
[RoutePrefix("business/api/v1")]
public class BusinessController : ApiController
{
    [Route("GetDetails/{id:int?}")]
    public HttpResponseMessage Get(int id)
    {
        // get business details code.
    }
}

can we pass null in the url parameter?


Can we create a dense set in the interval by this steps?

Question: I have a question that is something I am wondering for some time now and I couldn't even begin answering it. I guess it could be called a riddle.
So, let $x\in[0,1]$ and $k\in(0,1)$. We begin at $x$ and we say that we make a "step up" by going to $x+k(1-x)$ and we make a "step down" by going to $x-kx$. Notice that whatever $x$ and $k$ we choose we have $x-kx\in[0,1]$ and $x+k(1-x)\in[0,1]$.
Then let $X_0=\{x\}$ and $X_{n+1}=\bigcup_{x\in X_n}\{x,x-kx,x+k(1-x)\}$. So $X_{n+1}$ is the set we get if we add the "up step" and the "down step" of every element of $X_n$ to $X_n$.
Let $X_\infty=\lim_{n\to\infty}X_n$. So my question is: Is $\overline{X_\infty}=[0,1]$?
Another related question I couldn't also answer is: By beginning at an arbitrary $x$ is there any (finite) number of steps one can make to get back exactly to $x
Also I am not really sure about the tags, so feel free to modify them.
Comment: In general, no. For example, $x=0$ and $k=0$. Maybe it holds if you restrict $x \in (0,1)$ and $k \in (0,1)$?
Comment: Oh, well, ok. I changed it.
Comment: It makes the symmetry of the operations a bit clearer to set $K=1-k$ and consider $x\mapsto Kx$ and $x\mapsto 1-K(1-x)$.
Answer: No, the result is not dense for all $k\in(0,1)$. One particular value where it is not dense is $k=2/3$.
To see this, imagine the $x$'s written as base-3 fractions. Then $x\mapsto x-kx=\frac13x$ corresponds to inserting a 0 after the fraction point and shifting all of the existing trits one position to the right. And $x\mapsto x+k(1-x)=\frac23+\frac13x$ corresponds to inserting a 2 after the fraction point and also shifting all of the existing trits one position to the right.
Therefore, except from the countably many points that are hit exactly, the only numbers that can be approximated by the sequence are the Cantor set.
More primitively, for any $k>1/2$ there is an interval around $x=1/2$ that can never be hit by either of the two operations, and so $X_\infty$ is certainly not dense in that interval.
On the other hand, a very similar argument shows that the result for $k=1/2$ is dense.I suspect that $\overline{X_\infty}=[0,1]$ for all $k\in (0,1/2]$.

Added later: In fact, this construction generalizes directly to any $k\in(0,\frac 12]$. Proof sketch:

For any infinite sequence $(a_n)$ of $0$s and $1$s, consider the series $$\tag{*}A=\sum_{n=0}^\infty k(1-k)^na_n $$ and assuming it converges say that $(a_n)$ is a "modified binary expansion" of $A$.
If we know a modified binary expansion for $A$, then the possible successors of $A$ under your step rules have modified binary expansions that arise by shifting the one for $A$ one position to the right and putting either $0$ or $1$ in front of it. (To prove this just factor one $(1-k)$ out of the series for the two successor expansions, and simplify).
Prove that every $A\in[0,1]$ has at least one modified binary expansion (actually continuum many such expansions in most cases, but that is not important). To do so, just choose the bits one by one, such whenever we have chosen $a_0$ through $a_m$, the interval $$I_m = \left[\sum_{n=0}^m k(1-k)^na_n,\quad (1-k)^m+\sum_{n=0}^m k(1-k)^na_n \right]$$ contains $A$. We can continue doing that forever, because the union of the two possibilities for $I_{m+1}$ is exactly $I_m$ (here is where we use $k\le\frac 12$). Also, the length of the $I_m$s go towards zero (because $k>0$), so the partial sums of $(*)$ must converge towards $A$.
Choose some modified binary expansion $(x_n)$ for your starting $x$. Then $X_\infty$ consists exactly of those numbers that have modified binary expansions of the form $(b_0,b_1,\ldots,b_m,x_0,x_1,\ldots)$ for some $m\ge 0$ and some $b_n$s in ${0,1}$.
Let $Y\in[0,1]$ be arbitary; we wish so show $Y\in\overline{X_\infty}$. Now $Y$ must have a modified binary expansion $(y_n)$. Then for each $m\in\mathbb N$, let
$$ Q_m = \left(\sum_{n=0}^m k(1-k)y_n\right)+(1-k)^{m+1}x$$ It is clear that $Y$ is the limit of the $Q_m$s, and each $Q_m$ is in $X_\infty$ because it has the modified binary expansion $(y_0,y_1,\ldots,y_m,x_0,x_1,\ldots)$
Comment: This a very clever construction. Thank you very much. However couldn't find a proof that this happens for any $k\in(0,\frac{1}{2}]$.
Comment: @tst: It actually generalizes fairly straightforwardly. See edited answer.


Recurrent networks mimicking previous / current input

Question: So I have been trying to train an LSTM to predict the values of a certain stock. The error was pretty low, so I decided to create a graph out of the test set. It looked like this:

Red: actual, Black: my predition, Blue: input to get prediction
So i'm training the network with datsets like: in: xt-1, out: xt. But when ignoring the fact that the black line is much lower than the red line, you'll see that the network is actually mimicking the input to stay as close to the actual prediction.
So after doing some googling, I found out that this is a common 'trap:

I am sure there is one step lag between the actual time series and the predicted time series, this is the most seen "trap" if you do time series prediction like this, in which the NN will always mimic previous input of time series.

But are there things I do to avoid this? In the thread I linked some solutions are pointed out, but are there any better, generic solutions?

I have created a JSFiddle with the training of the neural network and the chart. View it here (open console before opening). Feel free to tweak around with the options to see if you get something working...
Answer: This is a very common problem. Here is an article with a good explanation. People have been trying to do this for a very long time, and it is safe to say there is no such thing as model that can tell you what the price of a financial instrument will be in the future with good accuracy. Some people believe that there isn't any way to predict the future prices of the market any better than flipping a coin (Random walk theory, Here is a good explanation of it). This is totally not true though. The movement of markets is almost a random walk, but not 100% random.
This does not mean that machine learning has no use for trading however. I won't give away too much, and anyone who has figured out how to use it to their advantage won't mention their details either, but you have to get outside the box a bit. Putting in price history and getting a future price is way too good to ever be true. A better approach is using multiple different networks for several different easier problems, and using what they come up with and your own knowledge to screen for a good stock to buy. If you really want to use machine learning for trading, you are going to have to be very dedicated to it and invest a huge amount of time. You not only need to master the machine learning side of it, but you will also have to master the market.
Comment: Very interesting article. Helped me a lot already. Got exactly the same results as the author had.


How do I know what assumptions I can make in a proof?

Question: I'm given this proof and am told to prove by deduction:
$(p∨(q∧r))→(((q∧r)→p)→p)$
I have the following rules that I can use:

∧ introductions and eliminations
∨ introductions
∨ eliminations (a case analysis where I prove each case)
→ introductions
Modus Ponens
Modus Tollens

My issue is that I do not know what I can assume as true/where to begin assuming which parts of the proof are true.
How do I know what assumptions I can make in a given proof? Is there a procedural way to determine what is safe to assume?
Comment: Work backwards from the result you want. You want to prove something of the form $A\to B$, so your last step could be a $\to$ introduction. This means you'll have a sub-proof that assumes $A$ and proves $B$.
Comment: You could use [this](https://www.umsu.de/trees/) as a guide.
Comment: [Here's a MathJax tutorial](https://math.meta.stackexchange.com/q/5020/104041) :)
Comment: Try [this](https://math.stackexchange.com/q/4645435/104041).
Comment: Thank you @Shaun! The second link was very helpful!
Comment: What do you mean by "introductions"? Can you give an example?
Comment: Also, you only wrote an expression, not a statement. An expression can't be "proved". Are you to prove something about this expression?
Comment: That makes a lot of sense, thank you @Karl!
Comment: I'm tempted to say "obviously $a \rightarrow (b \rightarrow c)$ is equivalent to $(a \wedge b) \rightarrow c$". Obvious from common sense, not from abstract symbol manipulation. If it's not obvious to you then you could derive it from the definition of $a \rightarrow b$ as $a \vee \neg b$ or from a truth-table.
Answer: Overall, this is a $ \rightarrow $ statement; that's the last operation outside of parentheses.  So for a direct proof, the last step would be $ \rightarrow $ introduction.  To do $ \rightarrow $ introduction, you assume $ P $ and try to derive $ Q $; if this works, then you can conclude $ P \rightarrow Q $.  So you know that you're going to assume $ p \vee ( q \wedge r ) $ and try to prove $ ( ( q \wedge r ) \rightarrow p ) \rightarrow p $.
Now, the thing that you assumed is a $ \vee $ statement, so you can use $ \vee $ elimination.  So now you have two tasks: assume $ p $ and prove $ ( ( q \wedge r ) \rightarrow p ) \rightarrow p $; and assume $ q \wedge r $ and prove $ ( ( q \wedge r ) \rightarrow p ) \rightarrow p $.  In the second case, you can also use $ \wedge $ elimination (although as it happens, you can skip this step in this particular problem).
Meanwhile, looking at the desired conclusion, that's another $ \rightarrow $ statement.  So you're going to assume $ ( q \wedge r ) \rightarrow p $ and try to prove $ p $.  Exactly how you do that will be different in the two cases, but it's what you're going to try to do.  You have a new assumption here, so you can analyse it using its elimination rule (which is Modus Ponens).
In this way, you work simultaneously from the top (applying elimination rules to your assumptions) and the bottom (seeking what you need in order to apply introduction rules to get your desired conclusion).  These will meet in the middle; for example, at one point in this problem, in one of the cases, you should see that you have $ p $ as an assumption and also want $ p $ as a conclusion, so those connect.
This method of direct natural proof will prove anything made of $ \wedge $, $ \vee $, and $ \rightarrow $ that's valid in so-called intuitionistic logic.  But there are some tautologies of classical logic (such as $ ( ( p \rightarrow q ) \rightarrow p ) \rightarrow p $, Pierce's Law) that won't work.  And even in intuitionistic logic, using negation ($ \neg $) is a little more subtle.  (You mentioned Modus Tollens, but this isn't the only thing that you need for $ \neg $.)
A really systematic way to handle anything in classical propositional logic, with or without $ \neg $, is to start with $ p \vee \neg p $ for every propositional variable, and do $ \vee $ elimination on all of them, then seek a direct proof in each of $ 2 ^ n $ cases.  This is effectively just making a truth table, a brute force method.  So a direct proof in natural deduction isn't always possible, but when it is, it's the most elegant.
Answer: Following this guide, which explains the process of writing such a proof . . .
$$\begin{array}{|lc}
1.\, p\lor(q\land r) & \text{Assumption} \\
\hline
 \rlap{\begin{array}{|lc} 2.\, p & \text{Assumption} \\
\hline
\rlap{\begin{array}{|lc}
3.\, (q\land r)\to p & \text{Assumption} \\
\hline
4.\, p & \text{2}
\end{array}}\\
5.\, ((q\land r)\to p)\to p & \to\text{-Intro(3,4)}\\
\end{array}}\\
6.\, p\to(((q\land r)\to p)\to p) & \to\text{-Intro(2,5)}\\
\rlap{\begin{array}{|lc}
 7.\, q\land r & \text{Assumption}\\
\hline
\rlap{\begin{array}{|lc}
8.\, (q\land r)\to p & \text{Assumption}\\
\hline
9.\, q\land r & \text{7}\\
10.\, p & \text{MP(8,9)}
\end{array}}\\
11.\, ((q\land r)\to p)\to p & \to\text{-Intro(8,10)}
\end{array}}\\
12.\, (q\land r)\to(((q\land r)\to p)\to p) & \to\text{-Intro(7,11)}\\
13.\, ((q\land r)\to p)\to p & \lor\text{-elim(1,6,12)}&
\end{array}$$


How can I have Multiple Yajra Datatables on one page in Laravel?

Question:
Problem: I need to use "Product DataTable" in Cash Page
where "Cash DataTable" already exists on this page.

I've searched for the issue, but I'm surprised no one has asked this before, so when I found a solution for this problem, I decided to share my solution with other programmers. I hope it is useful for you.
Let me first say what versions I work on.

"laravel/framework": "^8.40"
"yajra/laravel-datatables-buttons": "^4.0",
"yajra/laravel-datatables-html": "^4.0",
"yajra/laravel-datatables-oracle": "~9.0"

Now I show my project structures
I have route:list
 GET|HEAD | cash | cash.index| App\Http\Controllers\CashController@index
 GET|HEAD | product | product.index| App\Http\Controllers\ProductController@index

CashController.php
public function index(CashDataTable $cashDataTable)
{

    return $cashDataTable->render('cash.index');
}

Cash.index.blade.php
{!! $dataTableCash->table(['id'=>'dataTable']) !!}
{!! $dataTableCash->scripts() !!}

CashDataTable.php
use App\Models\Cash;
class CashDataTable extends DataTable

    public function dataTable($query)
    {
        $dataTable = new EloquentDataTable($query);

        return $dataTable->addColumn('action', 'cash.datatables_actions');
    }

    public function html()
    {
        return $this->builder()
            ->columns($this->getColumns())
            ->minifiedAjax()
            ...
    }
    ...
}

ProductDataTable.php
use App\Models\Product;

class ProductDataTable extends DataTable

    public function dataTable($query)
    {
        $dataTable = new EloquentDataTable($query);

        return $dataTable->addColumn('action', 'product.datatables_actions');
    }

    public function html()
    {
        return $this->builder()
            ->columns($this->getColumns())
            ->minifiedAjax()
            ...
    }
    ...
}

Answer: I think "Yajra \ DataTables \ Services;" Designed to show just one table, but I found a solution:
First, we need to override and change the default dataTable variable in CashDataTable and ProductDataTable,
Second, we need to set route URL in HTML minifiedAjax directly.
CashDataTable.php
use App\Models\Cash;

protected $dataTableVariable = 'dataTableCash';

class CashDataTable extends DataTable

    public function dataTable($query)
    {
        $dataTable = new EloquentDataTable($query);

        return $dataTable->addColumn('action', 'cash.datatables_actions');
    }

    public function html()
    {
        return $this->builder()
            ->columns($this->getColumns())
            ->minifiedAjax('/cash')
            ...
    }
    ...
}

ProductDataTable.php
use App\Models\Product;

class ProductDataTable extends DataTable

    protected $dataTableVariable = 'dataTableProduct';

    public function dataTable($query)
    {
        $dataTable = new EloquentDataTable($query);

        return $dataTable->addColumn('action', 'product.datatables_actions');
    }

    public function html()
    {
        return $this->builder()
            ->columns($this->getColumns())
            ->minifiedAjax('/product')
            ...
    }
    ...
}

Now in CashController, we need to set the variable as the HTML builder.
CashController.php
public function index(CashDataTable $cashDataTable, ProductDataTable $productDataTable)
{
    $dataTableProduct = $productDataTable->html();

    return $cashDataTable->render('cash.index', compact('dataTableProduct'));
}

Cash.index.blade.php
{!! $dataTableCash->table(['id'=>'dataTableCash']) !!}
{!! $dataTableCash->scripts() !!}

{!! $dataTableProduct->table(['id'=>'dataTableProduct']) !!}
{!! $dataTableProduct->scripts() !!}


the definition of order relation in Munkres's Topology

Question: In Munkres book, he defines an order relation as follows:
A relation $C$ on a set is called an order relation if it has the following properties:
1.(comparability) for every $x$ and $y$ in $A$ for which  $x\neq y$, either $xCy$ or $yCx$.
2.(nonreflexivity) for no $x$ in $A$ does the relation $xCx$ hold.
3.(transitivity) If $xCy$ and $yCz$, then $xCz$.
what is the formal definition of $x "=" y$ here, since it is not really very clear how to understand what he mean by $x \neq y$ here.
Comment: Why is '=' a confusing symbol? In what logic would '=' not be defined?
Comment: As Bishop would say: "No entity without identity". It's assumed in mathematics that we always know when two things of some sort are equal if we're claiming to understand the sort.
Comment: $x = y$ means $x$ and $y$ denote the same element in the set the relation is defined on.
Comment: Think about the trichotomy of real numbers. If $x\neq y$ then $x<y$ or $y<x$. Here "$<$" is the "C".
Comment: Equality itself is a relation.
Comment: Basically, for number 1, he's saying that either $x=y$, $x{\rm\;C}\;y$, or $y\rm{\;C}\;x$. An example of this type of relation is $<$, the less-than relation, on the set real numbers.
Comment: @Akiva: The question has nothing to do with topology or orders, it's about the definition of equality.
Answer: The definition of equality between two elements of a set is implicit in the axioms of ZFC set theory.
Elements of sets are again sets (under the hood) and so equality of elements is just the equality of those two sets. The axiom of extensionality is what tells you when two sets are equal.


For what values of $a$, $\sum_{n=1}^{\infty}\frac{(\cos n)(\sin na)}{n}$ converges?

Question: For what values of $a$, $$\sum_{n=1}^{\infty}\dfrac{(\cos n)(\sin na)}{n}$$ converges? Every hint is appreciated.
I know that $(\cos n)(\sin na)=\dfrac{1}{2}(\sin (n+1)a+\sin (n-1)a)$.
Comment: In fact
$$\cos n\sin(na)=\frac{1}{2}\left[\sin(n(a+1))+\sin(n(a-1))\right]$$
Comment: I know this, but what can I do after that?
Comment: Certainly $a=0$ will work!
Comment: I read somewhere before that the answer is for all $a$, but I don't know why!
Comment: @Math1988 that is hard to believe, but also hard to disprove. This is also trivial, but $a = \pm \pi, \pm 2\pi, \pm 3\pi \ldots$ will give you infinitely many values of $a$ that allow the series to converge.
Comment: @graydad Yes, of course. Thanks alot.
Comment: I suspect that it may also converge for $a=(2k+1)\frac\pi2$ by the alternating series test.
Comment: Hmm. I retract that comment.
Answer: Kobe's answer perfectly deals with convergence. As a side note, it is interesting to point out that
$$ f(x)=\sum_{n\geq 1}\frac{\sin(nx)}{n} $$
is the Fourier series of the function $\frac{\pi-x}{2}$ over the interval $(0,2\pi)$, hence
$$ g(x)=\sum_{n\geq 1}\frac{\cos n\sin(nx)}{n} $$
is a $2\pi$-periodic function whose value is given by:
$$ g(x)=\left\{\begin{array}{rcl}-\frac{x}{2}&\text{if}&x\in[0,1),\\\frac{\pi-2}{4}&\text{if}&x=1,\\\frac{\pi-x}{2}&\text{if}&x\in(1,2\pi-1),\\\frac{2-\pi}{4}&\text{if}&x=2\pi-1,\\\pi-\frac{x}{2}&\text{if}&x\in(2\pi-1,2\pi],\end{array}\right.$$
so $g(x)$ is everywhere defined and $|g(x)|<\frac{\pi-1}{2}.$
Answer: Assuming $a$ is real, the series converges for all $a$. It follows from the fact that $\sum_{n = 1}^\infty \sin[n(a+1)]/n$ and $\sum_{n = 1}^\infty \sin[n(a-1)]/n$ converge for all $a$. Let's consider the latter series. If $a - 1$ is an integral multiple of $2\pi$, then each summand is $0$, so the series converges to $0$. If $a-1$ is not an integral multiple of $2\pi$, then the series converges by Dirichlet's test. To see this, note that for $N \ge 1$, \begin{align}\sum_{n = 1}^{N} \sin[n(a-1)] &= \csc\left(\frac{a-1}{2}\right) \sum_{n = 1}^{N} \sin[n(a-1)]\sin\left(\frac{a-1}{2}\right)\\
&= \csc\left(\frac{a-1}{2}\right) \sum_{n = 1}^{N-1} \left(\cos\left[\left(n-\frac{1}{2}\right)(a-1)\right] - \cos\left[\left(n + \frac{1}{2}\right)(a-1)\right]\right)\\
&= \csc\left(\frac{a-1}{2}\right) \left\{\cos\left(\frac{a-1}{2}\right) - \cos\left[\left(N + \frac{1}{2}\right)(a-1)\right]\right\}.
\end{align}
(Keep in mind that $\csc((a - 1)/2)$ is defined since $(a - 1)/2$ is not an integral multiple of $\pi$.) It follows that the sequence of partial sums of the series $\sum_{n = 1}^\infty \sin[n(a-1)]$ is bounded by $2|\csc((a-1)/2)|$. Furthermore, the sequence $\{\frac{1}{n}\}_{n = 1}^\infty$ decreases to $0$. Thus, by the Dirchlet test, the series $\sum_{n = 1}^\infty \sin[n(a-1)]/n$ converges. A similar argument shows that the series $\sum_{n = 1}^\infty \sin[n(a+1)]/n$ converges for all $a$.


Compilar C++ usando o Gradle

Question: O Gradle e um grande aliado no desenvolvimento java e android. Eu estava olhando no site e percebi que ele também pode gerenciar projetos em c++.
Como eu posso usa-lo para compilar um projeto super simples (hello word)?
Comment: [Em inglês.](http://stackoverflow.com/questions/21059516/c-with-gradle)
Comment: https://docs.gradle.org/current/userguide/native_software.html
Comment: Rodrigo, esses links resolveram a dúvida? Se sim, por gentileza poste uma resposta explicando! Obrigado.
Comment: No endereço abaixo, disponivel no github, você encontrará vários exemplos de configurações disponíveis para o Android NDK e Gradle. https://github.com/googlesamples/android-ndk Inclusive você encontrará vários exemplos de "Hello"
Comment: Resolveram ou não?
Comment: nao ... mas eu ainda gostaria de ver a resposta
Answer: <code>// build.gradle
apply plugin: 'cpp'

libraries {
   hello {}
}
executables {
   main {
      binaries.all {
          lib libraries.hello.shared
      }
  }
}
</code>

Este exemplo disponibilizado aqui
caso queira aprender mais sobre gradle esse curso é bem completo e free

Compilar C++ usando o Gradle


How can I accept credit cards with Square Reader SDK (in development) without SSN number?

Question: Square requires authorizing the location even if you need to test credit card payments with Reader SDK. That means, I need an SSN number, but I don't have an SSN since I'm a foreigner.
How can I do that?
Answer: Currently Square Reader SDK is only available in the United States, and not available in our sandbox. Therefore you do need to be based in the United States and have credit card processing enabled, even for testing (because you would be testing with your production credentials). Please refer to our docs for more information: https://docs.connect.squareup.com/payments/readersdk/overview
Comment: Our company is a US based company. We have our EIN number, but founders don't have SSN. I think it should be possible to test it with that information.


There exists no injective function from the power set of A to A

Question: It is not so hard to see that there doesn't exist a surjective function from a set $A$ to $\mathcal{P}(A)$, the power set of $A$. Namely, let us suppose there does exist such a function $f:A\rightarrow\mathcal{P}(A)$. Then, consider the set $X=\{x\in A\mid x\not\in f(x)\}$. Since $f$ is surjective, there exists an $a\in A$ such that $f(a)=X$. This however instantly results in a contradiction.
Now, one would expect a proof of the statement

There doesn't exist an injective function from the power set of a set to the set itself

to be provable in a similar way. However, so far I have not been able to alter above proof to prove this statement, how would one do this?
Comment: May be it is answered [here](http://math.stackexchange.com/questions/464909/axiom-of-regularity-needed-to-show-no-set-has-its-power-set-as-a-subset)
Comment: @konewka Agreed. I suggest you point it out to him.
Comment: Indeed, tetori's answer gives the proof, although it still contains some notational errors.
Comment: @konewka What errors?
Comment: @GitGud Tetori talks about: "If $R\in R$, then ...", but this should be "If $r(R)\in R$", if I'm not mistaken
Comment: It depends on what set theory you're working in; for instance, in Quine's NF there is the universal set $V$ and $P(V)\subset V$.
Comment: When I receive upvotes, I realize something happens but I didn't get what 'something' is. Now I know what happens.
Answer: The usual diagonal argument works fine "in reverse":
Suppose $g:\mathcal P(X)\to X$, and consider
$$ A = \{ g(Y)\mid Y\subseteq X, g(Y)\notin Y \} $$
Let $x=g(A)$. If $x\notin A$, then setting $Y=A$ we see that $x\in A$, which is a contradiction. So $x\in A$.
On the other hand $x\in A$ implies that there is an $Y$ such that $g(Y)=x=g(A)$ and $x\notin Y$. Then $A$ and $Y$ are two different sets (one contains $x$, the other doesn't) that both map to $x$, so $g$ is not injective.
Answer: Assume there is an injective function $g: \mathcal{P}(X) \to X$ and denote by $M := g(\mathcal{P}(X)) \subset X$ its image. Then this means there is a surjective function $g^{-1}: M \to \mathcal{P}(X)$, which can easily be extended to a surjective function $f: X \to \mathcal{P}(X)$. This is a contradiction to the already stated assertion.
More generally, this has proven: For two sets $A, B$ there exists a surjective function $f: A \to B$ iff there is an injective function $g:B \to A$.
Comment: The last statement requires, of course, the axiom of choice. Not that I refuse it, but…
Comment: @Dominik: You don't need it to prove that there is a surjection $A\to B$ if there is an injection $B\to A$. You do need it for the converse.
Comment: @egreg: Is the axiom of choice really necessary here? I thought you don't need it because you only choose from singletons.
Comment: @CameronBuie: You are right, I somehow mixed up both directions in my head. For future reference see [this thread](http://math.stackexchange.com/questions/132495/why-dont-you-need-the-axiom-of-choice-when-constructing-the-inverse-of-an-inj).
Comment: Sorry, to bother you, but isn't it true that if you have injective map $A\rightarrow B$, then you can construct a surjective one $B\rightarrow A$ by looking at $A$'s image under the first one?However, if you start with a surjective map, then you need AC.


Deleting the last characters in the specific columns

Question: I have a sample text file with following columns
scff2  54   92   aa_bb_c4_1024_0_2 scff2   30  18   aa_bb_c4_1024_0_2
scff8  80   96   aa_bb_c4_24_0_2   scff8   14  42   aa_bb_c4_24_0_2
scff1  20   25   aa_bb_c4_98_0_1   scff4   11  25   aa_bb_c4_13_0_1
scff6  16   61   aa_bb_c4_84_0_1   scff6   15  16   aa_bb_c4_84_0_2

I would like remove the last characters in the column 4 and column 8 like following using awk
scff2  54   92   aa_bb_c4_1024_0 scff2   30  18   aa_bb_c4_1024_0
scff8  80   96   aa_bb_c4_24_0   scff8   14  42   aa_bb_c4_24_0
scff1  20   25   aa_bb_c4_98_0   scff4   11  25   aa_bb_c4_13_0
scff6  16   61   aa_bb_c4_84_0   scff6   15  16   aa_bb_c4_84_0

I tried using following script sed -i.bak 's/_[0-9]*$//' sample.txt but it did remove the characters after the last underscore in 8th column but not in the 4th column. Can some one can guide me in achieving my desired output. Thanks in advance.
Answer: You can use sub() in awk to perform a substitution in a specific field.
awk '{sub(/_[0-9]*$/, "", $4); sub(/_[0-9]*$/, "", $8); print}' sample.txt

Answer: It looks like all you need is:
$ sed 's/_[0-9]\( \|$\)/\1/g' file
scff2  54   92   aa_bb_c4_1024_0 scff2   30  18   aa_bb_c4_1024_0
scff8  80   96   aa_bb_c4_24_0   scff8   14  42   aa_bb_c4_24_0
scff1  20   25   aa_bb_c4_98_0   scff4   11  25   aa_bb_c4_13_0
scff6  16   61   aa_bb_c4_84_0   scff6   15  16   aa_bb_c4_84_0

or if your sed supports -E to enable EREs (which I expect yours does since you're using -i):
$ sed -E 's/_[0-9]( |$)/\1/g' file
scff2  54   92   aa_bb_c4_1024_0 scff2   30  18   aa_bb_c4_1024_0
scff8  80   96   aa_bb_c4_24_0   scff8   14  42   aa_bb_c4_24_0
scff1  20   25   aa_bb_c4_98_0   scff4   11  25   aa_bb_c4_13_0
scff6  16   61   aa_bb_c4_84_0   scff6   15  16   aa_bb_c4_84_0

or as @GlennJackman pointed out in the comments, with GNU sed (the above would work with other seds too, e.g. OSX sed), it'd be:
sed 's/_[0-9]\>//g'

Comment: That's smart, but not exactly what's OP asked, not specific columns. +1 from my side
Comment: With GNU sed: `sed 's/_[0-9]\>//g'`
Comment: @GillesQuenot Yeah but given the input and what the OP had tried previously I don't think she actually cares about selecting specific fields.
Answer: Sometimes it's useful to store the result of a substitution in gawk :
$ awk '{$4=gensub(/_[0-9]$/, "", 1, $4); $8=gensub(/_[0-9]$/, "", 1, $8)}1' file

Output :
scff2 54 92 aa_bb_c4_1024_0 scff2 30 18 aa_bb_c4_1024_0
scff8 80 96 aa_bb_c4_24_0 scff8 14 42 aa_bb_c4_24_0
scff1 20 25 aa_bb_c4_98_0 scff4 11 25 aa_bb_c4_13_0
scff6 16 61 aa_bb_c4_84_0 scff6 15 16 aa_bb_c4_84_0

But @Barmar solution is smarter/shorter/lighter
Not in all awk implementations : not nawk, need GNU awk or maybe mawks
Answer: In GNU awk, everything ending in `_[0-9]+' removed:
$ awk '{gsub(/_[0-9]+\>/,"")}1' file
scff2  54   92   aa_bb_c4_1024_0 scff2   30  18   aa_bb_c4_1024_0
scff8  80   96   aa_bb_c4_24_0   scff8   14  42   aa_bb_c4_24_0
...

Answer: awk '{gsub(/_0_./,"_0")}1' file

scff2  54   92   aa_bb_c4_1024_0 scff2   30  18   aa_bb_c4_1024_0
scff8  80   96   aa_bb_c4_24_0   scff8   14  42   aa_bb_c4_24_0
scff1  20   25   aa_bb_c4_98_0   scff4   11  25   aa_bb_c4_13_0
scff6  16   61   aa_bb_c4_84_0   scff6   15  16   aa_bb_c4_84_0


Switch case grande em C

Question: Estou desenvolvendo um sistema para a faculdade e gostaria de saber qual a melhor opção, no sentido de otimização do código, de melhora mesmo.
Tenho um switch case para Menu, onde tenho 88 cases.
Tenho uma tela chamada "Ajuda", nessa tela, o usuário poderá escolher entre 88 telas.
Exemplo abaixo:
Para acessar a tela "Ajuda", ele deve digitar "ajuda"
Vai acessar essa tela telaAjuda (); com varias opções dentro dela.
Tais opções estão entre 1 e 88. Exemplo abaixo:
printf("\n\t Op1 ...................................1\n");
printf("\n\t Op2....................................2\n");
printf("\n\t Op3....................................3\n");
printf("\n\t Op4....................................4\n");
printf("\n\t Op5...................................5\n\n");
...
printf("\n\t Op88...................................88\n\n");

E de acordo com o que é escolhido, o usuário é levado para outra tela de numero determinado (Como se fosse um esquema de paginação de livros).
Se ele escolher e digitar o numero 3, ele será levado a tela Op3.
A tela que uso o switch case é a subMenu_Ajuda () ,que chamo ela em baixo da ajuda(fiz duas funções distintas para isso, pois se eu quiser chamar o submenu ajuda em outro lugar do código, eu não vou precisar necessariamente chamar a tela ajuda junto), apenas para receber o valor digitado pelo usuário e a partir dele, escolher a opção no switch case.
Exemplo abaixo do subMenu_ajuda:
printf("\nnomePrograma : loginUsuario -> "); //usarlogin
scanf("%i", &opAjuda);

    switch (opAjuda) { //88 Cases

    case 1:
    system("clear");
    telaAjuda1 ();
    __fpurge(stdin);
    break;

    case 2:
    system("clear");
    telaAjuda2 ();
    __fpurge(stdin);
    break;

    ...

    case 88:
    system("clear");
    telaAjuda88 ();
    __fpurge(stdin);
    break;
}

Eu posso deixar o switch case desse tamanho mesmo ou é melhor eu criar um vetor para todos os cases e chamá-lo quando necessário?
Comment: É possível, teria que criar um vetor com com ponteiros para função. É uma recursos mais avançado que você não deve ter aprendido ainda. Quer que eu coloque uma resposta?
Comment: O __fpurge(stdin); é usado no linux, é a mesma coisa do fflush(stdin); do windows ;)
Comment: É, estamos agora na matéria de salvar em arquivo.txt. Não chegamos a esse ponto ainda. Se você puder me mostrar o caminho, eu agradeço. Apenas onde procurar e o que procurar já me ajuda muito.
Comment: O que faz o fpurge?
Answer: Não vou entrar em outros pontos, só vou fazer o que é pedido.
Cria-se um array com ponteiro para funções. Todas as funções precisam existir e estar acessível pelo código para que pegue seus endereços.
Para acessar a função, primeiro pegamos o endereço correspondente de acordo com a opção digitada. A sintaxe para chamar uma função pelo seu endereço é achar o ponteiro seguido da passagem dos parâmetros. No caso de não ter parâmetros, basta colocar o ().
Lembrando que todas as funções precisam ser compatíveis. Ter a mesma assinatura (mesmo retorno e mesmos parâmetros).
printf("\nnomePrograma : loginUsuario -> "); //usarlogin
scanf("%i", &opAjuda);
//seria bom validar se está entre 1 e 88
void (*opcoes[])() = {&telaAjuda1, &telaAjuda2, ..., &telaAjuda88}; //assinatura
system("clear");
(*opcoes[opAjuda - 1])();
__fpurge(stdin);

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Obviamente ali na reticências precisa colocar o nome de todas as funções usando o operador & pegando seu endereço de cada função, que obviamente precisa existir.
Comment: Ah legal. Vou tentar fazer aqui. Obrigada. ;)

Switch case grande em C


Appropriate non-parametric test for repeated measures in two groups

Question: I have two different study groups (A: intervention, B: no intervention/control), each around n~220 patients. Now, every patient has had monthly check-ups for 12 months where blood was drawn, so for each patient, I have 12 metric values of lab values. I ran tests to see whether the data (i.e. the lab values) was normally distributed; it was not, therefore I am looking for a non-parametric test.
My null hypothesis would be: "There is no significant difference between Group A and Group B in terms of lab values over the course of 12 months of follow up."
What test should I use?
Comment: *Data* do not need to be normally distributed. It is helpful (but often not necessary if you have "enough" data) for *residuals* to be normally distributed and homoskedastic. Best to check that first.
Comment: That said, you will need to be much more precise in your null hypothesis, whether you go with a parametric or a nonparametric test. Repeated measurements and especially time series are complex. Are you looking for differences at the last time point, differences at *any* time point, differences between the time series dynamics (one would expect autocorrelation between your measurements; do you posit a fixed AR(p) model or is the order to be determined by the data? In any case, differences in dynamics could mean differences in the first AR coefficient, or in multiple ones), or something else?
Answer: Welcome to CrossValidated Simon.
Consider stating the goals in terms of what you'd like to estimate.  Here it may be to estimate the longitudinal trajectories, by group A vs. B.  This can be done by modeling the fixed effect of time flexibly (e.g., using a regression spline) and using a longitudinal model that does not assume a distribution.  An example model is a proportional odds ordinal logistic semi parametric model, which can be extended to the longitudinal case using a Markov process, random effects, or GEE.  More information may be found here.  Any of these 3 approaches capitalizes on the proportional odds model being a generalization of the Wilcoxon test (a test you might have used were there to be only one time point).
If you want to do an analysis on the original scale in order to obtain mean trajectories, you may have to spend time transforming Y so that the residuals have a symmetric and Gaussian-like distribution.


Get indices of items in numpy array, where values is in list

Question: Is there a numpy way (and without for loop) to extract all the indices in a numpy array list_of_numbers, where values are in a list values_of_interest?
This is my current solution:
list_of_numbers = np.array([11,0,37,0,8,1,39,38,1,0,1,0])
values_of_interest = [0,1,38]

indices = []
for value in values_of_interest:
    this_indices = np.where(list_of_numbers == value)[0]
    indices = np.concatenate((indices, this_indices))

print(indices) # this shows [ 1.  3.  9. 11.  5.  8. 10.  7.]

Answer: Use numpy.where with numpy.isin:
np.argwhere(np.isin(list_of_numbers, values_of_interest)).ravel()

Output:
array([ 1,  3,  5,  7,  8,  9, 10, 11])

Comment: Had to search a single value in a numpy array which has 2 distinct values. So np.isin gave [True, False] or [False,True].  but was struggling around, didn't know how to get the exact index of True. Thanks!


About the non-constant harmonic function

Question: I want to see the steps for the proof of this result:
If $u:\mathbb R^n \rightarrow \mathbb R$ is a non-constant harmonic function, then $u^{-1}(c)$ is unbounded in $\mathbb R^n$ for any $c \in \mathbb R$
Answer: Step I. A non-constant harmonic function $u$ takes each real value. If it does not take the value $c\in\mathbb R$, then its range, due to intermiediate value theorem, would be a subset of $(c,\infty)$ or of $(-\infty,c)$. But according to Liouville's theorem, in such case $u$ would be constant.
Step II. If $u(x_0)=c$, then Mean Value Theorem for harmonic functions says that
$$
c=u(x_0)=\frac{1}{|S_r|}\int_{S_r} u(x+y)\,dy,
$$
i.e., $u(x_0)$ is the mean value of $u$ on the sphere $|x-x_0|=r$, which implies that $u$ takes $c$ on every sphere $|x-x_0|=r$.
Comment: @ Yiorgos S. Smyrlis: This fact does not apply to analytic function.
Comment: It only applies to its real and imaginary parts.
Comment: @ Yiorgos S. Smyrlis: Can we find conditions on analytic functions, so that happened.


How do I further expand the conditional probability?

Question:
A retail store is currently short of a certain product, and the manager is now planning on how many amounts of such product to import for the sales of them in next month. The store pays \$20 (the import price) per unit of the product, and then sells it for \$30 (the marked price in that store) per unit. However, if the store is not able to sell these imported products in the next month, these products must be disposed and can not be sold afterwards.
Therefore, there is a trade-off between maximizing the profits (the total amount of \$ gained by selling the products minus the total amount of \$ paid to import the products) and minimizing the risk of overstock (which will then result in wasting \$20 per unit of the unsold products).
Suppose that the demand for such products in a randomly chosen month has the Binomial distribution Binom(n = 20,p = 0.3).
Note that it is possible that the demand exceeds the amounts of the products in the store, in which case the store can only sell all the amount of the products in the store.
(a) Let A (a non-negative integer) denote the amount of such products that the manager imports, and let B (a non-negative integer) denote the demand of such products. Write down the expression of the profit (in $) that the store can make in next month, which should involve A and B.
(b) Let A (a non-negative integer that is not greater than 20) denote the amount of such products that the manager imports. Find the expression of the conditional probability that the demand of such products is k, given that the demand does not exceed A. You may assume here that k is some non-negative integer that is not greater than A. Your answer should involve A and k.
(c) Suppose the manager finally decides to import A units of such products (you may assume that A ≤ 20), find the expected profit that the retail store can make for selling these products in next month. Your answer should involve A.

for b) so far I have,
$P( k \mid k\leq A) =P(k \cap k\leq A)/P(k\leq A)$
I'm not too sure how to further expand.
Answer: You want $\mathsf P(B=k\mid B\leq A)$ where $B$ is the demand, a binomial (20,0.3) random variable, while $A$ and $k$ are values.
So $$\mathsf P(B=k\mid B\leq A)=\dfrac{\mathsf P(B=k)}{\mathsf P(B\leq A)}\cdot\big[0\leq k\leq A\big]$$
Comment: Is that multiplication, or just indicatiing the where k lies
Comment: It's the [Inverson Bracket](https://en.wikipedia.org/wiki/Iverson_bracket) notation for an indicator function. @Rita


Display values of custom fields created on media entity in a template file

Question: I'm trying to display the values from the custom fields that have created on my Media Entity to my page--media.html.twig file. The fields that I'm trying to output are Location and Photographer
I tried using this code below, to make it work.
{{ node.field_photographer.entity.value  }}
Also tried an alternative
{{ content.field_photographer.entity.value  }}
Comment: If you're trying to access it from a page-level twig template, you'll need to add a preprocess hook to make those variables available to the template.  You can use the Devel module and Devel Kint submodule to output what variables are currently available at the page-level template and debug/confirm your preprocess hook works.
Comment: as @AnsonWHan said, probably you are in the wrong template to access the variables. You can check the [available Variables](https://www.drupal.org/docs/8/theming/twig/discovering-and-inspecting-variables-in-twig-templates) in all Twig-Files easy. Do you need help for the preprocess hook to get the variables in the page-template?
Comment: @btemperli I wasn't aware that I need to use a `preprocess_hook` in order to achieve this. I'm still new to drupal 8
Answer: Your question is more about how to handle Drupal templates and passed variables. I suggest you to use Devel and Devel Kint modules to be able to debug variables just in your template like this:
{{ kint() }} - print all available variables
{{ kint(your_var_name) }} - print particular variable
And don't forget to enable twig debug mode - it will show you templates structure.
Once you have everything visible it becomes much easier to understand.


How to write extracted email headers in a new email

Question: I'm trying to develop an Outlook Add-In that allows to extract headers from a selected email and print them in a new email.
For that need, I used the following method to create a new email that includes, as an attachment, the selected email:
Office.context.mailbox.displayNewMessageForm({
    toRecipients: ["email@example.com"],
    subject: mailSubject,
    htmlBody: mailBody,
    attachments: [{ type: "item", itemId: Office.context.mailbox.item.itemId, name: Office.context.mailbox.item.subject }]
});

I looked at the following method to get the headers from the selected email:
Office.context.mailbox.item.getAllInternetHeadersAsync(
    function (asyncResult) {
        if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
            headers = asyncResult.value; // get the headers
        }
    }
);

(Un)fortunately, this method is asynchronous and I get the headers after the creation of the new email (displayNewMessageForm). My goal is to write these headers in the parameter htmlBody used for the creation of the new email.
I tried to used the async method for the email creation (displayNewMessageFormAsync), without success.
If possible, I want to get the headers (asynchronously) and pass them as a parameter of the displayNewMessageForm() method or update the created email to add the headers (if possible again).
I'm looking for your help!
Answer: displayNewMessageForm should be used in the callback handler of getAllInternetHeadersAsync.
This works for us:
Office.context.mailbox.item.getAllInternetHeadersAsync(
    function(asyncResult) {
        if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
            headers = asyncResult.value; // get the headers
            Office.context.mailbox.displayNewMessageForm({
                toRecipients: ["firstname.lastname@example.com"],
                subject: "Test Subject",
                htmlBody: "Internet headers: " + headers,
                attachments: [{
                    type: "item",
                    itemId: Office.context.mailbox.item.itemId,
                    name: Office.context.mailbox.item.subject
                }]
            });
        }
    }
);

Comment: Hello, thank you for the answer but it seems to not work on my side...

I added console.log() methods to check what it executed and when : it enters in the displayNewMessageForm() method but executes nothing (I don't see the mail).


Mailchimp package not adding email address to list

Question: I am using the following laravel package for my newsletters:
laravel-newsletter.
I have the following code in my newsletterController.php:
public function index() {
    Newsletter::subscribe('email@example.com', ['FNAME'=>'Goti', 'LNAME'=>'Loki'], 'test');
    return 'Ola !';
}

Now when i go to: /newsletter in my application i see Ola !, but when i open my mailchimp dashboard i see don't see email@example.com added to the list of emails for the list test.
I also tried the following method of the mailchimp package:
return Newsletter::isSubscribed('firstname.lastname@example.com');

This email address already exists in the list test, i get the following error:
Call to undefined method Spatie\Newsletter\Newsletter::isSubscribed()

What am i doing wrong ? Can somebody please guide me.
Comment: Mailchimp by default requires opt ins to be confirmed. Have you checked to see if you've had an email from mailchimp (might even be in your spam dir). If that is the case, check out their api docs as you can disable this.

Alternatively more info would be needed, your best bet is going to be to go through the package debugging out at different points to see where its failing. I doubt its a bug in the package however as it's a pretty widely used one.
Comment: @Rick Thanks for your insights :) the docs however don't mention any opt - ins http://kb.mailchimp.com/integrations/api-integrations/about-api-keys as required and i did't received a email. I will try debugging , not sure what u mean exactly by opt ins
Comment: Looks like it changed in the last api update. http://developer.mailchimp.com/documentation/mailchimp/reference/lists/members/ - you need to set the ip_opt and timestamp_opt values, and then set status to subscribed. Have a search around for 'double opt in mailchimp' as it's been mentioned a few times on SO before.
Comment: I think you not done subscribe with email@example.com
Comment: Rick thanks for the heads up !!
Comment: Did you have defined the list `test` in `laravel-newsletter.php`? And Did you install the package correctly?
Comment: @KelvinC i have installed the package just as suggested on the website and also yes i have defined test in my `laravel-newsletter.php` , which is inside the config folder .
Comment: @AlexanderSolonik Did you push your code to your github repository? I want to check the codes.
Comment: @AlexanderSolonik did you check Newsletter::getLastError(); ???
Comment: Did you call `subscribe` and `isSubscribed` in same class?
Answer: Please, verify if you have added an entry to the providers array at your config/app.php
// config/app.php
'providers' => [
    ...
    Spatie\Newsletter\NewsletterServiceProvider::class,
    ...
];

And at aliases array on the same file
// config/app.php
'aliases' => [
    ..
    'Newsletter' => Spatie\Newsletter\NewsletterFacade::class,
];

Also, you need to import the package on your controller. By doing:
use Newsletter;

Be sure to import this way.
If you did all of the steps above, now you can try to use the method:
return Newsletter::isSubscribed('email@example.com');

And to subscribe users to a list, you need to send a 'status' parameter.
The possible values for this field is:

subscribed
unsubscribed
cleaned
pending

See the docs here:
http://developer.mailchimp.com/documentation/mailchimp/reference/lists/members/
If this does not work for you, you can have a look at this package:
https://github.com/drewm/mailchimp-api


Código Sql Syntax Highlighting

Question: Olá, alguém conhece algum componente (ou função) capaz de destacar certas partes de um determinado texto (Highlighting).
Estou implementando um sistema onde o usuário poderá executar alguns comandos SQL's tais como SELECT, UPDATE, INSERT e etc, então gostaria de deixar algo mais 'bonito' o TMemo é apenas texto puro.
O Highlighting que busco implementar pode ser algo básico como deixar em Negrito ou Destacar com cor diferente os principais comandos.
Comment: Onde esse texto será exibido?
Comment: Atualmente o usuário esta escrevendo no TMemo. A saída do texto é o que menos nos interessa entende, temos TMemo, TRich etc etc...
Answer: O Componente SynEdit, vai resolver seu problema. Atualmente utilizo inclusive para sql, porém tem suporte para varias linguagens, como:c++, java, cobol, js, php, etc.
Como utilizar SynMemo:
Após instalar o componente, repare que vai surgir duas novas abas SynEdit e SynEdit Highlighters, então vá até a primeira aba e adicione o componente TSynMemo em seu form, assim como um TMemo, após feito isso, vá ate a segunda aba e selecione o componente para fazer o Highlighter em seu TSynMemo, no seu caso o TSynSQLSyn, e adicione ao Form.
Adicione a propriedade Highlighter do TSynMemo que está em seu Form, o TSynSQLSyn, e já estará funcionando.
Você também pode alterar as cores, negrito, itálico, etc., do Highlighter, diretamente no componente TSynSQLSyn.

Edição:
Como uma opção paga, temos o TAdvMemo, produzido pela TMS Software, com suporte para Delphi 7, 2007, 2009, 2010, XE, XE2, XE3, XE4, XE5, XE6, XE7, XE8 e 10 Seattle.
Realizei o teste e a maneira de utilizar é igual, porém a nomenclatura muda, ficando assim:
Como utilizar o AdvMemo:
Após instalar o componente, repare que vai surgir uma Aba TMS MEMO, então adicione o componente TAdvMemo em seu form, assim como um TMemo, após feito isso, vá até a aba e selecione o componente para fazer o Highlighter em seu TAdvMemo, no seu caso o AdvSQLMemoStyler, e adicione ao Form.
Adicione na propriedade SyntaxStyle do TSynMemo que está em seu Form, o TSynSQLSyn, e já estará funcionando.
Comment: @Júnior, dessa maneira não resolve?
Comment: +1 Resolve sim, estou procurando uma solução e ate mesmo usando alguns recursos das unit desse componente, a ideia é não ficar preso a componentes. Se você viu, este ate então não é atualizado a muito tempo, o medo de ficar preso a isto é grande, pois, aconteceu e acontece todo dia com diversos componentes! Logo posto resultados!
Comment: @JúniorMoreira adicionei uma opção paga ;) veja se atente.

Código Sql Syntax Highlighting


Trying Java Card Application On real smart card

Question: I will write an application for smart card with using Java Card Framework.When I finished my application I want to set up to a real smart card and try it.Which equipment I must have?How can I run my codes on a real smart card?I have to provide a connector between my computer and smart card , haven't I?
Answer: After writing your Java Card application (we call it applet) in your IDE (Such as Eclipse or Netbeans), you have the following steps to communicate with it on a real smart card :

Convert the .java file to .class file
Convert the .class file to .cap file using converter tool in the JCDK (Java Card Development Kit)
Upload the .cap file on the card.
Install the uploaded applet.
Select your applet on the card using APDU commands
Communicate with your applet.

Step 1 and 2:
If you want to use a Java Card v2.2.2 or v2.2.1 compatible card, you can simply do step 1 and step 2 by adding Eclipse-JCDE plugin and Java Card Dev Kit to Eclipse IDE. (A simple great step by step tutorial to use this plugin here and here)
If you want to use a Java Card v3.x compatible card, you can use the newer versions (Mine is 7.3) of Netbeans IDE that is contained necessary tools and plugins to do step 1 and step 2,by default.(A simple step by step tutorial, here)
During these steps you set two 5-16 bytes numbers to your application and its package as the applet AID(Identifier) and the package AID
Note that you can do this steps without any IDE and just using JCDK-s, but is is a little tricky. Moreover, Netbeans IDE added another Java Card simulator to the JCDK simulators (that was named CREF and JCWDE)
Step 3 and 4:
Connect a smart card reader (FYI it is Smart card writer also) to your computer. Then using JCManager tool (Easy use), or the newer tool named GlobalPlatformPro tool (Easy use, well documented, very comprehensive) you upload the .cap file and install the applet separately or simultaneously.
You need your card's authentication keys to have permission to upload and install applet on it.
Step 5 and 6:
Normally your smart card reader has a tool to let you communicate with the card (Sending APDU commands and receiving Data and Status Words), but you can also use some free open source tools such as OpenSC-tool. Firstly you send a SELECT APDU command to the card with your applet's AID in its data field. And secondly you send other commands to the card.
Notes:
You can use javax.smartcardio package in Java or PySCard library in Python, to write your proprietary programs for Step 3,4,5 and 6. (Is is easy for Step 5 and 6, but it is a little hard for steps 3 and 4) ;)
"APDU" (Application Data Protocol Unit) is the protocol that you use to send[receive] command[response] to[from] the card.
Comment: @emreturka "FYI" is acronym of "For Your Information".Google the words that they don't look similar to you :)
I was meant Smart card reader is equal with smart card writer. What do you mean by _"How can I connect my computer to this device?"_? A smart card reader is like other removable devices! like your mobile phone! You connect it to your computer using a USB cable or something, install its driver and communicate with it using the described tools. :)
Comment: Thanks for your reply @Abraham. If I want to set up my application on real smart card , I have to use FYI device , havent't I?How can I connect my computer to this device?
Comment: thank you @MartinPaljak and Abraham.I thought FYI in a Turkish logic. :)


Nested OR clause with EntityFieldQuery

Question: I have a table products structure like this
product_id   product_name   product_created_date   product_expiry_date  availability
----------   ------------   -------------------    -------------------  ------------
    1           x             12-NOV-13                14-JUN-14               No
    2           y             13-DEC-13                   null                Yes
    3           z             14-DEC-14                14-DEC-15              Yes
    1           p             12-NOV-13                14-JUN-14              Yes
    ----        --             -----                     ----               ----

I need a query like :
select product_id from products where (product_expiry_date>='12-DEC-14' or product_expiry_date is null) and availability='Yes'

how to do this using EntityFieldQuery?
Comment: Is that a table used from an entity. If it is not an entity, you cannot use `EntityFieldQuery`.
Comment: Yes, this table is from entity and i am able to retrive them without null, but i need that null records as well
Comment: Please take a look to this post http://drupal.stackexchange.com/questions/14499/using-or-with-entityfieldquery about using OR in EFQ. :-)
Comment: Its not possible. Check this post http://drupal.stackexchange.com/questions/14499/using-or-with-entityfieldquery "It is not possible, if not subclassing EntityFieldQuery, and overriding some methods." "One way round it might be to add a tag to the query with with ->addTag(), then implement hook_query_TAG_alter() to change the internal structure of the query manually for queries containing that tag."
Answer: I had to do a query like that once, here is how I achieve this with EFQ:
$matches = array();
yourmodule_mini_query('12-DEC-14', $matches);
yourmodule_mini_query('null', $matches);

function yourmodule_mini_query($value, &$matches) {
  $entityQuery = new EntityFieldQuery();
  $query = $entityQuery->entityCondition('entity_type', 'product');
  $query->fieldCondition('product_expiry_date', 'value', $value, '=');
  $query->fieldCondition('availability', 'value', 'Yes', '=');
  $results = $query->execute();

  if(count($results)) {
    foreach ($results['product'] as $p) {
      // By using product_id as array key, you deal with the duplicates
      $matches[$p->product_id] = $p->product_id;
    }
  }
}

Where $matches contains an array of product_id's that are available and for which product_expiry_date is null OR 12-DEC-14.
Hope it helped.
EDIT: As said in the comments below, the evaluation of the NULL value may require a second distinct query instead of calling twice the same function.
Comment: Isn't this second call to the mini query function going to query for fields with value as "null" string (I.e instead of an `IS NULL`, it queries `value='null'`.
Comment: Oh, actually, I haven't thought about that null value but indeed, it surely will. Maybe two distinct queries are inevitable here... Thanks for the tip :p

Nested OR clause with EntityFieldQuery


Como dar manutenção em sistemas com gettext?

Question: Desenvolvi um sistema utilizando a biblioteca php-gettext e seguindo esse tutorial .
Tudo funcionou normalmente e a troca de idiomas está ok, porém esse sistema vai sofrer mudanças com o tempo e novas strings surgirão bem como outras sairão do sistema.
Como faço para quando mudar o arquivo principal .pot, eu não perca as traduções já existentes nos arquivos .po?
Answer: Eu resolvi o problema gerando o arquivo .pot da mesma forma de quando o criei. Depois abri o arquivo ".po" (com as traduções) no PoEdit e utilizei o menu Catálogo > "Atualizar do Arquivo POT.  Esta função mantém os campos traduzidos.


Function $f$ with $\{x:f(x)>c\}$ being countable union of disjoint intervals

Question: Is there a term for functions $f:\mathbb{R}\to\mathbb{R}$ such that for any $c\in \mathbb{R}$, $\{x\in \mathbb{R}:f(x)>c\}$ is a countable union of disjoint intervals?
For example, if $f$ is upper semicontinuous, $\{x\in \mathbb{R}:f(x)>c\}$ is an open set and thus a countable union of disjoint open intervals. I would like to know the one for any intervals.

Following Jack's comment, I googled piecewise continuity and found the following definition:

Let $f$ be a real function defined on $\mathbb{R}$.
$f$ is piecewise continuous if and only if for any closed interval $[a,b]$, there exists a finite subdivision $\{x_0,x_1,\dots,x_n\}$ of $[a,b]$, where $x_0=a$ and $_n=b$, such that for all $i\in\{1,2,\dots,n\}$, $f$ is continuous on $(x_{i−1},x_i)$.

I am struggling to show the following:

$f$ is piecewise continuous if and only if for any $c\in \mathbb{R}$, $\{x\in \mathbb{R}:f(x)>c\}$ is a countable union of disjoint intervals.

Only if part:
Fix any interval $[a,b]$ and $c\in \mathbb{R}$.
Since $f$ is piecewise continuous, there exists $\{x_0,x_1,\dots,x_n\}$, where $x_0=a$ and $_n=b$, such that for all $i\in\{1,2,\dots,n\}$, $f$ is continuous on $(x_{i−1},x_i)$. Since any open set is a countable union of open intervals,
$$\{x\in(x_{i-1},x_i):f(x)>c\}=\bigcup_{j\in J_i}I^i_j,$$
where $I^i_j$ is an open interval and $J_i$ is a countable set. Thus,
$$ \{x\in[a,b]:f(x)>c\}=\left(\bigcup_{i=1}^n\bigcup_{j\in J_i}I^i_j\right)\cup\{x\in\{x_0,x_1,\dots,x_n\}:f(x)>c\},$$
which is a countable union of intervals.
How can we show that $\{x\in\mathbb{R}:f(x)>c\}$ is a countable union of intervals as well?

If part: I have no idea where to start.

Could anyone help me prove it? Thanks in advance!

Thanks to Divide1918's answer, I figured that the if part of the statement above does not hold. Now I wonder if the following is true:

$f$ is piecewise continuous if and only if for any $a,b,c\in \mathbb{R}$, $\{x\in[a,b]:f(x)>c\}$ is a finite union of disjoint intervals.

I will update once I figure it out, but I appreciate any help.
Update: Even the only if part does not hold. Counterexample: $x \sin \frac{1}{x}$.
It seems there is no term for functions such that for any $a,b,c\in \mathbb{R}$, $\{x\in[a,b]:f(x)>c\}$ is a finite union of disjoint intervals?
Comment: Informally, the term piecewise continuous is often used.
Answer: The only if part follows from what you have done, since $\Bbb R=\bigcup_{k\in\Bbb Z}[k,k+1]$. If the intervals overlap at some integer point, you may make one interval to be open and the other to be closed there, thus making all intervals disjoint.
I believe I have found a counter example to the reverse direction.
Let $f=1-\chi_C$ where $C$ is the Cantor set. Then for any $c\in\Bbb R,  \{f(x)\gt c\}\cap [0,1]$ is countable union of disjoint intervals, since it is either $[0,1], [0,1]-C,$ or $\emptyset$. But $\{f(x)\le \frac12\}=C$ contains no interval. $f$ is continuous on $[0,1]-C$, but each $x\in C$ is a discontinuity point of $f$. Since $C$ is uncountable, $f$ cannot be piecewise continuous.
Comment: Thank you! Now I wonder if the following is true: $f$ is piecewise continuous if and only if for any $a,b,c\in \mathbb{R}$, $\{x\in[a,b]:f(x)>c\}$ is a finite union of disjoint intervals.
Comment: I figured out it was totally wrong.


How can I add asc and desc sort symbols?

Question: I have a drupal 7 view, consists of table. I need to add sort symbol (both asc and desc)
in view header by default if no sorting applied.
I tried with altering views-view-table.tpl.php file, and added asc, desc images for each header.
But I need proper solution, Is there any hook there to alter the table headers?
Comment: you can add class to the table. Then you can do CSS
Answer: Implement theme_tablesort_indicator(). Please replace your theme name with example
<code>function example_tablesort_indicator($variables) {
  $style = $variables['style'];
  $theme_path = drupal_get_path('theme', 'example');
  if ($style == 'asc') {
    return theme('image', array('path' => $theme_path . '/images/arrow-asc.png', 'alt' => t('sort ascending'), 'width' => 13, 'height' => 13, 'title' => t('sort ascending')));
  }
  else {
    return theme('image', array('path' => $theme_path . '/images/arrow-desc.png', 'alt' => t('sort descending'), 'width' => 13, 'height' => 13, 'title' => t('sort descending')));
  }
}
</code>
Answer: I think your best bet without a lot of theming and template overrides, preprocessing and some JS is to use jquery TableSorter:

https://www.drupal.org/project/tablesorter
https://www.drupal.org/project/views_tablesorter

What you have linked to is actually an Angular based front end. TableSorter is the next closest thing without being Angular JS.