Best open source data visualization software to use with PowerPoint

Question: What is the best open source data visualization software? I require the following:

Can import data from Microsoft Excel (importing data from Oracle databases would be good too, but this is not mandatory).
Charts generated by the software can be exported to Microsoft PowerPoint (copy and paste is fine with me).
Open source & easy to use.
Comment: I would recommend switching from powerpoint to use auto generated presentations using Rmd and pandoc. Also selecting your data automatically from a database (as you suggest you already do) would greatly streamline your process. Once the data change or if you would like to followup a few weeks after all you have to do it rerun the script.
Comment: Is there a requirement that it run locally on a system? Is there a platform restriction (Win/Mac)?
Comment: [matplotlib](http://matplotlib.org/gallery.html) in Python, [ggplot2](http://rstudio-pubs-static.s3.amazonaws.com/5051_39c30acbb432498fa1a290f166c6b403.html) in R. Both can export to various formats -- both raster and vector -- but you will need to learn to work with their respective languages.
Comment: What kind of charts are you making? If you are using Excel and powerpoint, why not just use native charts? This way if the data changes, the slides can change relatively easily. Using a third-party solution will mean having to resave data, export, graph, and copy back into a powerpoint.
Answer: I don't know about "best", but the software environment you're named after fits all your requirements:

I keep my data in Excel spreadsheets; when I'm ready to import them to R, I save as CSV and use read.csv().

The RODBC and ora packages are available for importing from Oracle.

Images produced in R can be copied as bitmaps or metafiles and pasted directly into PowerPoint. You can find plenty of recommendations here for R as an open-source data visualization utility:

Open source tools for visualizing multi-dimensional data?
Does anyone know any good open source software for visualizing data from database?
Software for easy-yet-robust data exploration
Resources for learning to create data visualizations?
Resources for learning to use (/create) dynamic (/interactive) statistical visualization

R: update a graph dynamically!

How can I create nice graphs automatically?
Web visualization libraries
Free treemapping software
Recommended visualization libraries for standalone applications
Other suggestions in these threads are worth considering too, but I haven't tried them.
More enthusiasm about R in general (not just for data visualization):

What are some valuable Statistical Analysis open source projects?
What is your favorite, easy to use statistical analysis website or software package?
vs. Python as a statistics workbench ... a close contest at least!

R is open-source. Though its learning curve is nontrivial, it becomes easy to use with experience.
Comment: A non-original quip: The learning curve is steep. If you put in a little effort, you learn a lot. (Otherwise put, it's vital to know which variable is on which axis.)
Answer: Updated 2017-02-24:
I think that the best solutions is to use R with RStudio.  ( Python and iPython notebook is an alternative ):

Data import

Excel: readxl package
Oracle: ora or RODBC package

Plotting: ggplot2
Exporting plots

Copy-and-paste: RStudio's exports plot functionality
Programatically: ReporteRs package

TLDR;
Data Import
There are numerous ways to import excel (tabular) data. For Excel data, the readxl package provides the easiest and most versatile. It generally gets the variable types correct on import.
Alternatives are to save the file as CSV and re-import. The readr package is good for this. @Nick Stauner provides perhaps the most basic solution using read.csv; the limitation is that this requires the additional step of saving a worksheet as a CSV file.  This is not great if your data is spread across multiple sheets.  It can get tedious though there are VBA programs for saving all sheets as CSV files. Google for them. Another limitation is getting the types of the variables correct.  If you use read.csv, you often have to fix your types after importing in R.
There are a few packages that avoid these problems by allowing you to connect read/write  from the spreadsheet directly or by using ODBC.  Search on CRAN for excel or odbc to find the relevant one for your situation.
Plotting
In terms of getting plots into powerpoint, use Rstudio's export plot functions, the copy and paste method using Rstudio is:
export plot > copy plot to clipboard > copy as:  metafile captures the plot to the the paste buffer allowing you to paste directly into Power Point.
As far as generating plots, R has numerous options. The aforementioned ggplot2 package provides a very powerful interface for creating all sorts of plots.  There are additional packages for doing hundreds or thousands of other types of plots/animations/etc.  One limitation is that these are often buried in CRAN packages.
An alternative is to use the ReporteRs package.
Answer: I agree with Nick Stauner on R. And, with a username like "R Learner" I was tempted to not suggest other tools, but there are many. I'll wait to see what the answer to my questions are for more platform-specific ones, but Mondrian is a Java desktop program (so cross-platform) and supports many visualization types that you can easily get into PowerPoint.
Comment: Thanks all for your suggestion. Definitely I will try those packages in R.@hrbrmstr,yes I want to run it locally in my windows system


Why am I getting a segmentation fault on a limit less than 169?

Question: The program below is supposed to count the words in a C file. If I define MAXWORD to be less than 169 I get a segmentation fault. I find this to be confusing as I never use more than 8 characters from that 'word' string I declare inside of main. Not sure where or what to look at next so any pointers (no pun intended) would be appreciated.
After I compile it with gcc wc.c getword.c -o wc I run ./wc < wc.c I get a segmentation fault but only when I set MAXWORD less than 169.
This is the wc.c file
#include "getword.h"
#include <stdlib.h>

#define MAXWORD 169

struct tnode {
    char *word;
    int count;
    struct tnode *left;
    struct tnode *right;
};

struct tnode *addtree(struct tnode *, char *);
void printtree(struct tnode *);

int main(void) {
    char word[MAXWORD];
    struct tnode *root;

    while (getword(word, MAXWORD) != EOF) {
        printf("word: %s\n", word);
        if (isalpha(word[0]))
            root = addtree(root, word);
    }
    printtree(root);

    return 0;
}

struct tnode *talloc(void);

struct tnode *addtree(struct tnode *p, char *word) {
    int cond;

    if (p == NULL) {
        p = talloc();
        p->word = strdup(word);
        p->count = 1;
        p->left = p->right = NULL;
    } else if ((cond = strcmp(word,  p->word)) == 0)
        p->count++;
    else if (cond < 0)
        p->left = addtree(p->left, word);
    else
        p->right = addtree(p->right, word);
    return p;
}

struct tnode *talloc(void) {
    return (struct tnode *) malloc(sizeof(struct tnode));
}

void printtree(struct tnode *p) {
    if (p != NULL) {
        printtree(p->left);
        printf("%4d %s\n", p->count, p->word);
        printtree(p->right);
    }
}

And here's the getword.c file:
#include "getword.h"

#define STACKMAX 100

void skip_quote(char c);
void skip_comment(char c);
void skip_line(void);

int getch(void);
void ungetch(int);

int getword(char *word, int lim) {
    int c;
    char *w = word;

    while (isspace(c = getch()))
        ;
    if (c != EOF)
        *w++ = c;
    if (c == '#') {
        skip_line();
        return c;
    }
    if (c == '"' || c == '\'') {
        skip_quote(c);
        return c;
    }
    if (c == '/' && ((c = getch()) == '*' || c == '/')) {
        skip_comment(c);
        return c;
    }

    if (!isalpha(c)) {
        *w = '\0';
        return c;
    }

    for ( ; --lim > 0; w++)
        if (!isalnum(*w = getch()) && *w != '_') {
            ungetch(*w);
            break;
        }
    *w = '\0';
    return word[0];
}

void skip_quote(char type) {
    int prev, current;

    prev = type;
    current = '\0';
    while ((prev == '\\' || current != type) && prev != current) {
        prev = current;
        current = getch();
    }
}

void skip_comment(char c) {
    int prev;

    prev = '\0';
    if (c == '/')
        skip_line();
    else if (c == '*')
        while (prev != '*' && (c = getch()) != '/')
            prev = c;
}

void skip_line(void) {
    while (getch() != '\n')
        ;
}

int cstack[STACKMAX];
int sp = 0;

int getch(void) {
    return (sp > 0) ? cstack[--sp] : getchar();
}

void ungetch(int c) {
    if (sp < STACKMAX)
        cstack[sp++] = c;
    else
        printf("error: stack is full\n");
}

This is the header getword.h header file
#include <stdio.h>
#include <ctype.h>
#include <string.h>

int getword(char *, int);

Why am I getting a segmentation fault here?
Comment: I wonder why my question was downvoted. Is this type of question not appropriate on stackoverflow?
Comment: Discussed at MSO: http://meta.stackoverflow.com/questions/331796/is-this-newbie-question-about-a-segmentation-fault-in-c-not-acceptable-for-stack
Answer: You invoked undefined behavior by using a value of an uninitialized variable having automatic storage duration root, which is indeterminate, in the main() function. Try initializing it before use, like:
struct tnode *root = NULL;

Comment: @MariusPop *Do you know why it wasn't causing a segmentation fault when the MAXWORD limit was 169 or higher?*  Most likely the larger size of `char word[MAXWORD];` array pushes the `root` variable into memory that hasn't been used yet by the pre-`main()` startup code and is thus still all zeros, which is a `NULL` pointer value.
Comment: That worked. Thanks! Do you know why it wasn't causing a segmentation fault when the ``MAXWORD`` limit was 169 or higher?
Comment: It was undefined behaviour as well as you have used uninitialized pointer in all paths of execution of your code.
Comment: @MariusPop Anything can happen when *undefined behavior* is invoked. It seems beause you were unlucky enough not to find the issue.
Comment: @AndrewHenle I started to think that my question about undefined behavior doesn't make any sense. But your response helps a lot. Thank you!
Answer: In your function
struct tnode *addtree(struct tnode *p, char *word) {
    int cond;

    if (p == NULL) {

you are using value of pointer p, but you pass unitialized pointer to it in main function:
root = addtree(root, word);

SOLUTION:
Initialize pointer:
struct tnode *root = NULL;

You said

I get a segmentation fault but only when I set MAXWORD less than 169.

and you ask

Do you know why it wasn't causing a segmentation fault when the
  MAXWORD limit was 169 or higher?

The undefined behaviour happened independently of value of MAXWORD as you have used uninitialized pointer in all paths of execution of your code. It was undefined behaviour, so undefined behaviour is the answer to your question.
Comment: It feels difficult to accept that there is such a thing as an "undefined behavior" but I guess I have to get used to that. It is what it is. Thanks for the details!


Properties of this average over modular arithmetic unit subgroup: $G = \{ x \in (\Bbb{Z}/n)^{\times} : x^2 = 1 \pmod n\}$.

Question: Let $G = \{ x \in \{0, \dots, n-1\} \subset \Bbb{Z} : x^2 =1  \pmod n\}$ which is isomorphic to a subgroup of $ (\Bbb{Z}/n)^{\times}$.  You perform the operation modulo $n$ and then lift back to the least residue in $G$.
Now define the sum:
$$
A_G = \dfrac{1}{|G|}\sum_{g \in G} g
$$
Define $\Omega(n) = $ the total number of prime divisors of $n$ including multiplicties.  So $\Omega(40) = \Omega(2^3\cdot 5) = 4$.  Etc.
This is an element of $\Bbb{Q}$ in general.  When $n$ is squarefree and odd we know that $|G| = 2^{\Omega(n)}$ and when $n$ is squarefree and even we know that $|G| = 2^{\Omega(n) - 1}$.  Therefore that is well-understood.
Proof. Let $n = q_1 \cdots q_m$ be $n$'s prime factorization and $n$ square-free.  That means each $q_i$ is distinct and there are a total of $\Omega(n) = m$ of them. But $x \in G \iff x^2 = 1\pmod n \iff x^2=1$ modulo each $q_i$ by CRT.  Namely if $x^2 = 1 \pmod n$ then modulo that equation (which is possible beacuse $q_i \mid n)$ by $q_i$ to get $x^2 =1 \pmod q_i$.  And conversely if you have $x^2 = 1 \pmod {q_i}$ for each $i$ then by CRT isomorphism $\psi:\prod_i\Bbb{Z}/q_i \approx \Bbb{Z}/n$ we have that there exists an $x \in \{0, \dots, n-1\}$ such that $x^2 = 1 \pmod n$ and $x^2 = 1 \pmod {q_i}$.  Essentially there is a 1-1 correspondence between solutions in the product ring and solutions in $\Bbb{Z}/n$.  For each $q_i$ the only solutions modulo $q_i$ are from $x^2 - 1 = 0 \pmod {q_i}$ or $x = \pm 1 \pmod {q_i}$ necessarily since $q_i$ is a field.  Now multiply all the possibilities together to get the total count of solutions modulo $n$.  That would be $2^{\Omega(n)}$.  However modulo $q_i = 2$ or in the case that $2 \mid n$, we have that $\pm 1 = 1 \pmod {2}$ are the same number.  So we must subtract one possibility in that factor, making $2^{\Omega(n) - 1}$ whenever $2 \mid n$.  QED
Do we have an explicit formula for the average?
I know that:
$$
\sum_{g \in G} xg = S_G, \\
\forall x \in G
$$
because multiplication by an element $x \in G$ is a permutation of the group.
What I'm interested in are offsets in the ring.  If we similarly define $R = \{ 0, 1, \dots, n-1\}$ where multiplication is done in $\Bbb{Z}/n$ then lifted back to the least residue, then what is:
$$
\sum_{g \in G} (x + g)
$$
and how does it realte to $S_G$?
To be clear, the offset and $x\cdot g$ are done in $R, G$ respectively, but the $\sum$'s are done in $\Bbb{Z}$.

Okay, I partially-answered my question by providing an answer below.  The formula below can be written:
$$\frac{1}{|G|}\sum_{g \in G} (g + x) =
A_x({G_n}) :=\begin{cases} g - \dfrac{n\cdot\#(G_n \cap [n - g, n/2])}{|G_n|}, \text{ if } g \geq n/2 \\ \ \\ g + \dfrac{n\cdot\#(G_n \cap (g, n/2])}{|G_n|}, \text{ if } g \lt n/2 \end{cases} \\
$$
where $g := x_{(n)} =$ the unique element $g$ in $G$ such that $x = g \pmod n$.
But I am finding this formula not very nice to work with in practice.
So can you come up with a nicer formula, or asymptotic, given this as a baseline measurement of elegance?

Upon further reflection.

Main Question.  Does this mean that $A_x(G_n)$, or the average over $G$ with modulo'd-in offset $x$ always falls within the bounds $[x_{(n)} - n/2,x_{(n)} + n/2]$?  This would be since $\#(G_n \cap (x_{(n)}, n/2])$ is maximally $\dfrac{|G_n|}{2}$ for example.
Comment: I am confused....what is $\Omega(n)$ in this context? $|G| \le n-1$. What am I missing.
Comment: @DLeftAdjointtoU thank you for clarifying. But for the benefits of the site, I say you really need to put the elaboration in this comment into your OP. I am not sure if $\Omega(n)$ as used here is standard notation--in many branches of mathematics in fact, $\Omega(n)$ means something else altogether! [Note the 3 upvotes on my previous comment, indicating others probably found my question useful.]
Comment: @Shaun thanks and hi :)
Comment: You're welcome! Hello! This is an interesting question (+1).
Comment: I know it's not elegant, but at some point in the formula, something's going to have to do the dirty job of lifting back into $\Bbb{Z}$, because that's where counting etc happen.
Comment: @Shaun I know it doesn't seem like it, but it has connections to twin primes.  In particular a simple counting formula I'm looking at.
Comment: @Mike $\Omega(n) = $ the total number of prime divisors of $n$ including multiplicities.  So $\Omega(40) = \Omega(8) + \Omega(5) = 3 + 1 = 4$.  When $n$ is squarefree, the total number of elements of $G_n$ is necessarily $2^{\Omega(n) - 1}$ when $n$ is even because the two doesn't contribute two possibilities under CRT argument, only one, because $-1 = 1 \pmod 2$ the same number.  When $q \gt 2$ you get two possibilities $\pm 1 \pmod q$ modulo that prime $q$.  Now CRT every thing up to get $2^{\Omega(n) - 1} = |G_n|$ when $2 \mid n$ and $2^{\Omega(n)}$ when $2 \nmid n$.
Comment: @DLeftAdjointtoU in your OP you still need to define $\Omega(n)$ outright before you use it. This is really just the requirements of a good question, as you are using $\Omega(n)$ in a way that appears to not be standard.
Comment: @Shaun, I can by hand compute the average over $r^2 = 1 \pmod {15}$ or $G = \{1,4,11,14\}$ to be $2n = 30$, so the average value is $15/2 =n/2$ or $7.5$.
Comment: What's interesting about this group is that it only works for twin prime counting i.e. $x^2 = 1^2$ and not $x^2 = k^2$ for $k \gt 1$ (i.e. $4,6, \dots$-separated primes), because those don't necessarily form subgroups.  So the only time group comes into play in this route is with prime twins.
Comment: @Mike Fixed per your requirements and also added in found formula below.  So I ask about the bounds now.  Clearly it's $x_{(n)} \pm n/2$, right?
Answer: Pattern Evidence
Computing the "average" of this group does have a pattern, where $n \in \Bbb{N}$ is the domain of input, and not necessarily just square free:
from sympy import *

N = 1000

def square_roots_of_ksquared_modulo(d, k):
   roots = set()
   for x in range(0, d):
      if (x**2 - k**2) % d == 0:
         roots.add(x)
   return roots

def sum_of_roots_of1_modulo(n:int) -> int:
   G = square_roots_of_ksquared_modulo(n, 1)
   S = 0

   for g in G:
      S += g

   return S / len(G)

for n in range(1, N):
   S = sum_of_roots_of1_modulo(n)

   print(n, S)

The average (without offset) seems to have an amazing, regular pattern:
1 0.0
2 1.0
3 1.5
4 2.0
5 2.5
6 3.0
7 3.5
8 4.0
9 4.5
10 5.0
11 5.5
12 6.0
13 6.5
14 7.0
15 7.5
16 8.0
17 8.5
18 9.0
19 9.5
20 10.0
21 10.5
22 11.0
23 11.5
24 12.0
25 12.5
26 13.0
27 13.5
28 14.0
29 14.5
30 15.0
31 15.5
32 16.0
33 16.5
34 17.0
35 17.5
36 18.0
37 18.5
38 19.0
39 19.5
40 20.0
41 20.5
42 21.0
43 21.5
44 22.0
45 22.5
46 23.0
47 23.5
48 24.0
49 24.5
50 25.0
51 25.5
52 26.0
53 26.5
54 27.0
55 27.5
56 28.0
57 28.5
58 29.0
59 29.5
60 30.0
61 30.5
62 31.0
63 31.5
64 32.0
65 32.5
66 33.0
67 33.5
68 34.0
69 34.5
70 35.0
71 35.5
72 36.0
73 36.5
74 37.0
75 37.5
76 38.0
77 38.5
78 39.0
79 39.5
80 40.0
81 40.5
82 41.0
83 41.5
84 42.0
85 42.5
86 43.0
87 43.5
88 44.0
89 44.5
90 45.0
91 45.5
92 46.0
93 46.5
94 47.0
95 47.5
96 48.0
97 48.5
98 49.0
99 49.5
100 50.0
101 50.5
102 51.0
103 51.5
104 52.0
105 52.5
106 53.0
107 53.5
108 54.0
109 54.5
110 55.0
111 55.5
112 56.0
113 56.5
114 57.0
115 57.5
116 58.0
117 58.5
118 59.0
119 59.5
120 60.0
121 60.5
122 61.0
123 61.5
124 62.0
125 62.5
126 63.0
127 63.5
128 64.0
129 64.5
130 65.0
131 65.5
132 66.0
133 66.5
134 67.0
135 67.5
136 68.0
137 68.5
138 69.0
139 69.5
140 70.0
141 70.5
142 71.0
143 71.5
144 72.0
145 72.5
146 73.0
147 73.5
148 74.0
149 74.5
150 75.0
151 75.5
152 76.0
153 76.5
154 77.0
155 77.5
156 78.0
157 78.5
158 79.0
159 79.5
160 80.0
161 80.5
162 81.0
163 81.5
164 82.0
165 82.5
166 83.0
167 83.5
168 84.0
169 84.5
170 85.0
171 85.5
172 86.0
173 86.5
174 87.0
175 87.5
176 88.0
177 88.5
178 89.0
179 89.5
180 90.0
181 90.5
182 91.0
183 91.5
184 92.0
185 92.5
186 93.0
187 93.5
188 94.0
189 94.5
190 95.0
191 95.5
192 96.0
193 96.5
194 97.0
195 97.5
196 98.0
197 98.5
198 99.0
199 99.5
200 100.0
201 100.5
202 101.0
203 101.5
204 102.0
205 102.5
206 103.0
207 103.5
208 104.0
209 104.5
210 105.0
211 105.5
212 106.0
213 106.5
214 107.0
215 107.5
216 108.0
217 108.5
218 109.0
219 109.5
220 110.0
221 110.5
222 111.0
223 111.5
224 112.0
225 112.5
226 113.0
227 113.5
228 114.0
229 114.5
230 115.0
231 115.5
232 116.0
233 116.5
234 117.0
235 117.5
236 118.0
237 118.5
238 119.0
239 119.5
240 120.0
241 120.5
242 121.0
243 121.5
244 122.0
245 122.5
246 123.0
247 123.5
248 124.0
249 124.5
250 125.0
251 125.5
252 126.0
253 126.5
254 127.0
255 127.5
256 128.0
257 128.5
258 129.0
259 129.5
260 130.0
261 130.5
262 131.0
263 131.5
264 132.0
265 132.5
266 133.0
267 133.5
268 134.0
269 134.5
270 135.0
271 135.5
272 136.0
273 136.5
274 137.0
275 137.5
276 138.0
277 138.5
278 139.0
279 139.5
280 140.0
281 140.5
282 141.0
283 141.5
284 142.0
285 142.5
286 143.0
287 143.5
288 144.0
289 144.5
290 145.0
291 145.5
292 146.0
293 146.5
294 147.0
295 147.5
296 148.0
297 148.5
298 149.0
299 149.5
300 150.0
301 150.5
302 151.0
303 151.5
304 152.0
305 152.5
306 153.0
307 153.5
308 154.0
309 154.5
310 155.0
311 155.5
312 156.0
313 156.5
314 157.0
315 157.5
316 158.0
317 158.5
318 159.0
319 159.5
320 160.0
321 160.5
322 161.0
323 161.5
324 162.0
325 162.5
326 163.0
327 163.5
328 164.0
329 164.5
330 165.0
331 165.5
332 166.0
333 166.5
334 167.0
335 167.5
336 168.0
337 168.5
338 169.0
339 169.5
340 170.0
341 170.5
342 171.0
343 171.5
344 172.0
345 172.5
346 173.0
347 173.5
348 174.0
349 174.5
350 175.0
351 175.5
352 176.0
353 176.5
354 177.0
355 177.5
356 178.0
357 178.5
358 179.0
359 179.5
360 180.0
361 180.5
362 181.0
363 181.5
364 182.0
365 182.5
366 183.0
367 183.5
368 184.0
369 184.5
370 185.0
371 185.5
372 186.0
373 186.5
374 187.0
375 187.5
376 188.0
377 188.5
378 189.0
379 189.5
380 190.0
381 190.5
382 191.0
383 191.5
384 192.0
385 192.5
386 193.0
387 193.5
388 194.0
389 194.5
390 195.0
391 195.5
392 196.0
393 196.5
394 197.0
395 197.5
396 198.0
397 198.5
398 199.0
399 199.5
400 200.0
401 200.5
402 201.0
403 201.5
404 202.0
405 202.5
406 203.0
407 203.5
408 204.0
409 204.5
410 205.0
411 205.5
412 206.0
413 206.5
414 207.0
415 207.5
416 208.0
417 208.5
418 209.0
419 209.5
420 210.0
421 210.5
422 211.0
423 211.5
424 212.0
425 212.5
426 213.0
427 213.5
428 214.0
429 214.5
430 215.0
431 215.5
432 216.0
433 216.5
434 217.0
435 217.5
436 218.0
437 218.5
438 219.0
439 219.5
440 220.0
441 220.5
442 221.0
443 221.5
444 222.0
445 222.5
446 223.0
447 223.5
448 224.0
449 224.5
450 225.0
451 225.5
452 226.0
453 226.5
454 227.0
455 227.5
456 228.0
457 228.5
458 229.0
459 229.5
460 230.0
461 230.5
462 231.0
463 231.5
464 232.0
465 232.5
466 233.0
467 233.5
468 234.0
469 234.5
470 235.0
471 235.5
472 236.0
473 236.5
474 237.0
475 237.5
476 238.0
477 238.5
478 239.0
479 239.5
480 240.0
481 240.5
482 241.0
483 241.5
484 242.0
485 242.5
486 243.0
487 243.5
488 244.0
489 244.5
490 245.0
491 245.5
492 246.0
493 246.5
494 247.0
495 247.5
496 248.0
497 248.5
498 249.0
499 249.5
500 250.0
501 250.5
502 251.0
503 251.5
504 252.0
505 252.5
506 253.0
507 253.5
508 254.0
509 254.5
510 255.0
511 255.5
512 256.0
513 256.5
514 257.0
515 257.5
516 258.0
517 258.5
518 259.0
519 259.5
520 260.0
521 260.5
522 261.0
523 261.5
524 262.0
525 262.5
526 263.0
527 263.5
528 264.0
529 264.5
530 265.0
531 265.5
532 266.0
533 266.5
534 267.0
535 267.5
536 268.0
537 268.5
538 269.0
539 269.5
540 270.0
541 270.5
542 271.0
543 271.5
544 272.0
545 272.5
546 273.0
547 273.5
548 274.0
549 274.5
550 275.0
551 275.5
552 276.0
553 276.5
554 277.0
555 277.5
556 278.0
557 278.5
558 279.0
559 279.5
560 280.0
561 280.5
562 281.0
563 281.5
564 282.0
565 282.5
566 283.0
567 283.5
568 284.0
569 284.5
570 285.0
571 285.5
572 286.0
573 286.5
574 287.0
575 287.5
576 288.0
577 288.5
578 289.0
579 289.5
580 290.0
581 290.5
582 291.0
583 291.5
584 292.0
585 292.5
586 293.0
587 293.5
588 294.0
589 294.5
590 295.0
591 295.5
592 296.0
593 296.5
594 297.0
595 297.5
596 298.0
597 298.5
598 299.0
599 299.5
600 300.0
601 300.5
602 301.0
603 301.5
604 302.0
605 302.5
606 303.0
607 303.5
608 304.0
609 304.5
610 305.0
611 305.5
612 306.0
613 306.5
614 307.0
615 307.5
616 308.0
617 308.5
618 309.0
619 309.5
620 310.0
621 310.5
622 311.0
623 311.5
624 312.0
625 312.5
626 313.0
627 313.5
628 314.0
629 314.5
630 315.0
631 315.5
632 316.0
633 316.5
634 317.0
635 317.5
636 318.0
637 318.5
638 319.0
639 319.5
640 320.0
641 320.5
642 321.0
643 321.5
644 322.0
645 322.5
646 323.0
647 323.5
648 324.0
649 324.5
650 325.0
651 325.5
652 326.0
653 326.5
654 327.0
655 327.5
656 328.0
657 328.5
658 329.0
659 329.5
660 330.0
661 330.5
662 331.0
663 331.5
664 332.0
665 332.5
666 333.0
667 333.5
668 334.0
669 334.5
670 335.0
671 335.5
672 336.0
673 336.5
674 337.0
675 337.5
676 338.0
677 338.5
678 339.0
679 339.5
680 340.0
681 340.5
682 341.0
683 341.5
684 342.0
685 342.5
686 343.0
687 343.5
688 344.0
689 344.5
690 345.0
691 345.5
692 346.0
693 346.5
694 347.0
695 347.5
696 348.0
697 348.5
698 349.0
699 349.5
700 350.0
701 350.5
702 351.0
703 351.5
704 352.0
705 352.5
706 353.0
707 353.5
708 354.0
709 354.5
710 355.0
711 355.5
712 356.0
713 356.5
714 357.0
715 357.5
716 358.0
717 358.5
718 359.0
719 359.5
720 360.0
721 360.5
722 361.0
723 361.5
724 362.0
725 362.5
726 363.0
727 363.5
728 364.0
729 364.5
730 365.0
731 365.5
732 366.0
733 366.5
734 367.0
735 367.5
736 368.0
737 368.5
738 369.0
739 369.5
740 370.0
741 370.5
742 371.0
743 371.5
744 372.0
745 372.5
746 373.0
747 373.5
748 374.0
749 374.5
750 375.0
751 375.5
752 376.0
753 376.5
754 377.0
755 377.5
756 378.0
757 378.5
758 379.0
759 379.5
760 380.0
761 380.5
762 381.0
763 381.5
764 382.0
765 382.5
766 383.0
767 383.5
768 384.0
769 384.5
770 385.0
771 385.5
772 386.0
773 386.5
774 387.0
775 387.5
776 388.0
777 388.5
778 389.0
779 389.5
780 390.0
781 390.5
782 391.0
783 391.5
784 392.0
785 392.5
786 393.0
787 393.5
788 394.0
789 394.5
790 395.0
791 395.5
792 396.0
793 396.5
794 397.0
795 397.5
796 398.0
797 398.5
798 399.0
799 399.5
800 400.0
801 400.5
802 401.0
803 401.5
804 402.0
805 402.5
806 403.0
807 403.5
808 404.0
809 404.5
810 405.0
811 405.5
812 406.0
813 406.5
814 407.0
815 407.5
816 408.0
817 408.5
818 409.0
819 409.5
820 410.0
821 410.5
822 411.0
823 411.5
824 412.0
825 412.5
826 413.0
827 413.5
828 414.0
829 414.5
830 415.0
831 415.5
832 416.0
833 416.5
834 417.0
835 417.5
836 418.0
837 418.5
838 419.0
839 419.5
840 420.0
841 420.5
842 421.0
843 421.5
844 422.0
845 422.5
846 423.0
847 423.5
848 424.0
849 424.5
850 425.0
851 425.5
852 426.0
853 426.5
854 427.0
855 427.5
856 428.0
857 428.5
858 429.0
859 429.5
860 430.0
861 430.5
862 431.0
863 431.5
864 432.0
865 432.5
866 433.0
867 433.5
868 434.0
869 434.5
870 435.0
871 435.5
872 436.0
873 436.5
874 437.0
875 437.5
876 438.0
877 438.5
878 439.0
879 439.5
880 440.0
881 440.5
882 441.0
883 441.5
884 442.0
885 442.5
886 443.0
887 443.5
888 444.0
889 444.5
890 445.0
891 445.5
892 446.0
893 446.5
894 447.0
895 447.5
896 448.0
897 448.5
898 449.0
899 449.5
900 450.0
901 450.5
902 451.0
903 451.5
904 452.0
905 452.5
906 453.0
907 453.5
908 454.0
909 454.5
910 455.0
911 455.5
912 456.0
913 456.5
914 457.0
915 457.5
916 458.0
917 458.5
918 459.0
919 459.5
920 460.0
921 460.5
922 461.0
923 461.5
924 462.0
925 462.5
926 463.0
927 463.5
928 464.0
929 464.5
930 465.0
931 465.5
932 466.0
933 466.5
934 467.0
935 467.5
936 468.0
937 468.5
938 469.0
939 469.5
940 470.0
941 470.5
942 471.0
943 471.5
944 472.0
945 472.5
946 473.0
947 473.5
948 474.0
949 474.5
950 475.0
951 475.5
952 476.0
953 476.5
954 477.0
955 477.5
956 478.0
957 478.5
958 479.0
959 479.5
960 480.0
961 480.5
962 481.0
963 481.5
964 482.0
965 482.5
966 483.0
967 483.5
968 484.0
969 484.5
970 485.0
971 485.5
972 486.0
973 486.5
974 487.0
975 487.5
976 488.0
977 488.5
978 489.0
979 489.5
980 490.0
981 490.5
982 491.0
983 491.5
984 492.0
985 492.5
986 493.0
987 493.5
988 494.0
989 494.5
990 495.0
991 495.5
992 496.0
993 496.5
994 497.0
995 497.5
996 498.0
997 498.5
998 499.0
999 499.5

Thus, $f(1) = 0$ an for $n \geq 2$, $f(n) := \sum_{g \in G_n} \dfrac{g}{|G_n|} = \dfrac{n}{2}$.   This post is just about the evidence.  Not a proof of this apparent fact.
Comment: I also see now why it has to be true.  It's because you can pair up $r^2 = 1 \pmod n$ with $-r$, and they occur symmetrically across $n/2$ on the number line.  If there is one _at $r = n/2$_ then it would only help it become more averaged at that halfway point.
Answer: Sketch of formula proof.
Let's write $x_{(n)}$ to mean $x_{(n)} \in \Bbb{Z}$ but $x = x_{(n)} \pmod n$ and $x_{(n)}$ is the minimal such non-negative integer.  We can assume that $r \leq n/2$.
There are a few cases, where $x':= x_{(n)}$ can occur relative to $r$ and $n/2$:
$$
1 \leq r \leq n/2 \leq n-r \leq \textbf{x}' \lt n \textbf{ (Case 0)} \\
1 \leq r \leq n/2 \leq \textbf{x}' \lt n - r \lt n \textbf{ (Case 1)} \\
1 \leq r \leq \textbf{x}' \lt n/2\leq n-r \lt n \textbf{ (Case 2)}\\
1 \leq \textbf{x}' \lt r \leq n/2 \leq n-r\lt n \textbf{ (Case 3)}\\
$$
In Case 0, we clearly have $(x' - r)_{(n)} = x' - r$ and $(x' + r)_{(n)} = x' + r - n$.  So we have $2x' - n$ in case $0$.  In Case 1 we have both $(x' - r)_{(n)} = x' - r$ and $(x' + r)_{(n)} = x' + r$.  So in that case we get $2x'$.
In Case 2 we have $(x' - r)_{(n)} = x' - r$ and $(x' + r)_{(n)} = x' + r$ as well so $2x'$ in that case. Finally in case $3$ we have, $(x' + r)_{(n)} = x' + r $, but $x' - r \lt 0$ so that $(x' - r)_{(n)} = x' - r + n$, and what you end up with is $2x' + n$.

In the averaging problem we have:
$$
A({G_n}) :=\begin{cases} x' - \frac{n\cdot\#\{g \in G : g \leq n/2, g + x' \geq n\}}{|G_n|}, \text{ if } x' \geq n/2 \\ \ \\ x' + \frac{n\cdot\#\{g \in G : g \leq n/2, x' \lt g\}}{|G_n|}, \text{ if } x' \lt n/2 \end{cases}
$$

Verification code.
Though this formula may seem legit, the code doesn't check out:
from sympy import *
from functools import reduce

N = 100
k = 1

def square_roots_of_ksquared_modulo(d, k):
   roots = set()
   for x in range(0, d):
      if (x**2 - k**2) % d == 0:
         roots.add(x)
   return roots

def average_sqrt1_modulo(n, x:int):
   # x = internal offset
   S = 0

   roots= square_roots_of_ksquared_modulo(n, k=1)

   for r in roots:
      S += (x - r) % n

   return S / len(roots)

def formula_for_avg_sqrt1_modulo(n, x:int):
   S = x % n

   roots = square_roots_of_ksquared_modulo(n, k=1)

   if x >= n/2:
      for r in roots:
         if n - (x%n) <= r <= n/2:
            S -= n/len(roots)
   else:
      for r in roots:
         if (x%n) < r <= n/2:
            S += n/len(roots)

   return S

for n in range(1, N):
   for x in range(0, n):
      f = formula_for_avg_sqrt1_modulo(n, x)
      a = average_sqrt1_modulo(n, x)

      diff = f - a

      print(f'n,x,actual, diff={n},{x},{a}, {diff}')

Outputs.
n,x,actual, diff=1,0,0.0, 0.0
n,x,actual, diff=2,0,1.0, 1.0
n,x,actual, diff=2,1,0.0, -1.0
n,x,actual, diff=3,0,1.5, 0.0
n,x,actual, diff=3,1,1.0, 0.0
n,x,actual, diff=3,2,0.5, 0.0
n,x,actual, diff=4,0,2.0, 0.0
n,x,actual, diff=4,1,1.0, 0.0
n,x,actual, diff=4,2,2.0, 0.0
n,x,actual, diff=4,3,1.0, 0.0
n,x,actual, diff=5,0,2.5, 0.0
n,x,actual, diff=5,1,1.0, 0.0
n,x,actual, diff=5,2,2.0, 0.0
n,x,actual, diff=5,3,3.0, 0.0
n,x,actual, diff=5,4,1.5, 0.0
n,x,actual, diff=6,0,3.0, 0.0
n,x,actual, diff=6,1,1.0, 0.0
n,x,actual, diff=6,2,2.0, 0.0
n,x,actual, diff=6,3,3.0, 0.0
n,x,actual, diff=6,4,4.0, 0.0
n,x,actual, diff=6,5,2.0, 0.0
n,x,actual, diff=7,0,3.5, 0.0
n,x,actual, diff=7,1,1.0, 0.0
n,x,actual, diff=7,2,2.0, 0.0
n,x,actual, diff=7,3,3.0, 0.0
n,x,actual, diff=7,4,4.0, 0.0
n,x,actual, diff=7,5,5.0, 0.0
n,x,actual, diff=7,6,2.5, 0.0
n,x,actual, diff=8,0,4.0, 0.0
n,x,actual, diff=8,1,3.0, 0.0
n,x,actual, diff=8,2,4.0, 0.0
n,x,actual, diff=8,3,3.0, 0.0
n,x,actual, diff=8,4,4.0, 0.0
n,x,actual, diff=8,5,3.0, 0.0
n,x,actual, diff=8,6,4.0, 0.0
n,x,actual, diff=8,7,3.0, 0.0
n,x,actual, diff=9,0,4.5, 0.0
n,x,actual, diff=9,1,1.0, 0.0
n,x,actual, diff=9,2,2.0, 0.0
n,x,actual, diff=9,3,3.0, 0.0
n,x,actual, diff=9,4,4.0, 0.0
n,x,actual, diff=9,5,5.0, 0.0
n,x,actual, diff=9,6,6.0, 0.0
n,x,actual, diff=9,7,7.0, 0.0
n,x,actual, diff=9,8,3.5, 0.0
n,x,actual, diff=10,0,5.0, 0.0
n,x,actual, diff=10,1,1.0, 0.0
n,x,actual, diff=10,2,2.0, 0.0
n,x,actual, diff=10,3,3.0, 0.0
n,x,actual, diff=10,4,4.0, 0.0
n,x,actual, diff=10,5,5.0, 0.0
n,x,actual, diff=10,6,6.0, 0.0
n,x,actual, diff=10,7,7.0, 0.0
n,x,actual, diff=10,8,8.0, 0.0
n,x,actual, diff=10,9,4.0, 0.0
n,x,actual, diff=11,0,5.5, 0.0
n,x,actual, diff=11,1,1.0, 0.0
n,x,actual, diff=11,2,2.0, 0.0
n,x,actual, diff=11,3,3.0, 0.0
n,x,actual, diff=11,4,4.0, 0.0
n,x,actual, diff=11,5,5.0, 0.0
n,x,actual, diff=11,6,6.0, 0.0
n,x,actual, diff=11,7,7.0, 0.0
n,x,actual, diff=11,8,8.0, 0.0
n,x,actual, diff=11,9,9.0, 0.0
n,x,actual, diff=11,10,4.5, 0.0
n,x,actual, diff=12,0,6.0, 0.0
n,x,actual, diff=12,1,4.0, 0.0
n,x,actual, diff=12,2,5.0, 0.0
n,x,actual, diff=12,3,6.0, 0.0
n,x,actual, diff=12,4,7.0, 0.0
n,x,actual, diff=12,5,5.0, 0.0
n,x,actual, diff=12,6,6.0, 0.0
n,x,actual, diff=12,7,4.0, 0.0
n,x,actual, diff=12,8,5.0, 0.0
n,x,actual, diff=12,9,6.0, 0.0
n,x,actual, diff=12,10,7.0, 0.0
n,x,actual, diff=12,11,5.0, 0.0
n,x,actual, diff=13,0,6.5, 0.0
n,x,actual, diff=13,1,1.0, 0.0
n,x,actual, diff=13,2,2.0, 0.0
n,x,actual, diff=13,3,3.0, 0.0
n,x,actual, diff=13,4,4.0, 0.0
n,x,actual, diff=13,5,5.0, 0.0
n,x,actual, diff=13,6,6.0, 0.0
n,x,actual, diff=13,7,7.0, 0.0
n,x,actual, diff=13,8,8.0, 0.0
n,x,actual, diff=13,9,9.0, 0.0
n,x,actual, diff=13,10,10.0, 0.0
n,x,actual, diff=13,11,11.0, 0.0
n,x,actual, diff=13,12,5.5, 0.0
n,x,actual, diff=14,0,7.0, 0.0
n,x,actual, diff=14,1,1.0, 0.0
n,x,actual, diff=14,2,2.0, 0.0
n,x,actual, diff=14,3,3.0, 0.0
n,x,actual, diff=14,4,4.0, 0.0
n,x,actual, diff=14,5,5.0, 0.0
n,x,actual, diff=14,6,6.0, 0.0
n,x,actual, diff=14,7,7.0, 0.0
n,x,actual, diff=14,8,8.0, 0.0
n,x,actual, diff=14,9,9.0, 0.0
n,x,actual, diff=14,10,10.0, 0.0
n,x,actual, diff=14,11,11.0, 0.0
n,x,actual, diff=14,12,12.0, 0.0
n,x,actual, diff=14,13,6.0, 0.0
n,x,actual, diff=15,0,7.5, 0.0
n,x,actual, diff=15,1,4.75, 0.0
n,x,actual, diff=15,2,5.75, 0.0
n,x,actual, diff=15,3,6.75, 0.0
n,x,actual, diff=15,4,4.0, 0.0
n,x,actual, diff=15,5,5.0, 0.0
n,x,actual, diff=15,6,6.0, 0.0
n,x,actual, diff=15,7,7.0, 0.0
n,x,actual, diff=15,8,8.0, 0.0
n,x,actual, diff=15,9,9.0, 0.0
n,x,actual, diff=15,10,10.0, 0.0
n,x,actual, diff=15,11,7.25, 0.0
n,x,actual, diff=15,12,8.25, 0.0
n,x,actual, diff=15,13,9.25, 0.0
n,x,actual, diff=15,14,6.5, 0.0
n,x,actual, diff=16,0,8.0, 0.0
n,x,actual, diff=16,1,5.0, 0.0
n,x,actual, diff=16,2,6.0, 0.0
n,x,actual, diff=16,3,7.0, 0.0
n,x,actual, diff=16,4,8.0, 0.0
n,x,actual, diff=16,5,9.0, 0.0
n,x,actual, diff=16,6,10.0, 0.0
n,x,actual, diff=16,7,7.0, 0.0
n,x,actual, diff=16,8,8.0, 0.0
n,x,actual, diff=16,9,5.0, 0.0
n,x,actual, diff=16,10,6.0, 0.0
n,x,actual, diff=16,11,7.0, 0.0
n,x,actual, diff=16,12,8.0, 0.0
n,x,actual, diff=16,13,9.0, 0.0
n,x,actual, diff=16,14,10.0, 0.0
n,x,actual, diff=16,15,7.0, 0.0
n,x,actual, diff=17,0,8.5, 0.0
n,x,actual, diff=17,1,1.0, 0.0
n,x,actual, diff=17,2,2.0, 0.0
n,x,actual, diff=17,3,3.0, 0.0
n,x,actual, diff=17,4,4.0, 0.0
n,x,actual, diff=17,5,5.0, 0.0
n,x,actual, diff=17,6,6.0, 0.0
n,x,actual, diff=17,7,7.0, 0.0
n,x,actual, diff=17,8,8.0, 0.0
n,x,actual, diff=17,9,9.0, 0.0
n,x,actual, diff=17,10,10.0, 0.0
n,x,actual, diff=17,11,11.0, 0.0
n,x,actual, diff=17,12,12.0, 0.0
n,x,actual, diff=17,13,13.0, 0.0
n,x,actual, diff=17,14,14.0, 0.0
n,x,actual, diff=17,15,15.0, 0.0
n,x,actual, diff=17,16,7.5, 0.0
n,x,actual, diff=18,0,9.0, 0.0
n,x,actual, diff=18,1,1.0, 0.0
n,x,actual, diff=18,2,2.0, 0.0
n,x,actual, diff=18,3,3.0, 0.0
n,x,actual, diff=18,4,4.0, 0.0
n,x,actual, diff=18,5,5.0, 0.0
n,x,actual, diff=18,6,6.0, 0.0
n,x,actual, diff=18,7,7.0, 0.0
n,x,actual, diff=18,8,8.0, 0.0
n,x,actual, diff=18,9,9.0, 0.0
n,x,actual, diff=18,10,10.0, 0.0
n,x,actual, diff=18,11,11.0, 0.0
n,x,actual, diff=18,12,12.0, 0.0
n,x,actual, diff=18,13,13.0, 0.0
n,x,actual, diff=18,14,14.0, 0.0
n,x,actual, diff=18,15,15.0, 0.0
n,x,actual, diff=18,16,16.0, 0.0
n,x,actual, diff=18,17,8.0, 0.0
n,x,actual, diff=19,0,9.5, 0.0
n,x,actual, diff=19,1,1.0, 0.0
n,x,actual, diff=19,2,2.0, 0.0
n,x,actual, diff=19,3,3.0, 0.0
n,x,actual, diff=19,4,4.0, 0.0
n,x,actual, diff=19,5,5.0, 0.0
n,x,actual, diff=19,6,6.0, 0.0
n,x,actual, diff=19,7,7.0, 0.0
n,x,actual, diff=19,8,8.0, 0.0
n,x,actual, diff=19,9,9.0, 0.0
n,x,actual, diff=19,10,10.0, 0.0
n,x,actual, diff=19,11,11.0, 0.0
n,x,actual, diff=19,12,12.0, 0.0
n,x,actual, diff=19,13,13.0, 0.0
n,x,actual, diff=19,14,14.0, 0.0
n,x,actual, diff=19,15,15.0, 0.0
n,x,actual, diff=19,16,16.0, 0.0
n,x,actual, diff=19,17,17.0, 0.0
n,x,actual, diff=19,18,8.5, 0.0
n,x,actual, diff=20,0,10.0, 0.0
n,x,actual, diff=20,1,6.0, 0.0
n,x,actual, diff=20,2,7.0, 0.0
n,x,actual, diff=20,3,8.0, 0.0
n,x,actual, diff=20,4,9.0, 0.0
n,x,actual, diff=20,5,10.0, 0.0
n,x,actual, diff=20,6,11.0, 0.0
n,x,actual, diff=20,7,12.0, 0.0
n,x,actual, diff=20,8,13.0, 0.0
n,x,actual, diff=20,9,9.0, 0.0
n,x,actual, diff=20,10,10.0, 0.0
n,x,actual, diff=20,11,6.0, 0.0
n,x,actual, diff=20,12,7.0, 0.0
n,x,actual, diff=20,13,8.0, 0.0
n,x,actual, diff=20,14,9.0, 0.0
n,x,actual, diff=20,15,10.0, 0.0
n,x,actual, diff=20,16,11.0, 0.0
n,x,actual, diff=20,17,12.0, 0.0
n,x,actual, diff=20,18,13.0, 0.0
n,x,actual, diff=20,19,9.0, 0.0
n,x,actual, diff=21,0,10.5, 0.0
n,x,actual, diff=21,1,6.25, 0.0
n,x,actual, diff=21,2,7.25, 0.0
n,x,actual, diff=21,3,8.25, 0.0
n,x,actual, diff=21,4,9.25, 0.0
n,x,actual, diff=21,5,10.25, 0.0
n,x,actual, diff=21,6,11.25, 0.0
n,x,actual, diff=21,7,12.25, 0.0
n,x,actual, diff=21,8,8.0, 0.0
n,x,actual, diff=21,9,9.0, 0.0
n,x,actual, diff=21,10,10.0, 0.0
n,x,actual, diff=21,11,11.0, 0.0
n,x,actual, diff=21,12,12.0, 0.0
n,x,actual, diff=21,13,7.75, 0.0
n,x,actual, diff=21,14,8.75, 0.0
n,x,actual, diff=21,15,9.75, 0.0
n,x,actual, diff=21,16,10.75, 0.0
n,x,actual, diff=21,17,11.75, 0.0
n,x,actual, diff=21,18,12.75, 0.0
n,x,actual, diff=21,19,13.75, 0.0
n,x,actual, diff=21,20,9.5, 0.0

So this formula is valid for $n \gt 2$.  For $n = 1,2$ of course those are easy-to-handle simpler cases.
Comment: The reason you add $(x - r)_{(n)} + (x + r)_{(n)}$ is because for $n \gt 2$ the square roots of unity $r, -r$ can be paired together.


Using %>% operator from dplyr without loading dplyr in R

Question: I'm currently building a package and I was wondering if there was a way to call the %>% operator from dplyr without actually attaching the dplyr package. For example, with any function that is being exported from a package, you can call it with the double colon (::). So if I wanted to use the group_by function without attaching dplyr, I would enter dplyr::group_by. Is there something similar for operators?
Comment: I think the `%>%` function is actually imported from 'pkg:magrittr'. You would need to quote or backtick the `%>%`
Comment: You will have to use `magrittr::\`%>%\``
Answer: You can refer to any object with non-standard name by enclosing in backticks.  This means you can do this:
`%>%` <- magrittr::`%>%`

This will define the %>% operator in your current environment. For example:
iris %>% head

  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

Answer: The easiest way would be to load the magrittr package, which only does piping, and is the original source of %>%. If you don't want to load any packages, you can still use %>%, but not in any really useful way (unless you define it in your environment as Andrie suggests). Using it with :: would go like this:
# standard use
mtcars %>% summary()
# :: use
magrittr::"%>%"(mtcars, summary())

You really lose any advantage of readability/not nesting with this method.
Since you say you're building a package, you should put magrittr in Imports, or even just us importsFrom and grab the "%>%" function. See here for more info.
Answer: If you have 'dplyr' installed but not loaded you can get a result with:
 dplyr::`%>%`   # Note the backticks, although quotes work as well.

That displays the code but at the bottom you will see that its environment is actually the NAMESPACE of 'magritter' which 'dplyr' imports. As the two other knowledgeable respondents point out there are a couple of ways to use it as a function although it cannot just be interposed between a lhs and a rhs argument unless you make a local copy that has the flanking "%"'s or call it with the functional parentheses. The R parser won't allow:
>  mtcars dplyr::"%>%" summary()
Error: unexpected symbol in " mtcars dplyr"

Answer: There seems to be a clash between the pipe notation as implemented in dplyr and the double colon notation. I didn't find anything about it in the documentation.
## This works:
base::mean(1:10)

## This doesn't:
1:10 %>% base::mean

## It works after parenthesizing though:
1:10 %>% (base::mean)

It could be made a bit more prominent in the docs.
This issue was moved by romainfrancois from tidyverse/dplyr#3958.
source : https://github.com/tidyverse/magrittr/issues/183


Determining whether proofs of the Pythagorean theorem are essentially the same, or essentially different

Question: There are great annotated lists of proofs of the Pythagorean theorem, to name just two:

cut-the-knot.org
brilliant.org

There's an obvious difference between geometric and algebraic proofs (which use some algebraic notation usually including the binomial formula). There are other differences, especially the length and complexity of a proof (compare Pythagoras' and Euclid's proof here).
But even a non-expert gets the feeling that some of the proofs are "essential the same", among the geometric ones, among the algebraic ones, but even between geometric and algebraic ones.
Other pairs of proofs seem to be essentially different, at least for the non-expert (maybe not for the expert).

What I'm looking for is a diagram or table in which for each pair of proofs of the Pythagorean theorem it is indicated that (and maybe in which respect) they are essentially the same or different (optimally to which degree).

I'm aware that the question what makes two proofs essentially the same is a vague one (and subject of discussion, e.g. here and here). But assuming that the notion is not totally pointless, and that the answer at least sometimes is clear, I dare to ask this (i.e. for a reference which sums it up).
Comment: A good place to start may be Elisha Loomis' 300-page compendium, "The Pythagorean Proposition", sub-titled "Its Demonstrations Analyzed and Classified and Bibliography of Sources for Data of the Four Kinds of 'Proofs'". (A PDF of a microfiche transfer is [here](https://files.eric.ed.gov/fulltext/ED037335.pdf).)
Comment: Marvelous! That's the answer (at least a very promising one).
Answer: (Promoting my comment to an answer.)
A good place to start may be Elisha Loomis' 300-page compendium, "The Pythagorean Proposition" (1940), sub-titled "Its Demonstrations Analyzed and Classified and Bibliography of Sources for Data of the Four Kinds of 'Proofs'".
I believe the book is now out-of-print. A PDF of a microfiche transfer is available from the U.S. Department of Education here.


Is there any way to fixed the background image during the transition page? In jquery mobile

Question: I am making iphone app using jquery mobile.
I have two page which login and signup page.
Each page is different page and link with anchor

->signup.html

signup

when I click anchor the page change with transition.
!!!! But I don't want to change the background image during the transition
It means that only the content looks transitiong right to left.
Help me!
Answer: you can try below line of code;
$(el).css({ 'background-color': 'white', 'background-repeat':'repeat'});

OR
$(el).css({ 'background-image': 'url('images/background.png')' , 'background-repeat':'repeat'});

i think this will good enough helpful to you.
Thanks.
Comment: is there any way with using some image files? like "background.png"
Comment: yes obviously..you can do by replacing **color** with **image**; See my edited answer.. :)
Answer: You can also try to remove any background on the page and content area, set the background color or image on the body and then you should have sliding contents with fixed background. A persistent footer will also stay in place. Only drawback is the header, which will also slide in together with contents
Comment: i set background image on page using .ui-page
but when i set background-image on body it was hidden by page. How can  set background-image on body?


New to Objective-C --> Quick question(s)

Question: So I'm trying to make the horrible leap from VB.NET to objective-C.
My only curly-brace experience is a little ActionScript 3...  I'm having a hard time grasping the use of the * character.
Question 1:
The tutorial I'm using has these two lines next to each other..
IBOutlet UIPickerView *pickerView;
NSArray* myArray;

It's my understanding that the * denotes essentially a reference type.   Why does it precede the variable name on the first line, but the class name on the second?
Question two, about class declarations:
@implementation {
 Why is some code here
}

and other code here?
@end

Answer:
That's a big can of worms - the answer is that the syntax there is equivalent, you can do whichever you like.  Some people are pretty religious about one or the other, but the compiler doesn't care.
I think you mean @interface, right?  The code inside the braces is just a list of instance variables.  Outside the braces is where you put method declarations.

If you want to learn Objective-C, it is probably well worth it to go and learn C first.  Then when you understand the syntax and C concepts like pointers and forward declarations, you can pick up Objective-C pretty quickly.
Comment: One thing to keep in mind is that if you're declaring multiple variables per line (`NSArray *oneArray, *anotherArray;`) you need the `*` for each variable (`NSArray* oneArray, anotherArray;` is like `NSArray * oneArray; NSArray anotherArray;`). This might be a good reason to keep the `*` with the variable name. Or, if you prefer the `*` with the type (as I do), then it's a good reason to avoid ever declaring more than one variable per line. :)
Answer: Where you stick the * in a variable declaration doesn't matter so long as it is after the type.
This is actually wrong:
@implementation x {
}

@end

You can only do that with @interface:
@interface x {
  //ivars here...
}

//method declarations here...

@end

Answer: Whitespace around the "*" is irrelevant, so to the compiler the two lines you gave are identical - two pointers to objects (reference types as you called them).
Basically objects generally need "", where primitive types (and things like struct) do not - so for instance a CGRect would not use a "".
However just to confuse you a little more, there is a generic reference to an object "id" that does not need (and cannot have) a * - you would declare a variable like that as:
id delegate;


HIde shutter animation UIImagePickerController

Question: I want to hide animation that shows shutter opening while presenting UIImagePickerController to take picture. I checked this question for the same which contains the accepted but I was unable to replicate that functionality in my controller.
I gave overlayView as self.view and when I hide PLCameraView it shows blank white portion and than I am able to take picture. Is there any way to remove that white portion ?
IF needed I can post my full sourcecode project...
Can some body please highlight how to do this ?
Edit:
What I want to do is based on certain event and conditions I want to place image taken from camera or default image in db. And picture taking doesn't involve user interaction so I put NSTimer and take snapshot with the help of takePicture method.
Any thoughts ?
Answer: Instead of messing about with the view hierarchy of UIImagePickerController (which you are  forcefully warned against in the docs) you should probably use AVCaptureSession and create your own ImagePicker to capture raw images from the video feed.
See http://developer.apple.com/library/ios/#samplecode/AVCam/Listings/Classes_AVCamCaptureManager_m.html for hints.
Comment: link went down, changed to more detailed Apple image capture source


Workstations cannot see new MS Server 2008 domain, but can access DHCP.

Question: The XP Pro workstations do not see the new replacement domain upon boot; they only see their cached entry for the old (server 2003) domain controller.  The old_server is not connected to the network.  I have DHCP working with the same scope as the old_server.  In my "before-asking" search for a solution I came across the following two articles, and I recall doing things as suggested by the articles.
http://www.windowsreference.com/windows-server-2008/how-to-setup-dhcp-server-in-windows-server-2008-step-by-step-guide/
http://www.windowsreference.com/windows-server-2008/step-by-step-guide-for-windows-server-2008-domain-controller-and-dns-server-setup/
The only possible issue is: I was under the impression that the domain netbios needed to match the DC's netbios.  The DC netbios is city01 while the domain's FQDN is city.domain.org (I think this is mistaken and should have been just domain.org)
But, the second link led me to a post which I believe answers my question.  I did as they instructed by opening Local Area Connection Properties, then selecting TCP/IPv4 and setting the sole preferred DNS server to the local hosts static IP (10.10.1.1).
Search for "Your problems should clear up" for the post I'm referencing:
http://forums.techarena.in/active-directory/1032797.htm
Have I misunderstood their instructions?  I am hoping to reach the point where I can define users and user groups.  Also, does TechNet have a single theoretical overview document I could read.  I really don't like treating comps as magic.
I will be watching this closely and will quickly answer any questions.  If I've left anything out it is because I did not know it was needed.
PS: I am loath to ask obviously basic questions, but I am tired and wish to fix this before tomorrow.  Also, this is my first server installation, thank you for your help.
Comment: Ok, obviously I needed to join the domain... I knew that :)  But my knowledge didn't carry over.  I still need to add users and groups though.
Answer: Uh, have you tried actually Joining the Domain?  Right click My Computer on the workstation > Properties > Computer Name > Network ID > change the domain to the new domain.  You really should have left the domain as something shorter; like, CompanyName.com though.
Good luck adding users and groups.
Comment: Ok then, would someone point me to an explanation of Server 2008's groups and user accounts?
Comment: If you want to add users and groups to your domain then you need to do so through start->administrative tools -> active directory users and computers. Domain controllers don't have local users. I would suggest you do some reading up on how to administer active directory.


Prove that the set $\{x|\varphi_x \text{is total}\}$ is productive

Question: It's easy to show that the complement $\bar{T}=\{x|\varphi_x \text{is not total}\}$ is productive, since $\bar{K}$ is many-one reducible to it, but what about $T$?
Comment: Well, it's the standart definition. Check this: http://mathworld.wolfram.com/ProductiveSet.html
Comment: What do you mean by "productive" ? It must have a meaning for you, but please explain it or give a reference. More generally, a one-line question is much too short. You have to describe a little the context...
Answer: Using s-m-n theorem find a function $f(x)$ with
$$
\varphi_{f(x)}(y) = \begin{cases}
\uparrow,& \text{if } \varphi_x(x)\!\downarrow \text{in at most $y$ steps}; \\
0,& \text{otherwise.}
\end{cases}
$$
If $x \in K$, then $\varphi_{f(x)}$ diverges starting from the number of steps in the computation of $\varphi_x(x)$, and hence it is not total. If $x \notin K$, then $\varphi_{f(x)}$ is constant zero function and hence is total. This shows that $\overline{K} \leqslant_m T$. In fact, $T$ is known to be $\Pi_2^0$-complete, and since $\overline{K}$ is $\Pi_1^0$ it must be reducible to $T$.
Also you can show it directly by the definition of a productive set. Given an r.e. subset $W_x \subseteq T$, we need to effectively produce an index of a total function not in $W_x$. The standard idea here is to use diagonalization:

set $t = 0$ and  start enumerating $W_x$;
when (if ever) a new element $e$ appears in $W_x$ define $f(t) := \varphi_e(t) + 1$ and set $t := t + 1$;
while waiting for some $e \in W_x$ let $f(t) = 0$ and set $t := t + 1$;

The construction above is uniform and effective and so for some $p(x)$ we have $\varphi_{p(x)} = f$. Note that $\varphi_e$ is total for $e \in W_x$ and hence $\varphi_e(t)$ always converges, so $f(t)$ is a total function - if $W_x$ is infinite it is clear, but if $W_x$ is finite (or empty) while (endless) waiting for a new element is taking place the last bullet makes $f$ total. So $p(x) \in T$ for all $x$ such that $W_x \subseteq T$. If $p(x) \in W_x$, then at some stage we define $\varphi_{p(x)}(t) = f(t) = \varphi_{p(x)}(t) + 1$, and so $p(x) \in W_x \setminus T$, a contradiction.


How do i place this DataGrid in Material Ui correctly?

Question:
I have tried  a lot of different solutions to make this grid perfectly fit in, i can not seem to understand material ui sizing within this space.
As you can see the column titles are missing, and it's not centered in the middle.
I have used the clipped drawer also from MUI which is placed inside of Box
import * as React from "react";
import { DataGrid } from "@mui/x-data-grid";
import { Container, Grid, Paper, Box } from "@mui/material";

const columns = [
  { field: "id", headerName: "ID", width: 90 },
  {
    field: "firstName",
    headerName: "First name",
    width: 150,
    editable: true,
  },
  {
    field: "lastName",
    headerName: "Last name",
    width: 150,
    editable: true,
  },
  {
    field: "age",
    headerName: "Age",
    type: "number",
    width: 110,
    editable: true,
  },
  {
    field: "fullName",
    headerName: "Full name",
    description: "This column has a value getter and is not sortable.",
    sortable: false,
    width: 160,
    valueGetter: (params) =>
      `${params.row.firstName || ""} ${params.row.lastName || ""}`,
  },
];

const rows = [
  { id: 1, lastName: "Snow", firstName: "Jon", age: 35 },
  { id: 2, lastName: "Lannister", firstName: "Cersei", age: 42 },
  { id: 3, lastName: "Lannister", firstName: "Jaime", age: 45 },
  { id: 4, lastName: "Stark", firstName: "Arya", age: 16 },
  { id: 5, lastName: "Targaryen", firstName: "Daenerys", age: null },
  { id: 6, lastName: "Melisandre", firstName: null, age: 150 },
  { id: 7, lastName: "Clifford", firstName: "Ferrara", age: 44 },
  { id: 8, lastName: "Frances", firstName: "Rossini", age: 36 },
  { id: 9, lastName: "Roxie", firstName: "Harvey", age: 65 },
];

export default function DataGridDemo() {
  return (
    <Container>
      <Paper component={Box} width={1} height={700}>
        <DataGrid
          rows={rows}
          columns={columns}
          pageSize={5}
          rowsPerPageOptions={[5]}
          checkboxSelection
          disableSelectionOnClick
        />
      </Paper>
    </Container>
  );
}

Answer: You need to add <Toolbar/>
import Toolbar from '@mui/material/Toolbar';
<Container>
   <Toolbar/>
      <Paper component={Box} width={1} height={700}>
        <DataGrid
          rows={rows}
          columns={columns}
          pageSize={5}
          rowsPerPageOptions={[5]}
          checkboxSelection
          disableSelectionOnClick
        />
      </Paper>
    </Container>```

Answer: Put your code on codesandbox.io so that It easy to figure out the problem
Comment: It is nota an answer, it is a comment


I can not boot my VHDX which was created from physical drive

Question: I need to migrate my Server 2012 R2 Fileserver (physical) to another Server (virtual). That's why I need to create VHDX Files to run them later in Hyper-V
All my drives were no problem, except the C Drive.
Whenever I boot the created C Drive, I get this error:

If I simply open the VHDX on my filesystem, or on any server, I get the following error which says you need to format the F: Drive before you can use it:

As you can see, the VHDX strangely contains 2 drives, and one of them (F:) is not formatted. that's why I can't use the VHDX file, because it does not recognize this drive I guess. I guess this is where EFI is located.
I tried to create the VHDX in 3 different ways. For the first two ways I tried Disk2VHD
like this (I tried it with the \\?\volume and without the \\?\volume partition):

The third way I tried is directly from Hyper-V where I could say I wanted to create a VHDX from a physical drive.

but all of them get the same end result, the corrupted VHDX.
I read somewhere that I need to mountvol x: /s first to make my EFI Partition visible for disk2vhd, but mountvol does not seem to have a /s anymore?
How can I get a working VHDX? Thanks
Comment: A generic step, but can you boot on the install media to do a bootrec /fixboot ? or even bootrec /RebuildBcd
Comment: @yagmoth555 you mean start the newly created machine with an WindowsServer.iso and the C-drive attached?
Comment: Yes It's what I meant
Comment: @yagmoth555 in diskpart, I see that the "onknown" volume is the C:\ drive, and the actual C drive is E. I guess if I could change them it should work. but diskpart does not save the changes.... trying to do a bootrec....
Answer: I suggest bootrec /fixboot or bootrec /rebuildbcd while booting the VM with the disk attached, but to write a bit more for my tip in your case, as I seen your C drive is actually the E drive, check bcdedit please too;
Boot the virtual machine from the correct Microsoft Windows installation media (Correct architecture and version of the operating system).
Select the appropriate keyboard layout and language options and click Next.
Click Repair your computer.
Select the operating system to be repaired and click Next.
Click Start > Run, type cmd and click OK.
Type bcdedit and press Enter.
Under the Windows Boot Manager title with the identifier set to {bootmgr}, you may see that the device is set to boot. Similarly, under the Windows Boot Loader with the identifier set to {default}, you may see that the device and osdevice are set to boot. These items should be set properly for your environment. Usually these appear as partition=C:. In some cases the {default} identifier may have them set to partition=E:.
Run these commands to correct the configuration:
Note: bcdedit is located in this path: c:\windows\system32.
bcdedit /set {bootmgr} device partition=C:

bcdedit /set {default} device partition=C:

bcdedit /set {default} osdevice partition=C:

Type exit at the command prompt and select Shutdown. The reconfigure should now complete successfully. If it fails again, repeat Steps 1 to 7 and then run these commands to set the default device to partition=E:
bcdedit /set {bootmgr} device partition=C:

bcdedit /set {default} device partition=E:

bcdedit /set {default} osdevice partition=E:

Comment: I did it slightly different, with `DISKPART` i removed the letter from the C-drive `remove letter=C` then assign letter=C to the E-drive, then `bootrec /RebuildBcD` and I had to change Generation 2 VM to Generation 1 for it to work


Time-dependent Poisson regression

Question: I have a time series that count the number of "type 1" events in a city, for each day. The serie contains a lot of zeros because type 1 events are rare (about 80% of counts are zeros).
I'm using a Poisson Model but I don't know how to handle temporal dependencies. For example, I know that there are some other events (let say "type 2") which will increase the probability of an event of type 1 in the current day and/or in the next days. The Poisson parameter is not constant over time.
Do you know a good R package to handle this and a good way to model this situation ?
Thanks
Answer: You can still do this in a generalized linear model framework (using glm or glmnet in R).  A crude way of accounting for time would simply be to include it as a covariate with a model like
$$
\log(\lambda_i) = \alpha t_i + \beta^T x_i .
$$
This of course has problems because it assumes a linear relationship between $t_i$ and $\log(\lambda_i)$, and if you feel that certain days have more of an impact than others you might include indicator variables for those days and give them their own coefficients.
Another approach might be to use a generalized additive model (the gam package) instead, but the basic concept is the same.
Comment: I tried the Poisson Regression using the variable $t_i$ like you said, it helps a little. Then, predicting $x_t$, I added $x_{t-1}, ..., x_{t-7}$ to the model. It helped but the coefficient are not coherent since this is far from monotonous and I expect that $coeff(x_{t-1}) > ... > coeff(x_{t-7})$. Either I'm wrong with this expectation or I need a better model, I don't know.

Time-dependent Poisson regression


Find the rank of the tensor

Question: I need to find the rank of the tensor $t = a \otimes a \otimes b + a \otimes b \otimes a + b \otimes a \otimes a$. For simplicity let $a = (1, 0)^T$ and $b = (0, 1)^T$.
I know the answer, rank equals 3. And moreover as I know rank equals 3 for every pair of linear independent vectors $a$ and $b$. But I do not know how to prove that rank equals 3 even in this particular case.
I tried to write an assumption that $t = u_1 \otimes v_1 \otimes w_1 + u_2 \otimes v_2 \otimes w_2$ and write elementwise equations. But I got eight equations, so it looks difficult to solve:
\begin{cases}
t_{111} = u_{11}v_{11}w_{11} + u_{21}v_{21}w_{21} = 0\\
t_{112} = u_{11}v_{11}w_{12} + u_{21}v_{21}w_{22} = 1\\
t_{121} = u_{11}v_{12}w_{11} + u_{21}v_{22}w_{21} = 1\\
t_{122} = u_{11}v_{12}w_{12} + u_{21}v_{22}w_{22} = 0\\
t_{211} = u_{12}v_{11}w_{11} + u_{22}v_{21}w_{21} = 1\\
t_{212} = u_{12}v_{11}w_{12} + u_{22}v_{21}w_{22} = 0\\
t_{221} = u_{12}v_{12}w_{11} + u_{22}v_{22}w_{21} = 0\\
t_{222} = u_{12}v_{12}w_{12} + u_{22}v_{22}w_{22} = 0\\
\end{cases}
Thanks for the help, do not judge strictly it is my first experience with tensors.
Comment: This example is well-known, you may find two proofs in  http://epubs.siam.org/doi/abs/10.1137/06066518X  (see Lemma 4.7)
Comment: @Omnomnomnom, I have updated the post.
Comment: I think writing the system of equations is probably the way to go.  Can you write out the system of equations that you got?
Comment: @Omnomnomnom: The systen indeed leads to a contradiction(see below)
Answer: $8=2^2+2^2$
Let $\mathbf V=\left[\begin{matrix}v_{11}&v_{12}\\v_{21}&v_{22}\end{matrix}\right]$ and
$\mathbf W=\left[\begin{matrix}w_{11}&w_{12}\\w_{21}&w_{22}\end{matrix}\right]$.
Then the system above can be rewritten as
\begin{equation*}
\begin{split}
\mathbf V^T diag(u_{11},u_{21})\mathbf W =
\left[\begin{matrix}t_{111}&t_{112}\\t_{121}&t_{122}\end{matrix}\right]=
\left[\begin{matrix}0&1\\1&0\end{matrix}\right],\\
\mathbf V^T diag(u_{12},u_{22})\mathbf W =
\left[\begin{matrix}t_{211}&t_{212}\\t_{221}&t_{222}\end{matrix}\right]=
\left[\begin{matrix}1&0\\0&0\end{matrix}\right].
\end{split}
\end{equation*}
From the first equation it follows that $\det \mathbf V\cdot u_{11}\cdot u_{21}\cdot\det\mathbf W=-1\ne 0$.Hence,
$$
\mathbf V^T =
\left[\begin{matrix}0&1\\1&0\end{matrix}\right] \mathbf W^{-1}
diag(u_{11}^{-1},u_{21}^{-1}),
$$
and from the second equation,
$$
\left[\begin{matrix}0&1\\1&0\end{matrix}\right] \mathbf W^{-1}
diag(u_{11}^{-1},u_{21}^{-1})diag(u_{12},u_{22})\mathbf W = \left[\begin{matrix}1&0\\0&0\end{matrix}\right].
$$
Finally,
$$
\mathbf W^{-1}
diag(u_{11}^{-1}u_{12},u_{21}^{-1}u_{22})\mathbf W = \left[\begin{matrix}0&0\\1&0\end{matrix}\right],
$$
a contradiction (we have obtained that a diagonal matrix is similar to a jordan block).

Find the rank of the tensor


What are Panes, in a Übercart context?

Question: I was wondering what are "Panes" - I found them while I was messing with source code of Ubercart module. It looks like they're building page with something like panes - which I'm totally new to. Code looks like:
<code>  // Load through the cart panes...
  foreach (uc_cart_cart_pane_list($items) as $id => $pane) {
    // If the pane is enabled...
    if ($pane['enabled']) {
      // Add its output to the cart view.
      $build[$id] = $pane['body'];
      ...
</code>
So, are "panes" Ubercart concept, or some in-general thing? I searched with "Drupal Panes" but no luck.
Answer: Visit your checkout page (add product to cart, visit cart, then click Checkout), each fieldset (as in image) is a pane. It's not the same as for "panels" pane.
Comment: So `pane` is a term introduced by Ubercart? How do I work with pane? I.e. create own by my module/theme them/have a template etc? Please see my question here http://drupal.stackexchange.com/q/26739/3235

What are Panes, in a Übercart context?


Show that $\frac{2}{\pi}x<\sin x<x$ for $0<x<\frac{\pi}{2}$

Question: By considering the function $$f(x)=\sin x - x$$ for $0<x<\frac{\pi}{2}$, show that $$\frac{2}{\pi}x<\sin x<x$$ for $0<x<\frac{\pi}{2}$
My first step was to differentiate $f(x)$, upon which I get $\cos x - 1$. However, I do not know how to procede from there.
Answer: Let $f(x)=\frac{\sin x}{x}$. Note
$$ f(x)'=\frac{x\cos x-\sin x}{x^2}=\frac{x-\tan x}{x^2\cos x}<0,x\in(0,\frac{\pi}{2}) $$
and hence $f(x)$ is strictly decreasing in $(0,\frac{\pi}{2})$. So for $0<x<\frac{\pi}{2}$, one has
$$\frac{2}{\pi}=f(\frac{\pi}{2})< f(x)< \lim_{x\to0^+}f(x)=1 $$
or
$$\frac{2}{\pi}x< \sin x< x. $$
Here $\tan x>x$ for $x\in(0,\frac{\pi}{2})$ is used.
Comment: How does this help me solve the qn of $\frac{2}{\pi}<sinx<x$
Comment: @SydneySniper, yes, see the update.
Comment: why do you let $f(x) = \frac{sinx}{x}$? didn't the original qn mention $f(x) = sinx -x$
Comment: If you use $f(x)=\sin x-x$, you have to use $g(x)=\sin x-\frac{2}{\pi}x$. So it is better to use $\frac{\sin x}{x}$.
Comment: I only have one doubt... how does $$\lim_{x\to0^+}f(x)=1?$$
Answer: $\sin$ is a concave function on $[0,\frac{\pi}{2}]$.
Thus, $\sin{x}\geq\frac{2}{\pi}x$ because graph of $\sin$ and the line $y=\frac{2}{\pi}x$
have two common points $(0,0)$ and $\left(\frac{\pi}{2},1\right)$.
Thus, for all $x\in\left(0,\frac{\pi}{2}\right)$ we obtain $\sin{x}>\frac{2}{\pi}x$ .
$\sin{x}<x$ for all $x\in\left(0,\frac{\pi}{2}\right)$ follows from the definition of $\sin$
Answer: Maybe I can help you.
$$\frac{2}{\pi}x<\sin(x)<x, 0<x<\frac{\pi}{2}$$Let's use Cauchy's Mean Value Theorem: $$\frac{\sin\frac{\pi}{2}-\sin(x)}{1-\frac{2}{\pi}x}=\frac{-\cos(c)}{-\frac{2}{\pi}}<1$$
$$1-\sin(x)<1-\frac{2}{\pi}x$$
$$\sin(x)>\frac{2}{\pi}$$


verification of a solution of a Laplace-type equation

Question:

Prove that in $\mathbb{R}^3$ the function $\displaystyle \frac{e^{-k r}}{4\pi r}$ satisfies the equation:
$$\Delta u(r) - k^2u(r) =-\delta(\vec{r}).$$
    ($\Delta$ stands for the Laplace operator).

Question. In our case, operator $\Delta u$ should be replaced in spherical or cylindrical coordinates? (besides, since $u=u(r)$ here, only the $r$-part should be taken into account). Also, the $\delta$ symbol in the above equation stands for what exactly?
Thanks a lot in advance for the help.
Answer: You have to check that $f(r) = r^{-1} e^{-kr}$ is a fundamental solution of the differential operator $L = k^{2} - \Delta$. That is $Lf = \delta$ the Dirac mass.
To do so a fast and efficient is to use the Fourier transform $F$. By injectivity of $F$, if $F(Lf) =  F(\delta)$ then $Lf = \delta$. Since the Fourier transform plays nicely with differential operator you obtain $F(Lf)(\xi) = (k^{2} - |\xi|^{2}) F(f)(\xi)$ and it is well-known (and easily chackable) that $F(\delta) = 1$. You therefore need to check that $F(f)(\xi) = \frac{1}{k^{2} - |\xi|^{2}}$.
Since your function is radial, switching to spherical coordinates to compute the integral is the way to go. The computations are a bit heavy but in the end you will derive the result.
Answer: I assume the $\delta$ stands for the Dirac Delta distribution, which gives you the following for a suitable test function $\phi(x)$:
$$ (\delta_a)(\phi(x)) = \int \phi(x) \delta (x-a) dx = \phi (a) $$
for a given $a$. Here, for example ,we have $a=0$.
So, the first thing you notice is that your equation makes perfectly sense for $r\neq 0$, just by plugging in and using the Laplacian in spherical coordinates, independent of $\varphi$ and $\theta$ and the fact that the right side is zero in this case. But what about the case $r=0$? Here, you have to be careful, the term $\frac{1}{r}$ screws it up. So what to do? Take an arbitrary test function $f(r)$, integrate the left side over $\mathbb{R}$ (or $\mathbb{R}^3$), then you'll get:
$$\int_{r < \epsilon} f(r) (\Delta - k^2) \frac{e^{kr}}{4 \pi r}dr $$
since the integrand vanishes for $r<0$. Next, expand $e^{kr}$, forget about higher terms, and you'll get something like this:
$$ \int f(r) \Delta \frac{1}{r}dr + O(\epsilon^2)$$
But from elementary theory of distribution, we know that
$$\Delta \frac{1}{r} = -4\pi \delta(r) $$
And that is the route you have to take.
Comment: Jacob, regarding your comment "your equation makes perfectly sense for r≠0", the expression $\displaystyle \Delta u-k^2 u=u''(r)+\frac{2}{r}u'(r)-k^2u(r)$ (in our case) does not seem to be giving any desired expression, as one can easily check by substitution.


Uma linguagem subconjunto de uma linguagem livre de contexto é decidível?

Question: Se temos uma linguagem L livre de contexto e seja L' um subconjunto de L, então L' é decidível?
Comment: Só para dar mais contexto para quem for responder, imagina que temos uma LLC L de parênteses: todo parêntese aberto precisa ser fechado e não posso fechar algo que não foi aberto. Isso significa que `((()()))` é válido, porém `((())()))` não é válido. Agora imagina que eu pego essa linguagem e removo todas as palavras que contenham `(())` chamada L'; isso significa que `((())())` pertence a L, mas não a L', e `((()()))` pertence a ambas
Comment: O comentário acima foi para ilustrar que precisamos lidar com remoções infinitas de L para obter L', esqueci de adicionar essa motivação no meu comentário
Answer: Imagine que temos uma linguagem U que seja indecidível. As palavras dela pertencem ao alfabeto Σ. Se U existir, então ela é uma sublinguagem de Σ*.
Tomemos agora a seguinte gramática G que produza L(G):
S -> AS
S ->
A -> el(Σ)

Onde el(Σ) é uma letra de Σ, qualquer uma. Essa linguagem equivale a Σ*. Portanto, se existir uma linguagem U para esse alfabeto, temos que U é subconjunto de L(G). E L(G) é uma linguagem regular, portanto também é uma linguagem livre de contexto.


How to calculate the accuracy_score leaving out one class?

Question: My classifier: Random Forest
My labels: 6 labels and one label for data objects that does not belong to any of the 6 labels
When calling the method accuracy_score, the accuracy for 7 labels is calculated. But since the accuracy of the 6 'real' labels is important for me, I want their accuracy.
(It does not help to leave out the 7th label in the training data because I am comparing the accuracies after doing something with the 7th label.)
Code:
print(accuracy_score(y, y_pred))
Answer: you could do instead :
# outClass : the class you want to leave out
condition = (y != outClass)
score = (y[condition] == y_pred[condition]).sum()/ (y[condition]).size


Train/test split for a small dataset (classification tree/ random forest)

Question: I'm trying to solve a classification problem using Classification Tree with a small amount of data available. Depending on the content of particular train/test subsets (80:20 proportion) the total accuracy varies much between the runs (I'm observing values about 40% but values like 20% or 75% are not uncommon). This makes it hard to make a decision if the parameters of the tree are chosen well (e.g. the independent variables, max tree height, etc.).
Therfore I decided to run e.g. 1000 such a trees and average the accuracies to estimate the mean accuracy (i.e. the accuracy I would obtain using large train and test subsets).
Is it a good approach?
Also, I have build a Random Forest in a similar way. I have split the dataset 1000 times into different train/test subsets (again 80:20), built 1000 trees and for each entry in my dataset found those ~200 trees that have not been trained with that particular entry and used them to "vote" for the classification (majority wins).
Then calculated the accuracy of that Forest as usual. In this way the classification of particular entries is rather stable and thus little variance in the forest accuracy.
Again - is it a good approach?
Answer: For small dataset, I think it'd be better to use Leave-one-out cross-validation (LOOCV). Say you have 1000 examples. Then each time you pull out one as a test example, and then use the rest 999 as the training set. So eventually, you'll have 1000 tests.


Why docker container does not respond to my requests on loalhost (my laptop)?

Question: I have dockerized a simple golang project given in the link https://github.com/ashahbazi65/go-docker.git.
However, on my laptop the requests can't get any response from the app. Below is the curl response. Can anybody help me understand why?
<code>curl -v localhost:3000
*   Trying 127.0.0.1:3000...
* Connected to localhost (127.0.0.1) port 3000 (#0)
> GET / HTTP/1.1
> Host: localhost:3000
> User-Agent: curl/7.81.0
> Accept: */*
</code>
Comment: Can you include the command that you're using to start the docker container? Also, it would be cool if you could paste the entire curl message
Comment: are you exposing port 3000 when your run your docker command?
Comment: It's also important to show the code that sets up the network listener in the container.  Just the `curl` output isn't really enough to tell what might be going wrong; can you [edit] the question to include a [mcve]?
Answer: Based on your GitHub repo, your application doesn't run on port 3000 but runs on port 8081.
So when using go run main.go, your app will run on port 8081.
Why does it run on port 3000 when using Docker? It's because you expose port 3000 and then forward those requests to port 8081 inside the container using the docker-compose yaml file, which will reach your application.
Answer: Although the answer provided by @not1insight is technically correct - The question asks "... requests can't get any response from the app. Below is the curl response. Can anybody help me understand why?"
Looking at your repo, there are mainly 3 ways to run your app.

Lets say you ran it using 'go run main.go' then the app gets exposed on port 8081 as mentioned in your go code at http.ListenAndServe(":8081", router).

Lets say you ran it using docker-compose using "docker-compose up" then your app gets exposed on port 3000 on your laptop as you are actively mapping Docker container (your app's) port 8081 to your laptop's (host) port 3000 in your docker-compose file.

There is also another option to directly run your app using docker command with the help of Dockerfile. In this way, you can specify the port number on the docker run CLI command on which your app gets exposed. Reference - https://docs.docker.com/engine/reference/commandline/run/#publish

Depending on how you are running the app, check appropriate port.
As you've mentioned you are dockerizing your app, it means adding a Dockerfile so that it can be run in a container.
Docker run, docker-compose , Kubernetes, etc. are all different runtimes for running containerized apps.
Your port rules depend on that runtime configuration mapping to your code's port (8081 in this case).


How can I pass the loop.index from a view template to a node template?

Question: In a views template (views-view-unformatted.twig.html), I have
{% for row in rows %}
    {% set row_index = loop.index0 %}
    {{ row.content }}
{% endfor %}

where each row is processed in a node--view.twig.html.  How can I pass in row_index to the node--view.twig.html?  This is used simply to create an index.
Answer: This can be done using the preprocess function in my_theme.theme.  In the case above, the row was formatted in node--view--pagename.html.twig, so the preprocessor function name is mytheme_preprocess_node__view__pagename.  In the function, the view is iterated until the node matches the current node that is being processed, at that point, the row_index is determined and set and accessible in node--view--pagename.html.twig as {{ row_index }}.
function fu_preprocess_node__view__pagename(&$vars) {
    $view = $vars['view'];
    $node = $vars['node'];
    foreach($view->result as $key => $row){
        if($row->nid == $node->id()){
            $vars['row_index'] = $row->index;
        }
    }
}

Comment: This is great, thanks for sharing.
A small thing however, `$vars['view']` isn't available so you should try `$view = views_get_current_view();`


Regex: Detect pattern in multiline HTMLElement

Question: Basicaly I need to exclude [my-property] detection when in the content of a div but have when it's an attribute.
I have this regex : /(?<!\>)(\[\s*@?[-_a-zA-Z0-9.$]*%?\s*])(=)(["'])/
And theses tests :
Should return a match

Below should return no match

[my-property]="val"

    [my-property]="val"

Every test is correct but the last one, which also needs to be excluded.
How could I improve my negative lookbehind to exclude the last test ?
Regex 101
Comment: Regular expressions are really bad at distinguishing "inside" and "outside". Use A DOM parser library.
Comment: @markalex Many regexp engines don't allow variable-length lookbehinds.
Comment: Could you explain the logic? What are you trying to match and exclude?
Comment: Add `\s*` to your lookbehind. https://regex101.com/r/56TkVf/2
Comment: BTW, `>` has no special meaning in regexp, you don't need to escape it.
Comment: @Barmar See my edit, I need to detect `[my-property]`  as attribute but not as content in a `div`
Comment: @Barmar, since linked demo had a TS selected, I assumed it would be ok. But to be safe I've provided alternative without lookbehind.
Comment: Yeah I know that, but I'm limited to regex in my situation (I'm limite by the technical context, so I trying to do the best with what I have ! ) .
Comment: This whole thing is A LOT easier if you strive to capture what you're looking for in a capture group instead of the entire match.  So, `]+?([my-property]="[^"]*")` puts your result into capture group 1 (\1) without having to use a lookbehind.  Now @Barmar is still right about contextual problems, so you had better hope you have no Javascript in the  with greater-than tests, for example.
Answer: If negative lookbehind of variable/infinite length is acceptable, you could use
(?<!>\s*)(\[\s*@?[-_a-zA-Z0-9.$]*%?\s*])(=)(["'])

Demo here.
If not, you'll need to match also everything since previous < to check the was no > between.
(<[^>]*)(\[\s*@?[-_a-zA-Z0-9.$]*%?\s*])(=)(["'])

Demo here. I assume it should OK for this situation, as you already match a bunch of staff around.
Also, this solution comes with added bonus of lack of negative lookarounds, that are non supported by relatively recent versions of Safari.


How to manually install a SSL .cer on an IIS 6 site without CSR?

Question: Every CSR generated by my site gave an error when submitted so I made a new site and the CSR worked fine. Now I have the certificate. However I can't find a way to install it on my original site. I have the certificate but there is no pending request for this site. How can I manually choose to install my certificate?
Answer: You will just need to install the certificate to the same site where you generated the CSR/Pending Request. You can then go to the original site properties, click Server Certificate and then Assign an existing Certificate to select the cert on the other site.
Answer: I have found the best option is to export the certificate as a PFX, using the certificate wizard in IIS. This will package up the public and private keys, and let you move it to the other server. Then import from the PFX file, supply the password and your done.
Answer: You say you "have the certificate".
How do you have it? Installed on the new site? Saved as a .cer or .pfx file?
If you have it as a file, you simply need to import it in the web site.
If you have it installed on the new site, you need to export it first.


Buscando palavras separadas na mesma string no MySQL

Question: Minha pergunta é relativamente simples, mas não consegui achar uma resposta que realmente me ajudasse:
Meu usuário faz uma busca por um nome em um formulário: Fulano Silva
O registro em meu banco está como Fulano de Tal Silva
SELECT * FROM `dados` WHERE `nome` LIKE '%".Fulano Silva."%'

Ao realizar a busca com PHP no MySQL por Fulano Silva usando LIKE ele não conseguirá encontrar o registro!
Se ele tivesse buscado apenas por Fulano ou por apenas por Silva, ele encontraria, mas pelo fato de ter mais strings entre Fulano e Silva (de Tal) o registro não é encontrado.
Como posso resolver essa situação? Devo separar as strings na frase e procurá-las individualmente? Como poderia fazer isso? Obrigado!
Answer: Coloque % entre todas as palavras a serem filtradas:
SELECT * FROM `dados` WHERE `nome` LIKE '%".Fulano%Silva."%'

Coloquei um exemplo no SQLFiddle pra você ver funcionando
Comment: ... que pode ser feito através do `str_replace()`: `str_replace(' ', '%', $texto);`
Comment: Downvoter, pode comentar?
Comment: Por que o voto negativo?
Comment: Também não sei, estou esperando explicação :/
Comment: @ArturTrapp funcionou perfeitamente, era o que eu estava precisando.


sending mail with javamail throws NoSuchMethodError: sun.security.ssl.SessionId.checkLength

Question: My Java ee 8 webapp is using javamail 1.6.1 to send emails via gmail. I'm running it on Glassfish 5, Mac os High Sierra, and Glassfish 5 is set to run on jdk1.8.0_20 and I start it from Netbeans 8.2.
Here's the snippet where it's being done:
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);

// Get the Session object.
Session session = Session.getInstance(props,
    new javax.mail.Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

try {
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
    message.setSubject("Testing Subject");
    message.setContent(
                "
This message is embedded in HTML tags
",
                "text/html");
    Transport.send(message); // this line throws the exception
} catch (MessagingException e) {
    throw new RuntimeException(e);
}

The Transport.send line throws the exception in the title above. More precisely:
Caused by: java.lang.NoSuchMethodError: sun.security.ssl.SessionId.checkLength(Lsun/security/ssl/ProtocolVersion;)V
    at sun.security.ssl.HandshakeMessage$ServerHello.<init>(HandshakeMessage.java:504)
    at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:209)
    at sun.security.ssl.Handshaker.processLoop(Handshaker.java:984)
    at sun.security.ssl.Handshaker.process_record(Handshaker.java:919)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1043)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1343)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1371)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1355)
    at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:619)
    at com.sun.mail.util.SocketFetcher.startTLS(SocketFetcher.java:546)
    at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:2135)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:738)
    at javax.mail.Service.connect(Service.java:388)
    at javax.mail.Service.connect(Service.java:246)
    at javax.mail.Service.connect(Service.java:195)
    at javax.mail.Transport.send0(Transport.java:254)
    at javax.mail.Transport.send(Transport.java:124)

I've found this similar question here but all they say is to make sure that Glassfish is running on JDK 1.8, and mine is.
I noticed that the same javax.mail.Transport class exists in both dependecies, javaee-api and javamail, so I removed javamail from my dependencies in my pom.xml and I could still build the application, but got the same error when trying to send the email.
This is what my pom.xml looks like:
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-api</artifactId>
        <version>8.0</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>com.sun.mail</groupId>
        <artifactId>javax.mail</artifactId>
        <version>1.6.1</version>
    </dependency>

Comment: Perhaps try using a newer JDK 1.8 update release?
Comment: That was a good point, thanks. I upgraded to 1.8.0_172 which was the last 1.8 I could find and it has that method. Except now it fails with NoSuchMethodError: sun.security.ssl.SSLSessionImpl.(Lsun/security/ssl/ProtocolVersion;Lsun/security/ssl/CipherSuite;Ljava/util/Collection;Lsun/security/ssl/SessionId;Ljava/lang/String;I)V
Comment: Yes, sorry, I should've warned you about that problem with the newest versions of JDK 1.8.
Answer: Downgrading your JDK is not advisable. I found another solution which worked for me. See Antoine's answer in sun.security.ssl.SSLSessionImpl not found . You can remove the sun.* packages from the relevant file using a zip utility such as 7ZIP.
I haven't tried for this particular error message but I suspect it will be the solution as there seems to be many similar questions related to this package with the same root cause.
Answer: I upgraded the JDK 8 to 1.8.0_172 and started getting this other error:
NoSuchMethodError: sun.security.ssl.SSLSessionImpl.<init>(Lsun/security/ssl/ProtocolVersion;Lsun/security/ssl/CipherSuite;Ljava/util/Collection;Lsun/security/ssl/SessionId;Ljava/lang/String;I)V

That apparently is an issue with Glassfish 5 as discussed here.
So I downgraded the JDK 8 version to 1.8.0_152, which solved this problem.
To set netbeans to use the right update of the jdk configure this in the file netbeans_home/etc/netbeans.conf :
netbeans_jdkhome=/Library/Java/JavaVirtualMachines/jdk1.8.0_152.jdk/Contents/Home

Comment: This answer is correct in identifying that the problem happens with later versions of jdk 8. However, many of the JDK updates involve security so its not advised. I commented in another question I came across today which solved the problem for me. https://stackoverflow.com/questions/49383650/sun-security-ssl-sslsessionimpl-not-found


VPN from Windows XP to OpenSwan: correct setup?

Question: Main question is what I am doing wrong in my OpenSwan or L2TP client setup?
I am trying to create a Linux OpenSwan VPN connection from Windows XP machine, using preshared key and the builtin Windows XP L2TP IPsec option.
I have followed the instructions in Linux Home networking Wiki for setting up OpenSwan and a guide to making it work with the Windows XP client, but am now stuck.
The net setup is as follows:
[my windows client, private IP A]<->[f/wall B]<-internet->[g/w X]<->[Linux OpenSwan server Y]
A - private subnet /24
B - internet address
X - internet address /24
Y - internet address on same subnet as X

What I essentially want is for computer with A address to feel and work, as if it was in X subnet for purposes of outgoing and incoming TCP and UDP connections.
My OpenSwan setup is as follows:
/etc/ipsec.conf (AAA and YYY indicates ip address parts of A and Y addresses):
conn net-to-net
        authby=secret
        left=B
        leftsubnet=AAA.AAA.AAA.0/24
        leftnexthop=%defaultroute
        right=Y
        rightsubnet=YYY.YYY.YYY.0/24
        rightnexthop=B
        auto=start

the secret in /etc/ipsec.secrets is listed as:
B Y : PSK "0xMysecretkey"

where B & Y stand for respective IP adresses of gateway B and linux server Y
My L2TP WinXP setup is:

IP of destination: Y
don't prompt for username
security options: typical, require secured pass, don't require  data encryption, IPSec PSK set to 0xMysecretkey
networking options: VPN Type: L2TP IPSec VPN; TCPIP protocol (with automatic IP address assignment) and QOS packet schedulers enabled

The error I get from Windows client is 789: "error during initial negotiation"
Answer: without (left,right)protoport=17/1701 you've configured the openswan side for tunnel mode ipsec, not transport mode to encrypt l2tp.
what does main mode debugging say on the linux end? i bet it's a protocol mismatch.
you can also turn on RAS debugging on the winXP side
Comment: thank you, i got a bit ill and haven't been able to pursue this further, but i'll get back to it, when i am on track.


Vim E488: Trailing Characters in function

Question: I'm getting a trailing characters error for the 'for loop' in the following lines of code and I've no clue why.
function! s:HashID(str)  "{{{
    let l:hash_id = 0
    for i in split(a:str, '\zs')
        l:hash_id += float2nr(pow(2, stridx('abcdefg', i)))
    endfor
    return l:hash_id
endfunction

What am I goofing up here?
Comment: Upon startup. The function is called via an autocmd when the Buffer is entered. If I comment out the for loop, the error disappears
Answer: You need let command to assign value to variable.
Comment: Ah, damn damn damn. Guess it's time to call it a day


How to programmatically call a dusk test from a php artisan command

Question: I need to run one of my Laravel Dusk tests from an artisan command so that it processes daily. I've tried $this->call('dusk'); in my command but that runs all of dusk's tests and doesn't allow me to add a group or a filter. I need to run just 1 test. How can I add a filter?
$this->call('dusk', [ '--group' => 'communication_tests' ]);

or
$this->call('dusk', [ '--filter' => 'tests\Browser\myTestFile::myTestMethod' ]);

doesn't work and it ignores the options passed in. Any ideas on how to accomplish this?
Answer: 1st create your working Laravel Dusk Test. Test it out with php artisan dusk and make sure it's working.
2nd create your own command in the app\Commands folder called DuskCommand to overwrite laravels native DuskCommand and have it's signature be 'dusk'. Have it extend Laravel\Dusk\Console\DuskCommand and write into its handle method the code below (see https://github.com/laravel/dusk/issues/371 for other version of this code). I edited mine to remove the $this->option('without-tty') ? 3 : 2 ternary statement so it just reads 2 for mine as that option didn't exist or wasn't needed for my version of laravel.
3rd add your new class to the Kernel so that when you call php artisan dusk the class is recognized.
4th create your new command to programmatically run your dusk test using the final line added by @taytus.
5th add that new class to the Kernel also.
Here's my file run down below...
My laravel dusk test (tests\Browser\CommunicationsTest.php) (STEP 1)
<?php

namespace Tests\Browser;

use Tests\DuskTestCase;
use Laravel\Dusk\Browser;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use App\Models\User;

class CommunicationsTest extends DuskTestCase
{
    /**
     * A Dusk test example.
     * @group all_communication_tests
     * @return void
     */
    public function test_that_all_coms_work()
    {
        // Test Text
        $this->browse(function (Browser $browser) {

            $browser->resize(1920, 1080);
            $browser->loginAs(7)
                ->visit('/events/types/appointments')
                ->assertSee('Automated Messages')
                ->click('.text_message0')
                ->pause(1000)
                ->click('.send-eng-text-btn')
                ->pause(1000)
                ->type('phone', env('TESTING_DEVELOPER_PHONE'))
                ->click('.send-text')
                ->pause(5000)
                ->assertSee('Your test text has been sent.');

            // Test Email
            $browser->visit('/events/types/appointments')
                ->assertSee('Automated Messages')
                ->click('.email0')
                ->assertSee('Automated Messages')
                ->driver->executeScript('window.scrollTo(595, 1063);');
            $browser->click('.send-eng-email-btn')
                ->pause(2000)
                ->click('.send-email')
                ->pause(10000)
                ->assertSee('Your test email has been sent.');

            // Test Call
            $browser->visit('/audio/testcall')
                ->assertSee('Test Call')
                ->type('phone', env('TESTING_DEVELOPER_PHONE'))
                ->press('Call')
                ->pause(3000)
                ->assertSee('Test Call Queued');
        });
    }
}

My Overwritting dusk command (app\Console\Commands\DuskCommand.php) (STEP 2)
<?php

namespace App\Console\Commands;

use Laravel\Dusk\Console\DuskCommand as VendorDuskCommand;
use Symfony\Component\Process\ProcessBuilder;

class DuskCommand extends VendorDuskCommand
{

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'dusk';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Run Tests on our system... by extending the Laravel Vendor DuskCommand.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->purgeScreenshots();

        $this->purgeConsoleLogs();

        $options=array();
        // This line checks if it is a direct call or if has been called from Artisan (we assume is Artisan, more checks can be added)
        if($_SERVER['argv'][1]!='dusk'){
            $filter=$this->input->getParameterOption('--filter');
            // $filter returns 0 if has not been set up
            if($filter){
                $options[]='--filter';
                $options[]=$filter;
                // note: --path is a custom key, check how I use it in Commands\CommunicationsTest.php
                $options[]=$this->input->getParameterOption('--path');
            }
        }else{
            $options = array_slice($_SERVER['argv'], 2);
        }

        return $this->withDuskEnvironment(function () use ($options) {
            $process = (new ProcessBuilder())
                ->setTimeout(null)
                ->setPrefix($this->binary())
                ->setArguments($this->phpunitArguments($options))
                ->getProcess();

            try {
                $process->setTty(true);
            } catch (RuntimeException $e) {
                $this->output->writeln('Warning: '.$e->getMessage());
            }

            return $process->run(function ($type, $line) {
                $this->output->write($line);
            });
        });
    }

}

Now add that new command to the Kernel so it will register when you call it and overwrite the functionality of the native/vendor DuskCommand. (STEP 3)
/**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
         // .... preceding commands....
         Commands\DuskCommand::class,
   ];

Now create your command that will call dusk programmatically - here's mine (STEP 4)
<?php

namespace App\Console\Commands;

use DB;
use Illuminate\Console\Command;

class TestCommunications extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'test:communications';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Test Email, Text, and Phone Calls to make sure they\'re operational.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {

       $response = $this->call('dusk',['--filter'=>'test_that_all_coms_work','--path'=>'tests/Browser/CommunicationsTest.php']);

    }
}

and register it in the Kernel (STEP 5)...
/**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
         .... preceding commands....
         Commands\DuskCommand::class,
         Commands\TestCommunications::class,
   ];

Now run php artisan dusk and it should hit the extending DuskCommand and work fine. Then call your new php artisan command that replaces my TestCommunications.php file and it should run dusk perfectly... assuming your test works of course. Let me know if you have any question or if I left anything out.
Remember Dusk only works in a local environment ... this is not something you want/should/natively can implement on a production environment
Comment: BadMethodCallException
Method App\Console\Commands\DuskCommand::withDuskEnvironment does not exist.