text:
Q: In a family with 3 children, what is the probability that they have 2 boys and 1 girl? I'm doing some regents practice questions, and one of them asked

In a family with 3 children, what is the probability that they have 2
  boys and 1 girl?

And the answer choices are

*

*3/8

*1/4

*1/8

*1/2

My teacher said the answer was choice one but I'm having trouble understanding why.
My approach was to draw out the probabilities, since we have 3 children, and we are looking for 2 boys and 1 girl, the probabilities can be Boy-Boy-Girl, Boy-Girl-Boy, and Girl-Boy-Boy. So a 2/3 chance, but I don't get how it's a 3/8 chance. Any help is appreciated.

A: No, the possible outcomes are
$$\mathsf{BBB, \boxed{\mathsf{BBG}}, \boxed{\mathsf{BGB}}, \boxed{\mathsf{GBB}}, BGG,\mathsf{GBG}, GGB, GGG}$$
wherein $3$ meet the requirement. There are $8$ possible outcomes, all equally likely (if we assume each gender is equally likely).  Hence the choice is $3/8$.
We can also think about it in at least one more way:
You identified all the possible ways to get 2 boys and one girl. Since the events are disjoint, we can add up the probabilities
\begin{align*}
P(\text{2 boys, 1 girl}) &= P(\mathsf{BBG})+P(\mathsf{BGB})+P(\mathsf{GBB}) \\
&= \frac{1}{2}\frac{1}{2}\frac{1}{2}+\frac{1}{2}\frac{1}{2}\frac{1}{2}+\frac{1}{2}\frac{1}{2}\frac{1}{2} \\
&= \frac{3}{8}.
\end{align*}

A: Since there are two genders and three children, that's $2^3=8$ permutations. You had three permutations. They would be BBB, BBG, BGB, BGG, GBB, GBG, GGB, and GGG. Out of those, the permutations with two boys and one girl are BBG, BGB, and GBB. The answer is the ratio of how many choices fit your conditions to the total number of possibilities, $\frac{3}{8}$.

A: A systematic way to calculate @probablyme s answer to encode the letters B (boy) and G (girl) as a 3 digit binary number with the logical value 1 for true and 0 for false ( that the digit represents a boy ).
Then we loop through all combinations, for example by incrementing by 1  each step.$$000\to001\to010\to011\to100\to 101\to110\to111$$
We then count the total number of "ones" equals 2. This is the same as the "population count" function used in this question and answer.
The output of the function would be:
$$0\to1\to1\to2\to1\to2\to2\to3$$
And as we can see, for 3 of the 8 states the function evaluates to 2. This means that after counting all possibilities, we found that 3 of the 8 equiprobable states correspond to two boys. This gives a probability of $\frac{3}{8}$.

The strength of this approach is of course that if we modify the question to account for more advanced things, these can be included with fast logical bit-wise operations on the numbers!

A: I drew it out this way:

So the answer is $\frac{3}{8}$.
Another way to think about it. After a first boy we need one of each (50%). After a first girl we must have only boys (25%). So the probability is $.5*\frac{1}{2} + .25*\frac{1}{2} = .375$ which is also equal to $\frac{3}{8}$.

A: Combinations vs Permutations
In case this is causing confusion, combinations don't depend on order. So if you had a lottery ticket, it matters whether you had the right combination of numbers. Or in this case, we are asking for the number of boys and girls, rather than the order that they appeared. The Permutations do consider order, so that would be more like a code for a safe that must be done in order, or the letters in a password, or in this case the sequence of genders where BGB would be a different sequence to GBB.
So a combination is like the list of stuff at the beginning of a recipe, and the permutation is the order that you add the ingredients. You can take the same list of things and add them in different amounts and different orders, and it will likely make a big difference to the result.
Working from combinations
Just to add that you can do it via combinations, as you originally thought, but you have to take into account the relative probabilities of those combinations, which derive from the set of permutations. As we have seen from the other answers, there are 3 permutations out of 8 which contain 2 boys and a girl.
But what if we looked at the combinations instead? The combinations of 2 genders among 3 children are:

*

*3 girls

*2 girls, 1 boy

*1 girl, 2 boys

*3 boys

Now for the frequencies

*

*3 girls can only be arranged 1 way, so this is a frequency of 1

*2 girls, 1 boy can be rearranged, and the boy can have 3 positions (youngest, middle or oldest). Once we have the position of the boy, the girls are known, so there are 3 positions

*1 girl, 2 boys: same logic as above, frequency of 3

*3 boys: as with 3 girls, frequency of 1

The total of them all is 8, and the number matching our requirement is 3, giving 3/8ths.
In this question, the easiest and clearest approach was to list out the permutations and count how many matched our requirement. For larger problems, it can be simpler to either quickly collect the easy cases and then look at the permutations for a restricted set, or focus on the possible combinations. This is particularly true when there are more complex options in the construction of the set.
Edit: More on Combinations and Permutations
@WoJ has a question: why does order matter? Suppose they were triplets?
I'm not saying that the chronological order of birth is what matters, only that you have to label them. We generally write permutations as a sequence which maps to an ordering of the variables; if I flip a coin 3 times and the result is HTH then I'm implicitly saying that the sequence represents the flips ordered chronologically. But we could flip 3 coins and order them by size, or by the age of the coin; it's just a way of identifying the different flips so that we can correctly account for the possibilities.
But! You must label them before you consider how they landed. Arranging heads first then tails is already turning the result from a permutation to a combination, and making things much harder by making the result dependent on the values, when they were independent variables at the beginning. So to assess the relationship between the original tosses and the resulting combinations we have to label them first or we'll give ourselves a headache.
We can see that it is the permutations that matter rather than the combinations for random independent coin flips by doing this experiment: flip 2 coins, and if they land the same (2H or 2T), then mark 1 in the 'Same' column. If they land differently (1H 1T) then mark 1 in the 'Diff' column. If the probability is determined by the combinations, then there is only 1 combination (1H 1T) that will give a 'Diff' result, vs 2 (2H and 2T) that give a 'Same' result, and after a few rounds of flips we should see twice as many marks in the 'Diff' column. Feel free to try the experiment; run it maybe 20 times so that it is clear whether the answer is more like 2:1 or like 1:1.
I predict that the result will be 1:1, because the probability is in the coin flip, so we have to look there for the statistical basis of our calculations. The probability is 50/50 of a single independent coin flip. So the first flip (or the flip of the biggest or oldest coin) is 50/50 H or T. Now, given that the first flip was a Head, what will the second be? These are independent coin flips, so the chances are still 50/50. This gives us a second value. Since these are independent flips, we label them differently and draw up either a table of their values, or a list of the permutations:
          First
         H    T
2nd  H  0.25 0.25
     T  0.25 0.25

Now we can look at the categorisation of these permutations as combinations:
       H       T
 H    2H     1H 1T
 T   1H 1T    2T

So although there are 3 labelled combinations (2H, 2T, 1H 1T), they are not evenly spread among the permutations (HH, TT, HT, TH), and we have already said that in this case the probability is being driven by the permutations, not the combinations. So to correctly account for the probabilities assigned to those combinations, we have to start from the permutations and see how they map to combinations; 2 go to becoming '1H 1T', and one each to '2H' and '2T'. How do they then map to the categories of 'Same' and 'Diff'?
     H    T            1H 1T  Diff  = 0.25+0.25
 H   Same Diff   or    2H     Same  = 0.25
 T   Diff Same         2T     Same  = 0.25

And thus we have P(Same) = 0.25+0.25 = 0.5 and P(Diff) = 0.25+0.25 = 0.5.
At no point have we cared how we ordered the coins, only that we could identify them separately because they have independent probabilities assigned to their flips.
Are there cases where you can't get the answer by just looking at the permutations? Yes, absolutely. For example, the permutations are not always neatly equally likely as we have in these constructed problems. The possible colours of socks in my drawer might be Yellow, Green and Black, but I have a lot more Black socks because the world doesn't share my fascination with Green yet. If we looked at the permutations of 2 socks picked from the drawer, we would get YY, YG, YB, GY, GG, GB, BY, BG, BB. If we just naively looked at the permutations we might imagine the chance of getting a matched pair was 3/9, or 1/3. But it is not, because there are a lot more black socks.
We might instead have a lottery ticket, which only matters what the combination is; then looking at the permutations would be a fruitless exercise, as the drawing process enforces the relationship between probability and combination rather than permutation.
Triplets by combination
Do demonstrate the problems of arranging the triplet birth result into combinations before applying the probabilities, let's actually calculate it that way around. We flip 3 coins, and ignoring the chronology arrange them with heads first. The possible results are HHH, HHT, HTT, TTT. 4 combinations.
But how can we apply our probability that each birth is 50/50? By rearranging the order, we are breaking the mapping between an individual birth and the item in the combination; you can see that straight away in that the only way the first coin in our rearranged set can be a T is if all 3 coins came up T, and we know intuitively that that's much less likely than the probability for any given toss being T. Can we still do it? Well, yes, but it's tricky.
The first combination is HHH. What is the chance of throwing HHH? The flips are independent, and these coins can be rearranged however you like, but it will always have to be 0.5 x 0.5 x 0.5 = 0.125. So immediately the HHH combination has a chance of 0.125 instead of 0.25. Just because we have 4 categories, doesn't mean the probability relates to that number in any way.
The same argument applies for TTT. So now we have accounted for 0.25 of the probability out of half the combinations.
What of HHT and HTT? Well, since the chances of H and T are equal, we could relabel H as T and T as H, or call the sides A and B without any loss of generality, so the probabilities must be equal here too; both combinations are 2 of one and 1 of the other. So the remaining 6/8 of the probability give us 3/8 for each option.
What if H and T were not interchangeable? Suppose P(H) was 3/5, not 1/2? We can see that the combinations don't give us a straight answer because they are unchanged (3H, 2H, 1H, 0H) but we know intuitively that the chances of getting 2H must depend on the bias of the coin flip. Here we would have a remaining probability of 1 - 0.4*0.4*0.4 - 0.6*0.6*0.6 = 0.72. The two remaining combinations are HTT and HHT. So we know that the first and last of those coins came out the same, and this is the set of tosses which contain one head and one tail. Removing that head and tail leaves the outcome of a single coin. It doesn't matter which order the coins were tossed in, or even how we reordered them afterwards. The final coin has P(H)=0.6 and P(T)=0.4, so P(H)/P(T) = 1.5. We already have the other two coins, so we have P(2H 1T)/P(1H 2T) = 1.5. Distributing the remaining probability of 0.72 gives us P(2H 1T)+P(1H 2T)=0.72, and we can then substitute to get P(2H 1T)+P(2H 1T)/1.5=0.72, so P(2H 1T)=0.432.
By contrast, to calculate that from the original tosses, we have:
P(2H,1T) = P(HHT)+P(HTH)+P(THH)
         = .6*.6*.4 + .6*.4*.6 + .4*.6*.6
         = 0.144 * 3 = 0.432

So if we have independent variables (births, coin tosses), it is easiest to look at the permutations and collect the probabilities of the permutations we want than to start from the combinations and work backwards to figure out how their probabilities relate to the individual variable probabilities. But it is not impossible, and in some cases preferable.
TLDR: The important thing is to look at the mechanism by which randomness appears in the system, and to then measure the probabilities from there either in terms of combinations or permutations, but not blindly applying either as the method entirely depends on the mechanism of the randomness. Both approaches can be made to work, but only if you correctly account for the probabilities according to the system you are considering.

A: Since the question does not mention the order, the possible combinations are

*

*3 Boys

*2 Boys and 1 Girl (3 ways to do it)

*1 Boy and 2 Girls (3 ways to do it)

*3 Girls

That means the correct answer is 37,5% or 3/8

A: because 'not a boy' is same as a girl (opposite), it could be calculated like this.
$ \binom{3}{2}  (\frac{1}{2})^2(\frac{1}{2})^{2-1} = 0.375 $

$ \binom{n}{k}  (p)^k(1-p)^{n-k} $

A: The following method avoids any need to consider the number of permutations with 2 boys and 1 girl.
3 children must include either at least 2 boys or at least 2 girls (but not both). Hence:
P($\geq 2$ boys) + P($\geq 2$ girls) = $1$.
By symmetry, P($\geq 2$ boys) = P($\geq 2$ girls) = $1/2$.
P(3 boys) = $(1/2)^3 = 1/8$.
Hence P(2 boys, 1 girl) = P($\geq 2$ boys) - P(3 boys) = $1/2 - 1/8 = 3/8$.


text:
Q: Listings float with sublistings I want to have 2 listings side-by-side in a float environment with its own name (i.e. Listing 1 instead of Figure 1) and counter (so that I can have a separate listoflistings besides listoffigures). I also want the subcaptions aligned and not the listings themselves.
This is about what I'd imagine:

I don't see how to get the captions aligned with the subfigure package, but it works fine with the subcaption package:
\begin{figure}
\centering
\subcaptionbox{Subcaption a.}%
  [.47\textwidth]{\includegraphics[width=.45\textwidth]{imga}}
\subcaptionbox*{}[.03\textwidth]{}
\subcaptionbox{Subcaption b.}
  [.47\textwidth]{\includegraphics[width=.45\textwidth]{imgb}}
\caption{Main caption.}
\end{figure}

The problem is that I can't include lstlistings in the subcaption and that I still don't know how to get the separate counter and name from figure.
Related question about putting 2 listings side-by-side, which isn't what I have in mind.

A: I put this together to demonstrate how you can do this.  Since you did not give a full example, I can't guarantee that it will fit right into what you are doing.
I used newfloat to create a new float type listing, as you seem to have.  minipages are used to set the listings themselves into the sub-floats.  Depending on what you have already, this may be enough to fix your issues.
I also augmented the example to show referencing and a list of listings.  Within this bigger example, two problems still present themselves:

*

*The counter on subrefs is not set correctly; I have added a \refstepcounter to temporarily add 1 to the count to correct this.

*The \listoflistings puts the two sublisting captions above the main caption.  I'm not sure yet why this is happening of if it can be corrected.  The fix/hack would be to put the main caption at the top of the float, but that would move it in the final typesetting to the top as well, which may not be desired.
Even with these irregularities, a very nice result is obtained:

The MWE code:
\documentclass{article}

\usepackage{listings}
\usepackage{newfloat,caption}
\usepackage{subcaption}
\usepackage[demo]{graphicx}

\DeclareFloatingEnvironment[fileext=frm,placement={!ht},name=Listing,within=section]{listing}

\begin{document}

\tableofcontents
\listoflistings

\section{One}
\section{Two}

\begin{listing}
\refstepcounter{listing}
\noindent\begin{minipage}[b]{.45\textwidth}
    \begin{lstlisting}
add x1, x1, 5
stp fp, lr, [sp, #-16]!
add x5, x6, x7
    \end{lstlisting}
    \captionof{sublisting}{Some caption.}
    \label{lst:codeblockA}
    \end{minipage}%
    \hfill
\begin{minipage}[b]{.45\textwidth}
    \begin{lstlisting}
ldr x5, [x5]
    \end{lstlisting}
    \captionof{sublisting}{Some other caption.}
    \label{lst:codeblockB}
\end{minipage}
\addtocounter{listing}{-1}
\caption{Some text.  The quick brown fox\ldots}
\label{lst:codeblocks}
\end{listing}

Figure~\ref{lst:codeblocks} includes block \ref{lst:codeblockA} and \ref{lst:codeblockB}

\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Remove namespace declaration from XSLT stylesheet with XSLT I have an XSLT stylesheet like the following:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                  xmlns:XQHeaderFunc="java:com.sonicsw.xq.service.xform.HeaderExtension"
                  xmlns:saxon="http://saxon.sf.net/">

  <saxon:script language="java" implements-prefix="XQHeaderFunc" src="java:com.sonicsw.xq.service.xform.HeaderExtension" />

  <xsl:output indent="yes" omit-xml-declaration="yes"/>

  <xsl:template match="/">
    <xsl:variable name="processId" select="XQHeaderFunc:getProperty(XQHeaderFunc:new(),'processId',-1)" />
    <xsl:value-of select="XQHeaderFunc:setProperty(XQHeaderFunc:new(),'processId',string(@id),-1)"/>

    <root>
      <xsl:apply-templates />
    </root>

  </xsl:template>

  <!-- Other stuff -->

</xsl:stylesheet>

I want to transform this stylesheet using a second XSLT stylesheet to remove anything that has to do with the XQHeaderFunc and saxon namespaces. Is there a way I can do this?

I have now tried the following, which successfully deals with the elements, but the namespace declaration doesn't seem to want to disappear.
<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:XQHeaderFunc="java:com.sonicsw.xq.service.xform.HeaderExtension"
                xmlns:saxon="http://saxon.sf.net/"
                exclude-result-prefixes="XQHeaderFunc saxon">

  <xsl:param name="XQHeaderReplacement" />
  <xsl:variable name="apos">'</xsl:variable>

  <!-- Copy all nodes -->
  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>

  <!-- Remove saxon script tag -->
  <xsl:template match="saxon:script" />

  <!-- Remove elements with setProperty calls -->
  <xsl:template match="*[starts-with(@select, 'XQHeaderFunc:setProperty')]" />

  <!-- Replace getProperty calls with replacement value-->
  <xsl:template match="@select[starts-with(., 'XQHeaderFunc:getProperty')]">
      <xsl:attribute name="select">
        <xsl:value-of select="concat($apos, $XQHeaderReplacement, $apos)"/>
      </xsl:attribute>
    </xsl:template>
</xsl:stylesheet>

Output:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:XQHeaderFunc="java:com.sonicsw.xq.service.xform.HeaderExtension"
                xmlns:saxon="http://saxon.sf.net/">

  <xsl:output indent="yes" omit-xml-declaration="yes" />

  <xsl:template match="/">
    <xsl:variable name="processId" select="''" />

    <root>
      <xsl:apply-templates />
    </root>

  </xsl:template>

  <!-- Other stuff -->

</xsl:stylesheet>

A: I would add
 exclude-result-prefixes="foo"

onto your
 <xsl:stylesheet>

element. Then the namespace declaration for foo will be omitted if possible, i.e. if there no elements or attributes in that namespace to output.
FYI, the reason tnat this line
<xsl:template match="xsl:stylesheet/@xmlns:foo" />`

throws an error is because xmlns:foo in the input document is not an attribute; it's a pseudoattribute. What your match pattern is asking to match is an attribute named foo that is in a namespace corresponding to a namespace prefix xmlns. Since you have not declared a namespace prefix xmlns in your stylesheet, you get the error "prefix xmlns is not defined."
Update:
I see from your posted output (and my own testing) that exclude-result-prefixes hasn't been effective in removing the namespace declaration.
1) First I would ask why it matters. It doesn't change the namespace of anything in your output XSLT. Are you just trying to remove it for aesthetic reasons?
2) Looking at the XSLT 1.0 spec, it appears to me that <xsl:copy> pays no attention to exclude-result-prefixes:

Instantiating the xsl:copy element creates a copy of the current node.
  The namespace nodes of the current node are automatically copied as
  well...

AFAICT, only literal result elements will omit namespace nodes based on exclude-result-prefixes.
On that basis, I would try replacing <xsl:copy> in your identity template (for elements) with <xsl:element name="{name()}"> or some variant thereof. You would then need a separate identity template for non-element nodes.
I replaced your identity template with the following two templates:
<!-- Copy elements -->
<xsl:template match="*" priority="-1">
   <xsl:element name="{name()}">
      <xsl:apply-templates select="node()|@*"/>
   </xsl:element>
</xsl:template>

<!-- Copy all other nodes -->
<xsl:template match="node()|@*" priority="-2">
   <xsl:copy />
</xsl:template>

and that gave what I believe is the desired output, with no extraneous ns declarations:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
   <xsl:output indent="yes" omit-xml-declaration="yes" />

   <xsl:template match="/">
      <xsl:variable name="processId" select="''" />
      <root>
         <xsl:apply-templates />
      </root>
   </xsl:template>

   <!-- Other stuff -->
</xsl:stylesheet>

(I have adjusted the whitespace for clarity.)


text:
Q: Straight Flush probability with a huge hand. It's easy to calculate the probability of a straight flush when you're dealt $5$ cards. I'd like to ask for the probability of the same when you're dealt half the deck.
I seek $P(\text{straight flush})$ of any suit. We have $52$ cards, and $26$ are dealt. A straight flush is $5$ consecutive cards of the same suit.  An Ace may come either before a $2$ or after a King but not both.

A: You've posed a difficult problem my friend.  These types of problems are normally solved with inclusion-exclusion.  Consider the event of the A2345 of hearts being included in this 26 deck hand.  It is not too difficult to compute the probability of this specific event arising, by counting the number of hands including these five cards, and dividing by the number of all hands, getting $$\frac{{47\choose 21}}{{52\choose 26}}\approx 2.5\%$$
There are 35 similar events, corresponding to the 36 possible straight flush hands.  However, what you asked was the probability of at least one of these events happening, i.e. the probability of the union of these 36 events.  Enter the inclusion-exclusion principle.  Now we need to compute the probability of the intersection of every subset of the set of these 36 events. For example, the intersection of the event above, and the event "56789 of hearts", is the event "A23456789 of hearts", which has probability $\frac{{43\choose 17}}{{52\choose 26}}$.  Or, the intersection of the event "A2345 of hearts" and "56789 of clubs" is the event of both of those, which has probability $\frac{{42 \choose 16}}{{52\choose 26}}$.
In easier problems, these subsets have a nice pattern to find, and/or they quickly max out in size.  For example, if you were drawing a deck of six cards, TWO of the events might happen at the same time, but no more.  Hence the probability of all subsets of size three, four, ..., 36 is all zero.
In the OP however, the calculation of these probabilities has many tedious cases, which quickly devolves into tedious subcases.  The intersection of a pair of events is not too bad -- some pairs of five-card hands intersect in zero cards, some in one, some in two, some in three, and some in four.  Each of these probabilities is not too bad to compute, and I've done two examples above.  In a few minutes we can handle all ${36\choose 2}$ pairs of events.
But we now need to consider the intersection of three of these events.  Now it's quite complicated indeed.  Perhaps the three hands are all nonintersecting.  Perhaps the first two hands intersect in two cards, but no other intersections occur.  Perhaps the first two hands intersect in one card, and the last two hands intersect in one card as well.  And all of these can happen, because with 26 cards there is a lot of room for cards!  Hence this method suffers from combinatorial explosion and is more or less hopeless to compute by hand, without careful calculation of many possible cases that could take hours.  Sadly a computer can only help with the arithmetic, not with the modeling.
A related question that is easily answered is the expected number of straight flushes in your 26 card hand.  This can be found using linearity of expectation, hence we multiply the expected number of the (A2345 of hearts) event, by 36.  The result is $$\frac{759}{833}\approx 0.9111$$
i.e. on average you will find approximately $0.9$ straight flushes in each hand of 26 cards.  However this averages hands with zero, and hands with seven, in a manner that can only be fully understood by using the inclusion-exclusion principle as above.

A: It may be possible to get a computer to count it.
Each suit is disjoint from the other suits.
We only want the probability of zero straight flushes.
The 'distribution' is how many spades, how many hearts, and so on.
$$P(a,b,c,d)=\frac{{13\choose a}{13\choose b}{13\choose c}{13\choose d}}{52\choose 26}$$
Then, given $x$ cards in a suit, what is the chance of no straight flush in that suit?  Some easy values are $Q(0)=Q(1)=...Q(4)=1$, and $Q(13)=0$.  There are $2^{13}=8192$ subsets of thirteen cards.  It is simple to get a computer to run through all 8192, counting how many cards and whether there is a straight flush.  Lastly, get the machine to calculate $$\sum_{a+b+c+d=26}P(a,b,c,d)Q(a)Q(b)Q(c)Q(d)$$
There are $29\choose3$ ways that four non-negative numbers can sum to 26; the cases with $a>13$ can be covered by setting $Q(14)=...=Q(26)=0$.
The reason for $29\choose3$ is a stars-and-bars argument.  You have 26 cards, and three suit-dividers.  They fill 26+3=29 places.  Choose the three spots for the suit-dividers, and put unmarked cards in the other 26 spots.  Now you know how many of each suit there are.  All those to the left of the first divider are spades; all those between divider 1 and divider 2 are hearts, then diamonds; and all those to the right of the third divider are clubs.


text:
Q: i have Two array i want that unique value of array let array1 = ["apple", "banana", "mango"];
let array2 = ["apple", "banana", "mango", "red", "green"];

I want output is = array3 = [ "red", "green"];

I want to concat array1 and array2 and remove the duplicate code and output is array3.

There are two common ways (in ES5 and ES6, respectively) of getting unique values in JavaScript arrays of primitive values. Basically, in ES5, you first define a distinct callback to check if a value first occurs in the original array, then filter the original array so that only first-occurred elements are kept.

A: You can easily filter out the common elements using Map as:

let array1 = ["apple", "banana", "mango"];
let array2 = ["apple", "banana", "mango", "red", "green"];

const map = [...array1, ...array2].reduce(
  (map, curr) => map.set(curr, (map.get(curr) ?? 0) + 1),
  new Map()
);

const result = [];
for (let [k, v] of map) {
  if (v === 1) result.push(k);
}
console.log(result);


text:
Q: Parameter uncertainity in least squares optimization: rescaling Hessian Given a least squares optimization problem of the form:
$$ C(\lambda) = \sum_i ||y_i - f(x_i, \lambda)||^2$$
I have found in multiple questions/answers (e.g. here)  that an estimate for the covariance of the parameters can be computed from the inverse rescaled Hessian at the minimum point:
$$ \mathrm{cov}(\hat\lambda) = \hat H^{-1} \hat\sigma_r^2 = \hat H^{-1} \frac{\sum_i ||y_i - f(x_i, \hat\lambda)||^2}{N_{DOF}} $$
While I understand why the covariance is related to the inverse Hessian (Fisher information), I haven't found anywhere a demonstration or explanation for the $\hat\sigma_r^2$ term, although it appears reasonable to me on intuitive grounds.
Could anybody explain the need for the rescaling by the residual variance and/or provide a reference?

A: One can possibly look at the approximation for the covariance as a "rescaled inverse Hessian", but it kind of hides the simple deduction.
In principle it's the stopped series expansion of the term that is minimized. So, if one stops at the second term, the expression is in the simple 1D case around the (minimum) value of a:
$$f(x) = f(a) + f^\prime(a)(x-a) + \frac{1}{2}f^{\prime\prime}(a)(x-a)^2$$
If you change to the vectorized version, the derivatives are replaced by their respective vectorized parts.
At the minimum the slope is zero, which means the first derivative -- the Jacobian -- is zero. E.g. also https://en.wikipedia.org/wiki/Taylor_expansions_for_the_moments_of_functions_of_random_variables So, now you can identify the remaining part with the expression of the approximation at the minimum.
The actual scaling factor of the variance is a bit more complicated, why the number of degrees of freedom is a good choice. The logic behind this is that the term should neither be under-, nor overestimated. Sometimes this is described as "unbiased", but in my understanding this implies a dependency on the value itself. So, in my understanding it's more like a correction that can be verified by using analytical examples.


text:
Q: R rbind multiple dataframes with names stored in a vector/list I have a list that references the names of multiple dataframes
df_list
[[1]]
[1] "df_1"

[[2]]
[1] "df_2"

....

[[10]]
[10] "df_10"

How can I run the rbind command referencing df_list so I don't have to reference every one of the 10 names.
all_df <- rbind(df_list)

Instead of
all_df <- rbind(df_1,df_2,df_3,df_4,df_5,df_6,df_7,df_8,df_9,df_10)

A: Something like this may work.
Example data: a list with the name of the iris data frame, twice.
df_list<- list("iris", "iris")
df_list

[[1]]
[1] "iris"

[[2]]
[1] "iris"

Then use as.name to convert the strings to the variable names:
all_df <- do.call(rbind, lapply(df_list, as.name))
nrow(df)

[1] 300


text:
Q: Delete all the digits in the string using Regex, python I am new to regex. I am trying to remove all digits but digits corresponding to response should remain as is in the whole string and rest of the digits should be removed. For example 892 and 762 corresponding to response should be remain as it is in the string and whenever these values occurs again in the string should NOT be removed. But rest other digits should be removed.
mystr=" hey vi_pl12879 remove all the digits
        am_87284 remove all the digits except res value
        how are you response > 892
        omh 8241 del the digits
        delete the manm/alka/8726/uh/the
        the code for error is 892
        response > 762
        keep only res values in the whole string
        error code may be 762"

Expected Result:
mystr=" hey vi_ remove all the digits
        am_ remove all the digits except res value
        how are you response > 892
        omh  del the digits
        delete the manm/alka//uh/the
        the code for error is 892
        response > 762
        keep only res values in the whole string
        error code may be 762"

A: You can use a positive lookup ahead to remove all digits but digits which are after the first response > expression which you can find out using findall:
import re

mystr=" hey vi_pl12879 remove all the digits\
 am_87284 remove all the digits except res value\
 how are you response > 892\
 omh 8241 del the digits\
 delete the manm/alka/8726/uh/the\
 the code for error is 892\
 response > 762\
 keep only res values in the whole string\
 error code may be 762"

response_groups = re.findall(r".+?(response > \d+)", mystr)

res = re.sub(
    r"\d(?=.+?" + response_groups[0] + ")",
    "",
    mystr
)

print(res)

This prints:

hey vi_pl remove all the digits am_ remove all the digits except res value how are you response > 892 omh 8241 del the digits delete the manm/alka/8726/uh/the the code for error is 892 response > 762 keep only res values in the whole string error code may be 762


text:
Q: Probability question concerning maximums and minimums There are marbles in a jar for digits 1-10. For each digit, there is that corresponding number of marbles in the jar (1 labeled 1; 2 labeled 2, and so on). So, there are 55 total marbles in the bucket.
P(A) is that the probability of the maximum is 8, and P(B) is the probability that the minimum is 3.
For 5 draws with replacement
It asks to determine P(A): I calculated 8^5/10^5 - 7^5/10^5., or .1596.
P(B) I calculated to be (1-6^5/10^5) - (1-7^5/10^5), or .0903.
It then asks for P(A|B). I'm not sure how to proceed. Assuming that I did the other calculations correctly. I know the formula is P(Aint.B)/P(B), but I'm not certain how to find the intersection.

A: Comment: Mostly for verification.
I simulated a million 5-draw experiments. Results for $P(A)$ and $P(B)$ should be accurate
to two or three places. (Argument pr=1:10 sets the proportions of
each number; R turns them into probabilities. Argument repl=T means
sample with replacement. The m-vectors a and b are logical,
containing elements FALSE and TRUE; the mean of a logical vector is its
proportion of TRUE's.)
m = 10^6;  n = 5;  sm = lg = numeric(m)
for (i in 1:m) {
  x = sample(1:10, n, repl=T, pr=1:10)
  sm[i] = min(x);  lg[i] = max(x) }
a = (lg==8);  b = (sm == 3)
mean(a);  mean(b);  mean(a & b); mean(a[b])
## 0.085816    # aprx P(A)
## 0.193684    # aprx P(B)
## 0.020432    # aprx P(A and B)
## 0.1054914   # aprx P(A|B)

(36/55)^5 - (28/55)^5
## 0.08594705   # your P(A)
(52/55)^5 - (49/55)^5
## 0.194182     # your P(B)

A: In general we have $$P(A\,|\,B)=\frac {P(A\cap B)}{P(B)}$$ We know $P(B)\sim .19418$ So we just need $P(A\cap B)$.
To compute $P(A\cap B)$:  We define $P_1$, the probability that the max is $8$ assuming we don't draw any numbers below $3$.  There are $52$ marbles with a value of $3$ or greater, $33$ of those have values $≤8$ and $25$ have value $≤7$  so $$P_1=\left(\left(\frac {33}{52}\right)^5-\left(\frac {25}{52}\right)^5\right)\times \left(\frac {52}{55}\right)^5\sim .05835621$$
Now we define $P_2$, the probability that the max is $8$ assuming we don't draw any numbers below $4$. There are $49$ marbles with a value of $3$ or greater, $30$ of those have values $≤8$ and $22$ have value $≤7$  so $$P_2=\left(\left(\frac {30}{49}\right)^5-\left(\frac {22}{49}\right)^5\right)\times \left(\frac {49}{55}\right)^5\sim .03804284$$    Then $$P(A\cap B)=P_1-P_2\sim .02031337$$  Finally we get $$P(A\,|\,B)=\frac {P(A\cap B)}{P(B)}=\frac {.02031337}{.19418}\sim .10460992$$
Note:  Many thanks to @BruceET for simulating the process and identifying an error in the previous version of the post.  For those who are interested, the error was in the computation of the $P_i$.  The first draft failed to multiply by the probability of missing the lower values.


text:
Q: reactjs components communicating I have created two separate components and a parent component. I am trying to see how I can connect them so that I can have the dropdown for the children vanish when their checkbox is unchecked. I think I may have created this so the 2 components can't communicate, but I wanted to see if there was a way to get them to. Been trying different ways, but cannot seem to figure it out.
This is the parent component. It builds sections from some data and renders a checkbox treeview with the first (parent) checkbox having a dropdown. When the third option is selected in this dropdown, it renders in a dropdown for each child checkbox. I am trying to see if I can have the child dropdowns vanish when the checkbox is unchecked, but I can't seem to get the 2 components to communicate.

export default class CheckboxGroup extends PureComponent {

  static propTypes = {
    data: PropTypes.any.isRequired,
    onChange: PropTypes.func.isRequired,
    counter: PropTypes.number,
  };

  mapParents = (counter, child) => (

      <SegmentHeader style={segmentStyle} title={child.get('label')} icon={child.get('icon')}>

            <TreeCheckbox
              label={`Grant ${child.get('label')} Permissions`}
              counter={counter}
              onChange={this.props.onChange}
            />
            {child.get('items') && this.buildTree(child.get('items'), counter + child.get('name'))}

            <GrantDropdown label={child.get('label')} childItems={child.get('items')}/>

      </SegmentHeader>

  )

  mapDataArr = (counter) => (child) => (
    (counter === 0 || counter === 1000) ?
      this.mapParents(counter, child)
      :

        <TreeCheckbox label={child.get('label')} onChange={this.props.onChange}/>
        {child.get('items') && this.buildTree(child.get('items'), counter + child.get('name'))}

  )

  buildTree = (dataArr, counter) => (

      {dataArr.map(this.mapDataArr(counter))}

  )

  render() {
    return (

        {this.buildTree(this.props.data, this.props.counter)}

    );
  }
}

import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';

const pointer = { cursor: 'pointer' };

class TreeCheckbox extends PureComponent {
  static propTypes = {
    onChange: PropTypes.func,
    label: PropTypes.string,
    currentPerson: PropTypes.any,
  };

  componentDidMount() {
    if (this.props.currentPerson.get('permissions').includes(this.props.label)) {
      this.checkInput.checked = true;
      this.changeInput(this.checkInput);
    }
  }

  getLiParents = (el, parentSelector) => {
    if (!parentSelector) parentSelector = document; // eslint-disable-line
    const parents = [];
    let parent = el.parentNode;
    let o;
    while (parent !== parentSelector) {
      o = parent;
      if (parent.tagName === 'LI') parents.push(o);
      parent = o.parentNode;
    }
    return parents;
  }

  traverseDOMUpwards = (startingEl, steps) => {
    let elem = startingEl;
    for (let i = 0; i < steps; i++) {
      elem = elem.parentNode;
    }
    return elem;
  }

  markIt = (nodeElem, checkIt, indeter) => {
    const node = nodeElem;
    const up = this.traverseDOMUpwards(node, 1);
    node.checked = checkIt;
    node.indeterminate = indeter;
    this.props.onChange(up.children[1].innerText, checkIt);
  }

  changeInput = (event) => {
    const e = event === this.checkInput ? event : event.target;
    const selector = 'input[type="checkbox"]';
    const querySelector = (el) => el.querySelectorAll(selector);
    const container = this.traverseDOMUpwards(e, 2);
    const markAllChildren = querySelector(container.parentNode);
    const checked = e.tagName === 'LABEL' ? !markAllChildren[0].checked : e.checked;
    const siblingsCheck = (element) => {
      let onesNotRight = false;
      const sibling = [].slice.call(element.parentNode.children);
      sibling.filter(child => child !== element).forEach(elem => {
        if (querySelector(elem)[0].checked !== querySelector(element)[0].checked) {
          onesNotRight = true;
        }
      });
      return !onesNotRight;
    };
    const checkRelatives = (ele) => {
      let el = ele;
      if (el.tagName === 'DIV') el = el.parentNode;
      if (el.tagName !== 'LI') return;
      const parentContainer = this.traverseDOMUpwards(el, 2);
      if (siblingsCheck(el) && checked) {
        this.markIt(querySelector(parentContainer)[0], true, false);
        checkRelatives(parentContainer);
      } else if (siblingsCheck(el) && !checked) {
        const parent = this.traverseDOMUpwards(el, 2);
        const indeter = parent.querySelectorAll(`${selector}:checked`).length > 0;
        this.markIt(querySelector(parent)[0], false, indeter);
        checkRelatives(parent);
      } else {
        for (const child of this.getLiParents(el)) {
          this.markIt(querySelector(child)[0], false, true);
        }
      }
    };

    for (const children of markAllChildren) {
      this.markIt(children, checked, false);
    }

    checkRelatives(container);
  };

  getRef = (input) => { this.checkInput = input; }

  render() {
    const { label } = this.props;

    return (

          <input type='checkbox' onChange={this.changeInput} ref={this.getRef}/>

            {label}

    );
  }
}

const mapStatetoProps = (state) => ({
  currentPerson: state.get('currentPerson'),
});
export default connect(mapStatetoProps)(TreeCheckbox);

class GrantDropdown extends AbstractSettingsComponent {
  static propTypes = {
    label: PropTypes.string,
    currentPerson: PropTypes.any,
    counter: PropTypes.number,
    permissionOptions: PropTypes.any,
  };

  state = {
    items: new List(),
  }

  componentDidMount() {
    if (this.props.childItems) {
      this.getAllChildLabels(this.props.childItems);
    }
  }

  getAllChildLabels = (childItems) => {
    let list = new List();
    for (const item of childItems) {
      list = list.push(item.get('label'));
      if (item.get('items')) {
        for (const childItem of item.get('items')) {
          list = list.push(childItem.get('label'));
        }
      }
    }
    this.setState({ items: list });
  }

  handlePermissionChange = (label) => (e, { value }) => {
    this.updatePerson(['locationsPermissionsMap', label], value);
  }

  mapItems = (val, i) => { // eslint-disable-line
    const locationVal = this.props.currentPerson.getIn(['locationsPermissionsMap', val]);
    return (

          <OptionSelector
            options={this.firstThreePermissionOpt()}
            defaultValue={locationVal || 0}
            onChange={this.handlePermissionChange(val)}
          />
          {locationVal === 2 &&

              <LocationMultiSelect name={val} {...this.props}/>

          }

    );
  }

  render() {
    const { label, currentPerson } = this.props;
    if (!currentPerson.get('permissions').includes(label)) {
      return null;
    }
    const locationLabel = currentPerson.getIn(['locationsPermissionsMap', label]);
    return (

          <OptionSelector
            options={this.getPermissionOptions()}
            defaultValue={currentPerson.getIn(['locationsPermissionsMap', label]) || 0}
            onChange={this.handlePermissionChange(label)}
          />
          {locationLabel === 3 && this.state.items.map(this.mapItems)}

        {locationLabel === 2 &&

            <LocationMultiSelect name={label} {...this.props}/>

        }

    );
  }
}
const mapStatetoProps = (state) => ({
  currentPerson: state.get('currentPerson'),
  locations: state.get('locations'),
});
export default connect(mapStatetoProps)(GrantDropdown);

A: You can set the <input/> name attribute into a corresponding property in your state so the handler can get the name of the list / input via the event parameter and set the state respectively.
Then you can conditionally render the Dropdown according to the state.
Here is a small example of such behavior:

const lists = [
  [
    { value: "0", text: "im 0" },
    { value: "1", text: "im 1" },
    { value: "2", text: "im 2" }
  ],
  [
    { value: "a", text: "im a" },
    { value: "b", text: "im b" },
    { value: "c", text: "im c" }
  ]
];

const DropDown = ({ options }) => {
  return (
    <select>
      {options.map(opt => <option value={opt.value}>{opt.text}</option>)}
    </select>
  );
};

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showList0: false,
      showList1: true
    };
    this.toggleCheck = this.toggleCheck.bind(this);
  }

  toggleCheck(e) {
    const listName = e.target.name;
    this.setState({ [listName]: !this.state[listName] });
  }

  render() {
    return (

        {lists.map((o, i) => {
          const listName = `showList${i}`;
          const shouldShow = this.state[listName];
          return (

              <input
                type="checkbox"
                name={listName}
                checked={shouldShow}
                onChange={this.toggleCheck}
              />
              {shouldShow && <DropDown options={o} />}

          );
        })}

    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));

A: What you can do is set couple of props to send to child component to re-render them.
Example
   export default class CheckBoxComponent extends React.Component {
       changeInput() {
          this.props.onCheckedChanged();
       }

       render() {
         return(

              <input type='checkbox' onChange={this.changeInput} ref={this.getRef}/>

                {label}

         )
       }
   }

   export default class DropDownComponent extends React.Component {
       renderSelect() {
         // here render your select and options
       }
       render() {
         return(

             {this.props.checkboxChecked === false ? this.renderSelect : null}

         )
       }
   }

    export default class App extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                checkboxChecked: false
            };
        }
        onCheckedChanged() {
          this.setState({ checkboxChecked: !this.state.checkboxChecked });
        }
        render() {
            return(

                    <CheckBoxComponent onCheckedChanged={this.onCheckedChanged.bind(this)} />
                    <DropDownComponent checkboxChecked={this.state.checkboxChecked} />

            )
        }
    }


text:
Q: Recommendations on how to prevent users from closing browser window (via onbeforeunload) AFTER the save button has been clicked? I've found numerous solutions on how to prompt the user about closing a window down before the data is saved but in my scenario, this one page is saving a lot of data and is slow (takes about 30 seconds) and this is AFTER the save button is clicked.  What we are finding is that the user is clicking the save button and then navigating or leaving AFTER clicking save.  Depending on the browser, whatever has been sent to the server isn't necessarily saved (looking at you Chrome).
I opted to use this solution and almost does what I need except even when I click the save button, I'm still prompted to save the changes since I'm leaving the page.  Its like I need to turn off the prompt and then turn it back on after some delay.  Is this even possible?
    window.onbeforeunload = function() {
        if ( Flag == 'Y' ) {
            return "Changes made. Don't want to save?";
        }
    }

A: Why don't you try a "save as you go" approach?... You can send small quick requests as the user progress in the whatever data input mechanism you have, and store that on a temporary file on your server, so when the user hits the "save" button or closes the browser window you only send a tiny request, quick enough to allow a safe browser disconnection. The server then just reads the temporary file and processes it as if it was send by the user in a single operation. May not be easy, but you'll get rid of quite a few headaches.


text:
Q: Check Facebook App Login I have a problem that, I am using Facebook SDk for sharing products on Facebook in our Android App, its working fine but when we have logged into Facebook App preinstalled in Phone, and then we want to login in Facebook through our Application then it doesn't show Login Window. I don't know How this will managed in our code? \
Please help me out about this problem.
Thanks in advance.

A: If you want to show login dialog always, set Facebook.FORCE_DIALOG_AUTH option when you call Facebook.authorize() method.
Here's my code.
Facebook fb = new Facebook("1234567"); //your app key
return fb.authorize(this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH, fbDiagListener);

A: FB app & your app have no connection.
Implement FB Authentication flow. Check FB Dev site
Its OAuth 2.0.
Use Client side stuff as you are doing it inside your app.

A: I think your issue is mainly because of not correctly specifying the android key hash. Kindly go through the following link: "An error's occurred" when authenticating with Facebook's android sdk

A: kingori's solution is good but not the only one. You need to check the hash key in your app whether it matches with the one you pasted on the facebook console. I had the same problem and was solved by this method.


text:
Q: Adding custom image as separator in wordpress footer I want to add custom separator image in wordpress footer, here is my functions.php code:
function advertica_lite_widgets_init() {
register_sidebar(array(
    'name' => 'Page Sidebar',
    'id' => 'page-sidebar',
    'before_widget' => '
',
    'after_widget' => '
',
    'before_title' => '
',
    'after_title' => '
',
));
register_sidebar(array(
    'name' => 'Blog Sidebar',
    'id' => 'blog-sidebar',
    'before_widget' => '
',
    'after_widget' => '
',
    'before_title' => '
',
    'after_title' => '
',
));
register_sidebar(array(
    'name' => 'Footer Sidebar',
    'id' => 'footer-sidebar',
    'before_widget' => '
',
    'after_widget' => '
',
    'before_title' => '
',
    'after_title' => '
',
));  }

I want to add image as separator between all 3 blocks, i tried couple of google help but didn't got any help relevant to what i was looking for. Would there be anyone who can assist me the modification ?
i want it something like this:

A:

.ske-container{
    display: inline-block;
    padding: 0px 5px;
 width:30%;
 float:left;
    text-align:center;
    height:200px;
    background-image: url("https://i.stack.imgur.com/3vmnN.png");
    background-repeat: no-repeat;
    background-position: right top;
}
.ske-container:last-child{
 background-image: none;
}

    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

Would you please add above CSS in your current theme style.css? And check it.


text:
Q: Уровни стилей в HTML и нагрузка на HTTP-сервер от SSI Прохожу онлайн тест от института. На некоторые вопросы ответа не могу найти.

*

*Число уровней каскадных стилей в HTML?

*Где выполняются CGI-скрипты?

*Где выполняются SSI-команды?

*При использовании SSI увеличится ли нагрузка на HTTP сервер?
На 2 и 3 вроде бы знаю ответ, но не уверен: вроде оба на вебсервере выполняются?
A: *

*Наверно, имеется ввиду h1-h6. Поэтому ответ - 6.

*Да, на сервере.

*На сервере. На то они Server Side Include.

*При неправильном подходе - да, конечно. В любом случае, серверу приходиться компоновать страницу.


text:
Q: What does "d.addCallback(lambda protocol: protocol.ready)" do in Pika's Twisted example? The setup in Pika's example code with Twisted looks like this:
parameters = pika.ConnectionParameters()
cc = protocol.ClientCreator(
        reactor, twisted_connection.TwistedProtocolConnection, parameters)
d = cc.connectTCP('hostname', 5672)
d.addCallback(lambda protocol: protocol.ready)
d.addCallback(run)
reactor.run()

What effect does the d.addCallback(lambda protocol: protocol.ready) line have? Is reading the .ready attribute side-effecting? Or does addCallback use the return value of the callback?

A: Return value of each callback is passed to next callback in the d's callback chain.  So, protocol.ready value is passed to run (next callback).
See http://twistedmatrix.com/documents/current/core/howto/defer.html#multiple-callbacks


text:
Q: Partially mock `react-native` module I'm running unit tests in React Native that need the NativeEventEmitter and NativeModules mocked but leave everything else as passthrough to the real code.
This part seems to be working except when running I get this error.
    Invariant Violation: TurboModuleRegistry.getEnforcing(...): 'DevSettings' could not be found. Verify that a module by this name is registered in the native binary.

      at invariant (../node_modules/invariant/invariant.js:40:15)
      at Object.getEnforcing (../node_modules/react-native/Libraries/TurboModule/TurboModuleRegistry.js:39:3)
      at Object.<anonymous> (../node_modules/react-native/Libraries/NativeModules/specs/NativeDevSettings.js:30:37)
      at Object.<anonymous> (../node_modules/react-native/Libraries/Utilities/DevSettings.js:10:1)

Mocking:
jest.mock(
  'react-native',
  () => ({
    ...jest.requireActual('react-native'),
    NativeEventEmitter: class MockNativeEventEmitter {
      // ...
    },
    NativeModules: {
      // ...
    },
    Platform: {
      OS: 'android',
    },
  })
);

Online searches for this error all point to problems compiling in dev vs release mode, nothing remotely close to what I'm trying to do.

A: Have you tried importing DevSettings from react-native and adding the same imported module in your mock? This would be the process for every Component/Module being used in your tested component. Something like:
import { DevSettings } from 'react-native`

jest.mock(
  'react-native',
  () => ({
    ...jest.requireActual('react-native'),
    NativeEventEmitter: class MockNativeEventEmitter {
      // ...
    },
    NativeModules: {
      // ...
    },
    Platform: {
      OS: 'android',
    },
    DevSettings
  })
);


text:
Q: Add score board in ti-tac-toe game

var grid = document.getElementById('grid');
var msg = document.querySelector('.message');
var chooser = document.querySelector('form');
var mark;
var cells;

// add click listener to radio buttons
function setPlayer() {
  mark = this.value;
  msg.textContent = mark + ', click on a square to make your move!';
  chooser.classList.add('game-on');
  this.checked = false;
  buildGrid();
}

// add click listener to each cell
function playerMove() {
  if (this.textContent == '') {
    this.textContent = mark;
    checkRow();
    switchMark();
    computerMove();
  }
}

// let the computer make the next move
function computerMove() {
  var emptyCells = [];
  var random;

/*  for (var i = 0; i < cells.length; i++) {
    if (cells[i].textContent == '') {
      emptyCells.push(cells[i]);
    }
  }*/

  cells.forEach(function(cell){
    if (cell.textContent == '') {
      emptyCells.push(cell);
    }
  });

  // computer marks a random EMPTY cell
  random = Math.ceil(Math.random() * emptyCells.length) - 1;
  emptyCells[random].textContent = mark;
  checkRow();
  switchMark();
}

// switch player mark
function switchMark() {
  if (mark == 'X') {
    mark = 'O';
  } else {
    mark = 'X';
  }
}

// determine a winner
function winner(a, b, c) {
  if (a.textContent == mark && b.textContent == mark && c.textContent == mark) {
    msg.textContent = mark + ' is the winner!';
    a.classList.add('winner');
    b.classList.add('winner');
    c.classList.add('winner');
    return true;
  } else {
    return false;
  }
}

// check cell combinations
function checkRow() {
  winner(document.getElementById('c1'), document.getElementById('c2'), document.getElementById('c3'));
  winner(document.getElementById('c4'), document.getElementById('c5'), document.getElementById('c6'));
  winner(document.getElementById('c7'), document.getElementById('c8'), document.getElementById('c9'));
  winner(document.getElementById('c1'), document.getElementById('c4'), document.getElementById('c7'));
  winner(document.getElementById('c2'), document.getElementById('c5'), document.getElementById('c8'));
  winner(document.getElementById('c3'), document.getElementById('c6'), document.getElementById('c9'));
  winner(document.getElementById('c1'), document.getElementById('c5'), document.getElementById('c9'));
  winner(document.getElementById('c3'), document.getElementById('c5'), document.getElementById('c7'));
}

// clear the grid
function resetGrid() {
  mark = 'X';
 /* for (var i = 0; i < cells.length; i++) {
    cells[i].textContent = '';
    cells[i].classList.remove('winner');
  }*/
  cells.forEach(function(cell){
    cell.textContent = '';
    cell.classList.remove('winner');
  });
  msg.textContent = 'Choose your player:';
  chooser.classList.remove('game-on');
  grid.innerHTML = '';
}

// build the grid
function buildGrid() {
  for (var i = 1; i <= 9; i++) {
    var cell = document.createElement('li');
    cell.id = 'c' + i;
    cell.addEventListener('click', playerMove, false);
    grid.appendChild(cell);
  }
  /* cells = document.querySelectorAll('li'); //Returns a NodeList, not an Array
  See https://css-tricks.com/snippets/javascript/loop-queryselectorall-matches */
  cells = Array.prototype.slice.call(grid.getElementsByTagName('li'));
}

var players = Array.prototype.slice.call(document.querySelectorAll('input[name=player-choice]'));
players.forEach(function(choice){
  choice.addEventListener('click', setPlayer, false);
});

var resetButton = chooser.querySelector('button');
resetButton.addEventListener('click', function(e) {
  e.preventDefault();
  resetGrid();
});
html {
  box-sizing: border-box;
}
*, *:before, *:after {
  box-sizing: inherit;
}

body {
  background-color: #996E89;
  font-family: "Comfortaa", sans-serif;
}

h1 {
  font-family: "Lobster", serif;
}

.message {
  color: #fff;
  font-size: 1.5em;
  padding-bottom: 1em;
}

form {
  label {
    font-size: 4em;
    font-weight: bold;
    vertical-align: middle;
  }
  input[type=radio] {
    margin: 1em;
    cursor: pointer;
  }
  fieldset {
    display: block;
    opacity: 1;
    transition: all ease 1s;
  }
  &.game-on fieldset {
    opacity: 0;
    display: none;
  }
  &.game-on button {
    opacity: 1;
    display: block;
    margin: 0 auto;
  }

}

#grid-section {
  margin: 3em 0;
}

#grid {
  width: 300px;
  margin: 0 auto;
}

li {
  border: 1px solid #000;
  width: 100px;
  height: 100px;
  display: block;
  float: left;
  font-size: 3em;
  text-align: center;
  padding: .5em;
}

#c1, #c2, #c3 {
  border-top: none;
}

#c3, #c6, #c9 {
  border-right: none;
}

#c7, #c8, #c9 {
  border-bottom: none;
}

#c1, #c4, #c7 {
  border-left: none;
}

.winner {
  color: #9AE1E5;
}

.btn-primary,
.btn-primary:focus {
  background-color: #33B7A5;
  opacity: 0;
  outline: 0;
  transition: all ease .3s;
}

.btn-primary:hover {
  background-color: #4C2F39;
}

Player vs Computer Tic-Tac-Toe

Choose your player:

    <form action="#">
      <fieldset>
        <input type="radio" name="player-choice" id="player-choice-1" value="X" />
        X
        <input type="radio" name="player-choice" id="player-choice-2" value="O" />
        O
      </fieldset>
      <button id="reset" class="btn btn-primary">Reset</button>
    </form>

I wish to add a scoreboard on top where wins,loses,draws would be calculated. How do I go about the same? Also an another HTML page where I could see the number of wins, loses, draws.
I have tried adding table in the html and using it in JS but not able to implement the same.
Could you suggest any methods to implement these tasks in the project.


text:
Q: How to append database values to JSON data I have a JSON which lists the values from database. Below is the JSON data of 2 rows from the database.
[{"Name":"P1","Description":"pd1","Value":"v1","Attribute":"a1"},{"Name":"P1","Description":"pd1","Value":"v2","Attribute":"a2"}]

database values are the result of a left join query. Only 'Value' and 'Attribute' fields are different. Can I append that fields to JSON instead of multiple sets of record? I know there is 'push' to do this, but I am unaware where and how to use this in my code. below is the code for fetching values from db and serializing the values.
GetProfileDataService GetProfileDataService = new BokingEngine.MasterDataService.GetProfileDataService();
IEnumerable<ProfileData> ProfileDetails = GetProfileDataService.GetList(new ProfileSearchCriteria { Name = strProfileName });
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string strSerProfileDetails = javaScriptSerializer.Serialize(ProfileDetails);
context.Response.ContentType = "text/json";
context.Response.Write(strSerProfileDetails);

Below is my getJSON
$(document).ready(function () {
    $.getJSON('ProfileHandler.ashx', { 'ProfileName': 'Profile 1' }, function (data) {
        $.each(data, function (k, v) {
            alert(v.Attribute+' : '+v.Value);
        });
    });
});

Please help me here.

A: There are several things you can do.
Store value and attribute as arrays:
[{"Name":"P1","Description":"pd1","Value":["v1", "v2"],"Attribute":["a1", "a2"]}]
Or store them as a 'symbol'-separated string:
[{"Name":"P1","Description":"pd1","Value":"v1;v2"],"Attribute":"a1;a2"]}]
In order to use the first case, you'll have to try and figure out how to format the ProfileDetails in order to have javaScriptSerializer.Serialize parse it correctly. You will likely have to convert your data first in order for this to work (i.e. convert value and attribute to arrays).
For the second case to work you could modify your GetProfileDataService.GetList method so that values and attributes are merged to symbol-separated strings (something like this: GROUP BY to combine/concat a column)


text:
Q: declare 2nd array without size how can declare a 2nd or multidimensional array without first size in c++?
class numeric
{
    public:
    int int_array_numbers[][];
    ...
};

Error message:
declaration of 'int_array_numbers' as multidimensional array must have bounds for all dimensions except the first

A: you can declare your class as template from two arguments
something like this
template <int N, int M>
class numeric
{
public:
     int int_array_numbers[N][M];
...
};

A: You can't, C++ doesn't support VLA's (variable length arrays).
Use a std::vector<std::vector<int> > instead.


text:
Q: Graphics with dataframe I have a table with export of every EU country:
country 2001  2002  2003  .....
france  12023 54554 251515 ....
.....

I would like to do a plot with the value of every years for 4 country (e.g. Germany, Italy, France, Netherlands). It's a dataframe I have tried with those commands:
y<-ts(EXEU)
y
plot(y[5,],type="o")

But when I use ts I lose all the name of the countries and I have on the x-axis frequency not every years. It's possible to do the same without use ts().

A: Try this:
library(reshape2)
library(ggplot2)

#EXEU is your dataframe
EXEU<-melt(EXEU,id='country',variable.name='YEAR',value.name='VALUE')
ggplot(EXEU,aes(YEAR,VALUE,group=country, color=country))+geom_line()


text:
Q: Entity Framework core 2.1 Many To Many Select Query How would I create the following query using Linq?
SELECT product.name, product.code, category.Name FROM product
INNER JOIN productCategories ON product.ID = productCategories.productID
INNER JOIN category ON productCategories.categoryID = category.ID
WHERE productCategories.ID = idToFind

Product & Category Classes:
public class Product
{
    public Product()
    {
        this.Categories = new HashSet<Category>();
    }
    public int ID { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Category> Categories { get; set; }
}

public class Category
{
    public Category()
    {
        this.Products = new HashSet<Product>();
        this.Children = new HashSet<Category>();
    }
    public int ID { get; set; }

    [StringLength(150)]
    public string Name { get; set; }
    public int? ParentID { get; set; }
    public virtual Category Parent { get; set; }

    public virtual ICollection<Category> Children { get; set; }
    public virtual ICollection<Product> Products { get; set; }
}

I have tried a few different things and can get the results if I only need columns from one table, but can not get details from both tables i.e. category name & product name.
Edit:
I have now added a JunctionClass
public class CategoryProduct
{
    public int CategoryID { get; set; }
    public Category Category { get; set; }

    public int ProductID { get; set; }
    public Product Product { get; set; }

}

and tried :
var results = _context.Product.Include(e => e.categoryProducts).ThenInclude(e => e.Category).Where(c=>c.categoryProducts.Category.ID==169).ToList();

But I still cant make it work.
Getting the error:
'ICollection<CategoryProduct>' does not contain a definition for 'Category' and no accessible extension method 'Category' accepting a first argument of type 'ICollection<CategoryProduct>' could be found

A: In EF core, you need a junction table to map many-to-many relationships.
public class ProductCategory
{
    public int Id { get; set; }
    public int ProductId { get; set; }
    public Product Product { get; set; }
    public int CategoryId { get; set; }
    public Category Category { get; set; }
}

public class Product
{
    ...
    public virtual ICollection<ProductCategory> ProductCategories { get; set; }
}

public class Category
{
    ...
    public virtual ICollection<ProductCategory> ProductCategories { get; set; }
}

// DbContext
public DbSet<ProductCategory> ProductCategories { get; set; }

public override OnModelCreating(ModelBuilder builder)
{
    builder.Entity<ProductCategory>()
           .HasOne(pc => pc.Product)
           .WithMany(p => p.ProductCategories);

    builder.Entity<ProductCategory>()
           .HasOne(pc => pc.Category)
           .WithMany(c => c.ProductCategories);
}

// Query
var result = await dbContext.ProductCategories
                     .Select(pc => new {
                         ProductName = pc.Product.Name,
                         ProductCode = pc.Product.Code,
                         CategoryName = pc.Category.Name
                      })
                     .SingleOrDefaultAsync(pc => pc.Id == idToFind)

A: //Mock SomeData
List<Product> products = new List<Product>();
List<Category> category = new List<Category>();
//Linq
var result = products.SelectMany(product => product.Categories.SelectMany(productCategory => category.Where(category => category.ID == productCategory.ID).Select(category => new { category.Name, ProductName = product.Name, product.Code })));

A: Try this
var idToFind = 3;

var o = (from p in _products
         from c in p.Categories
         where c.ID == idToFind
         select new {ProductName = p.Name, ProductCode = p.Code, CategoryName = c.Name}).ToList();


text:
Q: On a users click, load a block of javascript into page I am adding a third party comment plugin on my html pages. The plugin slows down the pageload somewhat due to the number of connections the page makes to load the comment plugin.
The comment plugin will be contained within a div.
I would like to delay the loading of the comment javascript until a visitor clicks a 'add/read comments' button/link.
The language for the page is html5. I want to preferably, if possible, keep my pages as .html
The pages are html5 and css3.
my ccs3 and html5 knowledge is average. my javascript knowledge is poor. all other languages i haven't a clue about.
I was going to have the 'add/read comments' button/link, load up a duplicate page with the third party comment plugin loaded, but felt this was a messy way of doing this, as well as adding more time (another pageload then the plugin script) for the user to wait before being able to comment.
I don't want this comment plugin loading at all, not even in the background, until the user clicks the button. The reason for this, is because I don't want the user to see any indication of the page hanging/still loading, when the page load is complete without the comment plugin visable.
I sincerely hope this makes sense for someone to follow.
Answers will be much appreciated.
Thankyou for your time.
The following is the code livefyre gave me to insert into my html..

 <--- that is the div i am surrounding the comment plugin in

A: You can dynamically inserting external JavaScript to web pages when click on a button:
<button onclick="addScript()">Click</button>

A: It's not really difficult. Defer loading of JavaScript or external stuff is now needed for faster page loads. For example, there are Facebook/twitter plugins which I wanted to load once my page is loaded so one way to do is to initialize external plugins loading in window.onload or $(window).load in case of jQuery.
In your case, in the comment button onclick event, load the JavaScript of external plugin. What we typically do is manipulate the elements using Document Object Model (DOM).
As an example, I want to load an iframe on button click:
<input type="button" id="btnComment" onclick="createframe();" style="height:50px; width:120px;" value="Click Me!" />

function createframe() {
    var i = document.createElement("iframe");
    i.src = "http://www.adilmughal.com";
    i.scrolling = "auto";
    i.frameborder = "0";
    i.width = "90%";
    i.height = "220px";
    document.getElementById("container").appendChild(i);
}

What this will do is create a new iframe element with any src URL and append as container's child.
Output and code can also be viewed on http://jsfiddle.net/adilmughal/ZJZn7/

A: I've taken a look at the liveFire docs, and it looks like it should be easy enough to initialise it on click, rather than as the page loads.
However, liveFyre actually initialises as soon as it can - rather than playing nice and waiting for the page to be ready. This is very likely the reason it slows down your page load. Does your liveFyre code look like this?

If it does, try changing it to:

This should just make livefyre wait until the page is interactive before it tries to initialise. It may not help enough (or at all), but it's a safe and easy option to try first. If it doesn't help enough, post back, and we'll pursue your 'initialise on click' option.
--- UPDATE ---
Based on your comments with the code snippet, try this (I think the comment has been a little bit mangled - hopefully you can translate this over OK:

Again, the idea is just to wait for the page to be interactive before trying to initialise. Let us know what happens!


text:
Q: Different buttons to pass intent of mp3 files pulled from zip expansion files to a media player I am working on an education app and the expansion files have messed up my thinking a bit.
I have different buttons (a lot of them) in a RelativeLayout. Each display a sentence. When you click on one, it opens up a popup window, in which you have the option to play the mp3 file of the sentence that has opened the popup. It has been all okay, until I was forced to use expansion files.
So, each button click has to pass on an intent of a different audio file that it calls from the expansion file zip package.
I have implemented the zip_file package in the app and I have put the uncompressed zip and (just in case) an obb files on the memory card into an obb folder to be able to test it.
Here are a few sample lines from my original code.
final Button btn_L1R_en_L2 = (Button) findViewById(R.id.btn_L1R_en_L2);
btn_L1R_en_L2.setOnClickListener(this);
final Button btn_L1R_en_L6 = (Button) findViewById(R.id.btn_L1R_en_L6);
btn_L1R_en_L6.setOnClickListener(this);
final Button btn_L1R_en_L7 = (Button) findViewById(R.id.btn_L1R_en_L7);
btn_L1R_en_L7.setOnClickListener(this);

@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.btn_L1R_en_L2:
            if (popUpScreen != null && popUpScreen.isShowing()) {
                popUpScreen.dismiss();
                popUpScreen = null;
            } else {
                setEngSent(R.string.lesson1reading_en_L2);
                setFrnSent(R.string.lesson1reading_frn_L2);
                setDfAccSentAudio(R.raw.l1r_df_l2); //originally this is an audio file that the player would need to play, but from now on it has to come from the zip package. How?
                initiatePopupScreen();
            }
        break;

        case R.id.btn_L1R_en_L6:
            if (popUpScreen != null && popUpScreen.isShowing()) {
                popUpScreen.dismiss();
                popUpScreen = null;
            } else {
                setEngSent(R.string.lesson1reading_en_L6);
                setFrnSent(R.string.lesson1reading_frn_L6);
                setDfAccSentAudio(R.raw.l1r_df_l6); //originally this is an audio file that the player would need to play, but from now on it has to come from the zip package. How?
                initiatePopupScreen();
            }
        break;

        case R.id.btn_L1R_en_L7:
            if (popUpScreen != null && popUpScreen.isShowing()) {
                popUpScreen.dismiss();
                popUpScreen = null;
            } else {
                setEngSent(R.string.lesson1reading_en_L7);
                setFrnSent(R.string.lesson1reading_frn_L7);
                setDfAccSentAudio(R.raw.l1r_df_l7);
                initiatePopupScreen();
            }
        break;
    }
}

public void setDfAccSentAudio(int dfAccSentAudio) {
    this.dfAccSentAudio = dfAccSentAudio;
    sentencePlayer = MediaPlayer.create(this, dfAccSentAudio);
}

btn_default_acc = (ImageButton) layout.findViewById(R.id.btn_df_acc);
    btn_default_acc.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            pauseWholeTextPlayer();
            stopSentencePlayer();
            sentencePlayer = MediaPlayer.create(Lesson1Reading.this, dfAccSentAudio);
            sentencePlayer.start();
        }
    });


text:
Q: C++ Raspberry Pi Controlling GPIO I/O via class/objects with Header file This question comes after this subject :
Methods and parameters declaration problem in a class with header
I tried to solve this next problem, but without success.
I'm using a raspberry pi with C++ and trying to implement a GPIO control through a class.
Therefore, I have :

*

*my main cpp file where I call the object (it works, I'm sure of that, you'll see) called "RobotControl03.cpp"

*the class cpp file called "Motorcontrol01.cpp"

*the header file called "Motorcontrol01.h"

My goal here is to simply call a "while(1)" loop where the states of the GPIO outputs is contently changing just for tests purpose.
I check the output via my oscilloscope ;)
The problem is that it apparently execute correctly, shows what is expected on the screen (see screen capture at the bottom), but the output pins stay at 0V constantly.  :'(
I tried several modifications but nothing worked...
My code is more complex than what I show here, but I simplified it for tests purpose and it don't work anyway -_-
Main file called "RobotControl03.cpp" :
#include <iostream> //for Cout to display stuff
#include <cstdio>
#include <csignal>
#include <ctime>
#include <vector>   //for using vectors instead of arrays
#include <chrono>   //library for counting time
#include <thread>   //for multithreading
#include <termios.h>
#include <wiringPi.h>   //Raspberry pi GPIO Library
#include "RPMCounter01.h"
#include "MotorControl01.h" //looking in current dirrectory

bool RUNNING = true;    // global flag used to exit from the main loop

//###################################################################################
//  GPIO Pins definition
//###################################################################################
//int SPser = 13, SPclk = 19, SPrclk = 26; //Define the output pins used
int Motor0In = 17; //define the input pins used
int Motor1In = 18; //define the input pins used

/*int SPser = 13;
int SPclk = 19;
int SPrclk = 26; //Define the output pins used for the main shift registers
int PWMSPclk = 6;
int PWMSPrclk = 12; */

//###################################################################################
//    The array in which the different pins values will be stored
//###################################################################################
std::vector<std::vector<bool>> DataArr(16,std::vector<bool>(8, 0)); //create the array of data for the shift register. Each vector is of 8 values for the shift registers of the PWM control
//direction 0 = forward, 1 = backward. PWM = 0 is stop, over, it runs
 /* 0 = Direction   | Motor 1   8  =
     * 1 = PWM      | Motor 1   9  =
     * 2 = Direction    ] Motor2    10 =
     * 3 = PWM      ] Motor2    11 =
     * 4 =              12 =
     * 5 =              13 =
     * 6 =              14 =
     * 7 =              15 =
    */
int M0Speed = 0;
std::vector<bool> M0SpeedBin(8, 0); //Binary value of the motor speed
int M1Speed = 0;
std::vector<bool> M1SpeedBin(8, 0);

//###################################################################################
// Callback handler if CTRL-C signal is detected
//###################################################################################
void my_handler(int s)
{
    std::cout << "Detected CTRL-C signal no. " << s << '\n';
    RUNNING = false;
}
//###################################################################################
//              MAIN
//###################################################################################
int main()
{
    // Initialize wiringPi and allow the use of BCM pin numbering
    /*wiringPiSetupGpio();

    pinMode(SPser, OUTPUT);
    pinMode(SPclk, OUTPUT);
    pinMode(SPrclk, OUTPUT);
    pinMode(PWMSPclk, OUTPUT);
    pinMode(PWMSPrclk, OUTPUT);*/

    // Register a callback function to be called if the user presses CTRL-C
    std::signal(SIGINT, my_handler);

    MotorControl pouet; //Create an object, calling it pouet
    std::cout << "calling SendDataPWM " << '\n';
    pouet.SendDataPWM(DataArr); //calling the method of the object

}

The header file called "MotorControl01.cpp"
//###################################################################################
// Class for creating the different shift register entry data
//###################################################################################

#include <iostream> //for Cout to display stuff
#include <chrono>   //library for counting time
#include <thread>   //for multithreading
#include <vector>
#include <wiringPi.h>   //Raspberry pi GPIO Library
#include "MotorControl01.h" //looking in current dirrectory

MotorControl::MotorControl(){   //constructeur
    //std::vector<std::vector<bool>> MCDataArr(16, std::vector<bool>(8, 0));    //the vector of vectors with boolean values in it for transmitting the motors control data
    //mFrequency = 0;
    //mGPIOOutputNb = 0;
    //###################################################################################
    //  GPIO Pins definition
    //###################################################################################
    SPser = 13;
    SPclk = 19;
    SPrclk = 26; //Define the output pins used for the main shift registers
    PWMSPclk = 6;
    PWMSPrclk = 12; // define the output pins to control the PWM shift registers
}

void MotorControl::SendDataPWM(std::vector<std::vector<bool>> MCDataArr){

    // Initialize wiringPi and allow the use of BCM pin numbering
    wiringPiSetupGpio();

    //initialize the pins
    pinMode(SPser, OUTPUT);
    pinMode(SPclk, OUTPUT);
    pinMode(SPrclk, OUTPUT);
    pinMode(PWMSPclk, OUTPUT);
    pinMode(PWMSPrclk, OUTPUT);

    // copy the data of the received vecor to preserve it
    //std::vector<std::vector<bool>> EditDataArr(16, std::vector<bool>(8, 0));
    //EditDataArr = DataArr;

while (1) {
    digitalWrite(PWMSPclk, HIGH);       //after looping through every value, ticking the register to load everything on the output of the main registers
    digitalWrite(PWMSPclk, LOW);
    std::cout << "PWM SP CLK"<<  PWMSPclk <<'\n';
    digitalWrite(PWMSPrclk, HIGH);      //after looping through every value, ticking the register to load everything on the output of the PWM registers
    digitalWrite(PWMSPrclk, LOW);
    std::cout << "PWM SP R CLK"<< PWMSPrclk <<'\n';
    digitalWrite(SPclk, HIGH);      //after looping through every value, ticking the register to load everything on the output of the main registers
    digitalWrite(SPclk, LOW);
    std::cout << "SP CLK"<< SPclk<<'\n';
    digitalWrite(SPrclk, HIGH);     //after looping through every value, ticking the register to load everything on the output of the PWM registers
    digitalWrite(SPrclk, LOW);
    std::cout << "SP R CLK"<< SPrclk<<'\n';
}
}

And the pretty header file that goes with it :
#ifndef DEF_MotorControl
#define DEF_MotorControl
#include <vector>
class MotorControl{
    public:
        MotorControl();     //Constructeur
        void SendDataPWM(std::vector<std::vector<bool>> MCDataArr);

    private:
        //std::vector<std::vector<bool>> MCDataArr;
        int mFrequency;
        int mGPIOOutputNb;
        int SPser;
        int SPclk;
        int SPrclk; //Define the output pins used for the main shift registers
        int PWMSPclk;
        int PWMSPrclk;
};

#endif

Here is the command prompt result :

I hope I don't need to show a picture of an oscilloscope showing nothing ;)
Edit :
For those thinking that setting the GPIO port "on" then directly "off" don't let it time to get at level, I've been doing that since the beginning, here is the kind of result expected :

I have been able to perfectly control a shift register with it. It's just since I've put my code in separate files that it don't work anymore :(
Thanks for your help !
EDIT 2 :
I've added some sleeps in the code :
    digitalWrite(PWMSPclk, HIGH);
    sleep(1);
    digitalWrite(PWMSPclk, LOW);
    sleep(1);
    std::cout << "PWM SP CLK"<<  PWMSPclk <<'\n';
}
    digitalWrite(PWMSPrclk, HIGH);
    sleep(1);
    digitalWrite(PWMSPrclk, LOW);
    sleep(1);
    std::cout << "PWM SP R CLK"<< PWMSPrclk <<'\n';

    digitalWrite(SPclk, HIGH);
    sleep(1);
    digitalWrite(SPclk, LOW);
    sleep(1);
    std::cout << "SP CLK"<< SPclk<<'\n';

    digitalWrite(SPrclk, HIGH);
    sleep(1);
    digitalWrite(SPrclk, LOW);
    sleep(1);
    std::cout << "SP R CLK"<< SPrclk<<'\n';

I looped through only one of the signals, it gives something like this :
while (1) {

    //using namespace std::chrono;
    //CDelTime = 1ns; // interval at which a pin is turned HIGH/LOW

    digitalWrite(PWMSPclk, HIGH);       //after looping through every value, ticking the register to load everything on the output of the main registers
    //sleep(1);
    digitalWrite(PWMSPclk, LOW);
    //sleep(1);
    std::cout << "PWM SP CLK"<<  PWMSPclk <<'\n';
}

from where does this 6-7µs delay comes from?


text:
Q: Displaying NDVI from MYD09Q1 product with TIMESAT I use MODIS surface reflectance (MYD09Q1) for calculate NDVI in GEE and save it to .dat(ENVI std. format) then use TIMESAT image view to display the mosaic data, encountering file size warning:
Hi I received this error: file size does not match no or rows * no or columns * no of bytes. will still attempt to drow.


text:
Q: Setting an HTMLElement using TypeScript I'm converting my old JavaScript to TypeScript. I have a Table Of Contents JSX component that I use to easily scroll to a specific heading.
I use a function to find the total scroll offset required to scroll to the specified heading. After converting this to a '.tsx' file, I get an error:

Type 'Element' is missing the following properties from type 'HTMLElement': accessKey, accessKeyLabel, autocapitalize, dir, and 107 more.

// TOC.tsx
...
const accumulateOffsetTop = ( el: HTMLElement | null, totalOffset = 0 ) => {
  while ( el ) {
    totalOffset += el.offsetTop - el.scrollTop + el.clientTop
    el = el.offsetParent // <- Error here
  }
  return totalOffset
}
...

This function is called here:
// TOC.tsx
...
export default function Toc(
  { headingSelector, getTitle, getDepth, ...rest }
) {
  const { throttleTime = 200, tocTitle = `Contents` } = rest
  const [headings, setHeadings] = useState( {
    titles: [],
    nodes: [],
    minDepth: 0,
    offsets: [],
  } )
  const [open, setOpen] = useState( false )
  const [active, setActive] = useState()
  const ref = useRef()
  useOnClickOutside( ref, () => setOpen( false ) )
  useEffect( () => {
    const selector = headingSelector || Array.from(
      { length: 6 }, ( _, i ) => `main > h` + ( i + 1 )
    )
    const nodes = Array.from( document.querySelectorAll( selector ) )
    const titles = nodes.map( node => ( {
      title: getTitle ? getTitle( node ) : node.innerText,
      depth: getDepth ? getDepth( node ) : Number( node.nodeName[1] ),
    } ) )
    const minDepth = Math.min( ...titles.map( h => h.depth ) )
    const startingOffsets = nodes.map( el => accumulateOffsetTop( el ) - 100 )
    setHeadings( { titles, nodes, minDepth, startingOffsets } )
  }, [headingSelector, getTitle, getDepth] )

  const scrollHandler = throttle( () => {
    const { titles, nodes } = headings
    const offsets = nodes.map( el => accumulateOffsetTop( el ) )
    const activeIndex = offsets.findIndex(
      offset => offset > window.scrollY + 120
    )
    setActive( activeIndex === -1 ? titles.length - 1 : activeIndex - 1 )
  }, throttleTime )
  useEventListener( `scroll`, scrollHandler )
...
}

How do I set the types of the parameters passed to accumulateOffsetTop?

A: The error gets thrown because el.offsetParent is of type Element | null and not of type HTMLElement | null. The reason el.offsetParent does not return an HTMLElement by default is because el.offsetParent could also result in different types of Element such as SVGElement (issue#156). You will have to use type assertions here and maybe make sure the returned value is an HTMLElement if necessary.

A: The answer I ended up uses type assertions.
const accumulateOffsetTop = ( el: HTMLElement, totalOffset = 0 ) : number => {
  while ( el ) {
    totalOffset += el.offsetTop - el.scrollTop + el.clientTop
    el = el.offsetParent as HTMLElement
  }
  return totalOffset
}


text:
Q: "Show current location" Button (Like Maps.app) I state I'm a beginner so please don't miss any step!
I used that code to show and "jump" to the user location:
- (void)mapView:(MKMapView *)mv didAddAnnotationViews:(NSArray *)views {
for(MKAnnotationView *annotationView in views) {
    if(annotationView.annotation == mv.userLocation) {
        MKCoordinateRegion region;
        MKCoordinateSpan span;

        span.latitudeDelta=0.002;
        span.longitudeDelta=0.002;

        CLLocationCoordinate2D location=mv.userLocation.coordinate;

        region.span=span;
        region.center=location;

        [mv setRegion:region animated:TRUE];
        [mv regionThatFits:region];
    }
}

But I'd like to request it just when I press a button.. How can I do it? (Remember: I'm a beginner!). Thanks in advance!

A: All you need to do is not call your setRegion above, but just call it when you press the button.  Alternatively you can turn updating your map on and off with [locationManager startUpdatingLocation][locationManager stopUpdatingLocation], but leaving this on burns up battery, so be judicious.


text:
Q: Can POSIX/Linux unlink file entries completely race free? POSIX famously lets processes rename and unlink file entries with no regard as to the effects on others using them, whilst Windows by default raises an error if you even try to touch the timestamps of a directory which has a file handle open somewhere deep inside inside.
However Windows doesn't need to be so conservative. If you open all your file handles with FILE_FLAG_BACKUP_SEMANTICS and FILE_SHARE_DELETE and take care to rename files to random names just before flagging deletion, you get POSIX semantics including lack of restriction on manipulating file paths containing open file handles.
One very nifty thing Windows can do is to perform renames and deletes and hard links only using an open file descriptor, and therefore you can delete a file without having to worry about whether another process has renamed it or any of the directories in the path preceding the file's location. This facility lets you perform completely race free file deletions - once you have an open file handle to the right file, you can stop caring about what other processes are doing to the filing system, at least for deletion (which is the most important as it implicitly involves destroying data).
This raises the question of what about POSIX? On POSIX unlink() takes a path, and between retrieving the current path of a file descriptor using /proc/self/fd/x or F_GETPATH and calling unlink() someone may have changed that path, thus potentially leading to the wrong file being unlinked and data lost.
A considerably safer solution is this:

*

*Get one of the current paths of the open file descriptor using /proc/self/fd/x or F_GETPATH etc.

*Open its containing directory.

*Do a statat() on the containing directory for the leafname of the open file descriptor, checking if the device ids and inodes match.

*If they match, do an unlinkat() to remove the leafname.

This is race safe from the parent directory upwards, though the hard link you delete may not be the one expected. However, it is not race safe if within the containing directory a third party process were to rename your file to something else and rename another file to your leafname between you checking for inode equivalence and calling the unlinkat(). Here the wrong file could be deleted, and data lost.
I therefore ask the question: can POSIX, or any specific POSIX implementation such as Linux, allow programs to unlink file entries completely race free? One solution could be to unlink a file entry by open file descriptor, another could be to unlink a file entry by inode, however google has not turned up solutions for either of those. Interestingly, NTFS does let you delete by a choice of inode or GUID (yes NTFS does provide inodes, you can fetch them from the NT kernel) in addition to deletion via open file handle, but that isn't much help here.
In case this seems like too esoteric a question, this problem affects proposed Boost.AFIO where I need to determine what filing system races I can mitigate and what I cannot as part of its documented hard behaviour guarantees.
Edit: Clarified that there is no canonical current path of an open file descriptor, and that in this use case we don't care - we just want to unlink some one of the links for the file.

A: No replies to this question, and I have spent several days trawling through Linux source code. I believe the answer is "currently you can't unlink a file race free", so I have opened a feature request at https://bugzilla.kernel.org/show_bug.cgi?id=93441 to have Linux extend unlinkat() with the AT_EMPTY_PATH Linux extension flag. If they accept that idea, I'll mark this answer as the correct one.


text:
Q: Terminology on comparison of homotopy types I'm asked to compare the homotopy type of two topological spaces, and I'm not sure what words to use.
For example, given $S^1$ and $S^1\lor S^1$, I know that the fundamental group of $S^1$ is a proper subgroup of the fundamental group $S^1\lor S^1$. I would like to say something like "The homotopy type of $S^1$ is smaller than the homotopy type of $S^1\lor S^1$".
Furthermore, I wouldn't like to rely on the subgroup relation, since any free group has as subgroup any other free group. In the previous example I could use the fact that the rank of $\mathbb{Z}$ is strictly smaller than the rank of $\mathbb{Z}*\mathbb{Z}$.
Question: Is there any common terminology for the comparison of homotopy types?

A: It doesn't really make much sense in general to compare homotopy types in more than the most basic language. For example, how do the homotopy types of $S^1$ and $S^\infty$ compare? Since $S^1$ includes into $S^\infty$, you might be tempted to say that $S^1$ is 'smaller' than $S^\infty$. But $S^\infty$ is weakly contractible, so contains a lot less homotopic information than even $S^1$. These spaces are simply homotopically different.
It does make sense, however, to say that a space $A$ is a retract, or deformation of another space $X$ (which is the case for your example). This is really the only case that you might be tempted to say that $A$ is 'smaller' than $X$, since all the homotopy and homology groups of $A$ appear as summands of those of $X$. Hence $X$ contains all the basic homotopic information of $A$, as well as possibly more. You still need to take care, though, since $A$ and $X$ may actually be homotopy equivalent.


text:
Q: Keil arm Cortex - Find middle number of 3 Lets say that i load 3 number values to three different registers. And i want to find the middle number.
AREA median, CODE, READONLY
    EXPORT main
first  EQU 3
middle EQU 3
last   EQU 9
    ENTRY

main
     MOV R0, #first
     MOV R1, #middle
     MOV R2, #last
----------
Here i would like to compare these 3 values and find the middle number. (in this case, 3)

I tried something like CMP R1, R2 but i was not able to store the value that i wanted in a register. This is what i tried to find the smaller or bigger of two.
main:
        mov     r1, #3     /* setting up initial variable a */
        mov     r2, #9     /* setting up initial variable b */
        cmp     r1, r2     /* comparing variables to determine which is bigger */
        blt     r1_lower   /* jump to r1_lower in case r2 is bigger  */
        mov     r0, r1     /* if branching/jumping did not occur, r1 is bigger (or the same) so store r1 into r0 */
        b       end        /* proceed to the end */
r1_lower:
        mov r0, r2         /* end up here because r1 was smaller than r2, so move r2 into r0 */
        b end              /* proceed to the end */

Any thoughts ?

A: For three numbers specifically, there are two basic approaches:

*

*you can sort the three numbers and return the middle number from the sorted array.  For this, a three-stage sorting network is generally useful.  To build this, use this primitive which swaps r0 and r1 if r0 is larger than r1, using r3 as a temporary register:
cmp   r0, r1     # if (r0 > r1)
movgt r3, r1     #         r2 = r1
movgt r1, r0     #         r1 = r0
movgt r0, r3     #         r0 = r1

*alternatively, you can compute the maximum and minimum of the three numbers and subtract it from their sum, yielding the number in the middle.  For example, if the three numbers are in r0, r1, and r2, this can be done by:
cmp       r0, r1 # if (r0 > r1)
movgt r3, r0     # then r3 = r0  (r3 is max)
movgt r4, r1     # then r4 = r1  (r4 is min)
movle r3, r1     # else r3 = r1
movle r4, r0     # else r4 = r0
cmp       r2, r3 # if (r2 > r3)
movgt r3, r2     # then r3 = r2
cmp       r4, r2 # if (r4 > r2)
movgt r4, r2     # then r4 = r2
add   r5, r0, r1 # r5 = r0 + r1  (r5 is middle)
add   r5, r5, r2 # r5 = r5 + r2
sub   r5, r5, r3 # r5 = r5 - r3
sub   r5, r5, r4 # r5 = r5 - r5

A: What was the exact problem you encountered?  Your CMP instruction is fine, and will set the status flags depending on the relative values of R0 and R1, so you can then use a conditional branch (e.g. BHI or BGT) or one of the IT family of instructions that will allow you to execute other instructions conditionally using the same condition codes.
There's a quick reference for the Thumb-2 instruction set (as used by most of the Cortex-M devices, which I'll assume you're using in the absence of any other information) here, and there's plenty more documentation on conditional branching and conditional execution on the ARM Infocenter site, for example here for the Cortex-M3.


text:
Q: Extract substring with character instead of position I recently got into nautilus scripts, and for the one I'm writing I'd need to extract a substring from a filename. My problem is that I found tons of methods to extract a substring based on the position of a character, and not any on how to find a given character in my string and extract a substring from or up to this character.
cut -f1 -d "delimiter"

works, but cut only accepts 1-char delimiter.
Maybe awk or expr?
EDIT:
I'm writing in bash and for example I expect a file with the name
Any.Series.S01E01.VOSTFR.@whatever.com.avi

to be renamed to simply
Any Series S01 E01 VOSTFR.avi

A: With POSIX shells, using pattern stripping parameter expansion operators (initially from the Korn shell):
string=whateverDELIMrestDELIMmore
before_first_DELIM=${string%%DELIM*}
before_last_DELIM=${string%DELIM*}
after_first_DELIM=${string#*DELIM}
after_last_DELIM=${string##*DELIM}

A: If you had written how you would like to use this script, I would be a able to give a more specific answer, however I think the following line might be enough for you to adapt to your needs.
$ echo "abcde" | awk '{print substr($0, index($0, "c"))}'
cde

Just replace the second argument of index to the character you want.

A: Parameters expansion actually did the trick.
echo ${1%.S??E*}|sed 's/\./ /'

echoes the name of the series and changes potential dots to spaces. Wouldn't work for any series (for example Mr. Robot needs a dot) but, that's close enough already.

A: You only provided one example. More would be nice!
Any.Series.S01E01.VOSTFR.@whatever.com.avi
Which you want broken up into:

*

*Any Series

*S01

*E01

*VOSTFR

*avi
At first glance, this isn't too dissimilar to the problem of RPM package naming, where the first field (name) can contain the delimiter used elsewhere. However, I'm going to assume you have a fixed format field there which you also want to break into two fields.
For this, I would split on season+episode:
IFS=';' episode=( $(echo "$FILENAME"|sed -E 's/(.+)\.(S[0-9]{2})(E[0-9]{2})\.([^\.]+)\..*\.([^\.]+)/\1;\2;\3;\4;\5/') )

I'm setting the delimiter to semicolon for the scope of the assignment, then plugging the output of the regex into a bash array, which will have five fields: ${episode[0]} .. ${episode[4]}
I haven't expanded the episode name field dots to spaces. We could probably do it all in one go, but treating it separately allows you to do stuff like using underscores, or adding complication like looking for double .. in the case of Mr..Robot -> Mr. Robot. Simply:
episode[0]="${episode[0]//./ }"

And more complex, preserving . where it signifies an abbreviation as in "Mr. Robot":
episode[0]="$(echo "${episode[0]}"|sed -E 's/\.([^\.])/ \1/g')"

Lastly, I'd then construct a target filename, using array expansion to print four fields from field #0 delimited by spaces, then a period, then the last field:
TARGET="${episode[@]:0:4}.${episode[4]}"

Then it's just a matter of passing FILENAME and TARGET to mv, using quotes to be safe:
mv "$FILENAME" "$TARGET"