Is this really better analyzed in G minor than in Bb?

Question: So I have been analysing Rondo a Capriccio by Beethoven and I reached a point where a so called "expert's" opinion and mine differ drastically. It starts at bar 57 and continues to bar 68. After the last eighth in bar 68, my opinion and their opinion as far as the analysis are the same. First I will show both my opinion and the expert's opinion as far as analysis.
Here is mine:

As you can see, my opinion as far as analysis is concerned has 2 harmonic areas, Bb and Gm. Now here is the expert's opinion about these same measures:

As you can see, the so called expert thinks that the entire passage is in Gm. It makes for there being fewer modulations, but what previously made total sense is nonsense now. Like the vi ii V I, one of the most common chord progressions becoming i iv VII III, which is just total nonsense, even in a minor key. Also, the resolution to III diminishes the sense that you are in a minor tonality to begin with.
My way of analysing it avoids this problem by having the section from bars 57-68 be in Bb until it reaches the last eighth note of bar 68, at which point it pivots to Gm and it only makes sense in Gm.
Here is my reasoning behind analysing bars 57-68 in Bb instead of Gm:

Yes, you would expect to hear Bb major chords in a G minor piece. But in a G minor piece, if there is a resolution to III, that typically is a modulation to Bb and thus is truly a resolution to I, not III. VI and VII on the other hand can be resolved to without a sense of modulation in a minor key, just like how in a major key, you can resolve to vi without actually modulating to vi. So it just makes more sense to me for bars 57-68 to be in Bb, regardless of whether that means there is a modulation later on or not. And besides, Rondo a Capriccio has frequent modulations anyway.
Also, typically, in a minor key, III does not get inverted whatsoever. It usually is in root position. Here, if the whole passage is analyzed as being in Gm, you get all 3 inversions. There are only 2 chords(3 if you extend it to seventh chords) that typically get all the inversions. Those being I and V in major and i and V in minor(and also vii°7 if you extend it to seventh chords). Other chords like IV or vi typically only get 2 of the 3 inversions and a few others like III typically aren't inverted at all. So to see all 3 inversions of what is supposedly III in Gm makes me doubt that it is in Gm at all and instead think that it is in Bb.

So am I right in saying that it starts in Bb and then pivots to Gm? Or is the expert right in saying that the entire passage from bar 57 is in Gm? Which one makes more sense harmonically speaking, my analysis or the expert's analysis?
Comment: This question highlights a limitation of functional harmonic analysis.  It's like listening to a piece in triple time and then arguing whether it is in 3/4 meter or 3/8 meter: it's more about the conventions of analysis and notation than it is about the music itself.  It's a piece in G minor that spends some time in the tonal center of the mediant.  Whether a chord is labeled VII or V/III or is analysed in the context of B flat make instead of G minor is not of great concern.
Comment: In Bb I'd say the second half of bar 63 is V7 because of the Eb, which further strengthens the Bb major feel.
Comment: @Richard Teodor Lontos on Musescore.com is who I'm referring to. He commented on my harmonic analysis score there that bars 57-74 should all be analyzed in G minor instead of part of it being analyzed in Bb. Here is the link so you can see both his comment and my response to it: https://musescore.com/user/50070/scores/5667301
Comment: The i iv VII III chord progression is not total nonsense in a minor key. The VII-III chord progression is very common in classical music from my findings, and I used it effectively myself in one of my earlier classical music compositions. Stringing it together with i-iv is not implausible at all. In fact, i-iv-VII-III makes a very powerful sequence.
Comment: May I ask who the expert is?
Answer: Using the word "key" is too definite. The music progresses through lots of different tonal centers but most of them don't last long enough to be worth calling "keys".
Both of you are wrong about the whole passage, but the "expert" is more wrong.
The point which you both missed is the sequence in bars 66-70 with a V-I cadences in Bb major, C minor, and D major - which of course is the dominant of G, so we arrive back home.
Equally, trying to pretend that a G minor chord after a full cadence in G major is in any tonal center other than G is just ignoring what the music sounds like.
So, somewhere between bars 57 and 65 (and don't forget the passage is repeated) the tonal center shifts from G minor to B flat major. Exactly where does that happen? Frankly, who cares! If you like, you can claim you are both right, and the first time through the repeat is in G minor, but the second time in is B flat major. There is no rule that music has to have a unique, unambiguous analysis according to the "rules" in some textbook, and most good music is ambiguous to greater or lesser degree. The chord in "bar 57 following bar 56" doesn't necessarily have the same harmonic function as the chord in "bar 57 following bar 64" even though the notes are the same.
Incidentally, claiming that bar 75 is anything except a fresh start in Eb major is just as nonsensical as the debate in the OP. Once again, stop looking at the score, and start listening!
Answer: I suggest that it's ridiculous to analyse 57 as anything but i in G minor, but equally ridiculous to analyse the cadence at 64/65 as anything other than  V-I in B♭ major.   So have both.   G minor at 57 with an immediate modulation to B♭ major.   After that, at 64, it's a bit more up for grabs.  We know we're in G minor by bar 72.  What tonal centre do you prefer at bar 65?  A new one every couple of bars or not?  Perhaps Roman numerals aren't all that useful in this section!
Look at the whole piece.   Up to bar 57 we have been firmly in G major, key signature one sharp, and apart from an occasional 'V of V' completely diatonic.   The change at 57 is clearly to i of G minor (not vi of B♭ major), and your 'expert' has preferred to treat the entire section up to the return of G major as based on that key.   I see his point, from a structural viewpoint,  though I think it results, when analysing the detail,  in Roman numbers that aren't always very helpful.
https://musescore.com/classicman/scores/201476
Comment: but i iv VII III, which would be like vi ii V I but in minor, makes no harmonic sense because VII isn't a dominant function chord in minor. And the resolution to III and III showing up in all 3 inversions both weaken the minor tonality. The presence of III, III6, and III64 in particular makes it sound like the true tonic is actually Bb for that entire section, at least until bar 68 where afterwards, it only makes sense in G minor. If bars 57-68 are analysed in Bb major, these problems don't exist and it makes much more harmonic sense.
Comment: I was actually largely agreeing with you!   I've edited my answer to hopefully make it clearer.
Comment: @Caters If you want to say it's in Bb right at 57 then it's a "crash and go" modulation, which seems reasonable for Beethoven, but at least as reasonable is a modulation to Bb over a few bars (57-60) via a smoother modulation to the parallel minor. In the end, as long as you see what's going on I think you can be comfortable with your analysis. There's not necessarily one right answer for this kind of thing. I agree with this answer that the cadence at 63-64/65 is very strong in Bb and also once you get the F#s in 70 that really makes it sound like G Minor.
Answer: Look at how the excerpt falls into sections/phrases.  Harmony often isn't static, each section in a single key: it moves, on various timescales, through phrases and sections of a piece.
The first 8 bars of the excerpt, bars 57–64 (plus repeat), are most naturally read as starting in g minor, and ending in Bb major.  Then the next 8 bars, 66–75, go from Bb major back to g minor.  So when seen together as a 16-bar section (or 32-bar including repeats), it goes (g minor) –> (Bb major) –> (g minor).  The g minor is the key this section starts from and returns to; so it's the key that makes the most impression on the ear, and this is why it would generally be analysed as the main key of the section, although it's certainly true that in the middle, the section moves to a (shorter-timescale) tonal centre of Bb major.
Going back to the first phrase now, to see why it would usually be analysed as "starting in g minor, and ending in Bb major", rather than as "in Bb major, starting on the 6th":  When you first hear the g minor beginning, there's been nothing before it to suggest Bb major; it and the next bar clearly set up the idea of g minor.  Unless something later gives a strong reason to view things otherwise, the natural way to analyse this is that the phrase starts in g minor.  At this point, the listener has no reason to hear it as anything else.  Now, as you say, there is some reason to consider the alternative view, since the phrase immediately moves towards a clear cadence in Bb major.  However, it doesn't stay there — as quickly as it has moved to Bb major, it then moves back in the next phrase to an equally clear cadence in g minor.  So the Bb major isn't established for any longer than the g minor was; so it doesn't really give a compelling reason to reanalyse the start of the phrase in hindsight.
An example of the contrary, where the start of a phrase really does deserve reanalysis based on what comes after it, would be the Rondo of Beethoven's 4th Piano Concerto in G.  The first couple of bars seem to establish C major; but the rest of the theme, and the continuation, establish G major more strongly and for longer.  With so much surrounding context in G, it becomes natural to hear the opening bars as really being the subdominant of G, rather than establishing C as a tonic as they seem to on first hearing.  However, in your excerpt, there isn't anything like so much surrounding context to establish Bb major as a more significant tonal centre than the initial g minor.


How to replace a JPanel with another while the program is running

Question: The code has a JPanel with an inner JPanel that displays awt drawing. Upon mouseclick the inner JPanel is to be replaced by one of its polymorphic siblings. This code isn't replacing the jPanel.

class ContentPanel extends JPanel {
  private GraphicPanel graphicPanel;

  public ContentPanel(GraphicPanel graphicPanel) {
    this.graphicPanel = graphicPanel;
    add(this.graphicPanel);

  public void setGraphicPanel(GraphicPanel graphicPanel) {
    this.graphicPanel = graphicPanel;

//      invalidate();
//      revalidate();
//      repaint();
    }

Setting the graphicPanel to a polymorphic relative doesn't cause any errors, it just isn't painting the new graphicPanel. Using cardLayout is not preferred, there must be a cleaner way. How to proceed?
Comment: The cleaner way is to use a cardlayout.
Answer: in setGraphicPanel, you need to remove the current graphicPanel and add the new one. THEN call revalidate.
something like this:
public void setGraphicPanel(GraphicPanel graphicPanel) {
    this.removeAll();
    this.graphicPanel = graphicPanel;
    this.add(graphicPanel);
    this.revalidate();
}

Although CardLayout was designed to do just this thing. Are you sure you don't want to use CardLayout?


Render page callback output in another region than "content"

Question: I am implementing hook_menu and I want to render the output of one page callback in a certain region, other than content.
Is there a way of doing this?
Answer: Instead of defining a page via hook_menu it is better to define a block that you can place everywhere across the site.
Is there any requirement that restricts you to using a page?
If not the following code creates a block:
/**
* Implements hook_block_info().
*/
function YOUR_MODULE_block_info() {
  $blocks = array();
  $blocks['YOUR_BLOCK_ABC'] = array(
    'info' => t('YOUR BLOCK NAME'),
  );
  return $blocks;
}

/**
* Implements hook_block_view().
*/
function YOUR_MODULE_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'YOUR_BLOCK_ABC':
      $block['subject'] = '';
      $block['content'] = _YOUR_MODULE_BLOCK_ABC_CONTENT();
      break;
  }
  return $block;
}

function _YOUR_MODULE_BLOCK_ABC_CONTENT() {
  // This is where you code you use for the page goes.
  return t('Hello world');
}

Code from http://kahthong.com/2013/06/create-your-own-custom-drupal-block-programmatically
You can restrict the block visibility in the block settings to only be shown on single pages. Maybe this might solve the problem. To access arguments from the current page you can use the arg function.
Cheers
j
Comment: Unfortunately I do not know about something like that unless you digg into your theme and check for the path before rendering. Blocks are actually pretty straight forward, too I think ;)
Comment: Hey! Well.. I am not restricted to using `hook_menu`, but I wanted to create something directly on a certain page and I thought that was most straight way of doing it. So there is no way of forcing the output of the `page callback` to a certain region, eh?
Comment: without using a `hook_menu` there's no URL defined, so the block renders on a 404 page, only based on it's visibility settings. has anyone found a workaround for this other than @Marian
Answer: I have managed to move the output from the content region to the content_top custom region like this:
function MYMODULE_page_alter(&$page)
{
    list($path) = explode('/', current_path());

    if ('shopping-list' == $path) {
        $page['content']['#region'] = 'content_top';
        $page['content_top'] = $page['content'];
        unset($page['content']);
    }
}


Are random variables correlated if and only if their ranks are correlated?

Question: Assume $X,Y$ are continuous random variables with finite second moments. The population version of Spearman's rank correlation coefficient $ρ_s$ can be defined as the Pearson's product-moment coefficient ρ of the probability integrals transforms $F_X(X)$ and $F_Y(Y)$, where $F_X,F_Y$ are the cdf's of $X$ and $Y$, i.e.,
$ρ_s(X,Y)=ρ(F(X),F(Y))$.
I wonder whether one can generally conclude that
$ρ(X,Y)≠0↔ρ(F(X),F(Y))≠0$?
I.e., do we have linear correlation if and only if we have linear correlation between the ranks?
Update: In the comments two examples are given why
$\rho(F_X(X),F_Y(Y))=0\rightarrow \rho(X,Y) = 0$
is not true in general, even if $X$ and $Y$ have the same distribution. So the question should be reformulated as
$\rho(X,Y) = 0 \rightarrow \rho(F_X(X),F_Y(Y))$?
It is also of great interest to me whether this is true/false if $X$ and $Y$ have the same distribution.
(Note: If $X$ and $Y$ are positively quadrant dependent, i.e., $δ(x,y)=F_{X,Y}(x,y)−F_X(x)F_Y(y)>0$ then Hoeffding's covariance formula $Cov(X,Y)=∫∫δ(x,y)dxdy$ yields that $ρ(X,Y)>0$ and $ρ(F(X),F(Y))>0$.)
Comment: Hint: To obtain an answer, think about what happens to each correlation measure under an arbitrary strictly monotonic transformation.
Comment: You're correct. The second example does not work out as I intended/suspected. However, the general principle on how to construct such a counterexample still holds. And, yes, this matter can be tied in tightly with copulas. :-)
Comment: Once you have confirmed your counterexamples, please consider writing them up in an answer to this post. I will be happy to upvote it. Cheers.
Comment: @cardinal: well, spearman's rho is invariant under strictly monotonic transformations, the classical linear correlation coefficient will change, but its unclear how (?)...in particular I do not know whether the linear correlation value can change its value form zero to non-zero under strictly monotonic transformations...but maybe I missed your point?
Comment: You are on the right track! Let $X \sim \mathcal{N}(0,1)$ and $Y = X^2$. Now, look at strictly monotonic transformations of these two. I have not explicitly checked, but $g(z) = \exp(-z/2)$ is likely to work.
Comment: @cardinal: Fantastic! Your example shows that $cov(X,Y) = 0, cov(g(X),g(Y)<0$ but $cov(F_X(X),F_Y(Y))=0$, so we can conclude that $cov(F_X(X),F_Y(Y))=0 \rightarrow Cov(X,Y) = 0$ is false.  Many thanks! The remaining question then is whether $Cov(X,Y) = 0 \rightarrow Cov(F_X(X),F_Y(Y))=0$. Looking at the definition of these covariance measures I suspect that this also isn't true in general. But once again I cannot think of a counterexample...Any ideas?
Comment: Again, I have not checked explicitly, but try $U \sim \mathcal{U}(-1,1)$ and $V = |U|$.
Comment: I also have not checked this analytically but simulating 1000 times 1000 realizations of (U,V) indicate that $cov(U,V)=cov(F_U(U),F_V(V))=0$. I also recognized that if (X,Y) are connected with a t copula with zero correlation and degrees of freedom >2 and have both exponential margins then $cov(X,Y)\neq 0, cov(F_X(X),F_Y(Y))=0$, so even if the margins are identical then zero Spearman's correlation does not imply zero Pearson's correlation.
Answer: Neither correlation being zero necessarily tells you much about the other, since they 'weight' the data - especially extreme data - quite differently. I am just going to play with samples, but similar examples could be constructed with bivariate distributions / copulas.
1. Spearman correlation 0 doesn't imply Pearson correlation 0:
As mentioned in the question, there are examples in the comments, but the basic structure is "construct a case where Spearman correlation is 0, then take an extreme point and make it more extreme without changing the Spearman correlation"
The examples in comments cover that very well, but I am just going to play with a more 'random' example here. So consider this data (in R), which by construction has both Spearman and Pearson correlation 0:
<code>x=c(0.660527211673069, 0.853446087136149, -0.00673848667511427,
-0.730570343152498, 0.0519171047989013, 0.00190761493801791,
-0.72628058443299, 2.4453231076856, -0.918072410495674, -0.364060229489348,
-0.520696233492491, 0.659907250608776)
y=c(-0.0214697990371976, 0.255615059485107, 1.10561181413232, 0.572216886959267,
-0.929089680725018, 0.530329993414123, -0.219422799586819, -0.425186120279194,
-0.848952532832652, 0.859700836483046, -0.00836246690850083,
1.43806947831794)

cor(x,y);cor(x,y,method="sp")
[1] 1.523681e-18
[1] 0
</code>
Now add 1000 to y[12] and subtract 0.6 from x[9]; the Spearman correlation is unchanged but the Pearson correlation is now 0.1841:
<code>  ya=y
  ya[12]=ya[12]+1000
  xa=x
  xa[9]=xa[9]-.6
  cor(xa,ya);cor(xa,ya,method="sp")
[1] 0.1841168
[1] 0
</code>
(If you want strong significance on that Pearson correlation, just replicate the entire sample several times.)
2. Pearson correlation 0 doesn't imply Spearman correlation 0:
Here's two examples with zero Pearson correlation but nonzero Spearman correlation (and again, if you want strong significance on these Spearman correlations, just replicate the entire sample several times).
Example 1:
<code> x1=c(rep(-3.4566679074320789866,20),-2:5)
 y1=x1*x1
 cor(x1,y1);cor(x1,y1,method="spe")
[1] -8.007297e-17
[1] -0.3512699
</code>

Example 2:
<code> k=16.881943016134132
 x2=c(-9:9,-k,k)
 y2=c(-9:9,k,-k)
 cor(x2,y2);cor(x2,y2,method="spe")
[1] -9.154471e-17
[1] 0.4805195
</code>

In this last example, the Spearman correlation can be made stronger by adding more points on y=x while making the two points at the top left and bottom right more extreme to maintain the Pearson correlation at 0.


Find the standard matrix of a transformation

Question: Let
$M:\mathbb{R}^2\ \rightarrow\mathbb{R}^2$ be the linear transformation that first reflects it through the line $x_1=x_{2}$, and then rotates each point counterclockwise around the origin by
$\frac{5 \pi}{4}$ radians.
Find the standard matrix of $M$
So I was thinking, since it's the line $x_1 = x_2$, looking at it graphically, I would have
$$\begin{pmatrix}
cos(x)&-sin(x)\\
sin(x)&cos(x)\\
\end{pmatrix}$$
which then becomes
$$\begin{pmatrix}
sin(x)&cos(x)\\
cos(x)&-sin(x)\\
\end{pmatrix}$$
which then becomes (using $x = \frac{5\pi}{4}$)
$$\begin{pmatrix}
-\frac{\sqrt{2}}{2}&-\frac{\sqrt{2}}{2}\\
-\frac{\sqrt{2}}{2}&\frac{\sqrt{2}}{2}\\
\end{pmatrix}$$
But that's the wrong answer. Would really appreciate some help with these, I don't fully understand how to algebraically find / convert these reflections yet.
Thanks!
Answer: The reflection through the line $x_1=x_2$ maps $\left(1,1\right)$ into itself and it maps $\left(-1,1\right)$ into $\left(1,-1\right)$. So, its matrix with respect to the standard basis is $\left[\begin{smallmatrix}0&1\\1&0\end{smallmatrix}\right]$. And the matrix of a counterclockwise rotation around the origin with angle $\frac{5\pi}4$ is$$\begin{bmatrix}-\frac1{\sqrt2}&\frac1{\sqrt2}\\-\frac1{\sqrt2}&-\frac1{\sqrt2}\end{bmatrix}.$$So, take$$\begin{bmatrix}-\frac1{\sqrt2}&\frac1{\sqrt2}\\-\frac1{\sqrt2}&-\frac1{\sqrt2}\end{bmatrix}.\begin{bmatrix}0&1\\1&0\end{bmatrix}=\begin{bmatrix}\frac1{\sqrt2}&-\frac1{\sqrt2}\\-\frac1{\sqrt2}&-\frac1{\sqrt2}\end{bmatrix}.$$
Comment: No, I am **not** reflecting first. The matrix that I wrote is the matrix of a counterclockwise rotation around the origin with angle $\frac{5\pi}4$. **After** having computed that matrix, I multiply it by the matrix corresponding to the reflection.
Comment: In this problem, it is stated that the *first* transformation is the reflection. In that other problem, the reflection is the *second* transformation.
Comment: At no point I wrote that I first take the counterclockwise rotation and then the reflection. Take a look at my answer. I computed the matrix $R$ corresponding to the reflection, I computed the matrix $O$ corresponding to the counterclockwise rotation and then I wrote that the answer is $O.R$. By this order. The matrix $R$ is on the right since it is the **first** operation and the matrix $R$ is on the left since it is the **second** operation. The operations are written from the right to the left.
Comment: Why is the first row, second column the one that is positive rather than second row second column? We are first supposed to reflect, correct? If so, $-sin(x)$ will be in the second row second column I believe?
Comment: Because it's the matrix$$\begin{bmatrix}\cos\left(\frac{5\pi}4\right)&-\sin\left(\frac{5\pi}4\right)\\\sin\left(\frac{5\pi}4\right)&\cos\left(\frac{5\pi}4\right)\end{bmatrix}.$$
Comment: Yeah, but you're reflecting it first right? So shouldn't it be $-\sin(x)$ at the second row, second column?
Comment: Hey Jose, it's me again. I have a quick additional question to this. Let's call matrix $A$ the matrix we want to transform using a reflection, and the reflection being $R$. Why is it that in your example, it works perfectly fine doing $A \times R$ yet, in my other question from the other day, I need to multiply it like $R \times A$ (apparently order is important for matrix multiplication)? See my other question I'm referring to if you have a minute: https://math.stackexchange.com/questions/4158927/linear-transformations-and-reflections (the answer by mathcounterexample)
Comment: Thanks a bunch! I hope this was it, but I will probably think of a few more questions :P
Comment: I just tried another one for practice, and I keep getting it twisted with the concept of first and second transformation. Is there some intuitive way to think about this? You stated that you're not reflecting first, and that you first take the counterclockwise rotation and THEN reflect, but doesn't the problem state you should do it the other way around? Thanks in advance!
Comment: Oh right! Thanks a ton again!!


amCharts 3 - Making labels appear in pie and stopping on click

Question: I have the following chart:

AmCharts.makeChart("chartdiv", {
  "type": "pie",
  "theme": "light",
  "colorField": "color",
  "series": [{
    "type": "PieSeries",
    "alignLabels": false,
    "ticks": {
      "disabled": true
    },
    "labels": {
      "radius": "-40%",
      "fill": "white"
    }
  }],
  "dataProvider": [{
      "title": "Yes",
      "value": 3,
      "color": "#6bbdb9"
    },
    {
      "title": "No",
      "value": 2,
      "color": "#2f2f2f"
    }
  ],

  "titleField": "title",
  "valueField": "value",
  "labelRadius": 5,

  "radius": "42%",
  "innerRadius": "60%",
  "labelText": "[[title]]",

  "export": {
    "enabled": true
  }
});
#chartdiv {
  width: 100%;
  height: 500px;
}

I have two items I want to resolve:

I want the "Yes" and "No" labels to sit inside rather the slices, rather than be outside. From the V4 docs, I have tried this approach:
"series": [ {
  "type": "PieSeries",
  "alignLabels": false,
  "ticks": {
    "disabled": true
  },
  "labels": {
    "text": "{value.percent.formatNumber('#.0')}%",
    "radius": "-40%",
    "fill": "white"
  }
}]

But this approach doesn't work for me in V3 (does nothing).

When you click a slice, it animates the slice outwards, I want, on click, for it to do nothing. Can't find anything on the docs about this?

Any ideas?
Answer: A lot of what you're looking for is in the aptly named Version 3 documentation; I'm not sure why you were poking around in the version 4 documentation.
That said, to move the labels inside, you need to set a negative labelRadius as demonstrated here:
AmCharts.makeChart("...", {
  // ...
  labelRadius: -35, //adjust as needed
  // ...
});

To disable the pull out on click, set pullOutRadius to 0.
AmCharts.makeChart("...", {
  // ...
  pullOutRadius: 0,
  // ...
});

Demo below:

AmCharts.makeChart("chartdiv", {
  "type": "pie",
  "theme": "light",
  "colorField": "color",
  "dataProvider": [{
      "title": "Yes",
      "value": 3,
      "color": "#6bbdb9"
    },
    {
      "title": "No",
      "value": 2,
      "color": "#2f2f2f"
    }
  ],

  "titleField": "title",
  "valueField": "value",
  "labelRadius": -35,

  "radius": "42%",
  "innerRadius": "60%",
  "labelText": "[[title]]",
  "color": "#ffffff",
  "pullOutRadius": 0,

  "export": {
    "enabled": true
  }
});
#chartdiv {
  width: 100%;
  height: 500px;
}

Answer: Just put the "labelRadius" to a value lower than zero like "-35".
this.chart = this.AmCharts.makeChart('amchart-3', {
        'type': 'pie',
        "export": {
            "enabled": true,
            "menu": [ {
              "class": "export-main",
              "menu": [{
                        "format": "JPG",
                        "label": "Guardar como JPG",
                        "title": "Exportar gráfica a formato JPG",
                        'fileName': "Estadisticas  de planes de carga",
                    },{
                        "format": "PNG",
                        "label": "Guardar como PNG",
                        "title": "Exportar gráfica a formato PNG",
                        'fileName': "Estadisticas  de planes de carga",
                    }]
            } ]
        },
        "hideCredits": true,
        'dataProvider': this.datos,
        'titleField': 'townName',
        'valueField': 'tPlanes',
        'labelRadius': -35,
        'radius': '46%',
        'labelText': 'Planes [[value]] - fecha: [[title]]',
        'adjustPrecision': true,
        'angle': 30,
        "depth3D": 15,
        'marginRight': 40,
        'marginTop': 30,
        'marginBottom': 30,
        'fontSize': 10,
        'outlineAlpha': 1,
        'outlineThickness': 1,
        "legend":{
            "enabled": true,
            "position": "right",
            "divId": "legenddiv"
       },
       'balloonText': 'Total de planes: [[value]]  Fecha: [[title]]',
       "balloon": {
            "drop": true,
            "adjustBorderColor": false,
            "color": "#FFFFFF",
            "fontSize": 10,
            'maxWidth': 75,
        },
    });

In this example im using Angular and changed some atributtes


Scenebuilder rejects Webview in custom control

Question: I'm creating a rich text control that uses a WebView for display and HTMLEditor for editing. When I tried to add the control to Scenebuilder's custom controls an exception was thrown:
Exception for: com/spindotta/jfx/control/text/RichTextArea.class

javafx.fxml.LoadException:
at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)

...
Caused by: java.lang.IllegalStateException: Not on FX application thread; currentThread = LibraryFolderWatcher([library folder location])

...
at javafx.scene.web.WebEngine.checkThread(WebEngine.java:1216)

...
It seems that Scenebuilder tries to instantiate a WebView, which in turn tries to instantiate a WebEngine which seems to require an FX application thread, which the custom control doesn't generate.
Would be grateful for any ideas/workaround.
Thanks!
Answer: SceneBuilder has a built in mechanism that checks all the jars in the user library looking for custom controls.
For any given jar, that implies checking all its classes, looking for possible controls: concrete classes that are assignable from Node. Then it creates an instance for these and try to load it on the class path. If it works, it will be added to the library panel.
In case of your custom control, that includes a WebView node, this means that when your control is being checked by SceneBuilder, a new instance of WebView will be done. At this point you'll get the exception you mentioned:
Caused by: java.lang.IllegalStateException: Not on FX application thread; currentThread = LibraryFolderWatcher()
at com.sun.javafx.tk.Toolkit.checkFxUserThread(Toolkit.java:236)
at com.sun.javafx.tk.quantum.QuantumToolkit.checkFxUserThread(QuantumToolkit.java:423)
at javafx.scene.web.WebEngine.checkThread(WebEngine.java:1216)
at javafx.scene.web.WebEngine.<init>(WebEngine.java:856)
at javafx.scene.web.WebEngine.<init>(WebEngine.java:845)
at javafx.scene.web.WebView.<init>(WebView.java:271)

So the easy solution for this will be allowing the custom control to be loaded in the JavaFX application thread when being loaded in design mode by SceneBuilder.
This small custom control works for me:
public class WebControl extends StackPane {

    private WebView webView;

    public WebControl() {
        if (Platform.isFxApplicationThread()) {
            init();
        } else {
            // Intended for SceneBuilder
            Platform.runLater(this::init);
        }
    }

    private void init() {
        webView = new WebView();
        WebEngine webEngine = webView.getEngine();
        webEngine.load("http://www.google.com");
        getChildren().add(webView);
    }

}

Comment: @JPereda - Thanks for your reply, and especially for explaining the process step-by-step and how that lead to the exception. It's exactly what I thought was happening, but your explanation is more articulate which is probably because you know what you're doing and I ... don't. Relatively new here, so I don't know how to give you credit, would be grateful if you could comment back as to how. Thanks!
Comment: Just accept the answer (click on the check mark beside the answer) as valid and up vote it if you like. That will help others to find it as a valid source in case they run in the same problem.
Comment: Bro, you are a legend. Thank you!


Iterating over Key Set vs Iterating over Entry Set

Question: A coworker sent out a tip today that states that the latter snippet of code is more efficient because it does not have to do the lookup in the map on every iteration like the former (#1).
How is #2 (latter) more efficient? I just don't understand how #1 and #2 are different.
**#1 snippet**:
for (String key : map.keySet())
{
   String value = map.get(key); // does lookup for every key
   // do something with value
}

**#2 snippet**:
for (Map.Entry<String, String> entry : map.entrySet())
{
   String key = entry.getKey();
   String value = entry.getValue();
}

Answer: The issue is that map.get usually has a significant constant-factor cost, whereas iterating over map.entrySet() is usually just as cheap as iterating over map.keySet().
This is most significant for things like TreeMap, where the first loop would actually be O(n log n) and the second loop would be O(n), but even for HashMap, get has a constant-factor cost that could be avoided with the second loop.
Answer: Snippet #2 can be faster as the inner part of the loop is basically two calls for getting properties.
In snippet #1, at each iteration step you call map.get which is a worst-case O(n) operation if you have bad hash codes for key. Even with a good hash code, there is a constant cost associated with finding the right bucket and retrieving the value.
Note that the iteration in case of HashMaps for both versions is the same, as they both use a HashIterator:
 final class KeyIterator extends HashIterator
    implements Iterator<K> {
    public final K next() { return nextNode().key; }
}

final class EntryIterator extends HashIterator
    implements Iterator<Map.Entry<K,V>> {
    public final Map.Entry<K,V> next() { return nextNode(); }
}

Comment: I think you mixed up #1 and #2?


Is an element that is algebraic over $\mathbb{Q}$ algebraic over $\mathbb{Z}?$

Question: In Fraleigh's A First Course in Abstract Algebra, it states that $\mathbb{C}$ is an extension field of $\mathbb{Q}$. This I understand, but then it states that since $\sqrt{2}$ is a zero of $x^2-2$, $\sqrt{2}$ is algebraic over $\mathbb{Q}$.  I'm not clear on why it matters that $\mathbb{C}$ is an extension field of $\mathbb{Q}$, since $\sqrt{2}$ is in $\mathbb{R}$.  In this case, is $\sqrt{2}$ algebraic over $\mathbb{Z}$, also?
Thanks.
Answer: It is algebraic over $\mathbb Z$, since the monic polynomial $x^2-2$ has integral coefficients, and hence belongs to $\mathbb Z[x]$.
Answer: What Andres Mejia said is the reason $\sqrt{2}$ is algebraic over $\mathbb{Z}$, however judging by your question you might want to think whether "all elements that are algebraic over $\mathbb{Q}$ are also algebraic over $\mathbb{Z}$" is true or false. This is indeed very easy to think about.
Comment: If an element is algebraic over the rationals, then there it is a root of a polynomial with rational coefficients, but if we multiply out by e.g. the product of all denominators we get that it is also a root of a polynomial with integer coefficients, therefore it's algebraic over the integers. Is this correct?


Duvida na estrutura do código

Question: Nesse codigo:
class ShoppingList extends React.Component {
  render() {
    return (

Shopping List for {this.props.name}

Instagram

WhatsApp

Oculus

    );
  }
}

Bom, minha duvida é:
o React.Component é uma classe?
O render () é um método?
e nesse aqui:
class Square extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: null,
    };
  }

o Constructor é um metodo?
O Props é um parametro??
E o super é uma função??
Pode parecer idiota essas perguntas mas estou tentando enteder ao maximo como funciona a estrutura da linguagem e do framework.
Ja li a documentação tanto do JS quanto do React porém ainda me perco um pouco
Comment: Tirando o caso dos props (que não sei bem como é passado pq não uso react), a resposta é sim pra todas as as perguntas.
Comment: Sim para todos... !!! estudou bem...
Answer: Opa Matheus, boa parte dessas perguntas são em relação ao JS,
Constructor
É um tipo especial de método para criar e iniciar um objeto criado pela classe.
Super
Uma classe básica do React herda a classe React.Component, para passar parâmetros para a classe pai é necessário utilizar o método super, por isso ele é utilizado nesse caso, para passar as propriedades do componente para o pai da classe que é o React.Component.
Props
São as propriedades que o React recebe através das tags, abaixo um exemplo:
<Component title="Nome" />

Nesse exemplo acima, title é uma propriedade que vai vim nas props do React.
Answer:
O React.Component é uma classe?

Sim, é uma classe. Como especificado na API do React, para criar um componente de classe, você deve extender a classe Component, exposta pelo React.

O render() é um método?

Sim, é um método. No contexto do React, todos os componentes classe devem possuir um método render para renderizar o HTML daquele componente.
Para saber mais sobre o funcionamento geral de métodos no JavaScript, veja a documentação na MDN.

O constructor é um metodo?

Sim, é um método. Porém, especial. De acordo com a documentação MDN, um construtor é um método especial para criar e inicializar um objeto criado a partir de uma classe, o que significa que sempre será executado quando a classe for instanciada.
No contexto do React, sempre que o componente for instanciado, o construtor será iniciado. Geralmente, isso só acontece uma vez.

O props é um parametro?

Sim. Sempre que você renderiza um componente React, você tem a possibilidade de passar props, que poderão ser acessadas através do primeiro parâmetro do construtor da classe.
<ListItem name="Estudar React" />

O super é uma função?

Não! O super é uma palavra-chave do JavaScript usado para acessar a classe pai de uma classe.
No contexto do React, o super deve ser utilizado para passar as props para a classe pai React.Component.
Não entrarei em muitos detalhes sobre o porque dessa necessidade. Se você quiser, no entanto, saber mais sobre isso, recomendo a leitura do excelente artigo "Por Que Nós Escrevemos super(props)?", do Dan Abramov.

Duvida na estrutura do código


Is there a way to set a session variable but not save them in the sessions table?

Question: I wanted to save a huge array in a $_SESSION variable. If I understand it correctly, Drupal saves the entire $_SESSION into the sessions table. But when the $_SESSION variable gets to around 3mb, MySQL throws an error.
I don't want to increase max_allowed_packet size, and I don't really need Drupal to save the array variable in the sessions table.
So, is there a way to set a $_SESSION variable that can be excluded from being saved into the sessions table?
Comment: Why do you put the huge array in $_SESSION if you don't really need drupal to save the array variable in the session table? You could use a static variable? See https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/drupal_static/7.x
Comment: @4k4 I need it in a batch process, so a static variable won't work.
Answer: You should probably look first at either not storing this data but instead deferring its calculation, or at alternative storage methods, eg perhaps cache_set() and cache_get(). You could easily run into the same DB limitations there of course.
You probably don't need to store this data to the session at all, and as you've discovered it can be problematic to do so.
I've seen developers use  $_SESSION as a global variable to pass data around, and as temporary per-visitor storage. This is possible, but there are limitations and likely better ways - for which you might need to zoom out to the actual problem at hand. (Do you need to store a rendered collection of kitten profiles, or just a list of kitten IDs then render later?)
If you do actually need to store such large datasets to the session, you'd probably have to replace the default session management in Drupal or reconfigure your DB (which you've said you'd rather not do). In that case perhaps modules like Session Proxy or perhaps Memcache would help ... But try not to go there :)
Comment: Thank you. I am actually collecting the data through a batch process - and write to an excel file. It's just that through my tests, it is faster to collect all the data first, then do a single write to the excel file. Instead of writing to the excel file repeatedly.


Convert google comments in text file to rmarkdown footnotes

Question: I am working with text files that have been extracted from google docs. The google docs versions have comments and these are included in the file when they are converted to .txt. I would like to programmatically convert each comment to an rmarkdown flavoured footnote.
At present they look like so:
*Background:*[a] Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Nulla[b] a accumsan enim. Aenean sed elit a nunc efficitur pharetra.

*Method:* [c]Praesent dapibus turpis in dictum aliquam.

[a]This should be bolded
[b]What happens to a multiple

line

comment?
[c]How about we make this italics?

The desired output is
*Background:*^[This should be bolded] Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Nulla^[What happens to a multiple

line

comment?] a accumsan enim. Aenean sed elit a nunc efficitur pharetra.

*Method:* ^[How about we make this italics?]Praesent dapibus turpis in dictum aliquam.

There are an unknown number of comments in each file (some files have no comments). As demonstrated - comments can span multiple lines, but the comment text is always at the very end of the file. It's worth noting that there may be square brackets in text other than the comments, so ideally only values that had a comment marker (i.e. [a]) and a corresponding comment at the end of the file (i.e. [a]This should be bolded) would be processed.
Comment: You can make your own since it's literally just what happens when you make comments on a google doc and export it to a text file (although I know it's annoying to ask for help and then say "do it yourself"). Are there specific types of examples you'd want? If so I can try and generate some.
Comment: Interesting problem. Where can we find more test cases to test our algorithms on?
Comment: Can we trust the order to be a, b, c...?
Comment: Yes - they always in a-z (I'm not sure what happens if you get more than 26 comments).
Answer: Thanks to a (unfortunately now deleted) starting point from @OganM I've now managed to find a working solution.
library(dplyr)
library(stringr)

comment_to_footnote <- function(text) {
  pairs <- stringr::str_extract_all(text, '\\[[a-z]\\]') %>% {.[[1]]}

  comments <-
    stringr::str_extract_all(text, "(?s)\\n\\[[a-z]\\].*?($)") %>% {.[[1]]} %>%
    str_split("\\[") %>% {.[[1]]}

  comments <-
    as.data.frame(cbind(
      tag = sapply(str_split(comments, "\\]"), function(x) x[1]),
      comment = sapply(str_split(comments, "\\]"), function(x) x[2])
    )) %>%
    mutate(
      pattern = paste0("\\[", tag, "\\]"),
      tag = paste0("[", tag, "]"),
      comment_clean = str_replace_all(comment, pattern = "\\n", " ")
    ) %>%
    right_join(as.data.frame(x = pairs[duplicated(pairs)]), by = c("tag" = "pairs[duplicated(pairs)]"))

  for (i in 1:nrow(comments)) {
    # replace the initial occurence of the label with the
    # markdown style footer
    text = str_replace(
      string = text,
      pattern = as.character(comments[i, 3]),
      replacement = paste0('^[', comments[i, 4], '] ')
    )

    # get rid of the second occurence of the label that used
    # to have the text in it
    text = str_remove(string = text,
                      pattern = paste0("(?s)\\n", comments[i, 3], comments[i, 2], ".*?($)"))

  }
  return(text)
}

This ignores text in square brackets that does not have a matching comment at the end of the file.
text <- "*Background:*[a][b] Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis maximus urna ac erat tincidunt fermentum. Nulla[c] a accumsan enim. Aenean [d]sed elit a nunc efficitur pharetra. Vivamus ultricies pretium lobortis. Nam bibendum mi vel eros congue, ac ultrices lorem dictum. Orci varius [p < .001] natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed vitae feugiat orci. Integer hendrerit enim nec odio condimentum ornare. Vestibulum nisl quam, porttitor in semper et, porta ac enim. Phasellus a nisl vulputate, [This is handwritten and has no matching comment tag - should not be extracted]luctus mi sit amet, tincidunt enim. Sed ac est pellentesque, aliquam lacus non, rutrum neque. Sed vestibulum magna sit amet ipsum vehicula mollis. Suspendisse orci magna, vulputate ut neque et, consequat aliquam dui.

*Method:* [e]Praesent dapibus turpis in dictum aliquam. Maecenas ac molestie nunc. Nulla varius ultrices purus at blandit. Nulla dolor nisi, lacinia a ante eu, dictum semper nulla. Donec volutpat ultrices tempus. Proin non tristique metus, et tristique ante. Duis malesuada orci sit amet laoreet commodo. Donec faucibus vel erat tempus hendrerit. Vestibulum sit amet massa sit amet velit tempus dignissim. Etiam sed elit lacinia, euismod dui vitae, sagittis enim. Vestibulum ut eleifend orci, a semper massa. Quisque eu fringilla massa, at viverra nulla.[f]

*Results:* In laoreet, eros sed sagittis placerat, erat ex lobortis sem, ut pellentesque velit nisl ac est. Nulla mauris sapien, posuere hendrerit pulvinar a, molestie a orci. Suspendisse vitae risus augue. Nulla vel odio eget tellus sagittis pretium vitae nec enim. Fusce imperdiet, elit [g]maximus pellentesque tincidunt, mauris lacus ultrices massa, eget malesuada elit est et libero. Mauris vehicula urna augue, commodo varius sapien eleifend nec. Aenean ac lacinia nibh, faucibus scelerisque ligula. Sed tortor nisi, dictum ac augue et, auctor posuere ipsum. Curabitur condimentum urna [h]ut mi interdum porttitor. Fusce mi felis, hendrerit quis diam id, facilisis placerat nibh. Aliquam tempor lacus eget orci faucibus, id suscipit libero scelerisque. Nunc ultricies diam vitae vulputate mollis. Pellentesque ullamcorper placerat dui. Praesent lobortis vehicula augue ultricies interdum.

*Conclusion:* Curabitur eleifend ligula felis, ut condimentum lacus egestas nec. Suspendisse faucibus tempus maximus. Sed finibus facilisis ornare. Proin molestie interdum sapien at laoreet. Aenean sagittis dolor non volutpat fringilla. Etiam vulputate justo at orci pharetra condimentum. Mauris condimentum neque libero, in auctor lectus volutpat at. Pellentesque eros lacus, scelerisque eget dictum sed, porttitor sed elit. Morbi tristique nunc vel nunc consectetur, ut tincidunt tellus fermentum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus venenatis quis leo quis bibendum. Suspendisse efficitur quam sit amet nisi dignissim sodales. Nullam ex nulla, sagittis a diam non, dapibus scelerisque libero. Fusce ac ante ac dolor congue eleifend eu quis sem. Donec molestie finibus tortor at ullamcorper.[z]

[a]This should be bolded
[b]Comment reply. Good idea!
[c]What happens to a multiple

line

comment?
[d]I don't think this spelling is correct
[e]How about we make this italics?
[f]Gratuitous comments
[g]More here
[h]Add some comments"

cleaned_text <- comment_to_comment(text)

print(cleaned_text)

[1] "*Background:*^[This should be bolded ] ^[Comment reply. Good idea! ]  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis maximus urna ac erat tincidunt fermentum. Nulla^[What happens to a multiple   line   comment? ]  a accumsan enim. Aenean ^[I don't think this spelling is correct ] sed elit a nunc efficitur pharetra. Vivamus ultricies pretium lobortis. Nam bibendum mi vel eros congue, ac ultrices lorem dictum. Orci varius [p < .001] natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed vitae feugiat orci. Integer hendrerit enim nec odio condimentum ornare. Vestibulum nisl quam, porttitor in semper et, porta ac enim. Phasellus a nisl vulputate, [This is handwritten and has no matching comment tag - should not be extracted]luctus mi sit amet, tincidunt enim. Sed ac est pellentesque, aliquam lacus non, rutrum neque. Sed vestibulum magna sit amet ipsum vehicula mollis. Suspendisse orci magna, vulputate ut neque et, consequat aliquam dui.\n\n\n*Method:* ^[How about we make this italics? ] Praesent dapibus turpis in dictum aliquam. Maecenas ac molestie nunc. Nulla varius ultrices purus at blandit. Nulla dolor nisi, lacinia a ante eu, dictum semper nulla. Donec volutpat ultrices tempus. Proin non tristique metus, et tristique ante. Duis malesuada orci sit amet laoreet commodo. Donec faucibus vel erat tempus hendrerit. Vestibulum sit amet massa sit amet velit tempus dignissim. Etiam sed elit lacinia, euismod dui vitae, sagittis enim. Vestibulum ut eleifend orci, a semper massa. Quisque eu fringilla massa, at viverra nulla.^[Gratuitous comments ] \n\n\n*Results:* In laoreet, eros sed sagittis placerat, erat ex lobortis sem, ut pellentesque velit nisl ac est. Nulla mauris sapien, posuere hendrerit pulvinar a, molestie a orci. Suspendisse vitae risus augue. Nulla vel odio eget tellus sagittis pretium vitae nec enim. Fusce imperdiet, elit ^[More here ] maximus pellentesque tincidunt, mauris lacus ultrices massa, eget malesuada elit est et libero. Mauris vehicula urna augue, commodo varius sapien eleifend nec. Aenean ac lacinia nibh, faucibus scelerisque ligula. Sed tortor nisi, dictum ac augue et, auctor posuere ipsum. Curabitur condimentum urna ^[Add some comments] ut mi interdum porttitor. Fusce mi felis, hendrerit quis diam id, facilisis placerat nibh. Aliquam tempor lacus eget orci faucibus, id suscipit libero scelerisque. Nunc ultricies diam vitae vulputate mollis. Pellentesque ullamcorper placerat dui. Praesent lobortis vehicula augue ultricies interdum.\n\n\n*Conclusion:* Curabitur eleifend ligula felis, ut condimentum lacus egestas nec. Suspendisse faucibus tempus maximus. Sed finibus facilisis ornare. Proin molestie interdum sapien at laoreet. Aenean sagittis dolor non volutpat fringilla. Etiam vulputate justo at orci pharetra condimentum. Mauris condimentum neque libero, in auctor lectus volutpat at. Pellentesque eros lacus, scelerisque eget dictum sed, porttitor sed elit. Morbi tristique nunc vel nunc consectetur, ut tincidunt tellus fermentum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus venenatis quis leo quis bibendum. Suspendisse efficitur quam sit amet nisi dignissim sodales. Nullam ex nulla, sagittis a diam non, dapibus scelerisque libero. Fusce ac ante ac dolor congue eleifend eu quis sem. Donec molestie finibus tortor at ullamcorper.[z]\n\n"

This seems to work, but I'm sure that there are more elegant solutions.
Comment: Fantastic stuff, great to see this implemented in your `rmdrive` package, can't wait to try it out.


Change File extensions for entire folder

Question: I am trying to create a script where all the file extensions are changed from .bmp to .jpg. There have been some helpful answers I have found but I still can't get my script to work. If anyone had any suggestions on what I might need to change, it would be greatly appreciated. The script doesn't come up with any errors but none of the file extensions in the folder change.
import os, glob, sys
folder = '\\stsosage\...\LegalCardsTest'
for filename in glob.iglob(os.path.join(folder, '*.bmp')):
    os.rename(filename, filename[:-4] + '.jpg')

Comment: `print folder` should give you a hint. (See e.g. [here](http://pythonconquerstheuniverse.wordpress.com/2008/06/04/gotcha-%E2%80%94-backslashes-in-windows-filenames/))
Comment: You could just call out to the shell with a mv command, mv foo.bmp foo.jpg
Comment: Try [os.chdir](https://docs.python.org/2/library/os.html#os.chdir) prior to the loop to change to the relevant directory. Or, add the path prior to renaming.
Comment: Not entirely sure how to do that, but thank you for responding
Comment: More specifically - `use folder = r'\\stsosage\..`
Answer: try this:
import os

def walk_dir(targetdir,topdown=True):
    for root, dirs, files in os.walk(targetdir, topdown):
        for name in files:
            os.rename(targetdir+name, targetdir+name.replace(".bmp",".jpg"))

walk_dir(FOLDER_PATH_END_WITH_\)

Answer: My Code:
import os
os.chdir(input("Enter dir: "))
endv = input("File extension before: ")
endn = input("File extension after: ")
for s in os.listdir(pfad):
  if "."+endv in s:
    try:os.rename(s,s.replace("."+endv,"."+endn)
    except BaseException e:print(e)

Hope it works fine.
Answer: filename is only the file name and not the entire path that you need to provide to you mv function.
Try to concat folder with filename in your mv command.


Should NSFetchRequest be explicitly performed on context queue?

Question: Just a little question...
When performing CoreData requests (in objective-C), do I have to make them on the context queue explicitly, or are they assumed to do that by themselves?
In other words can I just write:
<code>NSArray *results = [context executeFetchRequest:request error:nil];
</code>
Or do I have to write (if I want to avoid issues):
<code>__block NSArray *results = nil;
[context performBlockAndWait:^{
    results = [context executeFetchRequest:request error:nil];
}];
</code>
Thanks!
Comment: You should use the `perform`/`performAndWait` to ensure it. You could also use the flag `-com.apple.CoreData.ConcurrencyDebug` to verify it.
Comment: Thanks Larme! So for clarity (as I'm using it often in my code) I can create a category on NSManagedObjectContext to handle that (with a -safeExecuteFetchRequest:error: method)
Answer: You can never assume that Core Data will use the correct queue. You always need to tell it via one of the "perform" methods. The only exception is if you have a main-queue context and you know your code is running on the main queue. You can skip "perform" in that one and only case.
You mention using a convenience method to do a fetch, using "perform" inside the method. That's fine, but don't forget that you also need to use "perform" any time you use any of the fetched objects. For example, you can't use property values from fetched objects unless you also use "perform" (again with the one exception I mentioned).
Comment: Thanks for your precisions! I didn't know we had to access properties on the context queue too... Good to know. I have to rewrite my accessors then..
Answer: So just to be sure Tom:
All my CoreData objects (subclasses of NSManagedObject) have their CoreData properties as private (with a prefix "cd_"). I never expose them and use wrapper properties instead:
<code>- (nullable NSString *) email {
    return self.cd_email;
}
</code>
I've created a method on NSManagedObject:
<code>- (id) safeValueForProperty: (SEL)property {
    __block id value = nil;
    [self.managedObjectContext performBlockAndWait:^{
        value = [self valueForKey:NSStringFromSelector(property)];
    }];
    return value;
}
</code>
So now I can use (from any thread in theory):
<code>- (nullable NSString *) email {
    return [self safeValueForProperty:@selector(cd_email)];
}
</code>
(and of course the same for setters).
Am I doing right?


How to calculate the surface area of an object?

Question: Calculate the area of the surface Y given by the equation $z = x^2 + y^2 − 1$ when $z ≤ 0$
Here is my solution:

I got the answer correct but there is something I just did (not toally randomly but I ignored certain requirements) which was the boundaries. In the question it says that $z\leq0$ but my boundaries where $0 \leq r \leq 1$ and $0 \leq \theta \leq 2\pi$ and I was wondering how in the hell my solution took into account that z is supposed to be less than 0?
Answer: You implicitly chose the boundaries of your parameterized integral in a way that satisfied the original condition. Indeed,
$$z\leq0\iff x^2 + y^2 \leq 1\iff r\leq 1.$$


Quickbooks PHP SDK Integration

Question: Can anyone Plese help me regarding the Quickbook API integration
I have downloaded SDK from
https://majorapi.com/developers/quickbooks/sdk/php
I have installed it and configured the keys.
I've got some db tables when executing the Quickbook.php file.
I'm stuck there, can anyone please help me further.
Answer: If you're building a SaaS app (allowing other people to connect their QuickBooks companies to your app):
If you're building for QuickBooks ONLINE:
Instead of using that lib, use the QuickBooks PHP DevKit that's available on GitHub. It's open-source and well supported, and works fine with OAuth and v3.
You can follow the QuickBooks PHP IPP v3 Quick-Start Guide to get started. You'll go through a similar process to what you went through above, where you'll find in your own OAuth token/secret and app token in the configuration, and then you'll be able to connect to QuickBooks.
From there, you'll find several example scripts:

https://github.com/consolibyte/quickbooks-php/blob/master/docs/example_app_ipp_v3/

If you're building something else (something internal or for use only by a single company):
If you're building for QuickBooks for WINDOWS:
Here is a PHP QuickBooks Library which does exactly what you want to do.
You should follow the QuickBooks PHP Web Connector quick-start guide to get started. You'll want to architect your application so that your PHP script can receive the data, store it temporarily in a database (MySQL, etc.) and then the Web Connector can pick up the data destined for QuickBooks from there.
The Web Connector is a little different than a standard web service in that it works in a sort of backwards manner - the Web Connector will call out to your PHP web service vs. you calling out to it.
There's a overview of how the Web Connector works over here.
You should refer to these scripts (as the quick-start guide does above):

https://github.com/consolibyte/quickbooks-php/tree/master/docs/example_app_web_connector
Comment: Thanks Keith. I will follow as you said..! Thanks again..!

Quickbooks PHP SDK Integration


javascript code for @

Question: I am trying to do validate my email address. In order to get this i have been over web and found these Regexs for validating email-
\b[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}\b

Can say there is no limit of regex over internet.
How do you code @ in javascript code?
When a user press keys- shift+2=@ .
Can we do this?
\b[A-Z0-9._%+-]+(keycode==64)(?:[A-Z0-9-]+\.)+[A-Z]{2,4}\b

I want to write key instead of writing simple @
Comment: You need to escape `@` character like `\@`.
Comment: @Bibhas: No, why? `@` is not a regex metacharacter.
Comment: The question is why would you want to do it? Keycode in REgex would surprise me
Comment: Regex works on the character/string itself. If you want to match `@`, you have to write `@`.
PS: *Why* do you want to do that?
Comment: @winner_joiner: I have cshtml page, when i write @ it counts it as call, so encounters an error.
Comment: @TimPietzcker In ASP.NET pages built using the Razor view engine, @ is the tag for starting a Razor code block, which means that Razor will try to parse everything after the @, so when the Javascript gets to it, half the regex will be missing because Razor will have removed it.
Comment: @anaximander: Thanks, that's interesting. Was there any way to guess this (because Razor wasn't mentioned anywhere in the question)?
Comment: The mention of `.cshtml` along with the [tag:asp.net-mvc-4] tag points at the Razor view engine. You're right, though - this might need a [tag:razor] tag, or more accurately [tag:razor-2], because Razor v1 used `<% ... %>` where v2 uses `@(...)`.
Comment: if you found a better solution, please share. thx :)
Answer: I found a way, just enter the HEX-Code for the @-Sign
Here is a small example (in Javascrip)
"@".replace(/\x40/,".") // Result --> "."

Your code would look like this
var reg = /\b[A-Z0-9._%+-]+\x40(?:[A-Z0-9-]+\.)+[A-Z]{2,4}\b/i
 "firstname.lastname@example.com".match(reg) // Result => ["firstname.lastname@example.com"]

=> Code Testet in Chrome 25+

javascript code for @


My template do not shows the context_processors's data

Question: In the testMulToM/context_processors.py, I have a custom function:
def custom_proc(request):
    user = {'name': 'allen', 'sex': 'man'}
    return user

And I also add to the context processors in settings.py:
TEMPLATE_CONTEXT_PROCESSORS = (

    "django.core.context_processors.i18n",
    "testMulToM.context_processors.custom_proc",  # add there
)

But when I run my server, and request the url to template, it does not fill the data to template:

my app04/index.html template:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

User:
{{ name }} : {{ sex }}

My app04/views.py:
def index(request):

    return render(request, 'app04/index.html')

EDIT
I tried return render(request, 'app04/index.html', {}) , but do not work.
And my python version is 2.7. My django version is 1.11.2
python -m django --version
1.11.2

Comment: what version of django you are using
Comment: Try adding a context: `return render(request, 'app04/index.html', {})`
Comment: @schwobaseggl I have edit my post, see it.
Answer: TEMPLATE_CONTEXT_PROCESSORS has not been a supported setting since Django 1.8. Assuming you are using a more recent version (which you definitely should be), the list of processors needs to go into the context_processors key inside the OPTIONS value for the relevant TEMPLATES dict.
Comment: can you give a link for detail introduce?
Comment: https://docs.djangoproject.com/en/1.11/topics/templates/#django.template.backends.django.DjangoTemplates
Comment: Note, that list is there by default; you should just need to append your processor to it.


How to call if condition if only one array is empty if both empty then call else condition?

Question: I am using CodeIgniter. I am getting the response from model and display on the controller.
Model
//some code here
return array('secondary_data'=> $result,'primary_data' =>$result2);// sending to controller
// some code here

Controller
$result=$this->Search_model->get_search_name($cust_name);//calling model
$data['secondary_data'] = $result['secondary_data'];
$data['primary_data'] = $result['primary_data'];

print_r($data['secondary_data']);
print_r($data['primary_data']);

output
Array
(
    [0] => stdClass Object
        (
            [member_id] =>
            [customer_id] =>
            [first_name] => qwer
            [last_name] => poiu
            [email] =>
            [member_type] => 2

        )

)
Array
(
    [0] => stdClass Object
        (
            [member_id] => 1
            [customer_id] => 0011
            [first_name] => asdasd
            [last_name] => asdasda
            [email] => firstname.lastname@example.com
            [member_type] => 1

        )

)

but sometimes I am getting empty array of print_r($data['primary_data']) because of no data. Yes, it's possible.;
but in below if condition I am checking the data count count($data) > 0 and if found empty then calling the else part.
I don't want to call else part if only one array is emply. if both array is empty then it should call else part
    if (count($data) > 0)
     {
        $data['title'] = "Search";
        $data['heading'] = "Search";
        $data['content'] = $this->load->view('search',$data,true);
        $this->load->view('dashboard/dashboard',$data);
        }
       else{
       echo "NO data available";
      }

Any idea how to do this? Thanks
Comment: if(count($data) && (!empty($data['secondary_data']) || !empty($data['primary_data']))){...}else{...}
Comment: write `condition for both array` or Use `loop` and check
Answer: Check your both array separately in or condition
if (count($data['primary_data']) > 0 || count($data['secondary_data']) > 0)
{
   $data['title'] = "Search";
   $data['heading'] = "Search";
   $data['content'] = $this->load->view('search',$data,true);
   $this->load->view('dashboard/dashboard',$data);
}else{
   echo "NO data available";
}

Answer: Try this condition with OR operator
if(!empty($data['primary_data']) || !empty($data['secondary_data'])){
//One or both array have values
}else{
//Both have no values
}

Comment: This is short and simple solution.
Comment: Your code is also working for me. upvote from my side
Answer: You can use separate condition for both array, If one of them is not empty then apply If condition otherwise else.
if ( !empty($data['secondary_data']) || !empty($data['primary_data']) ) {
    $data['title'] = "Search";
    $data['heading'] = "Search";
    $data['content'] = $this->load->view('search',$data,true);
    $this->load->view('dashboard/dashboard',$data);
} else {
   echo "NO data available";
}

Answer: start checking from $data then sub array
if(count($data) && (isset($data['secondary_data']) && !empty($data['secondary_data'])) || (isset($data['primary_data']) && !empty($data['primary_data']))){
      ....
    }else{
      ...
    }


Quantidade de marcadores no Google Maps

Question: Estava estudando algumas formas de implementar o Google Maps, e vi em um site do WordPress um mapa com a contagem das informações, eu queria saber se vocês conhecem um plug-in que faça o mesmo, ou através da documentação que o Google oferece para desenvolvedores, como implanta-lo. Gostaria de aprender mais sobre isso.
Comment: É possível fazer um efeito parecido seguindo os passos citados nesse [link](http://www.princiweb.com.br/blog/programacao/google-apis/google-maps-api-v3-criando-um-mapa-personalizado.html).
Comment: @Emanoel se quiseres dar uma resposta explicando esse link e trazendo exempo de como implementar o plugin seria uma resposta interessante.
Answer: Um tempo depois de fazer essa pergunta, achei a resposta por acaso (pois eu tinha parado de pesquisar), vi um rapaz falando sobre alguns recursos essenciais, entre os recursos estava lá! MARKPLACES <3 ...
Foi amor ao primeiro clique, e descobri uma documentação bem completa do Google!

"Too Many Markers!"
Some applications are required to display a large number of locations or markers. Naively plotting thousands of markers on a map can quickly lead to a degraded user experience. Too many markers on the map cause both visual overload and sluggish interaction with the map. To overcome this poor performance, the information displayed on the map needs to be simplified.

Tudo o que eu queria saber em relação ao agrupamento de marks está ali, muito bom e recomendo!
Fazer um plug-in para o WordPress com essa documentação ficou mais fácil!
Comment: Muito boa referência, mais tarde vou incluir na wiki da tag google-maps. Marcada como favorita!
Comment: @brasofilo Obrigado!

Quantidade de marcadores no Google Maps


Calculating remaining balance [Monthly compounding question with rate= 0.01]

Question: Suzanne opens a line of credit at a local bank, and immediately borrows 1870 dollars. 6 months later, she repays 1060 dollars. 5 months after the repayment, she borrows 570 more dollars. 6 months later, she repays 660 dollars. If no other transactions take place and the interest rate is 1 percent per month (compounded monthly), how much will she owe two years after she opened the line of credit?
First, after 6 months she owes 1870(1+0.01/12)^6=1879.37 and repays 1060
----> she finally owes 819.37 dollars
Then, 5 months after the repayment, she owes 819.37(1+0.01/12)^5 = 822.79 dollars and borrows 570 dollars --->she finally owes 1392.79 dollars.
Then, 6 months later, she owes 1392.79(1+0.01/12)^6 = 1399.77 dollars and repays 660 dollars ---> she finally owes 739.77 dollars.
Since there are 7 months left until 2 years, so 739.77(1+0.01/12)^7 = 744.1 dollars.
I think she owes 744.1 dollars after 2 years.
But this is not right answer and I would like to know where I made a mistake.
Thanks!
Comment: One **Hint**: The interest rate is $1\%$ per $\color{red}{\texttt{month}}$. Therefore the compound factor per month is $1+0.01=1.01$. You don´t have to divide the monthly interest rate by 12.
Answer: The error you made was to divide by 12. Since the interest is accumulated monthly, you don't need to do that. The numbers should look something like this:
1985.04
972.23
1637.11
1047.59

Code to compute it two different ways is here
package main

import (
    "fmt"
    "math"
)

var balance float64

func incMo() {
    balance = 1.01 * balance
}

func main() {
    balance = 1870
    for mo := 1; mo <= 24; mo++ {
        incMo()
        fmt.Printf("%d: %.2f\n", mo, balance)
        switch mo {
        case 6:
            balance -= 1060
        case 11:
            balance += 570
        case 17:
            balance -= 660
        }
    }
    balance = 1870
    balance *= math.Pow(1.01, 6)
    fmt.Printf("%.2f\n", balance)
    balance -= 1060
    balance *= math.Pow(1.01, 5)
    fmt.Printf("%.2f\n", balance)
    balance += 570
    balance *= math.Pow(1.01, 6)
    fmt.Printf("%.2f\n", balance)
    balance -= 660
    balance *= math.Pow(1.01, 7)
    fmt.Printf("%.2f\n", balance)
}

I wasn't sure whether to add the interest before or after the money was deposited or withdrawn, so you might get different answers.


Front Blank Webpage

Question: Hi I am working on moving my website from local to development, but get this error:
Uncaught PHP Exception InvalidArgumentException: "Class "Drupal\entity\QueryAccess\ViewsQueryAlter" does not exist." at /var/www/website/core/lib/Drupal/Core/DependencyInjection/ClassResolver.php line 24
When I try to render the front page it is blank, but when I target internal webpages, some of them work. I tried googling what this error meant to no avail. Any tips on how to debug this error would be of great help! Thank you!
Comment: I found out that I did not enable the same plugins, I had to use `composer install` to install the missing php dependencies! Thank you
Comment: Are you using the same database? And did you enable the same plugins?
Comment: Glad things worked out! I'll go ahead and add this as an answer so the question has an answer. Let me know if there's anything wrong with it.
Answer: You must install and enable the same plugins from your local as on your development if you are using things dependent on them. If your site was built with composer make sure you run 'composer update' or 'composer install'.

Front Blank Webpage


vuejs vuex firebase

Question: to com um problema para montar minha referencia do firebase seguinte
export default {
        firebase () {
            return {
                gastos: db.ref(`user/${this.uid}/shop/`),
            }
        },
        computed: {
            uid () {
                return this.$store.getters.getUser.uid
            },
        }
    }

o que acontece é que aqui gastos: db.ref(1user/${this.uid}/shop/') meu this.uid ainda não foi definido na minha store e não monta minha referencia do firebase
mas se eu utilizar {{uid}} no template ta ok, o que eu to fazendo errado?
Comment: Tenta utilizar no metodo mounted, acredito que no computed algumas coisas nao estejam ainda prontas.
Comment: @narukaioh agradeço a ajuda, não funcionou cmg pq acredito estar com erro de assync do firebase com vuex
Answer: Acredito que você precise retornar um valor padrão enquanto ainda não tem o valor do banco, ou augardar o valor chegar para exibir a página:
export default {
    firebase () {
        return {
            gastos: db.ref(`user/${this.uid}/shop/`),
        }
    },
    computed: {
        uid () {
            const ret = (this.$store.getters.getUser & this.$store.getters.getUser.uid) ? this.$store.getters.getUser.uid : "valor-padrao";
            return ret;
        },
    }
}

vuejs vuex firebase


How to sum multiple row values with groupby using pyspark?

Question: Given below is a pyspark dataframe and I need to sum the row values with groupby
load_dt|org_cntry|sum(srv_curr_vo_qty_accs_mthd)|sum(srv_curr_bb_qty_accs_mthd)|sum(srv_curr_tv_qty_accs_mthd)|
+-------------------+---------+------------------------------+------------------------------+------------------------------+
|2021-12-06 00:00:00|     null|                           NaN|                           NaN|                           NaN|
|2021-12-06 00:00:00|   PANAMA|                      360126.0|                      214229.0|                      207950.0|

condition:
1.groupby(load_dt,org_cntry)
2.sum row values (sum(srv_curr_vo_qty_accs_mthd)|sum(srv_curr_bb_qty_accs_mthd)|sum(srv_curr_tv_qty_accs_mthd)|
expected output
load_dt     org_cntry   total_sum
2021-12-06  Panama       782305

Comment: Could you add what is the expected output?
Comment: yes, I added the expected output. Basically it should add the row values based on groupby condition
Answer: simply sum(+) your result :
from pyspark.sql import functions as F

df.groupBy("load_dt", "org_cntry").agg(
    (
        F.sum("srv_curr_vo_qty_accs_mthd")
        + F.sum("srv_curr_bb_qty_accs_mthd")
        + F.sum("srv_curr_tv_qty_accs_mthd")
    ).alias("total_sum")
)

Comment: @PavithraKannan Are you using a pandas dataframe or a spark dataframe ?
Comment: 'DataFrame' object has no attribute 'groupBy' I'm getting this error
Comment: I've tried the above code, but I'm getting the above error. Can you pls help me on this @Steven
Comment: [`groupBy`](https://spark.apache.org/docs/2.4.7/api/python/pyspark.sql.html#pyspark.sql.DataFrame.groupBy) is a method of dataframe ... so I do not understand why you have this error ...
Answer: Use Spark2.4+ Higher order functions for this case.
Example:
#sample dataframe
#+-------------------+---------+--------+--------+--------+
#|            load_dt|org_cntry|      s1|      s2|      s3|
#+-------------------+---------+--------+--------+--------+
#|2021-12-06 00:00:00|   PANAMA|360126.0|214229.0|207950.0|
#+-------------------+---------+--------+--------+--------+

#create array from sum columns then add all the array elements.
df.selectExpr("*", "AGGREGATE(array(s1,s2,s3), cast(0 as double), (x, y) -> x + y) total_sum").show()

#using withColumn
df.withColumn("total_sum", expr("AGGREGATE(array(s1,s2,s3), cast(0 as double), (x, y) -> x + y)")).show()

#+-------------------+---------+--------+--------+--------+---------+
#|            load_dt|org_cntry|      s1|      s2|      s3|total_sum|
#+-------------------+---------+--------+--------+--------+---------+
#|2021-12-06 00:00:00|   PANAMA|360126.0|214229.0|207950.0| 782305.0|
#+-------------------+---------+--------+--------+--------+---------+


Interface Método GET e POST com Angular + Node.js

Question: Estou com algumas dúvidas de iniciante e queria a ajudar de vocês.
Criei uma Automação Residencial, baseada em Microcontrolador + Node.js + Angular.js.
A comunicação do Angular.js com o Microcontrolador está OK.
Porém, também farei o inverso. No qual o MIC irá enviar um comando POST para o Node.js, mais ou menos com esse parametro:
router.post('/Saidas', function(req,res) {
    saida = req.body.atuador;
    estado = req.body.estado;
    final = saida + estado;
    res.send('Enviado = Saida: ' + saida + '; Estado: ' + estado);
});

E posteriormente irei enviar para o site em HTML, via Angular.js com esse comando:
router.get('/SaidasSite', function(req,res){
    res.send(final);
});

**Acima está no código caminhos.js para o Node.js.
Porém, no meu Angular.js, fiz o seguinte código:

A minha idéia é a seguinte: Quando eu enviar o comando "QTD1LEDON" para o comando POST /Saidas, ele enviar o comando para o Node.js e posteriomente o site irá receber o comando GET com esse valor (GET /SaidasSite) e acionar um botão conforme a string que recebeu.
Ex: Botão QTD1LED ON acionado -> QTDLEDON -> Ativa Botão "Bootstrap Toogle".
Não estou encontrando o melhor jeito para fazer isso. Esse processo não está funcionando. Nesse código, ele sempre aciona o "QTD1LEDON".
Teria algum jeito melhor para arrumar esse código ou implantar outro processo? Obrigado!
Answer: Fala Luiz, boa tarde.
No seu código em JavaScript, nos ifs, você deve utilizar o operador == ou o operador === para verificar se a constante é igual a variável (como é string sugiro o === pois é mais performático).
O operador = é operador de atribuição, então no primeiro if, ele atribui "QTD1LEDON" à variável data e como ela é uma variável definida ele entra no if. Por isso está entrando no primeiro if sempre.
Sugiro colocar também um console.log('data = ', data) no começo da function de callback de success para você poder ver o que veio de resposta do nodejs.
Outra coisa também é o else - quando você tem outra condição ele deve ser else if( condição ).
Espero ter ajudado.


A particular complex of integral group ring is exact: proof of Jacobson

Question: Let $A$ be a $G$-module.
Let $C_n=\mathbb{Z}G\otimes \cdots \otimes \mathbb{Z}G$ ($n+1$ copies). It is free $\mathbb{Z}$-module with basis $g_0\otimes g_1\otimes \cdots \otimes g_n$, $g_i\in G$.
Denote $1\otimes g_1\otimes \cdots \otimes g_n\in C_n$ by $(g_1,\ldots,g_n)$. These $n$-tuples are basis of free $\mathbb{Z}G$-module $C_n$.
Define $\mathbb{Z}G$-module homomorphisms $d_n:C_n\rightarrow C_{n-1}$ by
$$d_n(g_1,\ldots,g_n)=g_1(g_2,\ldots,g_n)+\sum_{1}^{n-1}(-1)^i(g_1,\ldots, g_{i-1}, g_ig_{i+1},g_{i+2},\ldots, g_n)+(-1)^n(g_1,\ldots,g_{n-1}).$$
Let $\varepsilon:\mathbb{Z}G(=C_0)\rightarrow \mathbb{Z}$ be augmentation map.
Claim: The complex $\mathbf{(C)}$: $\cdots \rightarrow C_2\xrightarrow{d_2}C_1\xrightarrow{d_1}C_0\xrightarrow{\varepsilon} \mathbb{Z}\rightarrow 0$ is exact.
Proof in Jacobson's Algebra Vol.2 We define homomorphisms of abelian groups $s_i:C_{i+1}\rightarrow C_i$ such that $$\varepsilon s_{-1}=1_{\mathbb{Z}}; d_1s_0+s_{-1}\varepsilon=1_{C_0}; d_{n+1}s_n + s_{n-1}d_n=1_{C_n}.$$
Question: These conditions say that the maps $s_i$ define a homotopy between identity morphism $(\mathbf{C})\rightarrow (\mathbf{C}$) is homotopic to zero morphism from $(\mathbf{C})\rightarrow (\mathbf{C}$). But I didn't get how this implies the exactness of $(\mathbf{C})$? This could be trivial, but I was unable to see clearly the justification of Jacobson.
Answer: Suppose $d_n(a)=0$ ($a$ is a cycle). Then
$$a=(d_{n+1}s_n+s_{n-1}d_n)(a)=(d_{n+1}s_n)(a)=d_{n+1}(b)$$
for $b=s_n(a)$. Thus $a$ is a boundary. All cycles are boundaries, so
the chain complex is exact.


An example for this joint discrete random variable? $P_{X,Y}(x, y) = \frac{4!}{x!y!(4-x-y)!}(\frac{1}{2})^x(\frac{1}{3})^y(\frac{1}{6})^{4-x-y}$

Question: I have been asked to calculate the marginal pdf for the following equation, however, I'm interested to know how exactly would this equation fit in with a word-example?
$P_{X,Y}(x, y) = \frac{4!}{x!y!(4-x-y)!}(\frac{1}{2})^x(\frac{1}{3})^y(\frac{1}{6})^{4-x-y}$
Am I looking for something that counts the differences between two variables when $0 \le x+y \le 4?$
Answer: If you let $Z=4-X-Y$, we have $$P_{X,Y,Z}(x,y,z) = \frac{4!}{x!y!z!}\left( \frac12\right)^x \left( \frac13\right)^y \left( \frac16\right)^{z}$$
where $x+y+z=4$, we can see that this follows multinomial distribution.
Consider four traffic lights where each traffic light is independent. The probability of seeing green is $\frac12$, the probability of seeing amber is $\frac13$. That gives you the probability of seeing $x$ green signals and $y$ amber signals.


Calculating prime numbers

Question: I have a program which determines if a number is prime or not.  The basic algorithm simply checks for the number being divisible by 1 and itself.
My question is, is there an upper limit to checking numbers for divisibility without a remainder?  If yes, can you explain why?
My "gut" feeling is that any number above 1/2 the number being checked should be ignored, but I can't prove it.
Comment: Actually testing up to $\sqrt{n} \ll n/2$ (for $n \gt 2$) is good enough (there are certainly much cleverer things to do). Note that if $n = pq$ then either $p \leq \sqrt{n}$ or $q \leq \sqrt{n}$.
Comment: You're welcome. Maybe you want to check out the [Wikipedia page on primality tests](http://en.wikipedia.org/wiki/Primality_test). I'm sure that our local expert Bill Dubuque would have a lot more to say about this. I suspect that any decent library has much better methods implemented than any of the ones you could come up with yourself.
Comment: @Theo Buehler - Thanks for the tips.
Comment: @t.b. - where can you reference this equation online or do you have to derrive it ?
Answer: I will try to explain by using an example.
Let's check if $37$ is a prime number.

It's obviously not divisible by $2$,
it's not divisible by $3$ (because $3+7=10$ which is not divisible by $3$),
and it's not divisible by five (because the last digit is not $0$ or $5$).

These are all the possible candidates for factors of $37$, and I will try to explain why. If $7$ is a factor of $37$ (which would mean that $37$ is divisible by $7$, and hence not a prime) then the other factor must be greater or equal to $7$, since we have already shown that there is no factor less than $7$. But $7 \cdot 7 = 49 > 37$. Then there is no point in trying with greater factors, because then the product would have to be even larger.
So we have shown that for $37$, we only have to try to divide by $2$, $3$ and $5$. As both Raeder and Theo has pointed out we don't have to go higher than the square root of the number we want to check, and I hope that my example will help explaining why.
Edit: As Picakhu suggested, I will explain why these methods for checking divisibility by $2$, $3$, and $5$ works.
Checking divisibility by $2$ and $5$
When checking for divisibility by $2$ or $5$, it is sufficient to check that only the last digit is divisible $2$ or $5$ respectively. This has to do with the fact that we are using $10$, which is the product of $2$ and $5$, as our base. I will explain using three-digit numbers. The explanation would be very similar if we had used more digits. All numbers $abc$ (where $a$ is the first digit, $b$ the second, and $c$ the third) can be written on the form
$$abc = a\cdot 10^2 + b\cdot 10^1 + c\cdot 10^0 = a \cdot 100 + b \cdot 10 + c.$$
The notation I'm using can be confusing. To clear up: If, for example, $a=b=c=4$, then $abc = 444 \neq 4\cdot 4\cdot 4$. Let's see what happens if we divide by 2.
$$\frac{abc}{2} = \frac{a \cdot 100}{2} + \frac{b \cdot 10}{2} + \frac{c}{2} = a \cdot 50 + b \cdot 5 + \frac{c}{2}$$
We notice that this is a whole number if and only if $\frac{c}{2}$ is a whole number, no matter what $abc$ is. We get a similar result if we divide by $5$.
$$\frac{abc}{5} = a \cdot 20 + b \cdot 2 + \frac{c}{5}$$
Hence it is sufficient to check the last digit.
Checking divisibility by $3$
When checking for divisibility by $3$, it is sufficient to check that the sum of the digits is divisible by $3$. This is easiest to show using modular arithmetics. Keep in mind that $10 \equiv 1 \pmod 3$. If we use our three-digit number $abc$ again we see that
$$a \cdot 10^2 + b \cdot 10 + c \equiv a \cdot 1 + b \cdot 1 + c = a + b + c \pmod 3.$$
Hence $abc$ is divisible by $3$ if and only if $a + b + c$ is divisible by $3$.
Wikipedia has a list of more divisibility tests like these.
Comment: Good answer @Eivind, but perhaps you would want to talk about WHY checking sum for 3, checking last digit for 5,2 etc work. It all comes to modular arithimatics, but there are other ways to check if a number evenly divides another especially if software is used.
Comment: @picakhu: Thanks! The explanation of how to check divisibility with different numbers, wasn't really the objective for my post. On the other hand, it is an interesting topic, so maybe I should explain a little deeper. I'll see what I can do!
Answer: First, I guess you been divisible only by 1 and itself.
For the actual question, you only need to check for factors up the square root of the number, since by then you will have found all possible products less than your given number.
By the way, your gut feeling is correct, since twice something larger than half your number will be larger than your number.
If anything is unclear, I'd be glad to clarify.
EDIT: I see that Theo has explained why this is true in a much clearer fashion in the comments.

Calculating prime numbers


Prevent site marked for deletion being deleted? (SharePoint)

Question: Basically how do I manage the task mentioned in the Title?
Problem is: I am trying to administrate a SharePoint Portal (MOSS) and a user has been deleted (deactivated from AD)
Now we got an e-mail stating that "My Site" for this user is marked for deletion (I don't know when) and since there's critical information in that site (a subsite) I would like to stop the deletion process or at least move the subsite WITHOUT losing any versioning information - is that possible?
Answer: Here is some information on automatic site deletion.
Comment: Thx, that helped somewhat. Did move the site correctly though ánd it seems like I prevented the deletion also
Answer: Managed to move the site including versions (take a GOOD look at the options in export/import using stsadm). Initially I moved the site, but got 2 aditional (unwanted) versions added. After a few trials I managed to get only the original versions moved to the new site, off the personal site from which the data originated.


How do I add a Nexus resolver after local repository, but before the default repositories?

Question: We have an internal Nexus repository that we use to publish artifacts to and also to cache external dependencies (from Maven Central, Typesafe, etc.)
I want to add the repository as a resolver in my SBT build, under the following restrictions:

The settings need to be part of the build declaration (either .sbt or .scala, but not in the "global" sbt settings
If a dependency exists in the local repository, it should be taken from there. I don't want to have to access the network to get all the dependencies for every build.
If a dependency doesn't exist locally, sbt should first try to get it from the Nexus repository before trying the external repositories.

I saw several similar questions here, but didn't find any solution that does exactly this. Specifically, the code I currently have is:
externalResolvers ~= { rs => nexusResolver +: rs }

But when I show externalResolvers the Nexus repo appears before the local one.
Answer: So far, I've come up with the following solution:
externalResolvers ~= { rs =>
  val grouped = rs.groupBy(_.isInstanceOf[FileRepository])
  val fileRepos = grouped(true)
  val remoteRepos = grouped(false)
  fileRepos ++ (nexusResolver +: remoteRepos)
}

It works, but is kinda dirty... If anyone has a "cleaner" solution, I'd love to hear it.


Napoleon-like theorem concerning squares erected on sides of midpoint polygon of octagon

Question:
Given an arbitrary octagon, construct it's midpoint polygon(the midpoint formed by the midpoints of the sides). Erect squares on the sides of the midpoint polygon, all inwards or all outwards. Consider the four segments, each connecting the centroids of two squares corresponding to opposite sides of the midpoint polygon.
The midpoint of these segments form a square.

I distinctly remember seeing this theorem in some geometry article, but I have been unable to find that article. I believe it was attributed to Van Aubel, however I am not too sure. I want to find the source of this theorem because I have found a rather powerful generalisation and I want to revisit that article.
Does anyone find this theorem familiar?
Comment: Branko Grünbaum (RIP 2018) presented results of this type in a graduate course at the University of Washington many years ago. I'm not sure if they were published outside of lecture notes. There's a wonderful general result that goes something like this: Given an arbitrary $n$-gon, consider the various regular $(n/k)$-gons, defined as having vertices $(\cos 2\pi i k/n,\sin2\pi i k/n)$ for $i=0, 1, \ldots, n-1$. (These include "starry" and "multiply-traced" figures, as well as the "dot" ($k=0$).) [continued]
Comment: [continuation]  Erecting an $(n/k)$-gon on the sides of the $n$-gon and joining centroids gives a new $n$-gon; erecting *some other* $(n/k)$-gon on the new sides gives another $n$-gon; etc. Iterating for all-but-one of $(n/k)$-gons, the final polygon is the *remaining* $(n/k)$-gon. For an $8$-gon, the $(n/k)$-gons are the dot ($k=0$), the regular octagon ($k=1$), the doubly-traced square ($k=2$), "starry octagon" ($k=3$), quad-traced segment ($k=4$, whose derived polygon is a midpoint polygon), and "reverse-direction" versions. Similar to what you have, except for the "opposite sides" thing.
Comment: Ah, yes. That seems to be it.
Comment: Interestingly, the "opposite sides" thing seems attributable to a common alternative interpretation of $(n/k)$-gon. Rather than starting at $(1,0)$ of a regular "unit" $n$-gon and forming a single (possibly multiply-traced) path by jumping every $k$ vertices, possibly excluding some vertices, we connect *every* vertex of the $n$ gon to the vertex/vertices $k$ jumps ahead/behind. So, an $(8/4)$-gon would consist of four individual segments (perhaps best thought of as double-traced segments) instead one octo-traced segment. But your figure arguably *also* uses octo-traced segments. Intriguing.
Comment: I don't see very much the interest to start from the initial polygon, and then construct a second polygon. Why not start afresh from this second polygon ?
Comment: @Blue, aren't you describing the Petr-Douglas-Neumann Theorem? ( https://en.wikipedia.org/wiki/Petr-Douglas-Neumann_theorem )
Comment: The generalisation I have in mind concerns applying some special transformation(which in this case turns out to be the midpoint transformation) to an arbitrary $nk$-gon, constructing regular $n$-gons on the sides of the newly obtained $nk$-gon, and "collapsing" (in this case the midpoint of opposite sides thing) back to a regular n-gon. The transformation is related to obtaining an affine-regular polygon(in this case, viewing the octogon as an 4*2 gon, you can see that taking the midpoint polygon of a quadrilateral gives you a parallelogram, which is affinely regular)
Comment: A generalization of PDN, seems afoot, as well. Typically, the starting $n$-gon is an $(n/1)$-gon —a cycle— and we erect $(n/k)$-gons whose centroids join into another ostensible $(n/1)$-gon/cycle. The "opposite sides thing" introduces the flexibility of joining centroids to make *other* $(n/k)$-gons. Your figure amounts to this *ad hoc* "recipe": $$1\,(4)\,1\,(6)\,4^\star\,(4)\,1 = 2$$ where un-parenthesized #s say which $(n/k)$-gon joins centroids, and parenthesized #s say which $(n/k)$-gon is erected on edges. ($4$ vs $4^\star$ are the two types of $(8/4)$.) Which recipes are "interesting"?
Answer: I have a lenghty complex-vector-computational solution. The main idea is in a following lemma.
Lemma: If $ABCD$ is a square with center $S$, then $$ S = {1\over 2}(B-A)i+{1\over 2}(A+B)$$
where letters represent complex numbers of coresponding points (with the same name).

So we get 8 centers and then calculate all $4$ midpoints of those segments. Say we have octagon $ABCDEFGH$, then those midpoints (if we suppose that $A+B+C+D+E+F+G+H =0$) are:
$$ M_1 = {1\over 4}\Big[(D+H-B-F)i+(A+E-C-G)\Big]=-M_3$$
$$ M_2 = {1\over 4}\Big[(A+E-C-G)i+(B+F-D-H)\Big] =-M_4$$
Now it is easy to see that $M_2 = iM_1$ and we are done.
Comment: [+1] The approach using complex numbers' geometry is very adapted to such issues.
Comment: Thank you @JeanMarie, By the way, do you like this one:https://math.stackexchange.com/questions/3126169/stuck-on-a-geometry-puzzle/3126327#3126327
Comment: I didn't accept the answer because I am not looking for a proof (i knew how to prove it beforehand); I was looking for references to publications containing this theorem or similar results.
Comment: No problem, can you post your solution to this problem anyway?
Answer: This could be Proposition 9 and Proposition 10
written in Topic "Equilateral Triangle and Kiepert Perspectors in Complex number" written by Dao thanh Oai in Forum Geometricon Volume 15(2015) 105-114.
Proposition 10 (Thebault's theorem) ´ : Given an octagon $A_1A_2 ··· A_8$, let $B_j$ be the
midpoint of $A_jA_j+1$ for indices j = 1, 2,..., 8 (modulo 8). If $C_j$ , j = 1, 2,..., 8,
are the centers of the squares on $B_jB_j+1$, all externally or internally of the oc-
tagon, then the midpoints of $C_1C_5, C_2C_6, C_3C_7, C_4C_8$ are the vertices of a square.
Note: This above proposition is special case of this given below proposition
Proposition 9 (van Aubel's theorem). Given an octagon $A_1A_2 ··· A_8$, let $Cj , j$ =
1, 2,..., 8 (indices taken modulo 8) , be the centers of the squares on $A_jA_j+1$,
all externally or internally of the octagon. The midpoints of $C_1C_5, C_2C_6, C_3C_7,
C_4C_8$ form a quadrilateral with equal and perpendicular diagonals.
Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/1759484)
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Comment: This is exactly the article I was looking for all those years back. Thank you!
Comment: Is my answer is understandable or I have to edit more?
Comment: There is one downvote above, please feel free to mention the reason as I have just re-edited the message 1 hour ago.
Comment: @TannySieben, Hi , there is one more interesting answer of Proposition 09 and 10 which could be easily explained by Van Abuel's Theorem.  I will not give proof by Algebraic calculation but there are some very simple steps to reduce the proposition 09 and 10 into Van Abuel's Theorem which makes above two proposition obvious.... , Can I Write it as another answer for that , as your questions also ask for "Does anyone find this theorem familiar?"
Comment: I simply mean that Proposition 09 and 10 are Equivalent  theorem of  Van Abuel's Theorem which could be easily explained by some simple steps without Algebraic calculation.
Comment: Sure, would be interesting to see!
Comment: @TannySieben , I have mentioned all the steps and try to explain the things in deatail ........., My English is weak so if in any steps or paragraph , you need any further information then let me know.
Answer: This will be my another possible answer to Claim that Proposition 09 is Equivalent to Van Abuel's Theorem , So follow the Given steps to understand the Situation:
Step 01:Take Two Squares A1A2B1B2 and A9A10B9B10 then m(A2,A10) ;m(A1,A9) ; m(B2,B10);  m(B1,B9) makes Green Square as shown in figure:

Let G1,G5 be center of Square A1A2B1B2 and A9A10B9B10 then m(G1,G5) will be center of small green Square.

Step 02: We will name small green Square formed in step 01 as "Midpoint of Square A1A2B1B2 and A9A10B9B10".

Step03: Similarly make "midpoint of Square of A3A4B3B4 and A11A12B11B12" as Shown in this figure:

Step04: Now take again "midpoint of Square A5A6B5B6 and A13A14B13B14" as shown in figure:

Step 05: Now again take "midpoint of Square A7A8B7B8 and A15A16B15B16" as shown in figure:

Step 06: When points A2=A3; A4=A5; A6=A7; A8=A9 ; A10=A11 ; A12=A13 ; A14=A15 ; A16=A1 then Figure will looks like this:

Conclusion 01: in steps 01 , we have shown that m(G1,G5) will be center of small green Square and Similarly if we take {G2,G3,....,G8) as center of Squares made on Base {A3A4; A5A6; ......; A15A16} then m(G2,G6);m(G3,G7) ;m(G4,G8) will be center of Squares made in step 03,04,05 and from Van Abuel's Theorem we will understand why those two lines are perpendicular to each other.

Conclusion 02: Proposition 10 is Special case of proposition 09 but question may arise why it becomes a Square?
Solution: The reason  is very simple as "*It is well known fact that Centroid of Square made on sides of parallegram in same sence will makes another Square " which is mentioned as  Napoleon Barlotti theorem in case of Quadrilateral".
Here is Hint about Where is Parallegram,
Hint= Let A1A2....A8 be convex irregular octagon and Let {C1,C2,....,C8} be m(A1, A2); m(A2,A3); ........; m(A8,A1) then you will find that m(C1,C5) ; m(C2,C6); m(C3,C7);m(C4,C8) makes parallegram as Shown in this figure:

So from there you Can construct Square on C1C2, C2C3,...,C8C1 and Simillarly Apply all those Steps mentioned above , then you will find that Proposition 10 equivalent to Square mades on Sides of Parallegram!!.


How to prove that all Ternary representations (using $0$ and $2$ only) of the elements of the cantor set are distinct?

Question: There is a bijection between elements of $C$ and infinite sequences of $0$'s and $2$'s: $$\sum_{n=1}^\infty a_n3^{-n}\mapsto\langle a_1,a_2,\dots\rangle\;.$$
I know we will have uncountable such sequences.
That is why we will have uncountable such series. So the cantor set is uncountable.
But how we are knowing that each of the series is distinct ?
Can anyone please help me to understand?
Answer: Suppose that
$$\sum_{n\ge 1}a_n3^{-n}=\sum_{n\ge 1}b_n3^{-n}\,.$$
If the sequences $\langle a_n:n\in\Bbb Z^+\rangle$ and $\langle b_n:n\in\Bbb Z^+\rangle$ are different, let $m$ be the smallest positive integer such that $a_m\ne b_m$; without loss of generality we may assume that $a_m=0$ and $b_m=2$. Then
$$\sum_{n>m}a_n3^{-n}=2\cdot3^{-m}+\sum_{n>m}b_n3^{-n}\,.\tag{1}$$
But
$$\begin{align*}
\sum_{n>m}a_n3^{-n}&\le\sum_{n>m}2\cdot3^{-n}\\
&=\frac{2\cdot3^{-(m+1)}}{1-\frac13}\\
&=3^{-m}\\
&<2\cdot3^{-m}+\sum_{n>m}b_n3^{-n}\,,
\end{align*}$$
so $(1)$ is impossible, and $\langle a_n:n\in\Bbb Z^+\rangle$ and $\langle b_n:n\in\Bbb Z^+\rangle$ must be the same sequence.


Topology, metric spaces, equivalence of metric spaces

Question: The open $n$-cube is the set of all points
$x=(x_1,x_2,\dots,x_n)\in\mathbb R^n$
such that $0<x_i<1$ for $i=1,2,\dots,n$.
Prove that the open $n$-cube, considered as a subspace of $(\mathbb R^n,d)$, is topologically equivalent to
$(\mathbb R^n,d)$.
I'm working on a group of problems and got to this one and am completely lost on what to do. What is an $n$-cube? is it basically another way to write all the numbers in between $0$ and $1$? what function is on-to, $1$ to $1$, and continuous from $(0,1)$ to the reals? I'm dying out here, any assistance would be appreciated.
Comment: As the definition says, the open $n$-cube is the subset of $n$-dimensional space where all coordinates are in $(0,1)$. So the open $1$-cube is $(0,1)$, the open $2$-cube is $(0,1)\times (0,1)$, and so on. I'd think about the homeomorphism $(0,1)\to \mathbb{R}$ a little harder-it actually should be quite intuitive that it's true, so you shouldn't worry about explicit formulas to begin with.
Comment: Well i think i agree that it's true. It's obviously possible to link an open interval to R in 1 dimension but i have no clue how to PROVE it is true for n-dimensions
Comment: OK, so then it's time to write down a map in one dimension, which you will be able to generalize to $n$ dimensions.
Comment: A map f(x) = ln ( (1/x) - 1) is bijective from 0,1 to R but i don't know how to prove that is true or generalize it for multiple n
Comment: or f(x) = (2x-1)/(x-x^2)
Answer: Observe first that the function $f:(0,1)\to\mathbb R$, given by
$$
f(x)=\log\big(\log (x^{-1})\big),
$$
is a homeomorphism (also $C^\infty-$diffeomorphism) between $(0,1)$ and $\mathbb R$, and hence
$$
F(x_1,\ldots,x_n)=\big(\,f(x_1),\ldots,f(x_n)\big) : (0,1)^n\to\mathbb R^n,
$$
is also a homeomorphism between $(0,1)^n$ and $\mathbb R^n$.