Simplifying the Derivative

Question: How do I get this simplified result from derivation outcome?
I wish to simplify this$$-\frac {\frac x{\sqrt{x^2-1}}+1} {\sqrt{x^2-1}+x}$$
to this
$$-\frac 1 {\sqrt{x^2-1}}$$
Attached Image
Comment: Please add your equations to the question itself (preferably nicely formatted). Links to external images can become invalid in the future. Don't forget to describe *what* you tried.
Comment: Try to bring the enumerator $\left(\frac x{\sqrt{\ldots}}+1\right)$ to the common denominator form.
Answer: we have  $-\frac{\frac{x}{\sqrt{x^2-1}}+1}{\sqrt{x^2-1}+x}=-\frac{\frac{x}{\sqrt{x^2-1}}+1}{\sqrt{x^2-1}+x} \times \frac{\sqrt{x^2-1}-x}{\sqrt{x^2-1}-x} =- \frac{x+\sqrt{x^2-1}- \frac{x^2}{\sqrt{x^2-1}}-x}{x^2-1-x^2} = \sqrt{x^2-1}- \frac{x^2}{\sqrt{x^2-1}}= - \frac{1}{\sqrt{x^2-1}}$
Answer: $$-\frac {\frac x{\sqrt{x^2-1}}+1} {\sqrt{x^2-1}+x} =
-\frac {\left(\ \frac {x+\sqrt{x^2-1}}{\sqrt{x^2-1}}\ \right)} {\sqrt{x^2-1}+x} =
-\frac {\left(\ \frac 1{\sqrt{x^2-1}}\ \right)} 1 = -\frac 1{\sqrt{x^2-1}}$$

Simplifying the Derivative


How to show that $O(n^\frac{3}{4} \log n) = O(n)$?

Question: I try to analyze LazySelect algorithm (finds kth order statistic of a set). One of the steps is to take a sample of $n^\frac{3}{4}$ elements and sort it. It seems like this sorting is linear relative to original size $n$.
How to show that $O(n^\frac{3}{4} \log n) = O(n)$?
I was trying to show that for some large n: $\frac{n}{\log n} \ge n^\frac{3}{4}$ but don't know how to do it.
Comment: You can't. Note that $O(n^{\frac{3}{4}}\log n) = O(n) \implies O(n^{\frac{1}{4}}) = O(\log n)$ which is false.
Comment: Are you sure you can simplify?
Comment: @3d0 I think the point is that if $f=O(n^{3/4} \log n)$ then $f=O(n)$. The use of $=$ in Big Oh notation is a bit confusing in this respect.
Answer: Very simple : you even have more: it is standard that $n^\alpha\ln^\beta n=o(n^{\alpha'}\ln^{\beta'}n)$ as soon as $\alpha<\alpha'$. Just apply these rules of Asymptotic analysis:

if $f=o(g)$, then $O(f)=o(g)$,
if $f=o(g)$, then $f=O(g)$.
Comment: Can u give literature-hints where i can find the last two claims?
Answer: Since for all $a,b > 0$ we have $(\log n)^{a} = o(n^{b})$ as $n$ grows, so $n^{1/4} > \log n$ for large $n$, i.e. $n > n^{3/4}\log n$ for large $n$. If $f(n) = O(n^{3/4}\log n)$ as $n \to \infty$, then there is some $M \geq 0$ such that $|f(n)| \leq Mn^{3/4}\log n < Mn$ for large $n$, so $f(n) = O(n)$.


How to display elements responsively side by side using Bartik theme, similar to bootstrap grid?

Question: I am developing a module for Drupal 8, currently using the default Bartik theme. My module defines some pages through twig templates. As I am displaying several sections of a dashboard, I would like to show two DIVs next to each other side by side.
I am looking for something similar to the Bootstrap Grid. I am even thinking to just try to use Bootstrap inside my module regardless of the Drupal theme, as I used Bootstrap before but I am new to Drupal theming.
Is there some way the Bartik theme (or different Drupal 8 theme) provides to display elements responsively side by side?
Comment: The first thing that comes to mind is Display Suite and designing your own responsive layouts for it.
Comment: I would be happy to just assign a css class in my template or some similarly "raw" method. No drag'n'drop or other fancy stuff required. Still, thanks for pointing out Display Suite!
Answer: I ended up working around it by extracting the relevant css classes of bootstrap into my custom css file. Now I can use the bootstrap grid without disturbing the normal Drupal theme:
<code>.row {
  margin-right: -15px;
  margin-left: -15px;
  box-sizing: border-box;
}
.row:before, .row:after {
  display: table;
  content: " ";
}
.row:after {
  clear: both;
}

.col-md-1, .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-md-10, .col-md-11, .col-md-12 {
  position: relative;
  min-height: 1px;
  padding-right: 15px;
  padding-left: 15px;
  float: left;
  box-sizing: border-box;
}

.col-md-12 {
  width: 100%;
}
.col-md-11 {
  width: 91.66666667%;
}
.col-md-10 {
  width: 83.33333333%;
}
.col-md-9 {
  width: 75%;
}
.col-md-8 {
  width: 66.66666667%;
}
.col-md-7 {
  width: 58.33333333%;
}
.col-md-6 {
  width: 50%;
}
.col-md-5 {
  width: 41.66666667%;
}
.col-md-4 {
  width: 33.33333333%;
}
.col-md-3 {
  width: 25%;
}
.col-md-2 {
  width: 16.66666667%;
}
.col-md-1 {
  width: 8.33333333%;
}
</code>


Is there any way to get Microsoft Edge Web driver pushed to customers?

Question: I am looking for a way to monitor changes to Microsoft Edge Web driver programmatically.
Some possiblities:
      * Would be great if there is an API (REST) to monitor latest available Edge webdriver.
      * Since Edge driver is dependent on windows build version. some information about windows 10 build version in the API would be useful.
      * Or Even better.. Since Edge driver depends on windows 10 build version, is there any chance for the Edge driver to get shipped with windows 10 builds. something like the native calc.exe in the system32 folder...
Any guidance/information would be very helpful.
Thank you..
Answer: Primary versions of Web Driver can always be found on dev.microsoftedge.com. Presently, this includes versions for 10240, 10586, and the Fast Ring of the Windows Insider Program. Monitoring that page will give you insight as to when a newer version of Web Driver is available for Edge.
With regards to your other questions:

Can we have a REST API to identify latest/supported Web Driver / OS versions
Can Web Driver be shipped in Windows 10 directly

I'll reach out to the appropriate team member(s), and see if this is something they've considered.
For the time being, you may be able to infer the machine's build of Windows by leveraging common APIs. For instance, via Node, you could do the following:
require("os").release().match(/\d+$/);

Depending on your build of windows, this will return, [10240], [10586], or some newer build number, like [14379]. You could then use this to instruct the user as to which version of Web Driver they should download.
Comment: Thanks Sampson, for the temporary solution. But.. Points 1) and 2) will help in building a more robust and autonomous infrastructure ..


Possible to store 2 dimensional distribution as a univariate distribution?

Question: I am dealing with a dataset that has -

many "measurements" (say X, Y and Z)
a tremendous amount of data (at least considering we need to query it on the fly)
and a user base that is interested in joint probabilities of measurements (e.g. P(X >= x & Y <= y) | P(Y <= y))

**NOTE**: All measurements of interest are binned

Our univariate distributions are stored as t-digests that are pretty efficient and they are also accurate for our needs
Currently, we are storing the joint distributions - of say X, and Y - as nested maps in our database where keys of the outer map correspond to bins of X, those of the inner map correspond to bins of Y, and the values of the map correspond to frequency of x-bin, y-bin. while this helps us "build & answer" the joint probabilities queries, nested maps are computationally inefficient
Consequently, I am exploring to see if its possible to store the bivariate distribution (say of X, and Y) as univariate distribution of say Y projected onto X (for example, I could split the "bin of X" into total bins of Y and then frequency of a given x-y bin could be stored as that of this single projected variable) and then recruit the aggregate structures we use for univariate

Problem

My idea of "projection" isn't quite working out though. The projected variable's quantiles work out very different results compared to the 2-D distribution. I tried to account for two items I noticed -

x-bin, max-y-bin are too close to x-bin + 1, 0 - so I tried to split "x-bin" into total-y-bins * 3 and "interleave" y-bin values
I also built the distribution using a variable that is 5X the projected variable thinking the t-digest algorithm is perhaps merging these bins

Question
Not withstanding the t-digest approach to aggregating the univariate projection of the bivariate distribution (as that may be introducing issues, at least in part, to how the algorithm works relative to this problem), is it even possible in principle, to capture the distribution of a 2-d variable as a univariate distribution?
Comment: IIUC, you consider two binned random variables X and Y for which there is a belonging matrix that approximates the joint distribution of X and Y. This matrix is currently stored in nested maps and you think about changing that. When you say "projecting", do you just mean to flatten the matrix (i.e. mxn matrix becomes mx1), or do you mean marginalization?
Comment: @frank, yes - `flatten the matrix` was the approach I was trying to take. Is there another approach that helps store a 2 dimensional distribution as one dimensional?
Comment: I am sorry, I had a typo: flatten (as in https://numpy.org/doc/stable/reference/generated/numpy.ndarray.flatten.html ) means turning an mxn matrix into an (m*n)x1 matrix by concatenating all the rows or all the columns. But that is what you are referring to?
Comment: @frank, that's precisely what I was shooting for, but my precision was way off the mark :)
Comment: So, that answers your question? Or is there still something you want to know? I am not sure...
Comment: well in my case, I - a) `flattened`, and b) `used T digest`, the result of `a) and b)` did not yield correct answers. I guess my question was does `flattening` distort the 2d distribution beyond repair?
Answer: You can change your data by flattening the matrix without losing any information. You can convince yourself thereof by noting that you can of course easily re-create the matrix from the flat vector.
And, if you want to, you can also think of the $(n\cdot m)$-dimensional vector (that is the flattened $n\times m$ probability matrix) as a new one-dimensional probability density and apply your T digest to it.
But it will then be more cumbersome to compute those joint probabilities you mentioned above. Extracting those from the T digest of the flattened vector will be difficult and maybe the problems you will get are worse than the benefits.
Comment: Thanks @frank. It is helpful knowing that the `solution in concept` isn't flawed. I will definitely need to understand how t-digest affects the `implementation of this idea`.
Comment: If you like the answer, please consider accepting and/or upvoting it. If you think something is missing, please leave a pertinent comment.


Word Problem for Number of Seeds Required with Diminishing Returns

Question: So I've been trying to wrap my brain around this but it eludes me. The word problem would look something like this:
What is the minimum amount of seeds I need to buy to plant 850 seeds when only 60% of these planted seeds will produce a seed of their own. I can continue planting over and over until I reach my last seed.
I am looking for a formula I can use and plug into Excel - but a mathematical equation would be just great!
Thanks
Answer: You are just summing a geometric series.  If you start with $n$ the next generation gives you $0.6n$, the one after that gives $0.6^2n$, then $0.6^3n$ so you want $$850=n(1+0.6+0.6^2+0.6^3+\ldots )=\frac n{1-0.6}\cdot 850\\n=0.4\cdot 850=340 $$
Comment: that's awfully optimistic about the farmer's ability to successfully plant a fraction of a seed.
Comment: @Zackkenyon:  that is true.  I think my approach is in the spirit of the question.  I took the $0.6$ as a probability that each seed produces another.  We could round up a bit to cover.
Comment: @Zackkenyon thanks for not providing any helpful feedback. The question isn't based on a real world scenario.
Comment: @Ross that works! I don't quite see how you got from the first part 850=n(1+0.6+0.62+0.63+…) to this =(n/(1−0.6))*850 could you explain a little more in depth?
Comment: Look up geometric series on Wikipedia.  It is like converting a repeating decimal to a fraction.
Answer: 1 seed grows 2.5 seeds on average, so divide 850 by 2.5 and you have your answer.
You can use infinite geometric series formula to find expected number of seeds for 1 seed.
Comment: No one seed grows 0.6 seeds.


bVI Root Substitution

Question: Curious as to why this substitution of the root for a ♭VI chord works. It's pretty standard but I don't get the theory of it. I recently saw it being used in the context of a  ii - V - I to delay the final resolve of a song. Specifically the following:
|| A7#11(13) Amin9 | C/D D7b9 | EbMaj7♯11(13) ||
I've seen other progressions walk up to resolve as such: ii - V - ♭VI - ♭VII - I
What is the theory surrounding a ♭VI substitution like this?
Comment: Is it really necessary to give an example progression with #11, 13, b9, etc. to get to the point about a "root substitution?" Just use plain seventh chords and show the progression before and after the substitution.
Comment: Can you please write this in a very for-dummies way, like where is your "one" i.e. I chord, and what has been substituted with what? A root has been substituted? Which root, what note name? What was it substituted with? What does (13) in parenthesis mean, when you also say something about 7 and 11? Can you show all the notes you mean on a piano keyboard or something, and then mark them, which note you think is center, and where is the sixth that has been flatted. And where would the missing note be that was substituted with something, and what is the surprising thing about that.
Comment: @Flyswat. No. Those extensions _obscure_ the details of the leading tone, and the other functional tones of the resolution, because those extension tones _are not involved with the resolution._
Comment: As a general rule, when people as "how it works" they are asking about _functional harmony_, and when it comes to functional harmony mode changing details and extensions beyond the seventh (probably better stated as the tritone MI/FA) are irrelevant to essential function. In other words, essential function ("how it works") can usually be explained with plain triads in combination with tritone MI/FA.
Comment: @MichaelCurtis I disagree. The progression I'm referencing was written as such and sharing it with the extensions is important to get a more detailed picture of leading tones with the substitution.
Comment: This applies to jazz too. That fact that `ii V I` is a jazz fundamental is _literally_ writing out the _functional_ essentials in terms of only triads.
Comment: Thanks for sharing Michael I presumed it would be helpful to share the literal progression. Next time I'll stick to the 7's.
Answer:
I recently saw it being used in the context of a ii - V - I to delay the final resolve of a song. Specifically the following:

|| A7#11(13) Amin9 | C/D D7b9 | EbMaj7♯11(13) ||

I suppose you're asking about the D7b9 resolving to Ebmaj7 rather than to a tonic I chord rooted on G.
This should be a straight forward question and answer, but it's complicated by all the complex details of the example progression - lots of chord extensions and mode changing - and the notion that V ♭VI is a "root substitution."
Progressions V ♭VI or V vi are simply deceptive progressions. The idea is commonly covered in harmony textbooks. Basically, the "deception" is instead of V going to the tonic I or i, it goes to the chord of the submediant, vi or ♭VI. The "working" of that progression is the tritone of scale degrees ^4 ^7 resolves to ^3 ^1 in both progressions (V I and V vi of the minor mode versions) but the root of the second chord changes.
Using the basic idea of the example progression, it would be progressions the following where the tritone resolution is in the treble clef...

...those are not meant to be good jazz voicings. The idea is only to show the theoretical "workings" of the progressions which is the resolution of the tritone inward to a third or outward to a sixth.
It seems worth pointing out those progressions don't involve a root substitution but simply a root change, because it made the OP's question hard to understand.
The root of I (or i) is scale degree ^1. When the progression moves to ♭VI instead of I the root becomes scale degree ^6, but importantly the ^1 is still present in the ♭VI chord. Notice how G is still present in the deceptive resolution, but it becomes the chord's third...

If anything is being substituted in the chord of resolution it is scale degree ^5 (the chord's fifth not root) being substituted with scale degree ^6. That nuance is probably more apparent when the chord of resolution is a plain triad, which is the basis of the "working", rather than jazz seventh chords.
Comment: Excellent response. Thanks for sharing Michael!
Answer: It can operate in three ways:

As a deceptive cadence, but using bVI from the parallel minor rather than the native vi.
As a subdominant substitution. This is the case in the given bVI - bVII - I example, where the bVI leads to the dominant-function bVII.
It can also be used to form a sort of plagal cadence, especially if used in first inversion. That puts the root in the bass, the b6 can drop to 5 (as in a an actual plagal cadence), and the b3 can rise to 3.
Comment: Are there specific rules around borrowing from a parallel minor? Or is it just on a what works-is basis?
Comment: @Flyswat - I think my music theory textbooks actually implied you can borrow *everything* from the parallel minor at the risk of modulating to that parallel minor.
Comment: @Flyswat In the general way you're asking, yes, it's just a "it works if it works" type of thing. Dekkadeci said it well that the primary risk is an unintentional modulation.
Answer: To me the theory behind why the V7-bVI works is that the tritone of the V7 chord, resolves in exactly the same way as it does in a V7-i. The bVI comes from the parallel minor. Using your example's key of G, the F# leading tone of the D7 resolves up to a G and the C resolves down to a Bb. The notes G and Bb are in both the bVI (Eb) and the i (Gm) chords.
Comment: Yes John it is A dominant. The 7 has been added so that A7#11(13).
Comment: I mused on the A# as well. Been caught out by that printing before!. And why put the 13 in brackets, when there's 11 before it, presuming playing a 13 may well involve playing 11 too?
Answer: I think you're asking about the chord A♭ (or A♭7) followed by chord C, for example, in  key C.
If you are, there's only the C note in common, all the others are non-diatonic, which makes the listener pay more attention, expecting diatonics.
So, C, with CEG, and A♭7 with A♭ C E♭ G♭. It can come across as a key change - that chord is the V of C♯, a quite common key change up a semitone, which obviously doesn't happen.
Notes like to be heard to resolve cleanly, and one semitone is often the cleanest path to take. The E♭ will move to E, while both the G♭ and A♭ converge to the G.
It's almost a plagal cadence, which would be F>C, or Fm>C, as Fm is the relative of A♭, so using the parallel key, as Aaron states.

bVI Root Substitution


Is pci express 3.0 backwards compatible?

Question: Is PCI express 3.0 backwards compatible with the other revisions? I read on Wikipedia that this was going to be attempted, but I can't find anywhere this is confirmed.
Answer: Yes. The cards and bus (per card) will operate at the lowest common speed that both support.
Wikipedia: PCI Express mentions that it would be backwards compatible with existing PCIe implementations.
PCIe 3.0 Base Spec §4.2.2 elaborates:

For backwards compatibility, the Link
  initially trains to L0 at the 2.5 GT/s data rate using 8b/10b encoding as described in Section 4.2.1,
  then when the data rate is changed to 8.0 GT/s or higher, 128b/130b encoding is used.
Comment: Cool, do you have a source for this information? I can not seem to find it anywhere...


Can I determine what event triggered an event handler in jQuery if I bind multiple ones?

Question: Check this example:
$('button').bind('click focus', function() {

   // Did I click or focus?
});

Is there a way to work that out when binding multiple events to one handler?
This may work, but it is kind of ugly:
var eventType;

$('button').click(function() {
   eventType = 'click';
   do();
});

$('button').focus(function() {
   eventType = 'focus';
   do();
});

function do() {
    alert(eventType);
}

Answer: You can use event.type on the event object (the first param passed to the handler), like this:
$('button').bind('click focus', function(e) {
  if(e.type == "click") {
    //do something, it was a click
  }
});


CSS animation, fade in background on hover, stay, and go back to previous after a delay

Question: Lets say I have a HTML element which red with transparency. When I hover the element it should turn a solid red. When I stop hovering the element it should animate back to the first state, but only after X seconds.
So far so good, see code snippet.
My problem is when I stop hovering the element and then go back to hovering it. The initial animation starts again, but it hasn't animation to the initial state hasn't started yet and therefore there is an ugly jump from full colour to transparency and then fade to full colour.
Is there a way to solve this without JavaScript?
Then, by setting the background of the div to the full colour the colour when not hovering is kept. But it also sets it to the initial colour. How can I solve this? Removing it only removes the colour when not hovering!
Opacity with a transition isn't an option as I have content inside this div.

div {
  width: 100px;
  height: 100px;
  background: rgba(50, 60, 95, 1);
  animation-name: fadeItOut;
  animation-duration: 1s;
  animation-delay: 2s;
  animation-fill-mode: forwards;
}

div:hover {
  animation-name: fadeItIn;
  animation-duration: 1s;
  animation-delay: 0s;
  animation-fill-mode: forwards;
}

@keyframes fadeItIn {
  0% {
    background: rgba(50, 60, 95, 0.3);
  }
  100% {
    background: rgba(50, 60, 95, 1);
  }
}

@keyframes fadeItOut {
  0% {
    background: rgba(50, 60, 95, 1);
  }
  100% {
    background: rgba(50, 60, 95, 0.3);
  }
}

Comment: Sorry, I may have completely missed the point but why not just do [this](https://jsfiddle.net/nwvkzsvw/)?
Answer: I think you may have complicated things by using animation when a transition would have been the better option. Animations have a start and end point (the 0% and 100% keyframes) so when you hover-in or out, the element is first set to the state as at the 0% keyframe (since animation direction is normal) and then proceeds to the 100% keyframe. When you hover-in or out quickly (before previous animation is complete) you'd always see these jumps because of the setting of 0% keyframe's props.
The below should be what you need:

div {
  width: 100px;
  height: 100px;
  background: rgba(50, 60, 95, 0.3);
  transition-property: background;
  transition-duration: 1s;
  transition-delay: 2s;
}
div:hover {
  background: rgba(50, 60, 95, 1);
  transition-delay: 0s;
}

Comment: You got the point pretty well! :) I did try this once before but I have multiple transitions on the same element which killed each other because they where sent in different locations. This helped me find it. Thanks!
Answer: Your code just works.
This "horrible" effect as you said is just because you hover the element before the animation fadeOut finishes.
Try just to reduce the animation delay of the div like that:
div {
  width: 100px;
  height: 100px;
  background: rgba(50, 60, 95, 1);
  animation-name: fadeItOut;
  animation-duration: 1s;
  animation-delay: 1s;
  animation-fill-mode: forwards;
}

This is the fiddle i've made for let you see it: https://jsfiddle.net/oqyep7tt/
At least the Harry's way is way more better than this.
Answer: Try this
div {
  width: 100px;
  height: 100px;
  background: rgba(50, 60, 95, 1);
  transition: background 300ms;
  animation-name: fadeItOut;
  animation-duration: 1s;
  animation-delay: 0s;
  animation-fill-mode: forwards;
}

div:hover {
  animation-name: fadeItIn;
  animation-duration: 1s;
  animation-delay: 0s;
  animation-fill-mode: forwards;
}

@keyframes fadeItIn {
  0% {
    background: rgba(50, 60, 95, 1);
  }
  100% {
    background: rgba(50, 60, 95, 0.3);
  }
}

@keyframes fadeItOut {
  0% {
    background: rgba(50, 60, 95, 0.3);
  }
  100% {
    background: rgba(50, 60, 95, 1);
  }
}

live demo - https://jsfiddle.net/rye2gnp3/
Comment: But OP needs the delay to be present before state change on hovering out.
Comment: This one is correct @grinmax and that's exactly the suggestion I had given :)


What is the "tip" of the reed

Question: What is the "tip" of an oboe reed?
Is the upper part of the hole of the reed or the bottom part?
Comment: Think 'tip of the tongue...'
Answer: The tip of a reed usually refer to the front edge. For an oboe, that includes  both upper and lower parts of the reed. Here's a diagram:

Stolen from https://www.crookandstaple.com/pages/how-to-adjust-oboe-reeds

What is the "tip" of the reed


Aumentar Tamanho da fonte JavaScript/HTML/Jquery

Question: eu sei que eu já fiz uma pergunta parecida, mas alguém pode me ajudar com isso, fiz uma aplicação em HTML/JavaScript/Jquery ... e preciso de alterar a fonte de CADA UMA das TEXTAREAS com um botão, dê uma olhada, o usuário clica em adicionar textarea, adiciona também, um botão para alterar a cor e um para aumentar a fonte ... Preciso de adicionar a função de aumentar a fonte em cada uma ...
Se alguém tiver uma ideia ...

    <title>Página</title>

    <link href src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" media="screen">

Página

    <link href="design.css" rel="stylesheet" media="screen">

        <form name="input" method="get" id="mover">

                      <button type="button" class="button" onclick="add_field(); contador(); mover();">ADICIONAR CAIXAS DE TEXTO</button>

        </form>

        <button type="button" id="btnAumentar">Aumentar fonte</button>

        <form name="input" method="get">

                      <button type="button" class="btnsave">SALVAR</button>

        </form>

            <button onclick="mover();">Click</button>

Answer: Esse seu código está horrível, não da pra entender nada, como você está usando jQuery podemos melhorar isso criando um template e clonar o mesmo toda vez que o botão de adicionar for clicado, esse template ficara oculto, o código está comentado para você poder entender.

$(document).ready(function(){
  var _clone_index = 0;
  $("#btnAddCaixaTexto").on('click', function(){
    // Vamos usar um número de índice exclusivo para cada nova instância do item clonado
    _clone_index++;
    // Verifica a quantidade de caixa já adicionada
    if (_clone_index <= 10) {
      $(this).parent().parent().after($("#template").clone().attr("id","_clone_" + _clone_index));
      // Tornar o clone visível alterando CSS
      $("#_clone_" + _clone_index).css("display","inline");
      // Altera o atributo id da tag textarea
      $("#_clone_" + _clone_index + " textarea").attr('id', _clone_index);

      // Método para alterar o fundo da textarea
      $("#_clone_" + _clone_index).on('click', "#btnFundoAzul", function(){
        // Altera o fundo da textarea para Azul
        $(this).parent().find("textarea").css({"background": "blue"});
      });

      // Método para alterar o fundo da textarea
      $("#_clone_" + _clone_index).on('click', "#btnFundoBranco", function(){
        // Altera o fundo da textarea para Branco
        $(this).parent().find("textarea").css({"background": "white"});
      });

      // Método para Aumentar a fonte da textarea
      $("#_clone_" + _clone_index).on('click', "#btnAumentarFonte", function(){
        // Armazena o tamanho atual da fonte
        var tamanhoAtual = parseFloat($(this).parent().find("textarea").css("font-size"));
        // Incrementa + 1 no valor atual, e aplica o novo tamanho
        $(this).parent().find("textarea").css({"font-size": tamanhoAtual+1});
      });
    } else {
      // Caso for maior que 10, exibe a mensagem
      // e desabilita o botão
      alert("ATÉ 10 CAIXAS DE TEXTO");
      $(this).prop("disabled", true); // Desabilita o botão #btnAddCaixaTexto
    }
    mover();
  });

  function mover(){
    $('#mover').draggable(); // add draggable library
  };
});
/* Oculta a div[id="template"] */
#template {
  display: none;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="design.css" rel="stylesheet" media="screen">

Página

    <button type="button" id="btnFundoAzul" name="item" class="pular">Fundo Azul</button>
    <button type="button" id="btnFundoBranco" name="item" class="pular">Fundo Branco</button>
    <button type="button" id="btnAumentarFonte" class="pular">Aumentar Fonte</button>
    <textarea id="0" type="textarea" name="item" class="caixa_descer"></textarea>

  <form name="input" method="get" id="mover">

        <button type="button" class="button" id="btnAddCaixaTexto">ADICIONAR CAIXAS DE TEXTO</button>

  </form>

  <form name="input" method="get">

        <button type="button" class="btnsave">SALVAR</button>

  </form>

    <button onclick="mover();">Click</button>


Multiple Linear Regression Simulation

Question: I'm new to the R language. I would like to know how to simulate from a multiple linear regression model that fulfills all four assumptions of the regression.

ok.. thank you.
Let say i want to simulate the data based on this data set:
y<-c(18.73,14.52,17.43,14.54,13.44,24.39,13.34,22.71,12.68,19.32,30.16,27.09,25.40,26.05,33.49,35.62,26.07,36.78,34.95,43.67)
x1<-c(610,950,720,840,980,530,680,540,890,730,670,770,880,1000,760,590,910,650,810,500)
x2<-c(1,1,3,2,1,1,3,3,2,2,1,3,3,2,2,2,3,3,1,2)

fit<-lm(y~x1+x2)
summary(fit)

then i get the output:
Call:
lm(formula = y ~ x1 + x2)

Residuals:
     Min       1Q   Median       3Q      Max
-13.2805  -7.5169  -0.9231   7.2556  12.8209

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) 42.85352   11.33229   3.782  0.00149 **
x1          -0.02534    0.01293  -1.960  0.06662 .
x2           0.33188    2.41657   0.137  0.89238
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 8.679 on 17 degrees of freedom
Multiple R-squared:  0.1869,    Adjusted R-squared:  0.09127
F-statistic: 1.954 on 2 and 17 DF,  p-value: 0.1722

My question is how to simulate a new data that mimic the original data above?
Answer:
If you don't have them already, start by setting up some predictors, $x_1$, $x_2$, ...
Choose the population ('true') coefficients of your predictors, the $\beta_i$'s, including $\beta_0$, the intercept.
Choose the error variance, $\sigma^2$ or equivalently its square root, $\sigma$
generate the error term, $\varepsilon$, as an independent random normal vector, with mean 0 and variance  $\sigma^2$
Let $y = \beta_0 + \beta_1 x_1 + \beta_2 x_2 + ... + \beta_k x_k + \varepsilon$

then you can regress the $y$ on your $x$'s
e.g. in R you could do something like:
x1 <- 11:30
x2 <- runif(20,5,95)
x3 <- rbinom(20,1,.5)

b0 <- 17
b1 <- 0.5
b2 <- 0.037
b3 <- -5.2
sigma <- 1.4

eps <- rnorm(x1,0,sigma)
y <- b0 + b1*x1  + b2*x2  + b3*x3 + eps

produces a single simulation of $y$ from the model. Then running
 summary(lm(y~x1+x2+x3))

gives
Call:
lm(formula = y ~ x1 + x2 + x3)

Residuals:
    Min      1Q  Median      3Q     Max
-2.6967 -0.4970  0.1152  0.7536  1.6511

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) 16.28141    1.32102  12.325 1.40e-09 ***
x1           0.55939    0.04850  11.533 3.65e-09 ***
x2           0.01715    0.01578   1.087    0.293
x3          -4.91783    0.66547  -7.390 1.53e-06 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 1.241 on 16 degrees of freedom
Multiple R-squared:  0.9343,    Adjusted R-squared:  0.9219
F-statistic: 75.79 on 3 and 16 DF,  p-value: 1.131e-09

You can simplify this procedure in several ways, but I figured spelling it out would help to begin with.
If you want to simulate a new random $y$ but with the same population coefficients, just rerun the last two lines of the procedure above (generate a new random eps and y), corresponding to steps 3 and 4 of the algorithm.
Comment: Is it possible to change the standard error of the estimates? I used a slightly modified script (`rnorm()` instead of `11:30`), but no matter how much I increase the error (sigma), the standard errors of the estimate are roughly similar.
Answer: Here is another code to generate multiple linear regression with errors follow normal distribution:
sim.regression<-function(n.obs=10,coefficients=runif(10,-5,5),s.deviation=.1){

  n.var=length(coefficients)
  M=matrix(0,ncol=n.var,nrow=n.obs)

  beta=as.matrix(coefficients)

  for (i in 1:n.var){
    M[,i]=rnorm(n.obs,0,1)
  }

  y=M %*% beta + rnorm(n.obs,0,s.deviation)

  return (list(x=M,y=y,coeff=coefficients))

}

Multiple Linear Regression Simulation


Send email with CakePHP

Question: I setup an email verification after a user has signed up, but when user receives email, it just says "info" in the FROM column in GMAIL. Is there a way I can change it to say something else like "Example.com" or " Email Verification"? I just want the user to see whom the email is from before opening it.
Here's how it's defined in config/constants.php - using CakePHP
if(!defined('EMAIL_FROM')) {

define('EMAIL_FROM', 'email@example.com');

}

Please help.
Thanks
Answer: To define the from field you need to set it after initiating the CakeEmail object as shown in the documentation http://book.cakephp.org/2.0/en/core-utility-libraries/email.html
$email = new CakeEmail();
$email->from(array('firstname.lastname@example.com' => 'My Site'));
$email->to('firstname.lastname@example.com');
$email->subject('About');
$email->send('My message');

Comment: If you don't want to hardcode the email address you can use the Configure class to store the value, or a constant as the original poster.
Answer: I think adding it in front of the email adress would work :
if(!defined('EMAIL_FROM')) {
  define('EMAIL_FROM', 'Email Verification <firstname.lastname@example.com>');
}

Answer: I think this help you
$this->Email->from = Configure::read('FROM_EMAIL');

Send email with CakePHP


MSSQL 2008 R2 Update Error

Question: I've been getting the following error:
84B20001
"WindowsUpdate_84B20001" "WindowsUpdate_dt000"

I've tried just about everything but uninstall/reinstall which seems too much of a hassle.
I gave this a shot:

Uninstalled Logitech software and drivers for their webcam which had issues that was preventing SQL Server from installing because it would constantly say that there was a pending reboot needed to finish installing.
Cleaned up the registry where the Logitech install left junk that
was making the OS think that an existing install or update was still
in progress even after rebooting several times.
(a) Find the key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager
(b) Rename the PendingFileRenameOperations value to PendingFileRenameOperations2
(c) Restart your machine and then try again

What else can I do to get past this error when updating Microsoft SQL Server 2008 R2?
Comment: Which update are you trying to install?
Answer: One of the first things to try when any update for a Microsoft product does not work correctly is to download it straight from Microsoft's downloads web site and try it manually. SQL Server 2008 R2 SP1 is notorious for not installing correctly using the Windows Update control panel.
Download the full service pack that is right for your architecture. Once downloaded, install locally.
Comment: SQL Server Setup has encountered the following error:

A failure was detected for a previous installation, patch, or repair for instance 'MSSQLSERVER' during configuration for features [Analysis_Server_Full,]. In order to apply this patch package (KB2528583), you must resolve any issues with the previous operation that failed. View the summary.txt log to determine why the previous operation failed.

Error code 0x84B20001.

-- was worth a try.

MSSQL 2008 R2 Update Error


Aruco Marker World Coordinates

Question: I've been working with Python's OpenCV library, using ArUco for object tracking.
The goal is to get the x/y/z coordinates at the center of the ArUco marker, and the angle in relation to the calibrated camera.
I am able to display axes on the aruco marker with the code I have so far, but cannot find how to get x/y/z coordinates from the rotation and translation vectors (if that's even the right way to go about it).
This is the line of code which defines the rotation/translation vectors:
rvec, tvec, _ = aruco.estimatePoseSingleMarkers(corners, markerLength, camera_matrix, dist_coeffs) # For a single marker

Any ideas on how to get angle/marker position in the camera world?
Thanks!
Comment: tvec itself is the x/y/z coordinates of the marker in the coordinate system of the camera, and rvec is the rotation of the marker with respect to the camera (you could convert it to a 3x3 rotation matrix using Rodrigues()). Is this different to the result you are expecting?  You said the axes you draw line up correctly with the captured image, right?
Answer: After some tribulation, I found that the x and y coordinates in aruco can be determined by the average of the corners:
x = (corners[i-1][0][0][0] + corners[i-1][0][1][0] + corners[i-1][0][2][0] + corners[i-1][0][3][0]) / 4
y = (corners[i-1][0][0][1] + corners[i-1][0][1][1] + corners[i-1][0][2][1] + corners[i-1][0][3][1]) / 4

And the angle relative to the camera can be determined by the Rodrigues of the rotation vector, the matrix must be filled prior
rotM = np.zeros(shape=(3,3))
cv2.Rodrigues(rvec[i-1], rotM, jacobian = 0)

Finally, yaw pitch and roll can be obtained by taking the RQ Decompose of the rotation matrix
ypr = cv2.RQDecomp3x3(rotM)

Answer: As said by chungzuwalla, tvec represents the position of marker center in camera coordinate system and it doesn't change with the rotation of marker at a position. If you want to know about location of corners in camera coordinate system then one needs both rvec and tvec.
Here is a perfect explanation
Aruco markers with openCv, get the 3d corner coordinates?

Aruco Marker World Coordinates


Python code for searching .txt file. Print lines containing words in parantheses

Question: I think my regex function is wrong. I get an error. I want the program to read the .txt file line by line and print only lines which don't contain words in parenthesis.
Here is the code I used.
import os
infile=open("/Users/Julio/Desktop/database.txt", "r")

for line in infile:
    if not re.search('(')

     print(line, end='')

infile.close()

Comment: Read a basic [regex tutorial first](https://docs.python.org/2/howto/regex.html).
Comment: Thanks, I think that will help
Comment: I'm still not sure how to edit the code to make it work. Can someone point out what is wrong?
Comment: @JulioHans I do believe you have to add a second argument to re.search(). Try it, but I'm not too sure. `re.search('(', infile)`.
Comment: The title and third sentence contradict each other as to whether you want to print lines that do or do not contain whatever.  However, code difference will only be a `not` or not.
Answer: For something as simple matching a single character, why not just avoid regex and do something like:
with open("database.txt","rt") as f:
    for line in f:
        if "(" not in line:
            print(line)

Answer: A solution not using Regex, and looks for single words in parenthesis. Try to avoid using regex unless you have to.
for line in file_text.split("\n"):
    for word in line.split(" "):
        paren_flag = True if word[0] == "(" and word[len(word) - 1] == ")" else False
    if not paren_flag:
        print(line)

Some people, when confronted with a problem, think
  "I know, I'll use regular expressions."   Now they have two problems.

Note: I hope you were asking how to look for single words in parenthesis, because your question was/is unclear at the time of answering.
Comment: Thanks, I was looking for just "(". The parenthesis itself.
Comment: @JulioHans Ah, in that case you should edit you question to make that a little clearer. Maybe *"I want to see if a bracket is in a line"*?


Data - date_trunc para PHP

Question: O PostgreSQL possui uma função para data chamada date_trunc
Como posso reproduzi-la em PHP?
Necessito apenas dos opcionais:

second
minute
hour
day
week
month
quarter
year
Comment: O que `date_trunc` faz?
Comment: @rray eu uso ele na maioria das vezes para deixar as datas alinhadas por um período para apos aplicar no `GROUP BY`
Answer: Resolução
Funções Auxiliares
// REMOVE TUDO QUE NAO SEJA NUMERO, DA STRING
function onlyNumber($var){
    return preg_replace('/\D/', '', $var);
}

// AJUSTA OS NUMEROS A MASK PASSADA
function maskNumber($mask, $str){
    $str = onlyNumber($str);
    $return = '';

    for($i = 0, $j = 0; $i < strlen($mask); $i++){
        if($mask[$i] == '#' && isset($str[$j])){
            $return .= $str[$j++];
        }else{
            $return .= $mask[$i];
        }
    }

    return $return;
}

Função date_trunc
function date_trunc($field, $source){

    $source = maskNumber('####-##-## ##:##:##', $source);
    $source = str_replace('#', '0', $source);

    $date['year']   = 'Y-01-01 00:00:00';
    $date['mount']  = 'Y-m-01 00:00:00';
    $date['day']    = 'Y-m-d 00:00:00';

    $date['hour']   = 'Y-m-d H:00:00';
    $date['minute'] = 'Y-m-d H:i:00';
    $date['second'] = 'Y-m-d H:i:s';

    if(in_array($field, array_keys($date))){
        return date($date[$field], strtotime($source));
    }else{
        if($field == 'week'){
            return date($date['day'], strtotime("last Monday", strtotime($source)));
        }
        if($field == 'quarter'){
            $mount = explode('-', $source);
            $mount = $mount[1];
            $quarter = array(1=>'01',2=>'04',3=>'07',4=>'10');
            return date(sprintf('Y-%s-01 00:00:00', $quarter[ceil($mount/3)]), strtotime($source));
        }
        return date($date['day'], strtotime($source));
    }
}

Testes
date_trunc('day', '2015-10-30 14:48:15');       // 2015-10-30 00:00:00
date_trunc('week', '2015-10-30 14:48:15');      // 2015-10-26 00:00:00
date_trunc('mount', '2015-10-30 14:48:15');     // 2015-10-01 00:00:00
date_trunc('quarter', '2015-11-25 14:48:15');   // 2015-10-01 00:00:00
date_trunc('year', '2015-10-30 14:48:15');      // 2015-01-01 00:00:00

Data - date_trunc para PHP


Linking Content Types to Pages

Question: I have multiple content types like news, publications, etc and I will like to link them to pages on my site. So when a user posts a news item on a specific page, it only shows up on that page only. Also I will want users to be able to edit content on only pages they have been assigned to. Eg. A user will only be allowed to add news to pages they have rights to.
I was considering using groups for this, but I know more suggestions will be helpful.
Many thanks
Isacc
Answer: You can create different views and filter the content types.
Comment: Thanks John, but how do I restrict editing of the content types to only pages users have rights to?
Comment: you can use node_access module to restrict the content types/content

Linking Content Types to Pages


If $h(x) = \dfrac{f(x)}{g(x)}$, then find the local minimum value of $h(x)$

Question: Let $f(x) = x^2 + \dfrac{1}{x^2}$ and $g(x) = x – \dfrac{1}{x}$
, $x\in R – \{–1, 0, 1\}$. If $h(x) = \dfrac{f(x)}{g(x)}$, then the local minimum value
of $h(x)$ is :
My attempt is as follows:-
$$h(x)=\dfrac{x^2+\dfrac{1}{x^2}}{x-\dfrac{1}{x}}$$
$$h(x)=\dfrac{x^2+x^2-2+2}{x-\dfrac{1}{x}}$$
$$h(x)=x-\dfrac{1}{x}+\dfrac{2}{x-\dfrac{1}{x}}$$
Case $1$: $x-\dfrac{1}{x}>0$
$$\dfrac{x^2-1}{x}>0$$
$$x\in(-1,0) \cup (1,\infty)$$
$$AM\ge GM$$
$$\dfrac{x-\dfrac{1}{x}+\dfrac{2}{x-\dfrac{1}{x}}}{2}>\sqrt{2}$$
$$h(x)\ge 2\sqrt{2}$$
$$x-\dfrac{1}{x}=\dfrac{2}{x-\dfrac{1}{x}}$$
$$x^2+\dfrac{1}{x^2}-2=2$$
$$x^2+\dfrac{1}{x^2}=4$$
$$x^4-4x^2+1=0$$
$$x^2=2\pm\sqrt{3}$$
Only $x=\sqrt{2+\sqrt{3}},-\sqrt{2-\sqrt{3}}$ are the valid solutions.
Case $2$: $x-\dfrac{1}{x}<0$
$$x\in(-\infty,-1) \cup (0,1)$$
$$h(x)=-\left(\dfrac{1}{x}-x+\dfrac{2}{\dfrac{1}{x}-x}\right)$$
By $AM\ge GM$, $h(x)\ge-2\sqrt{2}$
We will get this minimum value at $-\sqrt{2+\sqrt{3}},\sqrt{2-\sqrt{3}}$
So answer should have been $-2\sqrt{2}$ but actual answer is $2\sqrt{2}$. What am I missing here.
Comment: In your question you write $h=fg$, then you proceed to write a solution for $h=f/g$.  Which is it?
Comment: You say that $h=fg$ but does the calculations using $h=f/g$. Either you made a typo on the statement of the problem or your solution is wrong from the first line.
Comment: sorry for trouble, it was a typo. I was not able to reply because my internet connection went off.
Answer:
Your calculation is fine, except the interpretation. Note that,
$$h(-\sqrt{2-\sqrt3}) = h(\sqrt{2+\sqrt3}) = 2\sqrt2$$
As seen from the plot, $2\sqrt2 $ at $-\sqrt{2-\sqrt3}$ and $\sqrt{2+\sqrt3}$ are the two local minima, while $-2\sqrt2 $ are the local maxima.
Comment: In Case $1$: $x\in(-1,0)\cup (1,\infty)$ and I think $x=\sqrt{2+\sqrt{3}},-\sqrt{2-\sqrt{3}}$ are the valid solutions.
Comment: @user3290550 - you're right, for $(1,\infty)$. Will correct.
Comment: yeah it is strange that at value at maxima is less than value at minima. I missed this possibility and thought that $-2\sqrt{2}$ there should be minima.
Comment: @user3290550 - yeah, it often happens with discontinuous functional range, such as here. it is always helpful to visualize it.
Answer: With $t:=x-\dfrac1x$
$$h(x)=\left(x^2+\frac1{x^2}\right)\left(x-\frac1x\right)=(t^2-1)t=t^3-2t.$$
Then by the chain rule
$$h'(x)=0\iff (3t^2-2)\left(1-\frac1{x^2}\right)=0.$$
We have the two solutions $x=\pm1$, and the solutions of
$$x-\frac1x=\pm\sqrt{\frac23},$$
which are
$$\dfrac{\pm\sqrt 6\pm\sqrt{42}}{6}.$$
Answer: Note that
$$\frac{f(x)}{g(x)}=\frac{(x-1/x)^2+2}{x-1/x}=x-\frac1x+2\frac{1}{x-\frac1x}.
$$
Letting $u=x-1/x$ we take the derivative of $u+2/u$ to get $u'-\frac{2}{u^2}u'=u'(1-2/u^2)=0$.  As $u'$ is always positive we must have $2=u^2=(x-1/x)^2$ which is easily solved; $x=\pm\sqrt{2\pm\sqrt3}$.
Comment: it was helpful by letting $u=x-\dfrac{1}{x}$, such a small thing but helps a lot, thanks.
Answer: If you are dealing with $h(x)=f(x)/g(x)$ then:
$$h'(x_0)=0=\frac{f'(x_0)g(x_0)-f(x_0)g'(x_0)}{[g(x_0)]^2}\to \frac{f'(x_0)}{g'(x_0)}=\frac{f(x_0)}{g(x_0)}   \quad \quad (1)$$
but, $f(x)=[g(x)]^2+2$, so
$$f'(x)=2g'(x)g(x)\to \frac{f'(x)}{g'(x)}=2g(x)\quad \quad (2)$$
From $(1)$ and $(2)$,
$$f(x_0)=2[g(x_0)]^2=[g(x_0)]^2+2$$
then,
$$g(x_0)=\pm \sqrt{2}=x_0-\frac{1}{x_0}$$
Can you finish?
Answer: Assuming that h(x)= f(x)/g(x), I would not actually calculate h itself.  Instead, use the "quotient rule": $\frac{h'(x)= f'(x)g(x)- f(x)g'(x)}{g^2(x)}$.  That will be 0 if and only if the numerator is 0: $f'(x)g(x)- f(x)g'(x)= 0$.
$f(x)= x^2+ x^{-2}$ so $f'(x)= 2x+ 2x^{-3}$, $g(x)= x- x^{-1}$ so $g'(x)= 1- x^{-2}$.
So $f'(x)g(x)- f(x)g'(x)= (2x+ 2x^{-3})(x- x^{-1})- (x^2+ x^{-2})(1- x^{-2})= 0$
Seeing that "$x^{-3}$ and $x^{-1}$ I would now multiply both sides by $x^4$ (of course x cannot be 0):
$(2x^4+ 2)(x^2- 2)- (x^4+ 1)(x^2- 1)= 2x^6- 4x^4+ 2x^2- 4- x^6+ x^4- x^2- 1= -3x^4+ x^3- 5= 0$.
Answer: Assuming that
$$h(x)=\frac{f(x)}{g(x)}\implies h'(x)=\frac{\left(x^2+1\right) \left(x^4-4 x^2+1\right)}{x^2 \left(x^2-1\right)^2}$$ Assuming $x\neq 0$ and $x\neq 1$ you are left with
$$x^4-4x^2+1=0 \implies (x^2)^2-4(x^2)+1=0$$ which is a quadratic in $x^2$.


ExtJS 5: displayfield binding performance

Question: I have a window that pops up for creating a new item... when I pass in the record for my bound fields, the dialog appears to lag significantly. The record is just a new record that I created, so it doesn't have any values associated to it, other than what the framework provides as defaults. In this example, I have 3 buttons:

The first one creates the dialog with the new record... this is the one with the most notable lag
The second one creates the dialog with no record, so updating the bound fields doesn't take place... the lag here is barely noticeable
The third one is using the passed in record to load up the field values through the form... the lag here is comparable to the 2nd one

It appears this performance issue has been addressed in the nightly builds for Ext JS 5 and 6, but I don't have time to upgrade to 6, and 5.1.3 isn't out yet... so basically, what am I doing wrong? Is there anything I can do to address this current issue (other than using the form)? Ideally I'd still be binding, as the table values are going to have to change dynamically.
Doing a little research, I came up with this SO thread, which does appear to alleviate some of the lag, if I change the displayfields to textfields, but I'd rather not do that, due to semantics.
Ext.define('HeaderView', {
  extend: 'Ext.panel.Panel',
  alias: 'widget.headerView',

  bodyPadding: '0 15',
  border: true,
  collapsible: true,
  layout: {
    type: 'hbox',
    align: 'stretch'
  },
  items: [{
    xtype: 'container',
    layout: {
      type: 'vbox',
      align: 'stretch'
    },
    margin: '0 20 0 0',
    width: 515,
    items: [{
      xtype: 'container',
      layout: {
        type: 'hbox',
        align: 'stretch'
      },
      height: 70,
      hidden: true,
      bind: {
        hidden: '{isNew}'
      },
      items: [{
        xtype: 'container',
        flex: 1,
        layout: {
          type: 'vbox',
          align: 'stretch'
        },
        defaults: {
          xtype: 'displayfield',
          flex: 1,
          cls: 'tightened-form-field'
        },
        items: [{
          fieldLabel: 'Status',
          bind: {
            value: '{currentRecord.Status}'
          }
        }, {
          fieldLabel: 'Condition',
          bind: {
            value: '{currentRecord.StatusCombinedCondition}'
          }
        }, {
          fieldLabel: 'Type',
          bind: {
            value: '{currentRecord.Type}'
          }
        }]
      }, {
        xtype: 'container',
        flex: 1,
        layout: {
          type: 'vbox',
          align: 'stretch'
        },
        defaults: {
          xtype: 'displayfield',
          flex: 1,
          cls: 'tightened-form-field'
        },
        items: [{
          fieldLabel: 'Status Date',
          bind: {
            value: '{currentRecord.StatusDate}'
          }
        }, {
          fieldLabel: 'Create Date',
          bind: {
            value: '{currentRecord.CreateDate}'
          }
        }, {
          fieldLabel: 'Number',
          bind: {
            value: '{currentRecord.Number}'
          }
        }]
      }]
    }, {
      xtype: 'container',
      flex: 1,
      layout: {
        type: 'vbox',
        align: 'stretch'
      },
      defaults: {
        xtype: 'container',
        cls: 'summary-table',
        layout: {
          type: 'hbox',
          align: 'stretch'
        },
        defaults: {
          flex: 1,
          xtype: 'displayfield',
          cls: 'right-align-field'
        }
      },
      items: [{
        cls: '',
        items: [{
          value: '',
          cls: 'table-header'
        }, {
          value: 'Missed',
          cls: 'table-header status-text-error-background'
        }, {
          value: 'Offered',
          cls: 'table-header status-text-success-background'
        }, {
          value: 'Difference',
          cls: 'table-header status-text-new-background'
        }, {
          value: 'Old Total',
          cls: 'table-header status-text-error-background'
        }, {
          value: 'New Total',
          cls: 'table-header status-text-success-background'
        }]
      }, {
        items: [{
          value: 'Total'
        }, {
          renderer: Ext.util.Format.usMoney,
          bind: {
            value: '{currentRecord.ValueTotal1}'
          }
        }, {
          renderer: Ext.util.Format.usMoney,
          bind: {
            value: '{currentRecord.ValueTotal2}'
          }
        }, {
          renderer: Ext.util.Format.usMoney,
          bind: {
            value: '{currentRecord.ValueTotal3}'
          }
        }, {
          renderer: Ext.util.Format.usMoney,
          bind: {
            value: '{currentRecord.ValueTotal4}'
          }
        }, {
          renderer: Ext.util.Format.usMoney,
          bind: {
            value: '{currentRecord.ValueTotal5}'
          }
        }]
      }, {
        items: [{
          value: '# Things'
        }, {
          bind: {
            value: '{currentRecord.CountTotal1}'
          }
        }, {
          bind: {
            value: '{currentRecord.CountTotal2}'
          }
        }, {
          bind: {
            value: '{currentRecord.CountTotal3}'
          }
        }, {
          bind: {
            value: '{currentRecord.CountTotal4}'
          }
        }, {
          bind: {
            value: '{currentRecord.CountTotal5}'
          }
        }]
      }, {
        items: [{
          value: 'Points'
        }, {
          bind: {
            value: '{currentRecord.Points1}'
          }
        }, {
          bind: {
            value: '{currentRecord.Points2}'
          }
        }, {
          bind: {
            value: '{currentRecord.Points3}'
          }
        }, {
          bind: {
            value: '{currentRecord.Points4}'
          }
        }, {
          bind: {
            value: '{currentRecord.Points5}'
          }
        }]
      }, {
        items: [{
          value: 'Cost'
        }, {
          renderer: Ext.util.Format.usMoney,
          bind: {
            value: '{currentRecord.Cost1}'
          }
        }, {
          renderer: Ext.util.Format.usMoney,
          bind: {
            value: '{currentRecord.Cost2}'
          }
        }, {
          renderer: Ext.util.Format.usMoney,
          bind: {
            value: '{currentRecord.Cost3}'
          }
        }, {
          renderer: Ext.util.Format.usMoney,
          bind: {
            value: '{currentRecord.Cost4}'
          }
        }, {
          renderer: Ext.util.Format.usMoney,
          bind: {
            value: '{currentRecord.Cost5}'
          }
        }]
      }]
    }]
  }, {
    xtype: 'container',
    maxWidth: 450,
    flex: 1,
    layout: {
      type: 'vbox',
      align: 'stretch'
    },
    items: [{
      xtype: 'textarea',
      name: 'Comment',
      fieldLabel: 'Comment',
      flex: 1,
      bind: {
        disabled: '{!isNew}'
      }
    }, {
      xtype: 'textarea',
      name: 'RejectReason',
      fieldLabel: 'Reject Comment',
      height: 70,
      flex: 1,
      hidden: true,
      bind: {
        hidden: '{isNew}',
        disabled: '{!isNew}'
      }
    }]
  }]
});
Ext.define('HeaderViewForm', {
  extend: 'Ext.form.Panel',
  alias: 'widget.headerViewForm',

  bodyPadding: '0 15',
  border: true,
  collapsible: true,
  layout: {
    type: 'hbox',
    align: 'stretch'
  },
  items: [{
    xtype: 'container',
    layout: {
      type: 'vbox',
      align: 'stretch'
    },
    margin: '0 20 0 0',
    width: 515,
    items: [{
      xtype: 'container',
      layout: {
        type: 'hbox',
        align: 'stretch'
      },
      height: 70,
      hidden: true,
      bind: {
        hidden: '{isNew}'
      },
      items: [{
        xtype: 'container',
        flex: 1,
        layout: {
          type: 'vbox',
          align: 'stretch'
        },
        defaults: {
          xtype: 'displayfield',
          flex: 1,
          cls: 'tightened-form-field'
        },
        items: [{
          fieldLabel: 'Status',
            name: 'Status'
        }, {
          fieldLabel: 'Condition',
            name: 'StatusCombinedCondition'
        }, {
          fieldLabel: 'Type',
            name: 'Type'
        }]
      }, {
        xtype: 'container',
        flex: 1,
        layout: {
          type: 'vbox',
          align: 'stretch'
        },
        defaults: {
          xtype: 'displayfield',
          flex: 1,
          cls: 'tightened-form-field'
        },
        items: [{
          fieldLabel: 'Status Date',
            name: 'StatusDate'
        }, {
          fieldLabel: 'Create Date',
            name: 'CreateDate'
        }, {
          fieldLabel: 'Number',
            name: 'Number'
        }]
      }]
    }, {
      xtype: 'container',
      flex: 1,
      layout: {
        type: 'vbox',
        align: 'stretch'
      },
      defaults: {
        xtype: 'container',
        cls: 'summary-table',
        layout: {
          type: 'hbox',
          align: 'stretch'
        },
        defaults: {
          flex: 1,
          xtype: 'displayfield',
          cls: 'right-align-field'
        }
      },
      items: [{
        cls: '',
        items: [{
          value: '',
          cls: 'table-header'
        }, {
          value: 'Missed',
          cls: 'table-header status-text-error-background'
        }, {
          value: 'Offered',
          cls: 'table-header status-text-success-background'
        }, {
          value: 'Difference',
          cls: 'table-header status-text-new-background'
        }, {
          value: 'Old Total',
          cls: 'table-header status-text-error-background'
        }, {
          value: 'New Total',
          cls: 'table-header status-text-success-background'
        }]
      }, {
        items: [{
          value: 'Total'
        }, {
          renderer: Ext.util.Format.usMoney,
            name: 'ValueTotal1'
        }, {
          renderer: Ext.util.Format.usMoney,
            name: 'ValueTotal2'
        }, {
          renderer: Ext.util.Format.usMoney,
            name: 'ValueTotal3'
        }, {
          renderer: Ext.util.Format.usMoney,
            name: 'ValueTotal4'
        }, {
          renderer: Ext.util.Format.usMoney,
            name: 'ValueTotal5'
        }]
      }, {
        items: [{
          value: '# Things'
        }, {
            name: 'CountTotal1'
        }, {
            name: 'CountTotal2'
        }, {
            name: 'CountTotal3'
        }, {
            name: 'CountTotal4'
        }, {
            name: 'CountTotal5'
        }]
      }, {
        items: [{
          value: 'Points'
        }, {
            name: 'Points1'
        }, {
            name: 'Points2'
        }, {
            name: 'Points3'
        }, {
            name: 'Points4'
        }, {
            name: 'Points5'
        }]
      }, {
        items: [{
          value: 'Cost'
        }, {
            name: 'Cost1',
          renderer: Ext.util.Format.usMoney
        }, {
            name: 'Cost2',
          renderer: Ext.util.Format.usMoney
        }, {
            name: 'Cost3',
          renderer: Ext.util.Format.usMoney
        }, {
            name: 'Cost4',
          renderer: Ext.util.Format.usMoney
        }, {
            name: 'Cost5',
          renderer: Ext.util.Format.usMoney
        }]
      }]
    }]
  }, {
    xtype: 'container',
    maxWidth: 450,
    flex: 1,
    layout: {
      type: 'vbox',
      align: 'stretch'
    },
    items: [{
      xtype: 'textarea',
      name: 'Comment',
      fieldLabel: 'Comment',
      flex: 1,
      bind: {
        disabled: '{!isNew}'
      }
    }, {
      xtype: 'textarea',
      name: 'RejectReason',
      fieldLabel: 'Reject Comment',
      height: 70,
      flex: 1,
      hidden: true,
      bind: {
        hidden: '{isNew}',
        disabled: '{!isNew}'
      }
    }]
  }]
});

Ext.define('MyModel', {
    extend: 'Ext.data.Model',
    fields: [{
        name: 'Status',
        type: 'string'
    }, {
        name: 'StatusCombinedCondition',
        type: 'string'
    }, {name: 'Type', type: 'string'},
{name: 'StatusDate', type: 'string'},
{name: 'CreateDate', type: 'string'},
{name: 'Number', type: 'string'},
{name: 'ValueTotal1', type: 'string'},
{name: 'ValueTotal2', type: 'string'},
{name: 'ValueTotal3', type: 'string'},
{name: 'ValueTotal4', type: 'string'},
{name: 'ValueTotal5', type: 'string'},
{name: 'CountTotal1', type: 'string'},
{name: 'CountTotal2', type: 'string'},
{name: 'CountTotal3', type: 'string'},
{name: 'CountTotal4', type: 'string'},
{name: 'CountTotal5', type: 'string'},
{name: 'Points1', type: 'string'},
{name: 'Points2', type: 'string'},
{name: 'Points3', type: 'string'},
{name: 'Points4', type: 'string'},
{name: 'Points5', type: 'string'},
{name: 'Cost1', type: 'string'},
{name: 'Cost2', type: 'string'},
{name: 'Cost3', type: 'string'},
{name: 'Cost4', type: 'string'},
{name: 'Cost5', type: 'string'},
{name: 'Comment', type: 'string'},
{name: 'RejectReason', type: 'string'}]
});

Ext.define('MyController', {
    extend: 'Ext.app.ViewController',
    alias: 'controller.myView',
    init: function() {
        var me = this;
        // push onto call stack to let view model breathe
        setTimeout(function() {
            me.getView().setLoading(false);
        }, 1)
    }
})

Ext.application({
    name : 'Fiddle',

    launch : function() {
        Ext.create('Ext.button.Button', {
            text: 'currentRecord',
            renderTo: Ext.getBody(),
            listeners: {
                click: function() {
                    Ext.create('Ext.window.Window', {
                        height: 500,
                        width: 500,
                        autoShow: true,
                        layout: 'fit',
                        items: [{
                            xtype: 'headerView',
                            height: 500,
                            width: 500
                        }],
                        listeners: {
                            afterrender: function(view) {
                                view.setLoading(true)
                            }
                        },
                        viewModel: {
                            data: {
                                isNew: false,
                                currentRecord: Ext.create('MyModel')
                            }
                        },
                        controller: 'myView'
                    })
                }
            }
        })
        Ext.create('Ext.button.Button', {
            text: 'no currentRecord',
            renderTo: Ext.getBody(),
            listeners: {
                click: function() {
                    Ext.create('Ext.window.Window', {
                        height: 500,
                        width: 500,
                        autoShow: true,
                        layout: 'fit',
                        items: [{
                            xtype: 'headerView',
                            height: 500,
                            width: 500
                        }],
                        listeners: {
                            afterrender: function(view) {
                                view.setLoading(true)
                            }
                        },
                        viewModel: {
                            data: {
                                isNew: false
                            }
                        },
                        controller: 'myView'
                    })
                }
            }
        })
        Ext.create('Ext.button.Button', {
            text: 'currentRecord form',
            renderTo: Ext.getBody(),
            listeners: {
                click: function() {
                    var myModel = Ext.create('MyModel');
                    console.log(myModel)
                    Ext.create('Ext.window.Window', {
                        height: 500,
                        width: 500,
                        autoShow: true,
                        layout: 'fit',
                        items: [{
                            xtype: 'headerViewForm',
                            height: 500,
                            width: 500,
                            bind: {
                                currentRecord: '{currentRecord}'
                            },
                            setCurrentRecord: function(record) {
                                console.log(record)
                                if (record) {
                                    this.loadRecord(record)
                                }
                            }
                        }],
                        listeners: {
                            afterrender: function(view) {
                                view.setLoading(true)
                            }
                        },
                        viewModel: {
                            data: {
                                isNew: false,
                                currentRecord: myModel
                            }
                        },
                        controller: 'myView'
                    })
                }
            }
        })
    }
});

Answer: Another solution I came up with was based on this SO thread, but I just extended on the css there... removed the borders, cursor, etc.  It's not ideal, but it definitely gets the job done.
Ext.define('FauxDisplayField', {
    extend: 'Ext.form.field.Text',
    alias: 'widget.fauxDisplayField',
    readOnly: true,
    tabIndex: -1,
    componentCls: 'faux-display-field'
});

.faux-display-field .x-form-trigger-wrap {
    border: none;
}

.faux-display-field input {
    text-shadow: 0 0 0 black; /* makes text show up without cursor */
    color: transparent; /* makes blinking cursor invisible */
    cursor: default;
    background-color: transparent;
    text-align: right;
}

Answer: One of the Sencha devs suggested this as a solution:
Ext.define('Foo', {
    override: 'Ext.util.Scheduler',

    notify: function() {
        Ext.suspendLayouts();
        this.callParent();
        Ext.resumeLayouts(true);
    }
});


RecyclerView items not changing visibility all at once

Question: I'm trying to show or hide my RecyclerView items whenever a particular button is clicked but for some reason nothing happens. I even tried using adapter.notifyDataSetChanged();. What needs to be fixed so that ALL of the items within this RecyclerView become visible or gone when the neccessary button (Expand All or Collapse All) is clicked?

public class MyFragment extends android.support.v4.app.Fragment {
    private static final String TAG = MyActivity.class.getSimpleName();

    public Boolean isSupposedToBeCollapsed;
    private static final int ITEM_TYPE = 100;
    private static final int HEADER_TYPE = 101;
    private static final int HEADER_TYPE_2 = 102;
    private static final int INTRO_TYPE = 103;

    public MyFragment() {}

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_rv, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        View v = getView();
        assert v != null;

        recyclerView = v.findViewById(R.id.my_recyclerview);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));

        // SpannableStrings
        int[] attrS = {R.attr.spannablestringtextColor};
        TypedArray ta = getActivity().getTheme().obtainStyledAttributes(attrS);
        int colorSS = ta.getColor(0, Color.BLACK); //Color.BLACK - default value (colour will change automatically depending on chosen theme)
        Log.d(TAG, "clickMethod 1) " + Integer.toHexString(colorSS));
        ta.recycle();

        // SpannableString (start)
        SpannableStringBuilder ssb1 = new SpannableStringBuilder();

        SpannableString str1a = new SpannableString(getString(R.string.placeholder1_placeholder2_placeholder3,
                " ", getString(R.string.title_1a), " "));
        str1a.setSpan(new BackgroundColorSpan(Color.BLACK), 0, str1a.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        str1a.setSpan(new ForegroundColorSpan(ContextCompat.getColor(getContext(), R.color.yellow)), 0, str1a.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        ssb1.append(str1a);

        SpannableString str1b = new SpannableString(" " + getString(R.string.title_1b));
        str1b.setSpan(new ForegroundColorSpan(colorSS), 0, str1b.length(), 0);
        ssb1.append(str1b);
        // SpannableString (end)

        // SpannableString (start)
        SpannableStringBuilder ssb2 = new SpannableStringBuilder();

        SpannableString str2a = new SpannableString(getString(R.string.title_2a));
        str2a.setSpan(new BackgroundColorSpan(Color.BLACK), 0, str2a.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        str2a.setSpan(new ForegroundColorSpan(ContextCompat.getColor(getContext(), R.color.yellow)), 0, str2a.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        ssb2.append(str2a);

        SpannableString str2b = new SpannableString(", " + getString(R.string.title_2b));
        str2b.setSpan(new ForegroundColorSpan(colorSS), 0, str2b.length(), 0);
        ssb2.append(str2b);
        // SpannableString (end)

        // init data
        dataTitle = new ArrayList<>();
        dataTitle.add(ssb1);
        dataTitle.add(ssb2);
        dataTitle.add(getString(R.string.title_c));
        dataTitle.add(getString(R.string.title_d));

        dataSubtitle = new ArrayList<>();
        dataSubtitle.add(getString(R.string.subtitle_a));
        dataSubtitle.add(getString(R.string.subtitle_b));
        dataSubtitle.add(getString(R.string.subtitle_c));
        dataSubtitle.add(getString(R.string.subtitle_d));

        dataDescription = new ArrayList<>();
        dataDescription.add(getString(R.string.description_a));
        dataDescription.add(getString(R.string.description_b));
        dataDescription.add(getString(R.string.description_c));
        dataDescription.add(getString(R.string.description_d));

        adapter = createAdapter();

        recyclerView.setAdapter(adapter);

        super.onActivityCreated(savedInstanceState);
    }

    RecyclerView recyclerView;
    ArrayList<CharSequence> dataTitle;
    ArrayList<String> dataSubtitle;
    ArrayList<String> dataDescription;
    RecyclerView.Adapter<MyFragment.ViewHolder> adapter;

    // creates the adapter
    private RecyclerView.Adapter<MyFragment.ViewHolder> createAdapter() {
        return new RecyclerView.Adapter<TabFragmentWATTerminus.ViewHolder>() {
            public Boolean expandedAll;
            public Boolean collapsedAll;

            @NonNull
            @Override
            public MyFragment.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int type) {
                switch (type) {
                    case HEADER_TYPE:
                        return new MyFragment.ViewHolder(inflateHelper(R.layout.recyclerview_header, parent));

                    case HEADER_TYPE_2:
                        return new MyFragment.ViewHolder(inflateHelper(R.layout.recyclerview_header, parent));

                    case ITEM_TYPE:
                        return new MyFragment.ViewHolder(inflateHelper(R.layout.recyclerview_item_tv_itemtype, parent));

                    case INTRO_TYPE:
                        return new MyFragment.ViewHolder(inflateHelper(R.layout.recyclerview_item_tv_intro, parent));

                    default:
                        return new TabFragmentWATTerminus.ViewHolder(inflateHelper(R.layout.recyclerview_item_tv_itemtype, parent));
                }
            }

            @Override
            public void onBindViewHolder(@NonNull final MyFragment.ViewHolder viewHolder, int position) {
                final Typeface iconFont = FontManager.getTypeface(getContext(), FontManager.FONTAWESOME);

                final RelativeLayout rlInformation = viewHolder.itemView.findViewById(R.id.rl_information);

                switch (getItemViewType(position)) {
                    case HEADER_TYPE:
                        Button expandButton = viewHolder.itemView.findViewById(R.id.button);
                        expandButton.setText(R.string.expand_all);

                    expandButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if(expandedAll){
                                expandedAll = true;
                                expandRL(rlInformation, txtArrowTV);
                                adapter.notifyDataSetChanged();
                            } else if(collapsedAll){
                                collapsedAll = true;
                                collapseRL(rlInformation, txtArrowTV);
                                adapter.notifyDataSetChanged();
                            }
                        }
                    });

                        break;
                    case HEADER_TYPE_2:
                        Button collapseButton = viewHolder.itemView.findViewById(R.id.button);
                        collapseButton.setText(R.string.collapse_all);

                        collapseButton.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                            if(rlInformation.getVisibility() == View.VISIBLE){                                                                                collapseRL(rlInformation, txtArrowTV);
                                    adapter.notifyDataSetChanged();
                            }
                        });
                        break;
                    case INTRO_TYPE:
                        TextView tvIntroA = viewHolder.itemView.findViewById(R.id.tv_placeholder;
                        tvIntroA.setVisibility(View.GONE);
                        break;
                    case ITEM_TYPE:
                        // get the current item
                        CharSequence itemA = dataTitle.get(position - 3);
                        String itemB = dataSubtitle.get(position - 3);
                        String itemC = dataDescription.get(position - 3);

                        //
                        final TextView txtTitle = viewHolder.itemView.findViewById(R.id.tv_title);
                        txtTitle.setText(itemA);

                        final TextView txtSubtitle = viewHolder.itemView.findViewById(R.id.tv_subtitle);
                        txtSubtitle.setText(itemB);

                        final TextView txtDescription = viewHolder.itemView.findViewById(R.id.tv_description);
                        txtDescription.setText(itemC);

                        final TextView txtArrowTV = viewHolder.itemView.findViewById(R.id.tv_expandcollapsearrow);
                        txtArrowTV.setText(R.string.fa_icon_chevron_down);
                        txtArrowTV.setTypeface(iconFont);

//                        final RelativeLayout rlInformation = viewHolder.itemView.findViewById(R.id.rl_information);
                        rlInformation.setVisibility(View.GONE);

                        //
                        CardView cardView = viewHolder.itemView.findViewById(R.id.cardview_item);
                        LinearLayout mLinearLayoutTV = viewHolder.itemView.findViewById(R.id.cardview_titlerow);

                        //
                        cardView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if(rlInformation.getVisibility() == View.GONE){
                                    expandRL(rlInformation, txtArrowTV);
                                } else {
                                    collapseRL(rlInformation, txtArrowTV);
                                }
                            }
                        });

                        mLinearLayoutTV.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if(rlInformation.getVisibility() == View.GONE){
                                    expandRL(rlInformation, txtArrowTV);
                                } else {
                                    collapseRL(rlInformation, txtArrowTV);
                                }
                            }
                        });

                        txtArrowTV.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if(rlInformation.getVisibility() == View.GONE){
                                    expandRL(rlInformation, txtArrowTV);
                                } else {
                                    collapseRL(rlInformation, txtArrowTV);
                                }
                            }
                        });
                        break;
                }
            }

            @Override
            public int getItemCount() {
                return dataTitle.size() + 3;
            }

            @Override
            public int getItemViewType(int position) {
                switch (position) {
                    case 0:
                        return HEADER_TYPE;
                    case 1:
                        return HEADER_TYPE_2;
                    case 2:
                        return INTRO_TYPE;
                    default: return ITEM_TYPE;
                }
            }
        };
    }

    private View inflateHelper(int resId, ViewGroup parent) {
        return LayoutInflater.from(getActivity()).inflate(resId, parent, false);
    }

    // inner class for viewholder to use,
    class ViewHolder extends RecyclerView.ViewHolder {
        ViewHolder(@NonNull View itemView) {
            super(itemView);
        }
    }

    public void expandRL(final RelativeLayout rlInformation, final TextView txtArrowTV) {
        rlInformation.setVisibility(View.VISIBLE);
        txtArrowTV.setText(R.string.fa_icon_chevron_up);
    }

    public void collapseRL(final RelativeLayout rlInformation, final TextView txtArrowTV) {
        rlInformation.setVisibility(View.GONE);
        txtArrowTV.setText(R.string.fa_icon_chevron_down);
    }
}

Comment: If this is the updated code, you're not actually doing anything when `expandButton` is clicked. You're just calling `notifyDataSetChanged()`. You need to actually call your expand functions.
Comment: TheWanderer is right, besides `notifyDataSetChanged()` updates if any changes is reflected on the recyclerView. But, right now there are not many changes to call it anyway.
Comment: @UmangBurman code updated (was supposed to be there first) but nothing happens
Comment: How are you expanding the `RelativeLayout` ? You seem to just set the visibility.
Comment: @UmangBurman Setting the visibility is what i meant. What I am Expanding/Collapsing is the CardView that the RelativeLayout is in.
Comment: @UmangBurman I have edited/rephrased the question
Comment: Okay, are you sure that `case HEADER_TYPE:` and `case HEADER_TYPE_2:` is been called. May be the click listeners are not being registered at all. so they arn't performing any actions. Try adding a `Toast` in the button's click to see if the are working.
Comment: @UmangBurman I did try that before asking this question it worked perfectly fine.
Answer: It's a bit hard to edit the code in answer because the braces are not pair. Anyway, you should define two boolean fields in the adapter class (for example expandedAll and collapsedAll). In click listener of collapseButton and expandButton, set correct value for expandedAll and collapsedAll then call notifyDataSetChanged(). After that in onBindViewHolder when view type is ITEM_TYPE, check the value of expandedAll and collapsedAll:
In MyFragment:
private RecyclerView.Adapter<MyFragment.ViewHolder> createAdapter() {
    return new MyAdapter(dataTitle, dataSubtitle, dataDescription);
}

MyAdapter.java:
public class MyAdapter extends RecyclerView.Adapter<MyFragment.ViewHolder> {

    public static final int ITEM_TYPE = 100;
    public static final int HEADER_TYPE = 101;
    public static final int HEADER_TYPE_2 = 102;
    public static final int INTRO_TYPE = 103;

    private ArrayList<CharSequence> dataTitle;
    private ArrayList<String> dataSubtitle;
    private ArrayList<String> dataDescription;

    private Boolean expandedAll;
    private Boolean collapsedAll;

    public MyAdapter(ArrayList<CharSequence> dataTitle, ArrayList<String> dataSubtitle, ArrayList<String> dataDescription) {
        this.dataTitle = dataTitle;
        this.dataSubtitle = dataSubtitle;
        this.dataDescription = dataDescription;
    }

    @NonNull
    @Override
    public MyFragment.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int type) {
        switch (type) {
            case HEADER_TYPE:
                return new MyFragment.ViewHolder(inflateHelper(parent.getContext(), R.layout.recyclerview_header, parent));

            case HEADER_TYPE_2:
                return new MyFragment.ViewHolder(inflateHelper(parent.getContext(), R.layout.recyclerview_header, parent));

            case ITEM_TYPE:
                return new MyFragment.ViewHolder(inflateHelper(parent.getContext(), R.layout.recyclerview_item_tv_itemtype, parent));

            case INTRO_TYPE:
                return new MyFragment.ViewHolder(inflateHelper(parent.getContext(), R.layout.recyclerview_item_tv_intro, parent));

            default:
                return new TabFragmentWATTerminus.ViewHolder(inflateHelper(parent.getContext(), R.layout.recyclerview_item_tv_itemtype, parent));
        }
    }

    @Override
    public void onBindViewHolder(@NonNull MyFragment.ViewHolder viewHolder, int position) {
        final Typeface iconFont = FontManager.getTypeface(getContext(), FontManager.FONTAWESOME);
        final RelativeLayout rlInformation = viewHolder.itemView.findViewById(R.id.rl_information);

        switch (getItemViewType(position)) {
            case HEADER_TYPE:
                Button expandButton = viewHolder.itemView.findViewById(R.id.button);
                expandButton.setText(R.string.expand_all);

                expandButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        expandedAll = true;
                        collapsedAll = false;
                        notifyDataSetChanged();
                    }
                });

                break;
            case HEADER_TYPE_2:
                Button collapseButton = viewHolder.itemView.findViewById(R.id.button);
                collapseButton.setText(R.string.collapse_all);

                collapseButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        expandedAll = false;
                        collapsedAll = true;
                        notifyDataSetChanged();
                    }
                });
                break;
            case INTRO_TYPE:
                TextView tvIntroA = viewHolder.itemView.findViewById(R.id.tv_placeholder;
                tvIntroA.setVisibility(View.GONE);
                break;
            case ITEM_TYPE:
                // get the current item
                CharSequence itemA = dataTitle.get(position - 3);
                String itemB = dataSubtitle.get(position - 3);
                String itemC = dataDescription.get(position - 3);

                //
                final TextView txtTitle = viewHolder.itemView.findViewById(R.id.tv_title);
                txtTitle.setText(itemA);

                final TextView txtSubtitle = viewHolder.itemView.findViewById(R.id.tv_subtitle);
                txtSubtitle.setText(itemB);

                final TextView txtDescription = viewHolder.itemView.findViewById(R.id.tv_description);
                txtDescription.setText(itemC);

                final TextView txtArrowTV = viewHolder.itemView.findViewById(R.id.tv_expandcollapsearrow);
                txtArrowTV.setText(R.string.fa_icon_chevron_down);
                txtArrowTV.setTypeface(iconFont);

//                        final RelativeLayout rlInformation = viewHolder.itemView.findViewById(R.id.rl_information);
                rlInformation.setVisibility(View.GONE);

                //
                CardView cardView = viewHolder.itemView.findViewById(R.id.cardview_item);
                LinearLayout mLinearLayoutTV = viewHolder.itemView.findViewById(R.id.cardview_titlerow);

                //
                cardView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (rlInformation.getVisibility() == View.GONE) {
                            expandRL(rlInformation, txtArrowTV);
                        } else {
                            collapseRL(rlInformation, txtArrowTV);
                        }
                    }
                });

                mLinearLayoutTV.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (rlInformation.getVisibility() == View.GONE) {
                            expandRL(rlInformation, txtArrowTV);
                        } else {
                            collapseRL(rlInformation, txtArrowTV);
                        }
                    }
                });

                txtArrowTV.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (rlInformation.getVisibility() == View.GONE) {
                            expandRL(rlInformation, txtArrowTV);
                        } else {
                            collapseRL(rlInformation, txtArrowTV);
                        }
                    }
                });

                if (expandedAll) {
                    expandRL(rlInformation, txtArrowTV);
                } else if (collapsedAll) {
                    collapseRL(rlInformation, txtArrowTV);
                }

                break;
        }
    }

    @Override
    public int getItemCount() {
        return dataTitle.size() + 3;
    }

    @Override
    public int getItemViewType(int position) {
        switch (position) {
            case 0:
                return HEADER_TYPE;
            case 1:
                return HEADER_TYPE_2;
            case 2:
                return INTRO_TYPE;
            default:
                return ITEM_TYPE;
        }
    }

    private View inflateHelper(Context context, int resId, ViewGroup parent) {
        return LayoutInflater.from(context).inflate(resId, parent, false);
    }

}

Above solution solves expand and collapse all problem, but another problem still there. You should maintain a boolean for each item that shows the item is collapsed or expanded.
I have handled the expansion of RecyclerView items in an open source library named PrimeAdapter. (It has android java sample app) I recommend you to use it if you like. It makes your code so simpler.
Comment: I've updated my code but I think I've slipped up somewhere. ALso, I don't know the correct way to check the value of  `expandedAll` and  `collapsedAll` in the  `onBindViewHolder` section.
Comment: Ok, I'm checking it.
Comment: Does `MyAdapter.java` go in its own java file?
Comment: Yes, it's so better to spread code in distinct classes and files.
Comment: `inflateHelper` in `MyFragment.ViewHolder(` returns an error: `Cannot resolve method 'inflateHelper(int, android.view.ViewGroup)'`
Comment: I've added `inflateHelper` method in bottom of `MyAdapter` class and changed `onCreateViewHolder` method consequently.
Comment: In `onCreateViewHolder` this error now appears: `Cannot resolve symbol 'parent'`
Comment: Note that I pass `parent.getContext()` to `inflateHelper` as first argument in `onCreateViewHolder` that you forgot it.
Comment: Okay. That app runs but it crashes when I launch the fragment: `java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Boolean.booleanValue()' on a null object reference` then `(MyAdapter.java:161)` points to this line: `if (expandedAll) {expandRL(rlInformation, txtArrowTV);} else if (collapsedAll) {collapseRL(rlInformation, txtArrowTV);}`, even though my `Boolean`s have clearly been declared
Comment: See my latest screenshot
Comment: Ok, I'll see it.
Comment: Change the `Boolean` to `boolean`.


Consulta SQL/Java

Question: Bom dia, galera sou iniciante em SQL e preciso fazer a seguinte busca.
Tenho esta tabela:
MINIMO    MAXIMO      CLASSE
    0        20         1
    21       40         2
    41       60         3
    60       10000      4

Preciso de um comando para ver qual classe se encaixa o número 32. Mais precisamente estou usando o ORMLITE no Java
Comment: Tenta isso: seuDAO.queryBuilder().selectColumns("name").where().le("minimo", 32).and().ge("maximo", 32);
Comment: Alguma resposta ajudou a resolver o problema e pode sanar dúvidas similares de outros usuários? Caso positivo não esqueça de marcar a resposta como aceita. Pra fazer isso é só clicar no ✓ do lado esquerdo da mesma (abaixo do indicador de up e down votes).
Answer: Considerando que você está utilizando o OrmLite e que você quer um resultado semelhante a:
SELECT classe
  FROM tabela
 WHERE 32 BETWEEN minimo AND maximo

Precisaremos criar uma query usando o queryBuilder do Dao. Segundo a documentação do where teremos:
Dao<Tabela, String> dao;
List<Tabela> resultados;

dao = DaoManager.createDao(conexao, Tabela.class);
resultados = dao.queryBuilder()
        .where()
        .le("minimo", 32)
        .and()
        .ge("maximo", 32)
        .query();

for (Tabela tabela : resultados) {
  System.out.println(tabela.getClasse());
}

le adiciona uma cláusula '<=' para que a coluna seja menor-que ou igual ao valor.
ge adiciona uma cláusula '>=' para que a coluna seja maior-que ou igual ao valor.
Answer: Você pode fazer assim:
SELECT `CLASSE` FROM `nome_da_tabela` WHERE `MINIMO` <= 30 AND `MAXIMO`  >= 30;

Comment: pesquise também BETWEEN
Comment: Na realidade ele especificou que está usando ORMLITE, ou seja, não é uma query exatamente que ele quer

Consulta SQL/Java


str_replace() with a full web page as the subject

Question: I'm trying to use str_replace() to search and replace specific strings in html pages. For example, I am replacing:
$search_string = 'The new funding follows a $40 million raise announced in January.';

with
$replacement = 'The new funding follows a $40 million raise announced in January.';

$subject = file_get_contents("some-web-site.html");

$new_string = str_replace($search_string, $replacement, $subject);

However, the replacement doesn't work, when $subject contains a lot of html. If i just do:
$subject = "some text some text " .  $search_string . "some text some text";

the sentence is correctly replaced. The issue seems to arise specifically due to the   element.. if the $search_string does not contain   then it will be replaced successfully no matter the complexity of the $subject element (i.e. even if it contains a full web page).
Any idea why is that ?
Comment: Are you using `preg_replace` or `str_replace`? You mention both. Doing `str_replace` with something like `" "` seems to work fine for me. `preg_replace` could be failing because it's coming across unescaped metacharacters, e.g. `&`.
Comment: Sorry for the confusion, I am using str_replace everywhere. But I would use preg_replace if it can solve the problem
Comment: Possible duplicate of [RegEx with preg\_match to find and replace a SIMILAR string](http://stackoverflow.com/questions/33671497/regex-with-preg-match-to-find-and-replace-a-similar-string)
Answer: It seems to be a problem with the $40 part of $search_string, not the  .
Take this program for example:
<?php

$input = '$40   replace failed'; // string literal

$str_replace_result = str_replace('$40   replace failed', 'str_replace worked', $input);
print_r($str_replace_result . "\n"); // ==> works

$preg_replace_result = preg_replace('/$40   replaced failed/', 'preg_replace worked', $input);
print_r($preg_replace_result . "\n"); // ==> fails

// Example without the "$40"
$another_string = '  replace 2 failed';
$preg_replace_result2= preg_replace('/  replace 2 failed/', 'preg_replace worked', $another_string);
print_r($preg_replace_result2. "\n"); // ==> works, implying the "$40" bit was the issue

To fix this issue use preg_quote, e.g.:
// Solution
$escaped_search = preg_quote('/$40   replace failed/');
$newnewstr = preg_replace($escaped_search, 'preg_replace worked', $input);
print_r($newnewstr . "\n"); // ==> works

More info in this question.
In conclusion, the issue was that unescaped metacharacters caused the matching to fail.
All that said, is it required that you replace the entirety of the web page in this way? This approach (as is apparent here) seems to be error prone.
Comment: Thanks but I dont think it's related to the dollar sign. If I create a small $subject = "some text". $search_string/*(this contains $40)*/ . "athoer text") it works
Comment: I just need to replace that string inside the web page, not the whole page
Comment: @user3857924 alright. Only other thing I could think of is using smart strings (`"`) vs string literals (`'`), where you want to be using the latter here due to the nature of pattern matching (this still relates back to the `"$"` issue). Other than that, if `preg_quote` doesn't fix your issue, I'm not sure, at least based on the given information.


Is there a flutter library for access to secure enclave?

Question: I've recently started using Flutter for mobile app development, which, in my case, usually involves cryptography.  I'd like to be able to generate/use keys in the secure enclave on iOS and the keystore on Android, per the documentation provided in the links above.
I've found a library for secure storage and, of course there is PointyCastle, but none of these options allow private keys to be generated and stored specifically in the enclave, without insecure handling in application code.
Is this available yet?
Comment: Isn't `secure enclave` exclusive to ios?
Comment: edited to clarify
Answer: There are no packages for this, but You could easily develop Your own Flutter plugin.
Check the docs for Flutter plugin development (link). Flutter plugin is nothing but a fancy name for a Dart package that does some stuff on iOS and Android (natively).
In essence, it boils down to writing quite simple wrapper classes and then calling native methods from there. If You ever had any experience with native development, it will be a piece of cake for you. :)
You can use the source code of FlutterSecureStorage plugin as a reference. It has some smaller issues, but it's a great starting point.
I hope You will make it and then write back with a github or pub.dev link! :)
Answer: Looks like https://pub.dev/packages/key_enclave is a libary to use the secure enclave.
However, the lib is a bit limited and does not have a lot of recent development.


How to keeping start datastax service on windows server 2012 r2?

Question: I installed Cassandra 3.3.0 on windows server 2012 r2 properly and without any error.despite on I set manual for stop/start datastaxs service on "services.msc", it goes to stop by windows server. My question is: "What should I do to keeping start datastaxs service all the time without any stopping?"
Comment: What does your system.log say?  Perhaps there is a reason it keeps stopping on you.  Basically, without establishing *why* it keeps stopping, talking about how to automatically restart it is a little premature.
Comment: @Aaron 8 how I can find "system.log"? you mean ../data/commitlog folder?
Comment: May be it is for minimum RAM requirements? My pcs RAM is: 4 GB (3.87 usable).
Answer: The problem appears for minimum RAM requirements on PC. When I move on another one with 8 GB ram, all work correctly.


Combine two regexes

Question: I have two regular expressions which are working perfectly fine when use independently.
First  : ^.+\.((jpeg)|(gif)|(png))\s*$ : search for .jpeg,gif or png at the end of url
Second : ^.+(javax.faces.resource|rfRes).* : search for two url patterns

I want to combine the above two expressions such that " url ends in any of the image " OR "url has javax.faces.resource or rfRes in its path"
I tried using | operator to join both but it seems its not working like below :
^.+\.((jpeg)|(gif)|(png))\s*$ | ^.+(javax.faces.resource|rfRes).*

but its not working.
Can anybody please help in joining above two regex ?
Comment: Why combining? Just check if both are true or something..
Answer: You have extra spaces around the | operator:
Your original regex
^.+\.((jpeg)|(gif)|(png))\s*$ | ^.+(javax.faces.resource|rfRes).*
^.+\.((jpeg)|(gif)|(png))\s*$|^.+(javax.faces.resource|rfRes).*
Fixed regex                  ^
                             |

Your solution will try to match "the end of the string and then a space," or "a space and then the beginning of the string." Remember, whitespace is significant in regexes.
Comment: Ha, I completely missed it... This is the right solution, +1. An alternative is to use e`X`tended flag.
Comment: @Doorknob:Thanks for help. It worked.I realy missed whitespaces
Answer: The spaces in your combined expression are erroneous.  You are requiring a space after end of line or before beginning of line, which is impossible in line-oriented input.
As a further improvement, you can remove the superfluous "anything" parts of the match, as well as a good number of redundant parentheses.
javax\.faces\.resource|rfRes|\.(jpeg|gif|png)\s*$

Notice also the proper quoting of literal full stop characters (a lone . matches any character).

Combine two regexes


VS – how to change code completion pop-up foreground

Question: How can one change foreground (text color) of code completion box items while Fonts and Colors do not allow this?
Answer: If you want this change you can count on that it's little bit tricky such it will affect other (more) items. So foreground will be changed in other undesired places.
Steps:

Install Color Theme Editor for Visual Studio.
In theme editor use Show All Elements toggle.
Find Environment ⟶ CommandBarTextActive.
Change color as you wish.
Comment: Hi, thank you for your sharing, default in VS and we can only go to Tools-Environment-Fonts and Colors and select Statement Completion to change the font, size and bold, not includes the foreground and background color, please mark your reply as answer when you have free time, that will help others to easier search this information, thanks in advance.
Comment: Yes, in VS 2019 these options are still disallowed.