Como diminuir o espaçamento entre as divs do bootstrap

Question: Boa tarde! Estou com uma dúvida/problema/problema.
Estou usando o bootstrap para fazer um layout, mas o espaçamento entre as divs é muito grande, queria que fosse menor... tem como?
é assim que as divs ficam, super afastadas

Mas queria que ficassem assim.

Obrigada por qualquer ajuda e tenham um ótimo dia!
Comment: Qual versão do Bootstrap?
Comment: @hugocsl versão 3
Answer: No Bootstrap 3 todas as colunas têm um padding nas laterais de 15px para cada lado.
.col-lg-1, .col-lg-10, .col-lg-11, .col-lg-12, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-md-1, .col-md-10, .col-md-11, .col-md-12, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-sm-1, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-xs-1, .col-xs-10, .col-xs-11, .col-xs-12, .col-xs-2, .col-xs-3, .col-xs-4, .col-xs-5, .col-xs-6, .col-xs-7, .col-xs-8, .col-xs-9 {
    position: relative;
    min-height: 1px;
    padding-right: 15px;
    padding-left: 15px;
}

Basta alterar esse valor nos paddings para "estreitar" esse espaço entre uma coluna e outra.
Aqui tem a documentação oficial e vc pode conferir o valor default do "gutter" padrão https://getbootstrap.com/docs/3.3/css/#grid-options
Exemplo com o padding ajustado, diminui do padrão 15px de cada lado para 6px de cada lado

div[class^="col-"] {
    box-sizing: border-box;
    border: 1px solid red;
    padding-left: 6px !important;
    padding-right: 6px !important;
}
.bg {
width: 100%;
height: 50px;
background-color: aquamarine;
}
<link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />

1

2

3

Comment: Muito obrigada pela resposta, Hugo! Mas ainda continuo com uma duvida, fiz o que vc disse e ficou o espaço entre elas como esperava, porém ficou um espaço nas laterais também. Não sei se deu para entender bem, por isso envio um print https://i.imgur.com/NFCeL2x.png
Desculpe qualquer erro, sou nova na area.
 Você sabe me dizer se esse "problema" com os paddings some na versão 4?
Comment: @Lia lia acabei de ver que eu tinha escrito ``, mas deveria ser ``, então tira onde está escrito ROW e coloca  `` para ver como fica
Comment: Se o erro continuar vou te pedir para editar sua pergunta e colocar o código inteiro na pergunta... inclusive com o CSS extra que estiver usando... repare que a forma que fiz tb é apenas para fins didáticos com "[class^="col-"]" o ideal seria vc tirar esse padding apenas onde vc realmente precisa...


Executing More Than 2 Dtsx Packages Parallely Using Thread Concept In C# Console Application

Question: I have console application which needs to executes totally 17 SSIS Dtsx packages in the below fashion.
[1] At first thread it should execute 3 packages all at once in parallel
[2] At second thread it should execute 5 packages all at once in parallel and so on...
I have heard of a concept called parallelism which is in use for higher versions of .Net Framework 4.0 etc.However I am not sure on how to implement the same in Projcet .
I have a tried a few sample using threads ,here is my code snippet.
            Thread.Sleep(2000);
            Thread First = new Thread(new ThreadStart(FirstThread));
            Thread Second = new Thread(new ThreadStart(SecondThread));
            Thread Third = new Thread(new ThreadStart(ThirdThread));
            First.Start();
            Second.Start();
            Third.Start();
    static void FirstThread()
    {
        try
        {
            DTSXProcesser pkgProcess = new DTSXProcesser();
            pkgProcess.ExecutePackage("Customers.csv");
            pkgProcess.ExecutePackage("RouteInfo.csv");
            pkgProcess.ExecutePackage("Items.csv");
        }
        catch (Exception ex)
        {
            Logger.Log("Exception in Execution Of Package. Error : " + ex.ToString());
            Thread.ResetAbort();
        }

    }

Kindly Help ...
Comment: What do you want to execute in a parallel way? The execution of the Dtsx packages (`pkgProcess.ExecutePackage` inside `FirstThread` for instance) or the method that executes it (`FirstThread`, `SecondThread`, `ThirdThread`) ?
Comment: The execution of the Dtsx packages (pkgProcess.ExecutePackage inside FirstThread as well as the method that executes it (FirstThread, SecondThread, ThirdThread) . I need to achieve both
Answer: With .NET 4:
Using Tasks:
Task[] tasks = new Task[]{
    Task.Factory.StartNew(FirstThread),
    Task.Factory.StartNew(SecondThread),
    Task.Factory.StartNew(ThirdThread)
};

Task.WaitAll(tasks);

or with the Parallel Class
Action[] actions = new Action[] {
    FirstThread,
    SecondThread,
    ThirdThread
};

Parallel.ForEach(actions, action => action());

And for the logic inside your methods (FirstThread...) you can implement the same concept (if there is no problem to execute the ExecutePackage method several times in parallel for the same instance of DTSXProcesser).
If you wonder which one to use you can see this question but they are almost equivalent.
With .NET 4.5 and C# 5 you can use the async await keywords.
Comment: Okay,Thanx .I would need to handle Threads In the Catch/Finally Block something like by checking if thread is alive need a proper managed code to abort it to avoid deadlock conditions. Can any one help me Right Now I am using Thread.ResetAbort(); in Catch I want to manage all my threads to Finally Block Is there A way?
Comment: You mean that you want to **cancel** the execution of other `Threads` if something go wrong in one `Thread` ? I don't see what you mean by *"avoid deadlock conditions"* in your case.
Comment: You can use the `CancellationToken` and `CancellationTokenSource` when working with `Tasks`: http://msdn.microsoft.com/en-us/library/dd997364.aspx
Comment: Tasks Is Available With Higher Versions Of FrameWorks ,As you said however Our application should be compatible with lower versions too.I want the thread concept to work for 3.5 framework as well where using System.Threading.Tasks; is not available.
Comment: After the complete execution of process ,I would like to make sure all my threads have completed/ended properly ,if at all incase if any of the thread is not killed/hung ,I would like to check the status of it first if it is alive and if so then I would need to Kill/Abort it.. Thats all for which I dont find a suitable instrunction to put in my finally block.catch (Exception ex)
            {
            Logger.Log("Exception in Execution Of Package. Error : " + ex.ToString());
                Thread.ResetAbort();
            }
            finally
            {

            }
Comment: You will need to keep a trace of your operations (success, error)http://stackoverflow.com/questions/11581236/c-sharp-threading-run-and-cancel-button-need-to-be-able-to-cancel-long-proccess. Other hint is to use [`BackgroundWorker`](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker(v=vs.90).aspx) (available since .NET 2 and up)


Alinha o sistema de postagem

Question: <?php
    require_once 'Postagem/system/config.php';
    require_once 'Postagem/system/database.php';
?>

<!DOCTYPE html>

<?php include 'include/head.php'; ?>
<?php include 'include/nav.php'; ?>

Forex

O maior site de conteudo forex da America Latina.

    <?php
        $posts = DBRead('posts', "WHERE status = 1 ORDER BY data DESC");

        if (!$posts)
            echo '
Nenhuma postagem encontrada!
';
        else
            foreach ($posts as $post):
    ?>

        <img class="card-img-top" src="Postagem/painel/uploads/<?php echo $post['image_text']; ?>" alt="Card image cap" height="318px" width="180px">

                    <a href="Postagem/exibe.php?id=<?php echo $post['id']; ?>" title="<?php echo $post['titulo']; ?>">
                        <?php echo $post['titulo']; ?>

                                <?php
                                    $str = strip_tags($post['conteudo']);
                                    $len = strlen($str);
                                    $max = 500;

                                    if ($len <= $max)
                                        echo $str;
                                    else
                                        echo substr($str, 0, $max) . '...';

                                ?>

<?php echo date('d/m/Y', strtotime($post['data'])) ?>
                                , Visitas <?php echo $post['visitas']; ?>,
                                por <?php echo $post['autor']; ?>

                        <a href="Postagem/exibe.php?id=<?php echo $post['id']; ?>" title="<?php echo $post['titulo']; ?>" class="btn btn-primary">Leia a Materia

    <?php endforeach; ?>

quero que ele imprima a postagem em linha vertical de 3
toda vez q tiver 3 postagem em uma linha vertical
ele pule de linha
preciso dessa ajuda
Comment: Olá Vitor! Vc é de Portugal?
Comment: OlA, sou do Brasil
Comment: Sua pergunta ficou confusa. Não seria "linha horizontal" em vez de "linha vertical"?
Comment: Porque "linha" geralmente quer dizer "horizontal", enquanto que "vertical" tem mais a ver com "coluna".
Comment: horizontal no caso
Comment: Entendi. A resposta abaixo resolve?
Comment: Ainda não, ele esta pulando,  e não ta deixando completa nem 3 ,
Comment: Então é porque 3 não cabe na tela na mesma linha.
Comment: http://farolandia.atspace.cc/png/
Comment: pra ver se fica facil
Comment: A ideia é essa da resposta do @Cayo Henrique Rodrigues... Coloque um `` em vez de ``, e no CSS retire o `height:40px;`, que aliás, não sei pra que q serve.
Comment: Tem uma tag `` com um `` dentro e vc colou um ``dentro do ``... isso tah errado tb
Comment: Seu HTML ficaria mais ou menos assim: https://jsfiddle.net/m3w6bypm/
Comment: Valeu, funcionou
Comment: Que bom. Sucesso!
Answer: Olá,
no seu foreach, voce pode pegar o index e dividi-lo por 3, caso a divisão tenha resto 0, você adiciona um
Assim
<?php
    foreach ($posts as $index => $post):
        if($index % 3 == 0) {
?>

<?php } ?>

Comment: não foi,  ele ta pulando linha,
Comment: porem , e nessa base a logica,
Comment: 3 postagem em uma linha ai ele automaticamente pula de linha
Comment: ai mais 3, porai vai
Comment: Qual o comportamento exato que você quer? Não era para pular de linha a cada 3 itens?
Comment: http://farolandia.atspace.cc/png/
Comment: pra ver se fica meio facil
Comment: como havia explicado, tipo, a cada 3 postagens horizontas, ele pula a linha, e coloca mais 3 postagens,
Comment: funcionou junto com a outra
Comment: funcionou sim,valeu o problema era o meu css

Alinha o sistema de postagem


Find().find() doesn't work in Chrome

Question: $(document).find('.AddressGroup').find('.toggle_container').slideDown("1000");

works in IE & FIREFOX but not in CHROME or OPERA. Why?
Answer: try body
$('body').find('.AddressGroup').find('.toggle_container').slideDown("1000");

or better yet just
$('.AddressGroup .toggle_container').slideDown("1000");

Answer: Try this:
$('.AddressGroup .toggle_container').slideDown(1000);

Find().find() doesn't work in Chrome


If $a \equiv b \pmod n$ and $c+d = n$, does $ca+bd \equiv 0 \pmod n$?

Question: I am trying to prove a different equation and am able to if the following is true, but I am not exactly sure if it is true.
If $a\equiv b \pmod{9}$ and $c+d = 9$, is $ca+bd \equiv 0 \pmod{9}$ a true statement?
I have tried various examples, like
$a = 29$, $b = 2$, $c = 2$, and $d = 7$
$a = 13$, $b = 4$, $c = 4$, and $d = 5$
and more.
If anyone has a counterexample, please let me know! Otherwise, if this is true, then can someone please explain why? Thanks!
Comment: Use $a=b+9k$ in $ca+bd$
Comment: Hint: eliminate $\,a\,$ & $\,c\,$ and apply congruence sum & product rules - see my answer.
Answer: If $a\equiv b\pmod n$, then this is just
$$a(c+d) \equiv an\equiv 0\pmod n$$
Answer: $a\equiv b\pmod{9}$ and $c+d=9$ implies $a-b\equiv 0\pmod{9}$ and $d\equiv -c \pmod{9}$ ,respectively. So
$$ca+bd\equiv ca-cb\equiv c(a-b)\equiv c\cdot 0\equiv 0 \pmod{9}.$$
Answer: $$ \begin{align}&\ \ \ \ \ \color{#c00}a\ \equiv\,\ \color{#c00}b\\ &\ \ \ \ \ \color{#0a0}c\ \equiv \color{#0a0}{-d}_{\phantom{|}}\\ \hline
{\Longrightarrow}\ \ &\ \ \  \color{#0a0}c\ \color{#c00}a\,+\,d\,b\\[.2em]
{\equiv}\ \ \ & \color{#0a0}{-d}\,\color{#c00}b\,+\,d\,b\,\equiv\, 0\end{align}\qquad$$
Comment: We *eliminated* $\,a\,$ & $\,c\,$ using the [Congruence Sum & Product Rules](https://math.stackexchange.com/a/879262/242) $\ \ $
Comment: @Jack  Sometimes I use tools (AHK,Emacs,etc) sometimes by hand (depends on the device).
Comment: Do you manually insert the code like `\color{#c00}` when needed or do you have a tool for coloring conveniently?
Answer: Just to list another approach:
$$
ac+bd = a\underbrace{(c+d)}_{\text{multiple of $9$}} + \underbrace{(b-a)}_{\text{multiple of $9$}}d,
$$
(this is an equal sign, not a congruent sign)
so the left-hand side must be a multiple of $9$, too.


When the size of object of firestoreConnect is more than 3 and includes "where" ,it occurs error

Question: Is there another way to solve this problem.
When the size of object of firestoreConnect is more than 3 and includes "where" then it does not work and component goes blank.
Unless the screen is reloaded or transited, the fetch result is shown.
As far as I see the console, the size of projects array is 0.
<code>export default compose(
  connect(mapStateToProps),
  firestoreConnect([
    { collection : 'projects',
      limit :55,
      orderBy: ['createdAt', 'desc'],
      where:["tags", "array-contains-any", ["stack"]] ,
    }])
)(Dashboard);
</code>
https://www.dropbox.com/s/feahktg87z0i11i/20221019_171555.mp4?dl=0
Comment: shinzo_abe, do let me know if the answer below was helpful.
Answer: The ordering of the compose function is important. You can try and use the firestoreConnect([...]) component to be the first parameter passed in, followed by connect(mapStateToProps).
It is now recommended to use Firestore hooks try useFirestoreConnect() from 'react-redux-firebase' and useSelector() from 'react-redux'.
You may have a look at this Github link mentioning a similar implementation
These are a few example links with helpful workarounds for the issue related to mapstateprops and firestore connect.
Check the useful documentation for Connect Mapstate


Recursive equation with limit

Question: Find $\alpha, \beta, \gamma$ for recursive equation:
$$ \alpha a_{n+3}-3a_{n+1}+\beta a_n = 18n$$  $$a_0=0,a_1=\gamma, a_2=3 $$
$$\lim_{n\rightarrow\infty}\frac{3a_n+(-2)^{n}}{n^3}=3$$
Hey guys,
normally I know my way around recursive equations, but when it comes to exercise with limits like this one I don't know how to use the information from the limit condition. I looked in to answers and found out, that first you have to figure out that $a_n$ is formed like $n^3-\frac{1}{3}(-2)^n+ ...$
How can I come to this and move on from there?
My attempt was something like this:
$$\frac{3a_n+(-2)^{n}}{n^3}=3/*n^3$$
$$3a_n+(-2)^{n}=3n^3/-(-2)^{n}$$
$$3a_n=3n^3-(-2)^{n}/*\frac{1}{3}$$
$$a_n=n^3-\frac{1}{3}(-2)^{n}$$
but I don't know if this is correct and which parts are missing in $+...$ Please help
Comment: One way: $a_m=b_m+a+bm+cm^2+dm^3$
Comment: Can you explain?
Comment: See http://math.stackexchange.com/questions/1192253/find-a-n-if-a-n-is-a-sequence-such-that-a-1-1-and-frac1a/1192254#1192254 OR http://math.stackexchange.com/questions/1199375/closed-form-of-recurrence-equation/1199383#1199383 OR http://math.stackexchange.com/questions/1193846/given-that-fn-n-fn-1-2n1-and-given-that-f0-1-we-can-write-the-solut/1193851#1193851
Comment: Are you certain $\alpha~a_{n+3}$ isn't a typo, rather $\alpha~a_{n+2}$ ?
Comment: I'm certain, it says $\alpha a_{n+3}$
Answer: First, convert the recursion to a linear recursion:
$$\alpha~a_{n+3}-3~a_{n+1}+\beta~ a_{n} = 18~n \tag{1}$$
$$\alpha~a_{n+4}-3~a_{n+2}+\beta~ a_{n+1} = 18~n +18 \tag{2}$$
$$\alpha~a_{n+5}-3~a_{n+3}+\beta~ a_{n+2} = 18~n + 36\tag{3}$$
Eliminate the nonlinear terms with linear algebra:
$$a_{n+5} = 2~a_{n+4} +
\left(\frac{3}{\alpha} - 1\right)~a_{n+3} +
\left(-\frac{\beta}{\alpha} - \frac{6}{\alpha}\right)~a_{n+2} +
\left(\frac{2\beta}{\alpha} + \frac{3}{\alpha}\right)~a_{n+1} -
\left(\frac{\beta}{\alpha} \right )~a_{n} \tag{4}$$
This is a linear recursion represented by the matrix:
$$\begin{bmatrix} a_{n+4} \\ a_{n+3} \\ a_{n+2} \\ a_{n+1} \\ a_{n+0} \end{bmatrix} =
\underbrace{\begin{bmatrix}
2 &
\frac{3}{\alpha} - 1 &
-\frac{\beta}{\alpha} - \frac{6}{\alpha} &
\frac{2\beta}{\alpha} + \frac{3}{\alpha} &
-\frac{\beta}{\alpha} \\
1 & 0 & 0 & 0 & 0\\
0 & 1 & 0 & 0 & 0\\
0 & 0 & 1 & 0 & 0\\
0 & 0 & 0 & 1 & 0\\
\end{bmatrix}^n}_M
\begin{bmatrix}a_{4} \\ a_{3} \\ a_{2} \\ a_{1} \\ a_{0}\end{bmatrix}
\tag{5}$$
For the recurrence to have a cubic $k^nn^3$ and an exponential $r^n$ term, then Jordan form of the matrix must contain subblocks:
$$\begin{bmatrix}
k & 1 & 0 & 0 \\
0 & k & 1 & 0 \\
0 & 0 & k & 1 \\
0 & 0 & 0 & k \\
\end{bmatrix} \text{ and } \begin{bmatrix} r \end{bmatrix}$$
Since the matrix is 5 by 5, with $k = 1$ and $r = -2$ the Jordan form can only be:
$${\rm Jordan}(M) =
\begin{bmatrix}
1 & 1 & 0 & 0 & 0\\
0 & 1 & 1 & 0 & 0 \\
0 & 0 & 1 & 1 & 0 \\
0 & 0 & 0 & 1 & 0 \\
0 & 0 & 0 & 0 & -2
\end{bmatrix}$$
So $M$ has an eigenvalue $1$ with multiplicity $4$ and eigenvalue $-2$ with multiplicity $1$.  Expanding $\det (\lambda I - M) = 0$  you get:
$$\begin{cases}\lambda^5
 - 2~\lambda^4
 - \left(\frac 3{\alpha} - 1\right)~\lambda^3
 + \frac{\beta+6}{~\alpha}~\lambda^2
 - \frac{2~\beta+3}{\alpha}\lambda + \frac \beta{\alpha} = 0 \\
(\lambda - 1)^4(\lambda + 2) = 0
\end{cases}$$
Solving gives $~\alpha=1$, $\beta=2$.
Comment: Thanks, but is there any other way?
Comment: There's probably a way to rewrite the limit as $$G(j, k) ~~:~~ \lim_{n \to \infty} k~a_{n+j} - \frac{1}{3} (-2)^{n+j} - (n+j)^3 + f(n) = 0$$ where $f(n)$ is some function asymptotically less than $n^3$.   Add up $G(3, \alpha) + G(1, -3) + G(0, \beta)$ and substitute the original recursion to eliminate the $a$ terms and equate coefficients of the $n$ terms to zero to make the limit exist and it might work.  Maybe.  Maybe not.  I think the approach in the answer is easier and more confident.
Comment: One thing you have to somehow realize is that because the lineared equation is only 6 terms, it can't contain an exponential term, and cubic, and another function of $n$.  There just aren't enough eigenvalues to make it happen.  I don't think there is an "ansatz and check" way to epiphany that.

Recursive equation with limit


lme summary in nlme-package (r) interpretation / fails to display all levels of fixed effects

Question: Need some help interpreting the summary() -function results.
I am running a lme from the package nlme in R.
I have a simple (and quite small) dataset with three grouping variables: origin, genotype and time, response is a continuous variable named Maxi.
Origin = 2 levels, called Ka and La
Genotype = 3 levels nested within origin Ka and 2 levels nested within origin La
Time = 2 levels nested within each genotype
I am interested in the main effects of Origin, Time and their interaction. In addition to testing I'd like to have their estimates. Here's the model I had in mind:
model = lme(fixed = Maxi ~ Origin*Time, random = ~ 1 |Genotype)

anova()s etc work fine and there's actually no significant interaction, but
here's the problem:
when I run summary(model), I get:
Fixed effects: Maxi ~ Origin * Time
                                   Value Std.Error DF   t-value p-value
(Intercept)                    15.399386 1.1127382 20 13.839181  0.0000
OriginLa                       -1.986388 1.7702416  3 -1.122100  0.3435
Timeeve                         0.074444 0.8942694 20  0.083246  0.9345
OriginLa:Timeeve               -1.387448 1.5648876 20 -0.886612  0.3858

Where are my estimates for the other levels of the factors? I thought that to be able to interpret these fixed effects the summary-table would have to show all the levels in some manner? Or do I interpret this such that:
    the estimate for OriginKa is 15.399386
    the estimate for OriginLa is 15.399386-1.986388
    the estimate for Timemor  is 15.399386
    the estimate for Timeeve  is 15.399386+0.074444

and then I can't even guess how to interpret the interaction estimate...

It doesn't feel intuitively right that the estimates would be the same for both a level of the Origin -factor and a level of the Time factor.
Notes:

I did NOT make my data into a groupedData (is it always necessary?)
I wanted to include random = 1 ~ |Origin/Genotype in the model but that produced NaNs in the output, apparently the model became too complex?

Any pointers?
Here's the data needed to reproduce my problem:
Orig.Genot.Time Maxi
Ka  Ka1     mor 14,59
Ka  Ka1     eve 13,42
Ka  Ka11    mor 14,08
Ka  Ka11    eve 16,29
Ka  Ka15    mor 14,38
Ka  Ka15    eve 14,56
La  La1     mor 17,82
La  La1     eve 13,28
Ka  Ka1     mor 16,44
Ka  Ka1     eve 15,52
Ka  Ka15    mor 13,76
Ka  Ka15    eve 13,55
Ka  Ka1     mor 19,15
Ka  Ka1     eve 19,12
La  La6     mor 10,54
La  La6     mor 11,38
La  La6     eve 10,48
Ka  Ka15    mor 15,25
Ka  Ka15    eve 16,51
La  La1     mor 17,46
La  La1     eve 15,57
Ka  Ka1     mor 16,83
Ka  Ka1     eve 15,63
Ka  Ka15    mor 14,54
Ka  Ka15    eve 15,09
La  La1     mor 11,3
La  La1     eve 11,94

Answer: I have also recently been struggling with lme(). For one, I know that your random effects syntax is incorrect. It should be random = ~ 1 | Origin/Genotype, if genotype is a nested factor within origin. Also, the reason your summary seems incomplete is again your syntax. The formula should be
lme(fixed = Maxi ~ Origin + Time + Origin*Time, random = ~ 1 |Origin/Genotype)
if you want to test Origin, Time, and the combination of Origin and Time. Because you didn't include the individual terms in your formula, it didn't calculate any correlations between these terms. You are essentially testing only the combined factor, not the individual ones. Also, if you want to test the interaction of origin and time as opposed to the combined effect, it should be Origin:Time, not Origin*Time.
Comment: Generally `Origin*Time` is shorthand for `Origin + Time + Origin:Time`, so that actually seems OK to me.  Maybe you could explain what the summary output of the model means?  Some related material in [this question/answers](http://stackoverflow.com/questions/17794729/test-for-significance-of-interaction-in-linear-mixed-models-in-nlme-in-r)
Comment: This is actually an old question, I posted this about a year ago, so not completely relevant anymore. However, some comments:
Comment: 1) I too think that Origin*Time is correct shorthand notation
2) I do understand now how to interpret the summary, for others who are interested I learned it from the master:
[link](http://stats.stackexchange.com/questions/138516/lme-summary-interpretation)
3) @WaterGeek, are you sure about nesting? I seem to remember that depending on your data structure you can use either style of syntax...
Comment: What I was referring to in 3) was something to this effect:
https://stat.ethz.ch/pipermail/r-sig-mixed-models/2010q2/003607.html.
I, for example, have uniquely labeled my Genotypes under each Origin, so the way I understood, I don't necessarily need to specify the random part as ~1|Origin/Genotype, but instead I can simply use ~1|Genotype, and I'm still using a nested model
Comment: Thanks for the corrections guys! My current working experience with lme is to look at several stream sites that were observed over many years, before and after a treatment was applied. In order to include the random effect of a site in a year I used ~ 1 | Year/Site. If I only cared about random effects at sites I would use ~1 | Site as OP mentions above. Comparing the models with anova() showed that this was a better result than using ~ 1 | Site, a combination of ~1 | Site + ~ 1 | Year/Site, or neither.


Is there any closed form for the integral $\int_0^{\frac{\pi}{2}} \frac{\ln ^n(\sin x) \ln ^m(\cos x)}{\tan x} d x?$

Question: Inspired by the question in the post, I started to generalise the integral
$$
\begin{aligned}
\int_0^{\frac{\pi}{2}} \frac{\ln^n (\sin x) \ln (\cos x)}{\tan x} d x =& \frac{1}{n+1} \int_0^{\frac{\pi}{2}} \ln (\cos x) d\left(\ln ^{n+1}(\sin x)\right) \\
=& \frac{1}{n+1}\left[\ln (\cos x) \ln ^{n+1}(\sin x)\right]_0^{\frac{\pi}{2}}+\frac{1}{n+1} \int_0^{\frac{\pi}{2}} \frac{\sin x \ln ^{n+1}\left(\sin x\right)}{\cos x} d x\\\stackrel{IBP}{=} &\frac{1}{2^{n+2}(n+1)} \int_0^{\frac{\pi}{2}} \frac{\ln ^{n+1}\left(\sin ^2 x\right)}{\cos ^2 x} d\left(\sin ^2 x\right)\\=& \frac{1}{2^{n+2}(n+1)} \int_0^{1} \frac{\ln ^{n+1} y}{1-y} d y \quad \textrm{ where }y=\sin^2 x\end{aligned}
$$
We then deal the last integral using an infinite series on the integral
$$
\begin{aligned}
\int_0^1 \frac{y^a}{1-y} d y=\sum_{k=0}^{\infty} \int_0^1 y ^a\cdot y^k d y =\sum_{k=1}^{\infty} \frac{1}{a+k}
\end{aligned}
$$
Differentiating both sides w.r.t. $a$ by $n$ times yields $$
\int_0^1 \frac{\ln^{n+1} y}{1-y} d y=\left.\frac{\partial^{n+1}}{\partial a^{n+1}} \int_0^1 \frac{y^a}{1-y} d t\right|_{a=0} =(-1)^{n+1}(n+1) ! \sum_{k=1}^{\infty} \frac{1}{k^{n+2}}= (-1)^{n+1}(n+1) !\zeta(n+2)
$$
Then we can conclude that
$$\boxed{\int_0^{\frac{\pi}{2}} \frac{\ln^n (\sin x) \ln (\cos x)}{\tan x} d x = \frac{(-1)^{n+1} n !}{2^{n+2}} \zeta(n+2)} $$

For examples,
$$
\begin{aligned}
&I_1=\frac{1}{8} \zeta(3);\quad  I_2=-\frac{1}{16} \cdot 2 \cdot \zeta(4)=-\frac{\pi^4}{720} ;\quad  I_{12}=-\frac{12 !}{2^{14} }\zeta(12)=-\frac{691 \pi^{12}}{21840}
\end{aligned}
$$

Similarly, I want to generalise the integral further as
$$I(n,m)=\int_0^{\frac{\pi}{2}} \frac{\ln ^n(\sin x) \ln ^m(\cos x)}{\tan x} d x =\frac{m}{2^{n+m}(n+1)} \int_0^1 \frac{\ln ^{n+1} y \ln ^{m-1}(1-y)}{1-y} d y $$
Noticing that
$$
\begin{aligned}
\int_0^1 y^a(1-y)^bd y =& \int_0^1 y^a(1-y)^{b} d y =B(a+1, b+1)
\end{aligned}
$$
Therefore
$$
\boxed{I(n, m)= \frac{1}{2^{n+2}(n+1)} \left.\frac{\partial^{n+1}}{\partial a^{n+1}} \frac{\partial^{m-1}}{\partial b^{m-1}}\left(\frac{\Gamma(a+1) \Gamma(b+1)}{\Gamma(a+b+2)}\right)\right|_{a=0,b=-1}}
$$
My question: Is there a closed form for the last high derivative?
Your comments and suggestions are highly appreciated.
Comment: You may be able to develop a general form for the partial derivative starting with e.g. https://functions.wolfram.com/GammaBetaErf/Beta/20/ShowAll.html then once you've found that, take the limit as $a\to 0$ and $b\to 0$.
Comment: Thank you, but is rather complicated.
Answer: After submitting the post, I suddenly recognise that $I(n,m) $ is actually a high derivative of a Beta function as
$$
\begin{aligned}
\int_0^{\frac{\pi}{2}} \frac{\sin ^a x \cos ^b x}{\tan x} d x
&=\int_0^{\frac{\pi}{2}} \sin ^{a-1} x \cos ^{b+1} x d x
=\frac{1}{2} B\left(\frac{a}{2} , \frac{b}{2} +1\right)
\end{aligned}
$$
Then we can write down
$$
\begin{aligned}\int_0^{\frac{\pi}{2}} \frac{\ln ^n(\sin x) \ln ^m(\cos x)}{\tan x} d x & =\left.\frac{1}{2} \frac{\partial^{n+m}}{\partial a^n \partial b ^m}\left(B\left(\frac{a}{2}  , \frac{b}{2} +1\right)\right)\right|_{a,b \rightarrow 0}\\&=\frac{1}{2^{n+m+1}} \lim _{a \rightarrow 0} \lim _{b \rightarrow 1}\left[\frac{\partial^{n+m}}{\partial a^n\partial b^m} B(a, b)\right]\end{aligned}
$$
Comment: https://functions.wolfram.com/GammaBetaErf/Beta/20/02/01/


Querying Git status with Subprocess throws Error under Linux

Question: I want to query the status of the git repo using python. I am using:
subprocess.check_output("[[ -z $(git status -s) ]] && echo 'clean'", shell=True).strip()

This works fine on MacOS. However, on Ubuntu Linux I get an error message:
{CalledProcessError}Command '[[ -z $(git status -s) ]] && echo 'clean'' returned non-zero exit status 127.

I went into the same folder and manually ran
[[ -z $(git status -s) ]] && echo 'clean'

and it works fine.
I further ran other commands like
subprocess.check_output("ls", shell=True).strip()

and that also works fine.
What is going wrong here?
Answer: When you set shell=True, subprocess executes your command using /bin/sh. On Ubuntu, /bin/sh is not Bash, and you are using Bash-specific syntax ([[...]]). You could explicitly call out to bash instead:
subprocess.check_output(["/bin/bash", "-c", "[[ -z $(git status -s) ]] && echo 'clean'"]).strip()

But it's not clear why you're bothering with a shell script here: just run git status -s with Python, and handle the result yourself:
out = subprocess.run(['git', 'status', '-s'], stdout=subprocess.PIPE)
if not out.stdout:
  print("clean")


Fundamental solution to the Poisson equation by Fourier transform

Question: The fundamental solution (or Green function) for the Laplace operator in $d$ space dimensions
$$\Delta u(x)=\delta(x),$$
where $\Delta \equiv \sum_{i=1}^d \partial^2_i$,
is given by
$$
u(x)=\begin{cases}
\dfrac{1}{(2-d)\Omega_d}|x|^{2-d}\text{ for } d=1,3,4,5,\ldots\\
\dfrac{1}{2\pi}\log|x| \ \ \ \ \ \ \ \ \ \ \ \ \text{for } d=2,
\end{cases}
$$
where $\Omega_d$ is the $d$-dimensional solid angle
$
\Omega_d=2\pi^{d/2}/\Gamma(d/2).
$
Indeed, it can be shown directly that for a test function $\varphi$:
$$
\int d^dx\,u(x)\Delta\varphi(x)=\varphi(0).
$$
I tried to obtain the same result by Fourier transforming the distributional equation
$
\Delta u(x)=\delta(x)
$
thus
$$
-k^2 \widehat u(k)=1\implies u(y)=-\frac{1}{(2\pi)^d}\int\frac{e^{ik\cdot y}}{k^2}d^dk.
$$
Now, using $d$ dimensional polar coordinates, we can write
$$
u(y)=-\frac{1}{(2\pi)^d}\int_0^{2\pi}d\phi\int_0^{\pi}d\theta_1\int_0^{\pi}d\theta_2\ldots\int_0^{\pi}d\theta_{d-2}\\
\sin\theta_1\sin^2\theta_2\ldots\sin^{d-2}\theta_{d-2}\int_0^\infty{dq}\,q^{d-1}\frac{e^{iq|y|\cos\theta_1}}{q^2}
$$
by an appropriate choice of the axis along $y$. Since the integrand depends only on the angle $\theta_1$, we can use:
$$
\Omega_d=\int_0^{2\pi}d\phi\int_0^{\pi}d\theta_1\int_0^{\pi}d\theta_2\ldots\int_0^{\pi}d\theta_{d-2}
\sin\theta_1\sin^2\theta_2\ldots\sin^{d-2}\theta_{d-2}
$$
$$
\implies \int_0^{2\pi}d\phi\int_0^{\pi}d\theta_2\ldots\int_0^{\pi}d\theta_{d-2}
\sin^2\theta_2\ldots\sin^{d-2}\theta_{d-2}=\frac{\Omega_d}{2};
$$
$$
u(y)=-\frac{\Omega_d|y|^{2-d}}{2(2\pi)^d}\int_0^{\infty}dl\,l^{d-3}\int_0^{\pi}d\theta\, \sin\theta\, e^{il\cos\theta}=-\frac{\Omega_d |y|^{2-d}}{(2\pi)^{d}}\int_0^\infty dl\,l^{d-4}\, \sin l.
$$
The integral
in the last line can be manipulated as follows: for $2<\Re e(d)<4$ Wick rotation yields
$$
\int_0^\infty dx\, x^{d-4}\, \sin x = \Im m \int_0^\infty dx\, x^{d-4}\, e^{ix}=\Im m \int_0^\infty idy\, (iy)^{d-4}\, e^{-y}=\Im m \left(i e^{id\pi/2}\right)\Gamma(d-3)=\Gamma(d-3)\cos\frac{\pi d}{2}.
$$
Of course this must be justified via an appropriate contour integration: see Proof that $ \int_0^\infty x^{d-4}\sin x\, dx = \cos \frac{\pi d}{2} \Gamma(d-3)$, for $2<\Re(d)<4 $?
Now for $2<\Re e(d)<4$ we get:
$$
u(x)=-\frac{\Omega_d|x|^{2-d}}{(2\pi)^d}\Gamma(d-3)\cos\frac{\pi d}{2},
$$
which reduces to the familiar
$$
-\frac{1}{4\pi|x|}
$$
for $d=3+\varepsilon$ as $\varepsilon\to0.$
It even yields
$$
\frac{1}{2\pi}\ln|x|
$$
for $d=2+\varepsilon$ as $\varepsilon\to0$ if one neglects an $x$-independent pole in $\varepsilon$.
The two expressions we have for $u(x)$ are not trivially coincident in the strip where the latter is defined, and in fact
Wolframalpha shows that the coefficients are equal
$$
\frac{\Gamma(d/2)}{2 \pi^{d/2}(2-d)}=-\frac{2^{1-d} \Gamma(d-3) \cos(\pi d /2)}{\pi^{d/2}\Gamma(d/2)}
$$
in the interval $2\le  d \le 4$ only for $d=2$ and $d=3$. So there is no point in trying to show that their expressions coincide in the whole strip. However,
is there a way to recover the above expression, which holds for any dimension $d=1,2,3,\ldots$ from the Fourier transform calculation?
The really tricky thing is just the coefficient, though: If $\Delta u(x)=\delta(x)$ then $u(x)=C |x|^{2-d}$ via Fourier transform?
Answer: The following argument works for d>3. From
Fourier transform of $1/|x|^{\alpha}$.
we know that if $f(x) = 1/|x|^{d-2}$ then $$\widehat f(x) = \frac{\pi^{(d-2)/2}}{\pi \Gamma((d-2)/2)}\frac{1}{x^2}.$$
Since $\Gamma(d/2) = ((d-2)/2)\Gamma((d-2)/2)$, we have $$\widehat f(x) = \frac{(d-2)\pi^{d/2}}{\pi^2 2\Gamma(d/2)x^2} = \frac{(d-2)\Omega_d}{4\pi^2 x^2 }.$$
Therefore, if we take the fundamental solution $$u(x) =\frac{1}{(2-d)\Omega_d |x|^{d-2}}, $$
we obtain
$$\widehat u (\xi) = -\frac{1}{4\pi^2 \xi^2}.$$
Comment: I believe there is still a little ambiguity in the prefactor due to the fact that you use the definition of FT with $2\pi$ in the exponent, but the path is clear. Thanks!
Comment: What is your definition of Fourier transform?
Comment: $\widehat{\phi}(x) = \int_{\mathbb R^n} \phi(y)e^{-2\pi i x\cdot y}dy.$
Answer: Just to put everything in the right place, since Hugo uses slightly different conventions. Here  If $\Delta u(x)=\delta(x)$ then $u(x)=C |x|^{2-d}$ via Fourier transform? it is shown that if
$$
f(x)={C_d}|x|^{1-d}
$$
then
$$
\widehat f({\xi})=-\frac{1}{|\xi|^2},
$$
which is what we want by the above calculation. Now, to fix the constant, one uses the identity
$$
\int_{\mathbb R^d}f(x) \widehat g(x) dx = \int_{\mathbb R^d}\widehat f(\xi) g(\xi) d\xi;
$$
choosing conveniently
$$
g(x)=e^{-x^2/2},
$$
we know that
$$
\widehat g(\xi) = \int_{\mathbb R^d} e^{-i\xi\cdot x}g(x) dx= (2\pi)^{d/2}e^{-\xi^2/2}.
$$
So
$$
\int_{\mathbb R^n}C_d |x|^{2-d}(2\pi)^{d/2}e^{-x^2/2} dx =
-\int_{\mathbb R^d}\xi^{-2} e^{-\xi^2/2} d\xi.
$$
Switching to polar coordinates
\begin{align}
(2\pi)^{d/2}C_d\int_{0}^{+\infty}\rho e^{-\rho^2/2}d\rho &= - \int_0^{+\infty}\rho^{d-3}e^{-\rho^2/2}d\rho \\
(2\pi)^{d/2}C_d\int_{0}^{+\infty} e^{-s/2}ds &= - \int_0^{+\infty}s^{(d-2)/2}e^{-s/2} ds\\
2(2\pi)^{d/2}C_d &= - 2^{d/2}\int_0^{+\infty}t^{(d-4)/2}e^{-t} dt\\
2(2\pi)^{d/2}C_d &= - 2^{d/2-1}\int_0^{+\infty}t^{(d-4)/2}e^{-t}\\
             C_d &= - \frac{\Gamma\left(\frac{d-2}{2} \right)}{4\pi^{d/2}}\\
&=\frac{\Gamma(d/2)}{2\pi^{d/2}(2-d)}.
\end{align}


How to calculate the angle between three points?

Question: If I have a circle with the center O(o1, o2), and three points A(x1, y1), B(x2, y2) and C(x3, y3) lying on its circumference, how can I find the angle AOC? The thing is, that there are two angles and I need the one which "contains" the point B.
I can use the law of cosines but I won't be able to tell if this is the angle that I need.
Edit:
I can check if OB and AC intersect. If yes, I need the angle that is less than pi, if no, I need the other one. Would that be correct?
Comment: By any chance are you supposed to find $|\langle ABC|$? $B$ plays no role in the question that is asked.
Comment: It does, the question is not only "how much should I walk from A to C", but "in which direction and how much should I walk from A to C"
Comment: I said $B$ plays no role and then you talk about $A$ to $C$... $B$ plays no role. If you find the angle $AOB$ then you can find the distance from $A$ to $C$ along the circumference... nothing to do with $B$... maybe you want to say the shorter way from $A$ to $C$ rather than the longer?
Comment: It could be shorter or longer, depending on the position of B. In the example, yes, it is the small angle.
Answer: We can use the two-dimensional analog of cross product here:
$$\sin\left(\angle AOC\right) = \frac{\vec{OA} \times \vec{OB}}{\lvert\vec{OA}\rvert \lvert\vec{OB}\rvert}$$
which is positive if $B$ is counterclockwise from $A$ in a right-handed coordinate system, negative if clockwise: $$-1 \le \sin\left(\angle AOB\right) \le +1$$or$$-180° \le \angle AOB \le +180°$$
Let $\vec{a}$, $\vec{b}$, and $\vec{c}$ be the vectors from the center of the circle to the respective points on the circumference:
$$\begin{array}
\; \vec{a} &= ( x_a, y_a ) = (x_1 - x_0, y_1 - y_0) \\
\vec{b} &= ( x_b, y_b ) = (x_2 - x_0, y_2 - y_0) \\
\vec{c} &= ( x_c, y_c ) = (x_3 - x_0, y_3 - y_0)
\end{array}$$
where $(x_0, y_0)$ is the center of the circle, and $\lvert\vec{a}\rvert = \lvert\vec{b}\rvert = \lvert\vec{c}\rvert = r$. Then,
$$\begin{array}
\; \sin\left(\angle AOB\right) &= \frac{x_a y_b - x_b y_a}{r^2} \\
\sin\left(\angle AOC\right) &= \frac{x_a y_c - x_c y_a}{r^2} \\
\sin\left(\angle BOC\right) &= \frac{x_b y_c - x_c y_b}{r^2}
\end{array}$$
So, if we calculate just
$$\begin{array}
\; \lambda_{AB} = r^2 \sin(\angle AOB) = x_a y_b - x_b y_a \\
\lambda_{AC} = r^2 \sin(\angle AOC) = x_a y_c - x_c y_a \\
\lambda_{BC} = r^2 \sin(\angle BOC) = x_b y_c - x_c y_b
\end{array}$$
we can use their signs to determine if $B$ is inside $\angle AOC$ or not. (Note that if all vectors have a nonzero length, the length multiplier only affects the scale; thus, this works, even if the points are not on the circumference of a circle.)
$B$ is inside $\angle AOC$ if and only if
$$\lambda_{AC} \ge 0 \text{ and } \lambda_{AB} \ge 0 \text{ and } \lambda_{BC} \le 0$$
or
$$\lambda_{AC} \le 0 \text{ and } \lambda_{AB} \le 0 \text{ and } \lambda_{BC} \ge 0$$
Otherwise $B$ is outside $\angle AOC$.
In pseudocode:
function inside(x_a, y_a, x_b, y_b, x_c, y_b):
    ab = x_a*y_b - x_b*y_a
    ac = x_a*y_c - x_c*y_a
    bc = x_b*y_c - x_c*y_b
    return ( (ac >= 0 && ab >= 0 && bc <= 0) ||
             (ac <= 0 && ab <= 0 && bc >= 0) )

or
function inside(x_0, y_0, x_1, y_1, x_2, y_2, x_3, y_3)
    ab = (x_1 - x_0)*(y_2 - y_0) - (x_2 - x_0)*(y_1 - y_0)
    ac = (x_1 - x_0)*(y_3 - y_0) - (x_3 - x_0)*(y_1 - y_0)
    bc = (x_2 - x_0)*(y_3 - y_0) - (x_3 - x_0)*(y_2 - y_0)
    return ( (ac >= 0 && ab >= 0 && bc <= 0) ||
             (ac <= 0 && ab <= 0 && bc >= 0) )

Answer: A formula you can use is as follows. Let $\alpha$ be the angle $\angle AOC$, then
$$cos(\alpha)=\frac{x_1x_3+y_1y_3}{\surd(x_1^2+y_{1}^2) \cdot \surd(x_3^2+y_{3}^2)}$$
Comment: why do i need cos? i need the angle itself. this won't help, since i need the sign of the angle and cos(a) equals cos(-a)
Comment: OK, now I understand your question. Have you had vectors? Because what you want is to test wether or not $B$ is in the positive span of $\bar{a}$ and $\bar{c}$, so can you find $\lambda \gt 0$ and $\mu \gt 0$, such that $\bar{b}=\lambda \bar{a}+\mu \bar{c}$? This amounts to two linear equations with two unknowns, $\lambda$ and $\mu$.
Answer: For three given points $A,B,C $ coordinates of center $ O(O_1,O_2) $ are uniquely fixed, you cannot specify it separately.So ignore $O$ and go for $P$.
Coordinates of center $ P(P_1,P_2) $ can be calculated. Using dot product, angle $APC$ can be found.
$$ \cos^{-1} \frac{PA.PC}{|PA||PC|} $$
Comment: sorry, i don't understand
Comment: Do you know how to construct perpendicular  bisectors $ AB,BC$ to find center $O$  as the cutting point?


Apply diff fonts for diff types of Text content in UILabel - ios

Question: I am trying to apply diff types of fonts on name of person example " Gopinath Puppala 123". this is dynamic person name coming from service.
Here in name() any where any numbers of symbols might come. So i should apply system font only to see exactly it.
for Gopinath Puppala i should apply custom font. This should not impact on symbols. This custom font do not have symbols inside font.
Please suggest solution how to apply one font for symbols, one font for alphabets etc..
Thanks In Advance
Gopinath PUPPALA
Comment: Try using `NSAttributedString`, `UILabel` supports it.
Comment: are you getting sybols and names saperatly ?
Answer: Try this:
Extract symbolString and nameString separately and use in the code below
let labelString = NSMutableAttributedString()
let symbolString = NSAttributedString(string: symbolString : UIFont.systemFont(ofSize: 15.0)])
labelString.append(symbolString)
let nameString = NSAttributedString(string: nameString "CustomFontName", size: 11.0)])
labelString.append(nameString)

labelObject.attributedText = labelString


Contraposition and law of excluded middle

Question: Does truth-equivalence of an $A \rightarrow B$ and contrapositive $\neg B \rightarrow \neg A$ rely on the law of excluded middle?
Comment: Almost everything rely on this, what do you mean ? (As it mean something is false or true)
Comment: I think this is almost a duplicate of http://math.stackexchange.com/questions/838184/contraposition-in-intuitionistic-logic . Please try not to divide questions in that way; it leads to fragmented answers that are hard for others to follow
Answer: Consider the following proof:

$\quad A \to B\\
\quad\quad|\quad\neg B\\
\quad\quad|\quad\quad|\quad A\\
\quad\quad|\quad\quad|\quad B\\
\quad\quad|\quad\quad|\quad \bot\\
\quad\quad|\quad\neg A\\
\quad \neg B \to \neg A$

We assume $\neg B$ at the second line, then make new assumption $A$, and use modus ponens to get a contradiction. So the second assumption must be false. So the assumption $\neg B$ implies $\neg A$: which entitles us to conclude $\neg B \to \neg A$. That shows $A \to B$ implies $\neg B \to \neg A$, without any appeal to excluded middle or an equivalent.
But that is only half the job: what about the reverse implication? Let's start off trying to prove that:

$\quad \neg B \to \neg A\\
\quad\quad|\quad A\\
\quad\quad|\quad\quad|\quad \neg B\\
\quad\quad|\quad\quad|\quad \neg A\\
\quad\quad|\quad\quad|\quad \bot\\
\quad\quad|\quad\neg\neg B\\
\quad\quad|\quad B\\
\quad A \to B$

Now, that argument works in classical logic, but crucially we've used the rule that from $\neg\neg\varphi$ we can infer $\varphi$. And that rule is famously equivalent (on standard background assumptions) to the law of excluded middle.
OK that's just one attempt that fails without (an equivalent rule) to excluded middle. But indeed, you can't argue from $\neg B \to \neg A$ to $A \to B$ intuitionisitically, i.e. in the usual logic which drops excluded middle.
In summary, only one direction of the classical equivalence of $A \to B$ and $\neg B \to \neg A$ holds in the usual logic without excluded middle.
Comment: Your first proof seems to rely on $(A \vdash \bot) \vdash \lnot A$.  What is the difference between this and the law of the excluded  middle?  It seems to be just another way of declaring that $A$ is a two valued variable.  Also, Why would your logic have an inference $(A \vdash \bot) \vdash \lnot A$ but not have an inference $(\lnot B \vdash \bot) \vdash B$?  Is there a philosophical distinction between the two?  Thanks~
Comment: @DanielV: in intuitionistic logic, $\lnot A$ is simply an abbreviation for $A \to \bot$. But from this, if we have $\lnot B \vdash \bot$, we only get $\lnot\lnot B$, not $B$.
Comment: @CarlMummert That explains it, thanks.
Answer: It would seem that it does not, but rather, on the law of non-contradiction. Assume

$A\implies B$
$\neg B$

Now, to obtain a contradiction, suppose $A$. Then we have $B$ from (1). But we have $\neg B$ from (2), so by the law of non-contradiction, it follows that we have $\neg A$, and finally we have $\neg B \implies \neg A$.
The distinction between this and the law of the excluded middle is subtle but it's there. In order to prove via the law of excluded middle, we would knock out assumption (2), and instead assume $\neg (\neg B\implies \neg A)$, and from here derive a contradiction, yielding $\neg \neg (\neg B \implies\neg A)$, and by the law of the excluded middle, we would conclude that $\neg B \implies \neg A$.
For more on the distinction, see here.
Comment: This surely only deals with one direction of the equivalence: the other direction is more problematic. See my answer.
Comment: I get that $\neg B \rightarrow A \rightarrow B$ means both $B$ and $\neg B$ being true, leading to violation of law of non-contradiction. But what is the ground that THAT leads to $\neg B \rightarrow \neg A$? I do get that the law of excluded middle only applies for logical truth and not implication, but I don't still see the complete ground for concluding this way.
Comment: @Materialist as far as I know (I am not an expert), the law of the excluded middle is formally equivalent to negation elimination. If we can obtain a statement without using negation elimination (i.e. without invoking $\neg\neg P \iff P$), we have proven it without making use of the law of the excluded middle. Here, we begin with, say, $(A\to B) \& \neg B$. If we can now show $\neg A$, then we've shown that $(A\to B)\to (B\to A)$. Now, assume $A$; we show that this leads to $B\&\neg B$, which allows us to conclude $\neg A$ without making use of the law of the excluded middle.
Answer: No, it doesn't.
In Lukasiewicz three-valued logic we have that Cab is truth-functionally equivalent to CNbNa and CNbNa is truth-functionally equivalent to Cba, but ApNp is not a tautology.  Here's the relevant three-valued truth-tables, where "f" is falsity, "n" indicates the third-truth value, and "t" truth.
C   f  n  t  N  A  f  n  t
f   t  t  t  t  f  f  n  t
n   n  t  t  n  n  n  n  t
t*  f  n  t  f  t  t  t  t

So, the truth tables for Cab and CNbNa we can write as follows:
a  b  Na  Nb  Cab  CNbNa
f  f  t   t   t    t
f  n  t   n   t    t
f  t  t   f   t    t
n  f  n   t   n    n
n  n  n   n   t    t
n  t  n   f   t    t
t  f  f   t   f    f
t  n  f   n   n    n
t  t  f   f   t    t

But, AnNn=Ann=n, and thus the law of the excluded middle is not a tautology.
One can also prove that from Wajsberg's basis under detachment and uniform substitution

CCpqCCqrCpr
CpCqp
CCCpNppp
CCNpNqCqp

that CCpqCNqNp follows.


Undefined index for input type of file

Question: I have an input file named file, but upon submitting the form, it returns:

Undefined index: file in C:\xampp\htdocs\Rehab\image_upload\index.php on line 26.

Line 26 refers to this: $file = $_FILES['file'];

here's my html:
<form class="container-fluid d-flex justify-content-between" action="index.php" method="POST">

      <legend class="display-4">Image Upload</legend>

      Title
      <input type="text" class="form-control" name="title" id="title" autocomplete="off">

      Image
      <input type="file" class="form-control" name="file" id="name">

      <button class="btn btn-outline-primary" name="submit">Post</button>

</form>

and here's my php code:
if(isset($_POST['submit'])){
  $file = $_FILES['file'];

  if ($file['error'] > 0) {
    return echo "Error!";
  }

  if($error === 0){
    $name = $file['name'];
    $type = $file['type'];
    $size = $file['size'];
    $tmp_name = $file['tmp_name'];

    $name_explode = explode('.', $name);
    $file_ext = strtolower($name_explode[1]);

    $allowed = array('jpg','jpeg','png','gif');

    if(!in_array($file_ext, $allowed)) {
      return echo "Invalid file type!";
    }

    $new_name = uniqid('', true) . "." . $file_ext;
    $location = 'assets/images/' . $new_name;
    $query = $conn->query("INSERT INTO medicine VALUES ()");
    $move = move_uploaded_file($tmp_name, $location);
  }
}

Comment: Was it the missing `enctype="multipart/form-data"` in your form? Would be nice if you posted your "solution" for others that might have a similar problem
Comment: i just copied the code from my previous project which works just fine
Comment: nevermind, solved it! hahaha
Comment: yes, enctype="multipart/form-data"
Comment: sorry, i forgot to post the answer :(
Answer: you need to add enctype="multipart/form-data" in your form tag.because enctype attribute is used for <input type="file">
your tag should be
<form class="container-fluid d-flex justify-content-between" action="index.php" method="POST" enctype="multipart/form-data">

Undefined index for input type of file


Erro no pom.xml

Question: Estou trabalhando em um projeto, utilizei a ferramente eclipse IDE java ee configurei meu projeto para maven project, e nisso configurei meu pom.xml para rodar hibernate + jpa e esta me ocorrendo o seguinte erro:

java.lang.ClassNotFoundException:
  com.sun.jersey.spi.container.servlet.ServletContainer     at
  org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1291)
    at
  org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1119)
    at
  org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:544)
    at
  org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:525)
    at
  org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:150)
    at
  org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1044)
    at
  org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:983)
    at
  org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4939)
    at
  org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5249)
    at
  org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1421)
    at
  org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1411)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)     at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Meu pom.xml esta configurado no seguinte modo:

    src

        src

          **/*.java

        maven-compiler-plugin
        3.1

          1.8
          1.8

        maven-war-plugin
        2.4

          WebContent
          false

            snapshot-repository.java.net
            Java.net Snapshot Repository for Maven
            https://maven.java.net/content/repositories/snapshots/
            default

<properties>
    <jersey.version>2.22.1</jersey.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey</groupId>
            <artifactId>jersey-bom</artifactId>
            <version>${jersey.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-server</artifactId>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet-core</artifactId>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-multipart</artifactId>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.ext</groupId>
        <artifactId>jersey-mvc</artifactId>
        <exclusions>
            <exclusion>
                <groupId>javax.servlet</groupId>
                <artifactId>servlet-api</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.ext</groupId>
        <artifactId>jersey-mvc-jsp</artifactId>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>javax.ws.rs</groupId>
        <artifactId>javax.ws.rs-api</artifactId>
        <version>2.0.1</version>
        <scope>compile</scope>

    </dependency>

    <dependency>
       <groupId>org.slf4j</groupId>
       <artifactId>slf4j-api</artifactId>
       <version>1.7.25</version>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-server</artifactId>
        <version>2.25.1</version>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet</artifactId>
        <version>2.23.2</version>
        <scope>compile</scope>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.2.10.Final</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.2.2.Final</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.reflections</groupId>
        <artifactId>reflections</artifactId>
        <version>0.9.9-RC2</version>
    </dependency>

    <dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>eclipselink</artifactId>
      <version>2.5.0</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.37</version>
    </dependency>

    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.3.1</version>
    </dependency>

    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest-core</artifactId>
        <version>1.3</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit-dep</artifactId>
        <version>4.10</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest-library</artifactId>
        <version>1.3</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>1.9.0</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20160810</version>
    </dependency>

    <dependency>
        <groupId>org.jboss.weld.servlet</groupId>
        <artifactId>weld-servlet-core</artifactId>
        <version>2.4.3.Final</version>

    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.ext.cdi</groupId>
        <artifactId>jersey-cdi1x</artifactId>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
    </dependency>

    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-core-asl</artifactId>
        <version>1.9.13</version>
    </dependency>

    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.13</version>
    </dependency>

    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.2.3</version>
    </dependency>

</dependencies>

Comment: Coloque o seu arquivo web.xml.
Answer: Boa noite pessoal tudo bem ?
Consegui resolver o meu problema no pom.xml
o que eu fiz atualizei todas as minhas dependências e coloquei algumas a mais fiquei 72 horas + quebrando a cabeça nele, vou postar meu pom.xml completo para quem no futuro tiver o mesmo erro só seguir ele que dara tudo certo.
http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4.0.0
  br.com.NomeProjeto
  NomeProjeto
  0.0.1-SNAPSHOT
  war

    src

        src

          **/*.java

        maven-compiler-plugin
        3.1

          1.8
          1.8

        maven-war-plugin
        2.4

          WebContent
          false

<dependencies>

    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-server</artifactId>
        <version>2.27</version>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet-core</artifactId>
        <version>2.27</version>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.inject</groupId>
        <artifactId>jersey-hk2</artifactId>
        <version>2.27</version>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-multipart</artifactId>
        <version>2.27</version>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet</artifactId>
        <version>2.27</version>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.ext</groupId>
        <artifactId>jersey-mvc</artifactId>
        <version>2.27</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.1.2</version>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.0</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.ext</groupId>
        <artifactId>jersey-mvc-jsp</artifactId>
        <version>2.27</version>
    </dependency>

    <dependency>
        <groupId>javax.ws.rs</groupId>
        <artifactId>javax.ws.rs-api</artifactId>
        <version>2.1</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.25</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.2.16.Final</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.2.16.Final</version>
    </dependency>

    <dependency>
        <groupId>org.reflections</groupId>
        <artifactId>reflections</artifactId>
        <version>0.9.11</version>
    </dependency>

    <dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>eclipselink</artifactId>
        <version>2.7.1</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.11</version>
    </dependency>

    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.2</version>
    </dependency>

    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest-core</artifactId>
        <version>1.3</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest-library</artifactId>
        <version>1.3</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>2.18.0</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20180130</version>
    </dependency>

    <dependency>
        <groupId>org.jboss.weld.servlet</groupId>
        <artifactId>weld-servlet-core</artifactId>
        <version>3.0.3.Final</version>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.ext.cdi</groupId>
        <artifactId>jersey-cdi1x</artifactId>
        <version>2.27</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
        <version>2.27</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.9.5</version>
    </dependency>

    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.13</version>
    </dependency>

    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.2.3</version>
        <scope>test</scope>
    </dependency>
</dependencies>

Erro no pom.xml


Can I access request headers in my graphql query, in nestjs?

Question: I am trying to access the ip-address of the user in the query of graphql. But I cannot reach any header information. How can I access the context I am creating in my factory, inside of my graphql requests?
// app.module.ts
...

@Module({
  imports: [
    ConfigModule,
    GraphQLModule.forRootAsync({
      imports: [
        LanguageModule,
        SearchModule],
      inject: [ConfigService],
      useFactory: () => ({
        autoSchemaFile: 'schema.gql',
        debug: true,
        fieldResolverEnhancers: ['guards'],
        formatError: (error: GraphQLError): GraphQLFormattedError => {
          return error.originalError instanceof BaseException
            ? error.originalError.serialize()
            : error;
        },
        context: ({ req }): object => {
          console.log("req.ip: ", req.ip); // Here I have the ip
          return { req };
        },
      }),
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

// search.resolver.ts
...

@Resolver(() => Search)
export class SearchResolver {
  constructor(private readonly service: service) {}

  @Query(() => Search)
  async search(@Args() args: SearchArgs): Promise<Search> {

    // I want the ip here, I want to send it as an argument into the query function below
    const response = await this.service.query(args.query, {
      language: args.language,
    });
    return response;
  }
}

Answer: According to this thread resolver context parameter should contain req but it depends [on configuration].
Resolvers typically takes (parent, args, context, info) arguments - check if context is defined in yours.
Comment: Thanks! I could access it with the context argument exactly like you said. Like this:
'''@Query(() => Search)
async search(@Args() args: SearchArgs, @Context() context): Promise {
  console.log(context);
  ...
}'''


Enzyme testing Reactjs component that uses global jQuery object

Question: I'm integrating Reactjs incrementally into a web app frontend built with HTML5 and jQuery. My react component uses global jQuery object (for AJAX and some animations here and there) that would be available when the react component javascript is loaded.
Now, when I try to mount() this component for testing with Enzyme, it get following error
 ReferenceError: jQuery is not defined

How do I make jQuery object available for the mounted component?
Testing a React component that uses jQuery & window object is a similar question with 0 answers...
I'm willing to update the component code if necessary.
ANY help would be greatly appreciated.
Edit
Sample code of my component
  import React from 'react';

  export default class MySimpleComponent extends React.Component {

     constructor(props) {
        super(props);
     }

     componentDidMount() {
        var add_btn = this.refs.btn_add;
        (function ($) {
           $(add_btn).click(function (ev) {
              ev.preventDefault();
              console.log('button was clicked');
           });
        })(jQuery);
     }

     render() {
        return (

              <form action="/">
                 <input type="text" name="myinput" value="" />
                 <button className="button" ref="btn_add">New Record</button>
              </form>

        );
     }
  }

Comment: Could you post the component code please
Comment: @spirift I've added the code
Answer: Okay so you might be able to do this with jsdom. You have to setup some globals as they say in the readme. Just add in global.jQuery = () => {}; as well.
var jsdom = require('jsdom').jsdom;

global.document = jsdom('');
global.jQuery = () => {};
global.window = document.defaultView;
Object.keys(document.defaultView).forEach((property) => {
  if (typeof global[property] === 'undefined') {
    global[property] = document.defaultView[property];
  }
});

global.navigator = {
  userAgent: 'node.js'
};

I have not had a chance to try out the above. However I would not recommend this as a sustainable solution. A much better approach would be to drop jQuery. Here is your component refactored without it.
  import React from 'react';

  export default class MySimpleComponent extends React.Component {

     constructor(props) {
        super(props);
     }

     clickHanlder(ev) {
       ev.preventDefault();
       console.log('button was clicked');
     }

     render() {
        return (

              <form action="/">
                 <input type="text" name="myinput" value="" />
                 <button className="button" onClick={this.clickHanlder}>New Record</button>
              </form>

        );
     }
  }

As you can see it's not that different. You can attach the event handlers directly to the elements, for me this makes the code easier to read and see where the action is, so to speak.
Comment: Thanks for your answer. I've actually modified a small part of my component to use native event handling and it has eliminated the error. I think I will eventually remove all jQuery code from my component and try to incorporate some other way of animating elements.. CSS transitions may be.
Comment: Check out [react velocity](https://github.com/twitter-fabric/velocity-react) or [react motion](https://github.com/chenglou/react-motion)
Comment: What does `global.jQuery = () => {};` do?  It looks like you are setting jQuery to an empty object but why?
Comment: It's setting jQuery to be a none operational function, or a no-op. This way when the code being tested calls jQuery is does NOT throw an error about jQuery not being a function.


Word prediction using WordNet

Question: Lets say I have a text in English and there is a word missing somewhere in it.
I have a list of candidate words from a dictionary with no other information. These candidate words are selected by some other, rather inaccurate, algorithm. I would like to use WordNet and the context around the missing word to assign probabilities to candidate words.
There is an obvious ad-hoc way that came to my mind on how to solve this. One way would be to extract "interesting" words surrounding the missing word, calculate semantic similarity with every candidate word according to some metric and assign probabilities to candidate words based on the average score.
However I was unable to find any useful research papers on this problem.
So, what i'm asking is if you're aware of any research (papers) about this problem, how do you find my proposal and do you have a better idea?
Comment: This doesn't seem like a coding question.
Answer: You can start from Experiments: Enriching indirect answers. A good article is Semantic web access prediction using WordNed.

Word prediction using WordNet


How to get the date of [(selection)] of primeNg data table. Angular 2

Question: I have an angular 2 project which uses primeng table wih multiple selection function. The selected value are stored in the [(selection)]. My question is how can I call/use the [(selection)] value in the component.ts. I tried logging the [(selection)] value in the console but getting an error.

Excluded Stores

<button (click)="showPersonsSelected()"> Show List of person selected </button>

in my Component
export class SelectclusterComponent{

persons = [];

selectedPersons: person [];

showPersonsSelected(){
 console.log(this.selectedPersons);
}

}
Answer: You also can use ViewChild to access Datatable class directly in component:
Template:

Component
import { ViewChild } from '@angular/core';
import { DataTable } from 'primeng/primeng';

@ViewChild('tbUsers') tbUsers: DataTable;

rowSelected(){
    console.log(this.tbUsers.selection);
}

Answer: Please add function onRowSelect into tag p-dataTable below:

In .component.ts get information of selected row below:
onRowSelect(event) {
    console.log(`Query selected: ${event.data.orderNumber} - ${event.data.country}`);
  }

Answer: You should be using onRowSelected event as below,

And you have the selected items
 rowSelected(event){
    console.log(this.selectedData);
  }

LIVE DEMO
Comment: My bad I'm calling the wrong function in my code. That's why. My code is as is. It's working. But I have a question @Aravind. I like to have the table to a specific number of rows regardless if the data is empty. Lets say I like the displayed rows in the table to be 10 rows minimum even if data from service is empty..
Comment: reach me at fb @ aravind2109 to avoid lengthy conv here
Comment: @ilovejavaAJ you need more help ?
Answer: there is an Event Emitter "selectionChange" the event equal
selections value

in ts file
 onSelect(selectedUsers: User[]) {
  console.log(selectedUsers);
 }


while (end of array) - how to recognize

Question: I have an array of numbers {1,2,3,4,5} or an array of chars or whatever. I want to a write a template method to print out the full array. It works, there are just some problems. Maybe i post first the code:
template <typename A>
void printArray(A start) {
    int i = 0;
    while (start[i] != 0) {
        std::cout << start[i] << std::endl;
        i++;
    }
}

int main(int argc, char **argv) {

    using namespace std;
    int xs[] = {1,2,3,4,5,6,7}; //works
    //int xs[] = {1,0,3,6,7}; of course its not working (because of the 0)
    int *start = xs;

    printArray(start);

    return 0;
}

Can you see the problem? while(start[i] != 0) is not the best way to read an array to end ;) What do I have for other options?
Thank you!
Comment: You're not passing an array, you're passing a pointer.
Comment: Don't treat ordinary arrays as C-style null terminated arrays.
Answer: Option 1: pass a pointer and the number of elements
 template<class T>
 void doSth(T* arr, int size)

Upside - will work with both dynamic and automatic arrays.
Downside - you must know the size. You must pass it.
Option2: parametrize the template with the size which will be auto-deduced
template <class T, int N>
void doSth(T(&arr)[N])

Downside - Dynamic arrays cannot be passed
Option 3: Be a good programmer and use std::vector's
Comment: All sound solutions, but the advice is the best part.
Answer: Since you are using C++, a vector<int> and iterators will do you better over the long haul.
Answer: If you want to use array, not pointer, then you can write the function template as:
template <typename T, size_t N>
void printArray(T (&start)[N])
{
    int i = 0;
    while ( i < N) {
        std::cout << start[i] << std::endl;
        i++;
    }
}

int xs1[] = {1,2,3,4,5,6,7};
int xs2[] = {1,0,3,6,7};
printArray(xs1); //okay
printArray(xs2); //okay

int *start = xs1;
printArray(start); //error - cannot pass pointer anymore!

So better solution would be  : std::vector<T>.
Or even better use range (pair of iterators) which is very idiomatic, as:
template <typename FwdIterator>
void printArray(FwdIterator begin, FwdIterator end)
{
    while (begin != end) {
        std::cout << *begin << std::endl;
        begin++;
    }
}

int xs1[] = {1,2,3,4,5,6,7};
int xs2[] = {1,0,3,6,7};
printArray(xs1, xs1 + sizeof(xs1)/sizeof(xs1[0])); //okay
printArray(xs2, xs2 + sizeof(xs2)/sizeof(xs2[0])); //okay

int *start = xs1;
printArray(start, start + sizeof(xs1)/sizeof(xs1[0])); //okay!

printArray now can be use with std::vector<T> also:
std::vector<int> vec; //you can use std::list as well!
//populate vec

printArray(vec.begin(), vec.end());

Comment: Two comments: unless you count on using it with several different types of containers, there's no point in making it a function template; a normal function will do.  And secondly, of course, rather than `xs1, xs1 + sizeof(xs1)/sizeof(xs1[0])`, you want the usual `begin(xs1), end(xs1)`.
Comment: @James Kanze: 1) OP has used template, so I made this template as well, assuming he wants to make it work for many different types.2) `std::begin()` and `std::end()` is available with C++0x which I didn't assume in my solution. :-)
Comment: OK then for the templates:-).  As for `begin` and `end`, I (and I doubt many others) didn't wait for the standard.  It's been more or less standard in most people's toolkit for over 10 years now.
Comment: @James: That is true. Utility such as `begin` and `end` can be implemented with much less effort, even in C++03.
Answer: Pass both the address of array and its length.
Answer: If you are using a compile-time array, you can do this with a template:
template <typename T, size_t N>
static inline void print_array(const T (&a)[N])
{
  for (size_t i = 0; i < N; ++i)
    std::cout << a[i] << std::endl;
}

int main()
{
  int a[] = {1,2};
  print_array(a);
}

If all you need is to print arrays, also check out the pretty printer, which uses this sort of stuff internally.
Comment: @iammilind: And Armen beat me to it by 30 seconds, too :-)

while (end of array) - how to recognize


Binomial Distribution

Question: I'm trying to solve this question, but since I missed the lecture I'm not where to start, and looking online doesn't help.
Can someone show me how to answer:
Given that X has a binomial distribution with n = 20 and p = 0.39, what is the probability that X takes on the value 8?
I would appreciate all the help I can get.
Comment: You seem to have edited your question to change the problem. The answer given by Michael Hardy isn't really meaningful now. If you want to ask another question, I suggest you write another one. Also, revert the edit so others can understand Michael's answer
Answer: This is one of those instances where the quickest way to find the probability of an event is to find the probability that the event does not happen, and then subtract that from $1$.  Thus, find the probability that $X=0$, and subtract that probability from $1$.
It appears that you cannot well afford to skip lectures, since this is one of the most routine problems you'll ever see.
Later note: The question has been changed.  It now asks for $\Pr(X=8)$.  That's a standard formula.  My second paragraph remains intact.
Comment: Thanks for your help, Michael.
Comment: @Michael Question seems to have been edited, I suggested a roll back, but you might wanna track it to keep your answer in context
Answer: This is if I got your question correctly:
You have 20 identical and independent (i.e. outcomes thereof do not affect each other) experiments, each is either success w.p. $P(S)=0.39$ or failure w.p. $P(F)=1-P(S)$. You do not care, which exactly (out of 20) experiments succeed or fail but you want the probability that exactly 8 thereof succeed.
For a better intuition think of 20 coin tosses w.p. $P(H)=0.39$ and all ways you can get 8 $H$ out of 20 tosses, $\binom{20}{8}$. The probability of this specific outcome is $0.39^8$ and therefore 12 $T \ 0.61^{12}$, hence:
$$
P(S)=\binom{20}{8} 0.39^8  0.61^{12}
$$
Comment: This doesn't match with Michael answers, as you see, the question has been edited to a completly different question. I think we should wait for OP to decide which question he wants to ask
Comment: I agree, but if the OP ants to learn something about Bernoulli experiments, this should be helpful too.

Binomial Distribution


Domain Access Database prefix

Question: I am on D7.x
I have not quite figured out how to solve the table prefix problem that was solved with domain access table prefix in the 6.x branch.
I know that I will need separate caching tables for instance, but I'm not quite sure how to allow the table prefixing when everything is based off the same settings.php file.
Thanks for your help.
Answer: I figured this out by making decisions in the settings.php file.  I have a switch statement that gets the url and then sets a table prefix variable and then that determines the db name, the db password and the prefix.  The default is to share everything if something is not found.

Domain Access Database prefix


Derivative Arc-tangens

Question: We have to show that $(\arctan(x))' = \frac{1}{1+x^2}$, derived with the chain rule.
The hint given is that we should start with deriving $\tan(\arctan(x)) = x$; I am not sure though how this is helpful, since the derivative of $\arctan(x)$ is what we are looking for yet..
Comment: What does the chain rule yield for the left hand side?
Answer: Let $y = \arctan x.$
Then $x = \tan\Big(\arctan x\Big)= \tan y$
Then $$\dfrac{dx}{dy}=\sec^2y = 1 +\tan^2 y$$
Since we have $x = \tan y$,
$$\dfrac{dx}{dy}= 1 + (\tan y)^2 = 1+x^2 $$
Hence, it follows that:
$$\frac{dy}{dx}=\dfrac{d}{dx}\left(\arctan x\right) = \dfrac{1}{1+x^2 }$$
Comment: Hello, @Babak! ;-)
Comment: Good mornin my friend. :)
Answer: You are given $\tan(\tan^{-1} x) = x$. Take a derivative of that to get $\displaystyle \sec^2(\tan^{-1} x) \cdot \frac{d}{dx} \left(\tan^{-1} x\right) = 1$.
Now, consider a right triangle with adjacent length $1$ and opposite length $x$, so that the triangle has an angle $\theta$ such that $\tan \theta = x$. Now we take $\displaystyle \sec \theta = \frac{1}{\cos \theta} = \frac{1}{\frac{1}{\sqrt{x^2+1}}} = \sqrt{x^2+1}$. So, $\sec^2 (\tan^{-1} x) = \sec^2 \theta = x^2+1$. Plugging this back into the original equation, we get $$\frac{d}{dx} \left(\tan^{-1} x\right) = \frac{1}{x^2+1}.$$
Comment: sorry, why is sec^2(tan^-1x) = sec^2phi?
Comment: $\tan \theta = x \rightarrow \tan^{-1} (\tan \theta) = \theta = \tan^{-1} x$.

That's a theta, btw, not a phi. This is a theta: $\theta$. And this is a phi: $\phi$.
Answer: $(f\circ g)' = (f' \circ g) \cdot g'$
You are looking for $g'$, so just solve for it and substitute the functions given.

Derivative Arc-tangens


Using Squeeze Theorem to show the following limits

Question: Consider a function f (x) defined on R satisfying:

for all x distinct 0.
Calculate: lim f(x) with x→∞ and limf(x) with x→−∞

Issue information:

if x → ∞ then we can consider | x | = x
if x → -∞ then we can consider | x | = -x
I can use x² = | x |?
Answer: $x^2\ne |x|$. The formula gives you
$$\frac{7^2+5x|x|+2}{x^2+16}-\frac{1}{x^2}\leq f(x)\leq \frac{7^2+5x|x|+2}{x^2+16}+\frac{1}{x^2}$$
You can use the fact that $x|x|=x^2$ when $x\rightarrow\infty$ and $x|x|=-x^2$ when $x\rightarrow -\infty$. Also $\frac{1}{x^2}\rightarrow 0$ when $x\rightarrow \pm \infty$.
Comment: I am not sure whether your $7^2$ is a typo though.
Comment: It is not an error, the expression contain 7²
Comment: I see. Just a comment. That doesn't really affect the answer.


Place tag before input text field in search-block-form

Question: I would like to add an li tag infront of the input field in the search-block.
Should be possible with hook_form_alter. I've already printed the array containing the search-block-form, but I couldn't find input type text to add a prefix value.
function myTheme_form_alter(&$form, &$form_state, $form_id) {
   if ($form_id == 'search_block_form') {
     print_r($form); -> no input type text here to add prefix to.
   }
}

Answer: The "input" type you are referring to, is actually the element defined inside the array $form['search_block_form'],  of #type 'textfield'. That's the element that provides the input field when rendered.
In order to add a
 tag in front and back of this input field, try using the properties   #prefix and #suffix. Also I would suggest creating a custom module for this, avoid using it inside the template.php file. Try the following (haven't tested it myself, though).
function myModule_form_alter(&$form, &$form_state, $form_id) {
   if ($form_id == 'search_block_form') {
     $form['search_block_form']['#prefix'] = '
';
     $form['search_block_form']['#suffix'] = '
';
   }
}

Comment: Args, now the li wraps and div. inside that theres a label followed by the input i want the li to be placed :D
Comment: I'm sorry, I'm not following what you are saying. You want to add  to a label, not to the actual textfield (input) field? If so, just add $form['search_block_form']['#title'] = 'My cool label';  (BTW this #title property adds the content inside the  tag)
Comment: No no :) It should look like .....
Comment: Then you want to override search-block-form.tpl.php. But I wonder if it would be easier to just do this with css, you know, as in     display: list-item;     list-style-type: disc; for one of the classes there
Comment: of course, but i need a none css fallback..thanks anyway
Comment: Then go for overriding the search-block-form.tpl.php . I'd be nice if you could mark my answer as correct, also.


How to check if field exists in an entity?

Question: In entity node, I want to check if 'abc' field exists or not. If exists, I will get its value by $value->get('abc').
But the content type where this field doesn't exists, gives error:
The website encountered an unexpected error. Please try again later.
How to check if field exists in an entity?
Answer: Since Drupal 8, you can use FieldableEntityInterface::hasField().
$entity->hasField('abc')


have directory assume name of file

Question: I have a bunch of video files that I want to put into directories that have the same name as the video file minus the extension (.mov)
For example, given the following directory, how would I write a script to create a directory for each .mov file with the same name as the file (minus the .mov) and then place the .mov file into that directory?
/Volumes/06a_SD_Video_01/_COLLECTIONS/TR2014_295_Walter_Reed/DER_01/
├── TR2014_295_10_1a_PM.mov
├── TR2014_295_11_1a_DER_01.mov
├── TR2014_295_12_1a_DER_01.mov
├── TR2014_295_13_1a_DER_01.mov
├── TR2014_295_14_1a_PM.mov
├── TR2014_295_15_1a_DER_01.mov
├── TR2014_295_16_1a_DER_01.mov
├── TR2014_295_17_1a_DER_01.mov
├── TR2014_295_18_1a_DER_01.mov
├── TR2014_295_19_1a_DER_01.mov
├── TR2014_295_19_1b_DER_01.mov
├── TR2014_295_1_1a_PM.mov
├── TR2014_295_20_1a_DER_01.mov
├── TR2014_295_21_1a_PM.mov
├── TR2014_295_22_1a_DER_01.mov
├── TR2014_295_22_1b_DER_01.mov
├── TR2014_295_23_1a_DER_01.mov
├── TR2014_295_2_1a_PM.mov
├── TR2014_295_3_1a_DER_01.mov
├── TR2014_295_4_1a_DER_01.mov
├── TR2014_295_5_1a_DER_01.mov
├── TR2014_295_6_1a_DER_01.mov
├── TR2014_295_7_1a_DER_01.mov
├── TR2014_295_8_1a_DER_01.mov
├── TR2014_295_9_1a_DER_01.mov
Comment: And why would you spam your readers with all those commented-out lines?
Comment: fixed. i thought they might be useful. @Jens
Comment: Apart from the obvious `MEDIAID=$TARGET` or what?
Comment: @tripleee doing that does create a folder with the file name but it also creates a tree directory of every the full path i.e.
`└── 06a_SD_Video_01
    └── _COLLECTIONS
        └── TR2014_295_XXX
            └── AIPS
                └── Box_02
                    └── TR2014_xxx_xx_xx_PM.mov
                        └── objects
                            └── TR2014_xx_xx_xx_PM.mov`
Comment: I just want `└── TR2014_xxx_xx_xx_PM.mov └── objects └── TR2014_xx_xx_xx_PM.mov`
Comment: creating the directory without the .mov would be great, too.
Comment: your friend's script looks like vogon poetry. better to just clearly describe what you're trying to do and not show us this.
Comment: Ok. I hope that is more clear. @webb
Comment: yes, much! thank you.
Answer: here is a way:
script:
cd "$1"
for m in *.mov; do
  d=`echo "$m" | sed 's/\.mov$//'`
  mkdir "$d"
  mv "$m" "$d"
done

usage:
sh

have directory assume name of file


Mutable object state replication across distributed web sessions

Question: I'm wondering why there is no single notice about the importance of immutability property when storing serializable objects in the HTTP session? I tried to check the JSF and Servlet API specifications but couldn't find anything related.
I've seen a specific problem in the case of JSF based clustered application where <code>@SessionScoped</code> managed bean is mutable i.e. user-modified parameter is stored as a field of this managed bean.
Trouble begins when the node "owning" the session (thanks to stickiness requirement in servlet API specs) dies and different node starts to take over serving the session, the latest state is lost. In fact, only the initial state is replicated. I believe this is because managed beans are placed in session (and replicated to backup nodes) only when they are created for the first time, at least this is confirmed by my tests performed on Websphere.
While one can debate whether this is a good design or not, JSF and even Servlet API still allows it to happen.
I also found some note in Oracle docs:

As a general rule, all session attributes should be treated as immutable objects if possible. This ensures that developers are consciously aware when they change attributes. With mutable objects, modifying attributes often requires two steps: modifying the state of the attribute object, and then manually updating the session with the modified attribute object by calling javax.servlet.http.HttpSession.setAttribute(). This means that your application should always call setAttribute() if the attribute value has been changed, otherwise, the modified attribute value will not replicate to the backup server.

Apart from manually updating the attribute as described above, is there any clean solution, preferably in an idiomatic JSF way?
Comment: To exclude the one and other, do you have `distributable` flag enabled in `web.xml` as indicated in the currently accepted answer to this related question? https://stackoverflow.com/q/35102645 If not then you may indeed run into the described problem (and actually much more such as broken view scoped beans as indicated in that related question). If you already have set it, then your problem is in the end indeed most likely related to a WebSphere-specific config as indicated in the answer of Allan here below.
Comment: @BalusC. I just noticed there is no distributable flag in web.xml, but it seems that Websphere still enforces session stickiness most of the time. However, as mentioned in the link you provided, I do see VEEs sometimes, and as per my observation, it happens when I try to emulate the node failure. Viewstate is stored at the server-side for the record. I'll give a try to set the distributable flag!
Comment: Servlet spec says to set distributable flag when you want to deploy WAR to a cluster. This will among others ensure that libraries such as JSF are aware of this and pay extra attention to this which is otherwise unnecessarily expensive in a non-cluster environment.
Answer: In WebSphere Liberty, there is a property called
writeContents = "GET_AND_SET_ATTRIBUTES"
for the mutable session objects. For details, please see:
https://github.com/OpenLiberty/open-liberty/issues/2802
https://www.ibm.com/support/knowledgecenter/en/SSEQTP_liberty/com.ibm.websphere.liberty.autogen.nd.doc/ae/rwlp_config_httpSessionCache.html
Same property apply for database persistence.
Comment: Thanks Allan. Is this available in Liberty only? Any alternatives in traditional Websphere 8.5 or 9? Out of curiosity, how is this implemented? How does the container know that attribute value (object) was mutated?
Comment: That is correct, GET_AND_SET_ATTRIBUTES replicate is only available in Liberty. Traditional Websphere still relies on application to call setAttribute (ONLY_SET_ATTRIBUTES).
Comment: Container won't know the attribute value object was mutated. GET_AND_SET_ATTRIBUTES option simply replicate all attributes for which getAttribute is invoked (even without setAttribute calls).
Comment: Apparently this is also possible in traditional Websphere as described [here](https://www.ibm.com/support/knowledgecenter/SS7K4U_8.5.5/com.ibm.websphere.zseries.doc/ae/uprs_rtuning_custom.html), but I couldn't make it work yet
Comment: For traditional Websphere, you have to select "All session attribute" in Write contents option for mutable object.


How do I insert a   tag outside the   tag on my main menu

Question: I have been scouring the web trying to find a way to get a  tag just AFTER each of my main menu items. Looking at this solution I am able to get a  tag in there, but it's INSIDE the link. I just don't want it to be a link.
I'm pulling my hair out trying to figure this out. I just don't know enough PHP to place it outside the link. This is what I have so far in my template.php:
function motg_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';
  $element['#localized_options']['html'] = TRUE;

if ($element['#below']) {
$sub_menu = drupal_render($element['#below']);
}

if ($element['#original_link']['menu_name'] == "main-menu"){

$element['#title'] .= ''.$element['#localized_options']['attributes']['title'].'';
}

$output = l($element['#title'], $element['#href'], $element['#localized_options']);
return '
' . $output . $sub_menu . "
\n";
}

Any help would be great!
Answer: If you want your menu link to be like this
Link 1Description
, ie., the description is outside the  tags, then try the code below.
function motg_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';
  $element['#localized_options']['html'] = TRUE;

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }

  if ($element['#original_link']['menu_name'] == "main-menu" && isset($element['#localized_options']['attributes']['title'])){
    $description = '' . $element['#localized_options']['attributes']['title'] . '';
  }

  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . $description."
\n";
}

The reason your code didn't work was, you used the description tag within the l() function. In drupal the l() function always renders an  tag and so the description was inside the  tag.


Fake book music. Why are there two lines of chords?

Question: I have a piece of music from a fake book which has two lines of chords above the melody.
Is the second line an alternative, or should it be played on the repeat?
Answer: Generally, the top line of chords is the standard, often the original. The alternatives are just that, alternative chord ideas, which usually give more scope to players and improvisers. Of course, the second line could be played later in the song, but usually a band will stick to one set or the other, perhaps even making subtle changes of their own. Maybe something like Eb, Cm for the first bar.
Comment: Way too early to say this is the preferred answer. Others may well come along that are better!  'Ain't Misbehaving'?
Comment: I doubt anyone could improve on that simple, correct answer.  But sure, let's see...


Why alamofire downloads progress in alert will flashing and the behind screen starts to be fade to black?

Question: I have progress view in alert when downloading with alamofire, but the problem is that when I want to download the progress view in alert will start to be complete but flashing and the other problem is that the behind screen will start to be fade to black I think in every second a new alert with progress view will show and at the end there are lots of alerts how can I avoid them?
downloadTimer = Timer.scheduledTimer(timeInterval: 1 , target: self, selector: #selector(flashingDownload), userInfo: nil, repeats: true)

        let destination = DownloadRequest.suggestedDownloadDestination()

        Alamofire.download("http://example.com", to: destination).downloadProgress(queue: DispatchQueue.global(qos: .utility)) { (progress) in

            print("Progress: \(progress.fractionCompleted)")

            sixthLevelViewController.progressdownload = Float(progress.fractionCompleted)

            if sixthLevelViewController.progressdownload == 1.0 {

                self.downloadfinished = true

                let alertController = UIAlertController(title: "finish download   ", message: " download Completed! ", preferredStyle: UIAlertControllerStyle.alert)

                let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default)
                {
                    (result : UIAlertAction) -> Void in
                    self.view.isUserInteractionEnabled = true

                }
                alertController.addAction(okAction)
                self.present(alertController, animated: true, completion: nil)

                alertController.view.tintColor = UIColor.green
                alertController.view.backgroundColor = UIColor.green
                alertController.view.layer.cornerRadius = 0.1 * alertController.view.bounds.size.width

            }

            } .validate().responseData { ( response ) in
                print(response.destinationURL!.lastPathComponent)
        }

and here is the codes for timer
  func flashingDownload() {

  while (topViewController.presentedViewController != nil){
            topViewController = topViewController.presentedViewController!
        }

        DispatchQueue.main.async {
            let alert = UIAlertController(title: "downloading", message: "pls wait", preferredStyle: .alert)
            let progressBar = UIProgressView(progressViewStyle: .default)
            progressBar.setProgress(sixthLevelViewController.progressdownload, animated: true)
            progressBar.frame = CGRect(x: 10, y: 70, width: 250, height: 0)
            alert.view.addSubview(progressBar)
            self.topViewController.present(alert, animated: false, completion: nil)

            if sixthLevelViewController.progressdownload == 1.0 {

                print("finished download !")
                self.topViewController.dismiss(animated: false , completion: nil)
                self.downloadTimer.invalidate()

            }

       }

as you see in my codes I have another variable that controls the download finish so when progress is 1.0 I want to dismiss alert
Answer: The Problem here is that you are presenting the alert view inside the 'downloadProgress' closure. This is not what its meant for.
The 'downloadProgress' closure basically gets called every time there has been a change in the progress.
So when downloading a file this obviously can lead to many alert views layered on top of each other as you described.
Actually you should instantiate your Alert View somewhere outside and only use this closure to update it's content.
But if you want to keep this structure, test for progress.isFinished instead for a specific value.


How to create a 2D ArrayList?

Question: I'm trying to use Java to create a 2-dimensional array. The size of rows is known, while the size of columns is unknown. Here is my code and it doesn't work. Could anyone give me some idea?
ArrayList<Integer> paths[];
paths = new ArrayList[2];// 2 paths
for (int i=0; i<2; ++i)
    paths[i].add(1); // add an element to each path

Answer: Initialize the array element before adding to it. Put the initialization into the for loop:
@SuppressWarnings("unchecked")
ArrayList<Integer>[] paths = new ArrayList[2];

for (int i=0; i<2; ++i) {
    paths[i] = new ArrayList<Integer>();
    paths[i].add(1);
}

This way you can avoid the NullPointerException.
Comment: @user2570387 Lazier way: Put your mouse on the warned tokens and the options will show.
Comment: I got a error saying "cannot create a generic array of ArrayList" for the 1st line.
Comment: What editor do you use? What java version? In my Eclipse it is only a warning, and compiles and runs perfectly (I use 1.7 compiler with 1.6 source code level). I also set `@SuppressWarnings("unchecked")`, it does not even warn.
Comment: I use eclipse and the JDK7u10
Comment: Thanks GaborSch, I got it! But how to set the warning to be "unchecked"? Why ArrayList[] paths = new ArrayList[2] not ArrayList[] paths = new ArrayList[2]?
Comment: Updated the answer. Press `Ctrl-1` in Eclipse and select from the options. The other "magic" is `Ctrl-Space`. Use them everywhere, there are million suggestions!
Comment: Just found it. Thanks!
Comment: If you put ``, you will get `Cannot create a generic array of ArrayList` error.
Comment: @johnchen902 I'm a keyboard-fan, but it's good to know. I simply can't wait until the popup shows :D
Answer: This is a "2d" ArrayList:
ArrayList<ArrayList<Integer>> paths = new ArrayList<>();

And here is the non-diamond operator version for Java < 1.7:
ArrayList<ArrayList<Integer>> paths = new ArrayList<ArrayList<Integer>>();

Comment: Type mismatch: cannot convert from ArrayList> to
  ArrayList>
Comment: Type mismatch: cannot convert from ArrayList> to ArrayList>[]
Comment: @user2570387 the line I posted doesn't try to convert to `ArrayList>[] `, it creates an `ArrayList` of `ArrayLists` of `Integer`
Comment: "'<>' operator is not allowed for source level below 1.7" - most likely OP has something lower that 1.7, so probably this won't work.
Answer: I would recomend this
    ArrayList<ArrayList<Integer>> paths = new ArrayList<ArrayList<Integer>>();
        for (int i=0; i<2; ++i)
            paths.add(new ArrayList<Integer>());

How to create a 2D ArrayList?


SSH2.php is there a way to increase time for a response from server?

Question: I seem to get these errors sometimes;
Unable to open channel in /home/Net/SSH2.php on line 3833
And was wondering if there was a way to mitigate these issues by increasing time to wait for a response?
Thanks
Answer: By setting the timeout, like this:
$ssh = new Net_SSH2('hostname');
$ssh->setTimeout(10);

Comment: how long of a timeout is `10` ? seconds? milliseconds?
Comment: The [official documentation](https://api.phpseclib.org/1.0/Net_SSH2.html#method_setTimeout) does not say buy I'm 99% sure it's in seconds.


Com criar um programa que leia 10 números e escreva o menor e maior valor lido (Python)?

Question: Estou com uma certa dificuldade nesse exercício.
Aqui está meu código:
python
num = float(input('Digite o 1 numero: '))

guarda_maior = num
guarda_menor = num

for n in range(1, 10):

    num = float(input(f'Digite o valor de {n}: '))

    if num > guarda_maior:

        num = guarda_maior

    elif num < guarda_menor:

        num = guarda_menor

print(f'{guarda_maior}, {guarda_menor}')

Se alguém puder me ajudar.
Grato.
Answer: O problema estava no fato de que o num estava recebendo a var ao invés da var estar recebendo o num
if num > guarda_maior:

        guarda_maior = num #troquei a ordem, agora guarda_maior recebera num ao inves de num receber guarda_maior

    elif num < guarda_menor:

        guarda_menor = num #troquei a ordem, agora guarda_menor recebera num ao inves de num receber guarda_menor

print(f'{guarda_maior}, {guarda_menor}')

Dessa forma acredito que será resolvido.
Comment: Nossa, tava tentando monte de coisa hahahaha.
Comment: Pequena falta de atenção...
Comment: Muito obrigado, João.
Comment: De nada, Douglas


Add an item among those displayed in a Views block that links to the item creation page

Question: The goal:

How do I add the "Add new project" item as the first among the other projects shown in the Views block? The content would link to the project creation page (node/add/project) ?
Please suggest other methods/alternatives if this is not feasible.
Answer: Add a header to the view and style it to fit your needs.
You can chose between rendered entity: custom menu link or just add a textarea and enter your link. The first option might be better because it provides an access check.
You might need to customize some of the fields HTML within the fields style settings to make this work.