How to compute $\sum_{j=1}^{n} {{n}\choose {j}} \cdot (-1)^{j+1} \cdot \frac{(n-j)^{n-1}}{n^{n-1}}$

Question: Hey I am wondering if the sum
 $$\sum_{j=1}^{n} {{n}\choose {j}} \cdot (-1)^{j+1} \cdot \frac{(n-j)^{n-1}}{n^{n-1}}  = 1 $$
 I got this formula from some question I tried to solve, the question is long so I will not post it here, but I am stuck with this sum, thanks for helping! I really do not know how to continue solving this sum, so how can i continue from here?
Comment: Is this even true for $n=2$? Seems false.
Comment: @A.Pongrácz opps my bad, i meant one
Answer: 1st proof. The identity is equivalent to
$$ \sum_{j=0}^{n} \binom{n}{j}(-1)^j (n-j)^{n-1} = 0. $$
Let us prove a slightly general identity. Let $m \in \{0, \cdots, n-1\}$. Then
\begin{align*}
\sum_{j=0}^{n} \binom{n}{j}(-1)^j (n-j)^m
&= \left. \left(\frac{d}{dx}\right)^{m}\sum_{j=0}^{n} \binom{n}{j}(-1)^j e^{(n-j)x} \right|_{x=0} \\
&= \left. \left(\frac{d}{dx}\right)^{m} (e^x - 1)^n \right|_{x=0} \\
&= 0,
\end{align*}
where the last line follows from the fact that $(e^x - 1)^n = x^n \varphi_n(x)$ for some smooth function $\varphi_n$.

2nd proof. Alternatively, fix $m \geq 0$ and define $a_n = \sum_{j=0}^{n} \binom{n}{j}(-1)^j (n-j)^m$. Its exponential generating function satisfies
\begin{align*}
\sum_{n=0}^{\infty} \frac{a_n}{n!}x^n
&= \sum_{n=0}^{\infty} \left( \sum_{i+j=n} \frac{(-1)^j i^m}{i!j!} \right) x^n \\
&= \left( \sum_{j=0}^{\infty} \frac{(-1)^j}{j!}x^j \right)\left( \sum_{i=0}^{\infty} \frac{i^m}{i!}x^i \right) \\
&= e^{-x} \left( x \frac{d}{dx} \right)^m e^x.
\end{align*}
Now consider the operator $L$ defined by $L(f) = e^{-x} x \frac{d}{dx} (e^x f)$. By a direct computation, we find that $L = x(1 + \frac{d}{dx})$. So
$$ \sum_{n=0}^{\infty} \frac{a_n}{n!}x^n = L^m(1). $$
But the operator $L$, applied to a polynomial of degree $d$, results in a polynomial of degree $d+1$. So $L^m(1)$ is a polynomial of degree $m$, and so, $a_n = 0$ for all $n > m$.
Answer: Let $\delta$ be the forward difference operator, bringing $p(x)$ into $(\delta p)(x)=p(x+1)-p(x)$. This operator
has the property that $\deg p\geq 1$ gives $\deg\delta p=\deg p-1$, hence $m>\deg p$ implies $\delta^m p(x)=0$.
If we consider $p(x)=x^{n-1}$, then
$$ 0=\delta^{n} p(x)=\sum_{k=0}^{n}\binom{n}{k}(-1)^k p(x+k)=(-1)^n\sum_{k=0}^{n}\binom{n}{k}(-1)^k p(x+n-k) $$
hence
$$ \sum_{k=0}^{n}\binom{n}{k}(-1)^k (n-k)^{n-1} = 0 $$
and
$$ \sum_{k=1}^{n}\binom{n}{k}(-1)^{k+1} (n-k)^{n-1} = n^{n-1}. $$
Answer: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$

$\ds{\sum_{j = 1}^{n}{n \choose j}\pars{-1}^{j + 1}\,
{\pars{n - j}^{n - 1} \over n^{n - 1}}  = 1:\ {\LARGE ?}}$.

$\ds{\Huge\left. a\right)}$
\begin{align}
&\bbox[10px,#ffd]{\sum_{j = 1}^{n}{n \choose j}\pars{-1}^{j + 1}\,
{\pars{n - j}^{n - 1} \over n^{n - 1}}}
\\[5mm] = &\
-\,{1 \over n^{n - 1}}\sum_{j = 1}^{n}{n \choose j}\pars{-1}^{j}\,
\bracks{z^{n - 1}}\bracks{\pars{n - 1}!\expo{\pars{n - j}z}}
\\[5mm] = &\
-\,{\pars{n - 1}! \over n^{n - 1}}
\bracks{z^{n - 1}}\expo{nz}\sum_{j = 1}^{n}{n \choose j}
\pars{-\expo{-z}}^{j}
\\[5mm] = &\
-\,{\pars{n - 1}! \over n^{n - 1}}
\bracks{z^{n - 1}}\expo{nz}\bracks{\pars{1 - \expo{-z}}^{n} - 1}
\\[5mm] = &\
-\,{\pars{n - 1}! \over n^{n - 1}}
\underbrace{\bracks{z^{n - 1}}\pars{\expo{z} - 1}^{n}}
_{\ds{= {{n - 1 \brace n} \over \pars{n - 1}!} = 0}}\ +\
{\pars{n - 1}! \over n^{n - 1}}\
\underbrace{\bracks{z^{n - 1}}\expo{nz}}_{\ds{n^{n - 1} \over \pars{n - 1}!}}
\\[5mm] = &\ \bbx{\large 1}
\end{align}

$\ds{m \brace k}$ is the
  Stirling Number of the Second Kind which satisfies

$\ds{{m \brace k} = 0\ \mbox{when}\ m < k}$.

$\ds{\Huge\left. b\right)\ {\large\mbox{The}\ "easy\ one\ !!!".\quad}}$ ( see details in the above answer )
\begin{align}
&\bbox[10px,#ffd]{\sum_{j = 1}^{n}{n \choose j}\pars{-1}^{j + 1}\,
{\pars{n - j}^{n - 1} \over n^{n - 1}}} =
-\,{\pars{n - 1}! \over n^{n - 1}}
\bracks{z^{n - 1}}\pars{\expo{z} - 1}^{n} + 1
\\[5mm] = &\
-\,{\pars{n - 1}! \over n^{n - 1}}
\bracks{z^{-1}}\pars{\expo{z} - 1 \over z}^{n} + 1
\\[5mm] = &\
-\,{\pars{n - 1}! \over n^{n - 1}}\
\underbrace{\bracks{z^{-1}}\bracks{\sum_{k = 0}^{\infty}
{z^{k} \over \pars{k + 1}!}}^{n}}_{\ds{=\ 0}}\ + 1 = \bbx{\large 1}
\end{align}


JavaScript Loop to setData method

Question: I want to dynamically update the data for every series I have in a line chart (Highcharts.js). Currently, I'm doing it by manually passing new data to a series using the setData method:
$(document).ready(function() {
$(chart_id).highcharts({
chart: chart,
title: title,
credits: credits,
xAxis: {},
Axis: yAxis,
legend: legend,
series: series

 });

   var chartz = $(chart_id).highcharts();
   $('#data-labels').click(function () {
    chartz.series[0].setData([129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4,25,29],true,true,true);

    });

What I would like to do is update:
chartz.series[i]

Where is the index of each individual series (I have about 36 and new ones are added all the time)
How do I code and implement a javascript for loop that counts the series length and passes into the series[i].setData variable? I'm very inexperienced in JavaScript, so I'm not really sure where to even begin or where to place this function? I'm guessing it will look something like (where i < is pseudo code):
for (var i = 0; i < "series length + 1"; i++)

Answer: Try:
for (var i = 0; i < chartz.series.length; i++) {
    chartz.series[i].setData(DATA);
});

JavaScript Loop to setData method


Is it possible to put an image from a URL into the terminal

Question: I have an image hosted at a specific url online and I would like that image to appear in the terminal when run. Is that possible or is there a way the image can be shown in a native image viewer?
Comment: Other than using an image viewer that accepts URLs?
Comment: Are you sure you want the image to appear in the terminal, if so, [this question](https://stackoverflow.com/questions/12233105/how-can-i-display-an-image-in-the-terminal) provides some options could be launched from python. What operating system are you running on?
Answer: You'll need some way of fetching and displaying the image. A web browser can do both of those things, so one way to do what you want is to start up a web browser and point it at the desired URL:
import webbrowser
webbrowser.open(url)

If the user already has a web browser open but it is not currently visible (i.e. it's minimized or it's on a different virtual desktop), it might work better to tell webbrowser to open the page in a new window, which would (presumably) be displayed on the current screen:
webbrowser.open_new(url)

However, this is not guaranteed to work (perhaps the browser is configured to always display new urls in a tab instead of a new window, etc etc.)


Is Glove a prediction-based model?

Question: I read "Improving Distributional Similarity with Lessons Learned from Word Embeddings" and authors mentioned that Glove is a prediction-based model while it is clearly factorizing co-occorrence matrix which brings it close to SVD or LDA.
Also in Glove paper they said:

Unlike the matrix factorization methods, the shallow window-based
  methods suffer from the disadvantage that they do not operate directly
  on the co-occurrence statistics of the corpus. Instead, these models
  scan context windows across the entire corpus, which fails to take
  advantage of the vast amount of repetition in the data.

It's not clearly mentioned which category Glove belongs to. Can anybody explain which category Glove goes into?
Answer: Answer of Omer Levy to my question:

The distinction between "count" and "predict" models is quite
  artificial, but at the time (2014), people saw Glove & word2vec as
  something distinctly different from the more "traditional" approaches
  (explicit matrices and SVD). One attribute where Glove differs from
  SVD (and is more similar to SGNS in that sense) is that it uses SGD to
  optimize a non-convex objective, whereas SVD guarantees an optimal
  decomposition (according to its objective).
Comment: Quite a [lot](https://www.cl.cam.ac.uk/~ek358/CEWE_Final_lecture.pdf) of [research](http://anthology.aclweb.org/P/P14/P14-1023.pdf) on [NLP](https://arxiv.org/pdf/1511.02024.pdf) concludes that the difference between count and predict models is *not* artificial; Maybe its better to label them as [distributional vs. embedding models](http://blog.aylien.com/overview-word-embeddings-history-word2vec-cbow-glove/), though. Plus, there is (Brown) [clustering](https://web.stanford.edu/~jurafsky/slp3/16.pdf), too. In any case, the distinction probably is anything but artificial.
Comment: As a side note: from [here](www.aclweb.org/anthology/P14-1023):

We owe the first term to Hinrich Schutze (p.c.). Predictive
DSMs are also called neural language models, because
their supervised context prediction training is performed with
neural networks, or, more cryptically, "embeddings".
Answer: It's a bit of both, but mainly I'd categorize it as prediction based, but using the help of counts. Note that the Glove paper describes a classifier to optimize the cost function in Eqn. (8) as a WLS regression problem. Or, as taken directly from their conclusions:

We construct a model that utilizes this main benefit of count data while simultaneously capturing the meaningful linear substructures prevalent in recent log-bilinear prediction-based methods like word2vec.

Is Glove a prediction-based model?


Appium not work with Android default Web Browser

Question: How to configure Appium to work with Android default Web Browser for mobile web testing?
Answer: try this, worked for me
<code> DesiredCapabilities capabilities = new DesiredCapabilities();
            capabilities.setCapability(CapabilityType.BROWSER_NAME, "Browser");
            capabilities.setCapability("platformName", "Android");
            capabilities.setCapability("deviceName", "Android Emulator");
            capabilities.setCapability("platformVersion", "4.4.2");
            WebDriver driver = new RemoteWebDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
</code>
set your capabilities for version
Comment: One more notice is that Appium not works with non AOSP browser (which replace by Manufacture's browser on Samsung, HTC or LG... devices).
Comment: How is Appium related to this answer? I don't understand where exactly Appiums goes into work here, looks like you use driver (WebDriver) implementation with RemoteWebDriver...


Python - wrong encoding, regexp

Question: I have a text in Polish language in which I want to filter out non-Polish letters, but the problem is that Polish specific letters disappear
# coding: utf-8
import re

_NOT_LETTERS = re.compile('[^a-ząćęłóńśżź]+')

text = u'dzień dobry i wszystkiego najlepszego życzę'

data = _NOT_LETTERS.sub(' ', text)

print data

and the result is
 dzie dobry i wszystkiego najlepszego ycz

instead of expected
dzień dobry i wszystkiego najlepszego życzę

How can I fix this ? I receive variable text from a third-party library
Comment: The pattern must use a unicode string too: `re.compile(u'[^a-ząćęłóńśżź]+')` otherwise multibyte characters are seen as separated bytes *(ie: one byte, one char)*.
Comment: Great, it works. If you want add an answer and I'll accept it
Answer: Accented letters are not in the ascii range and need several bytes when encoded in UTF-8, for example the character:
U+0144  ń       LATIN SMALL LETTER N WITH ACUTE

is encoded on two bytes: c5 84
When you write a string without specifying that it is a string with multibyte characters, each single byte is seen as a character (the character \xc5 and the character \x84 but not the character ń (U+0144) that isn't recognized.)
In Python 2.7 you need to specify that your string is a unicode string otherwise all multibyte characters are seen as single bytes. You can test it yourself writing:
>>> text = u'dzień'
>>> [c for c in text]
[u'd', u'z', u'i', u'e', u'\u0144']

>>> text = 'dzień'
>>> [c for c in text]
['d', 'z', 'i', 'e', '\xc5', '\x84']

Characters are not found because your pattern isn't in a unicode string like your subject string. You need to write:
re.compile(u'[^a-ząćęłóńśżź]+')

Python - wrong encoding, regexp


Subgroup of $\mathbb{Q}$ with finite index

Question: Consider the group $\mathbb{Q}$ under addition of rational numbers. If $H$ is a subgroup of $\mathbb{Q}$ with finite index, then $H = \mathbb{Q}$.
I just saw this on our exam earlier and was stumped on how to show this. Any ideas?
Comment: You might want to look at the quotient group $\mathbb Q / H$ and note that it's finite.
Answer: Show that if $[\Bbb Q:H]=n$, $nq\in H$ for every $q\in\Bbb Q$. Conclude that $n\Bbb Q\subseteq H$. But $n\Bbb Q=\Bbb Q$, so $H=\Bbb Q$.
Answer: A group $(G,+)$ (not necessarily commutative, although as a concession to the special case the OP has asked about, I am writing it "additively") is divisible if for every $x \in G$ and positive integer $n$, there is $y \in G$ with $ny = x$.
Here are two easy but important facts:
1) A quotient of a divisible group is divisible.
2) The only finite divisible group is the trivial group.
Applying this to $G = \mathbb{Q}$ and a finite index subgroup $H$, we get that $G/H$ is finite and divisible, hence trivial: $H = G$.
Comment: Hi, this might not be the venue for saying this, but I thought you might be interested in knowning that [the wikipedia article of divisible group](https://groupprops.subwiki.org/wiki/Divisible_group)  requires abelian, maybe someone should edit that. (of course is not your problem, but since you are an active math contributor to the internet, you may want to set that article straight)
Answer: Since $[\mathbb{Q}:H]=n=\left|\dfrac{\mathbb{Q}}{H}\right|$ then for every $q\in\mathbb{Q}$, $n(q+H)=H$. But this means that $nq+H=H$ or $nq\in H$. Hence $n\mathbb{Q}\subseteq H$ but as stated above that $n\mathbb{Q}=\mathbb{Q}$. Thus, $H=\mathbb{Q}.$
Answer: This is a solution using only the definition of cosets.
Suppose $[\mathbb{Q}:H] = n$. Let $q \in \mathbb{Q}$ an arbitrary rational number and consider $\{H, q+H, 2q + H, \dots , nq + H\}$. In this set there are $n+1$ cosets, therefore there exists an integer $1 \leq k \leq n$ such that $H = kq + H$, or equivalently $kq \in H$.
Now, consider the rational number $q' = q\frac{1}{n!}$ with $q \in \mathbb{Q}$. By the preceding paragraph we know that there exists an integer $1 \leq k \leq n$ such that $kq' = q\frac{k}{n!} \in H$. But $\frac{k}{n!} = \frac{1}{1\cdot 2 \cdot \dots (k-1)\cdot(k+1)  \dots  n}$, i.e. $kq' = q\cdot\frac{1}{1\cdot 2 \cdot \dots (k-1)\cdot(k+1)  \dots  n}$. Therefore adding repeatedly $kq'$ (exactly $1\cdot 2 \cdot \dots (k-1)\cdot (k+1) \dots
  n$ times) we get that $q \in H$ and $q \in \mathbb{Q}$ is arbitrary, therefore $H = \mathbb{Q}$.


What are the values of $a$ and $b$?

Question: I got this question from our quiz wrong I wonder how my teacher got the correct answers shown. I tried solving the first question but didn't get the right answers. I know the formula for the surface of a right circular cone is $S=πr(r+\sqrt {r^2+h^2})$ but I still followed the given formula for the sake of trying to obtain what my teacher got.
My solution:
Let $x$ be $r$ and $4x$ be $h$. Then,
$$πx\sqrt {x^2+(4x)^2}=8$$
$$πx\sqrt {17x^2}=8$$
$$17π^2x^4=8^2$$
$$x^4=\frac{8^2}{17π^2}$$
$$(x^4)^\frac{1}{4}=(\frac{8^2}{17π^2})^\frac{1}{4}$$
$$x=±\frac{2\sqrt 2}{17^\frac{1}{4}π^\frac{1}{2}}$$
$$x=\frac{2\sqrt 2}{17^\frac{1}{4}π^\frac{1}{2}}$$
$$h=\frac{8\sqrt 2}{17^\frac{1}{4}π^\frac{1}{2}}$$
$$h^2=\frac{128}{17^\frac{1}{2}π}$$
$$a=128$$
$$b=17$$
Comment: Please, use MathJax the next time you ask a question instead of pasting a hand-drawn image
Comment: @AmaanM then why on the question it is $(\frac{a\sqrt b}{bπ})$? I wonder...
Comment: Your "known" formula $S=\pi r(r+\sqrt {r^2+h^2\;})$ includes the area of a base added to the cone, which doesn't apply here.
Comment: @AlejandroBergasaAlonso I edited the question.
Comment: @Joffan so what can you say about my solution?
Comment: You didn't quite finish off and write down the values of $a$ and $b$ but apart from that it looks good.
Comment: @Joffan I edited the question. My teacher got different answers. she $a=2$ and $b=8$. I am not sure how she got those.
Comment: No; I don't see any way to get that answer even varying some of the phrasing. Also, technically there's no answer at all, since a distance squared ("the square of its height") can't be represented in inches.
Answer: Your math is correct. Given $S = 8$, $h = 4r$, and $h^2 = \frac{a\sqrt{b}}{b\pi}$, we have:
$$ S = \pi r\sqrt{r^2 + h^2} $$
$$ = \pi \frac{\pi h}{4} \sqrt{\frac{1}{16}h^2 + h^2} $$
$$ = \pi \frac{h}{4} \sqrt{\frac{17h^2}{16}} $$
$$ = \frac{\pi h^2 \sqrt{17}}{16} $$
Substituting in $S = 8$, we have
$$ 8 = \frac{\pi h^2 \sqrt{17}}{16} $$
$$ \Rightarrow h^2 = \frac{128}{\sqrt{17}\pi} $$
$$ = \frac{128\sqrt{17}}{17\pi} $$
$$\Rightarrow a = 128, b = 17 $$
Now, if we take the "correct" solution with $a = 2$ and $b = 8$, we still have (from the algebra above):
$$ S = \frac{\pi h^2 \sqrt{17}}{16} $$
Substituting in $a = 2$ and $b = 8$, we have
$$ S = \frac{\pi \sqrt{17}}{16} \frac{2 \sqrt{8}}{8 \pi} $$
$$ = \frac{\sqrt{34}}{32} \neq 8 $$

What are the values of $a$ and $b$?


What are Extra Jumbo Frets?

Question: So I've been looking around Shechter guitars and some guitars there have X-Jumbo frets, for example https://www.schecterguitars.com/guitars/banshee-mach-7-detail
From what I've gathered Jumbo frets come in few sizes, but non of the documentation I've searched contained a word about X-Jumbo. Is X-Jumbo just a synonym for the 6100 Jumbo frets which to my understanding are the biggest ones?
Thanks.
Answer: Something like medium / jumbo / extra jumbo / whatever is not really standardized, so each guitar maker more or less does its own thing. 6100's are for example really large, so although Dunlop calls them "Jumbo" many guitar builders and fret wire brands will use smaller sizes for what they call jumbo. Of course that also depends on the neck geometry.
So you'd need to ask Schecter guitars what sizes they use. That being said, the largest fretwire by Dunlop and what they consider extra jumbo would be 6000, which is 0.07mm higher and 0.2mm wider than 6100s.

What are Extra Jumbo Frets?


What is the role of the Captain on the (american) football field?

Question: After reading this post about soccer or football (for europeans), What is the on-field role of the captain? i was curious about this issue in american football.
What is the role of the football captain(s) besides the coin toss?
Also, how many captains are there on the football (american) team? Is there one captain per team (special teams, defense, offense)?
Answer: In both the NFL and NCAA, there are official capacities that the captain must fulfill. Only one designated captain (at a time) is permitted to communicate the teams official decision of a penalty (to accept or decline) to the referee, and there are rules about how you can change captains.
NFL:

Rule 18 Guidelines for Captains  Article 1   * One hour and thirty
   minutes prior to kickoff: Respective coaches designate the captain(s)
   a maximum of six per team.
Article 2 Coin toss:
(a) Up to six captains per team can participate in the coin toss
  ceremony; only one captain from the   visiting team (or captain
  designated by Referee if there is no home team) can declare the choice
  of   coin toss.
  (b) The team that won the toss may then have only one
  captain declare its option.
  (c) The team that lost the coin toss may
  then have only one captain declare its option.
Article 3 Choice on Penalty Option: Only one captain is permitted to
  indicate the team's penalty option.
Article 4  Change of Captains:
  (a) The coach has prerogative of informing
  Referee when he wishes to make a change in team captains;  or
  (b) A
  captain who is leaving can inform the Referee which player will act as
  captain in his place when he  is substituted  for; or
  (c) When a
  captain leaves the game, the incoming substitute is permitted to
  inform the Referee which   player the  respective coach has designated
  as captain.
  Note: A captain on the field has no authority to request a change of fellow team captain when that captain  remains on the field

NCAA:

Rule 1, Section 1, Article 5. Each team shall designate to the referee not
  more than four  players as its field captain(s). One player at a time
  shall speak for his team in  all dealings with the officials.
Rule 3, Section 1,  Article 1. b) Three minutes before the scheduled
  starting time, the referee shall toss a  coin at midfield in the
  presence of not more than four field captains from  each team and
  another game official, first designating the field captain of the
  visiting team to call the coin toss. Before the second half, the
  referee will  obtain the teams' second-half options
Rule 3, Section 3, Article 7, g) The field captain must exercise his penalty option before he or a teammate
  consults with his coach on a sideline during a timeout.
Comment: +1, I didn't realize that was in the official rules, however from a practical standpoint, the coach typically handles all of those duties during the game. Not doubting what you're saying, as it's obviously in the rulebook, but it seems like those rules are not very strict.
Answer: While team captains have been elected by their clubs throughout the history of football, the team captain was only an official part of the NFL starting in 2007.
Their role on the field is not anything more than representing the team during the coin toss. If they are on the field during a penalty, they are typically the one who communicates with the referee about accepting or declining the penalty, but this is not always so. In the NFL, each team elects a captain (either by vote of the players or appointed by the coaching staff) from the offense, defense and special teams based on leadership on and off the field. In the NCAA, most schools have three team captains but this varies from school to school and the responsibilities of the captain are the same as in the NFL.
During special event games such as the Super Bowl or a BCS Bowl, schools will often bring in former players or VIP's from the school to serve as honorary team captains.
Comment: I'm sorry, but almost everything in the second paragraph is factually incorrect. See my answer below, particularly text in bold.


Notify a user if a node has a comment or status updated

Question: I'm trying to build a simple ticketing system with Drupal 8.6. I'm able to create a content type for these tickets and the comments will be the responses to the ticket. Also I have a status field for open, pending, and closed. I want to be able to email all the users on the ticket if the node is updated or commented on. And I have another user reference field for "assigned ticket to".
What modules would I need that work with 8.6 to get this kind of funtionality? I prefer no modules, but I'm not sure if core itself supports this type of thing.
Comment: If it would be me, I think I'd implement https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_entity_update/8.6.x in a custom module. If you don't like to program yourself, you may give https://www.drupal.org/project/rules a try.
Answer: I recently did something similar, for reacting when the node is updated i used hook_node_presave(). Here's an example on how to send an email when the node is updated and the status is changed from "open" to "pending".
function my_module_node_presave(NodeInterface $node){
  if($node->getType() == 'your_content_type_name' AND $node->isNew() == FALSE) {
   $status_original = $node->original->get('status_field')->value;
   $status_updated = $node->get('status_field')->value;

 if ($status_original !== $status_updated AND $status_original == 'open' AND $status_updated == 'pending') {
   send_mail();
  }
 }
}

For creating the send_mail function or whatever you'd like to call it i used the following resource and modified the code where necessary: How to send a mail programmatically in Drupal 8. Also, i used the SMTP Authentication Support module to send the emails using a gmail account: SMTP Authentication Support. The configuration page of the module is on admin/config/system/smtp.
For checking if a comment has been posted you can use hook_ENTITY_TYPE_insert() and replace "ENTITY_TYPE" with "comment" and inside the hook you can call again the send_mail function.
I did not quite understood how you are storing "all the users on the ticket", but it would be the case of getting the users email address with getEmail();


UISearchBar appearance issues in iOS 7

Question: Im facing issues with iOS in UISearchBar. I'm using following code to Customize UISearchBar :
- (void)showSearchBarCustomColorAndDesignWithTargetForiOS7:(id)target{
    UIView * subview;
    NSArray * subviews = [self subviews];

    for (subview in subviews){
        for (UIView *level2SubView in subview.subviews){
            if ([level2SubView isKindOfClass:[UITextField class]])
            {
                [((UITextField*)level2SubView) setEnablesReturnKeyAutomatically:NO];
                ((UITextField*)level2SubView).delegate=target;
                [((UITextField*)level2SubView) setEnabled:TRUE];
                ((UITextField*)level2SubView).borderStyle = UITextBorderStyleLine;
                ((UITextField*)level2SubView).textColor = [UIColor whiteColor];
                ((UITextField*)level2SubView).font =[UIFont fontWithName:@"ProximaNova-Light" size:24.0];
                ((UITextField*)level2SubView).autocorrectionType = UITextAutocorrectionTypeNo;

                ((UITextField*)level2SubView).layer.borderWidth = 1.0;
                ((UITextField*)level2SubView).layer.borderColor = UIColorFromRGB(0x2774A7).CGColor;
                [[((UITextField*)level2SubView) valueForKey:@"textInputTraits"] setValue:[UIColor whiteColor] forKey:@"insertionPointColor"];
                ((UITextField*)level2SubView).autocapitalizationType = UITextAutocapitalizationTypeNone;
                break;

            }
            if ([level2SubView isKindOfClass:NSClassFromString(@"UISearchBarBackground")])
            {
                [level2SubView removeFromSuperview];
            }
        }
    }

    self.delegate = target;
    [self setImage:[UIImage imageNamed:@"search_white.png"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
    [self setImage:[UIImage imageNamed:@"delete_white.png"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal];
    [self setBackgroundColor:UIColorFromRGB(0x2774A7)];
}

Whenever I click on UISearchBar first time it's not calling searchBarShouldBeginEditing. Also it's not showing the text I'm entering. However, when I click second time it's behaving properly. Also, it's showing some black patch. My Search bar is looking like this :
Answer: This issue may be by adding this code

[[searchBar.subviews objectAtIndex:0] removeFromSuperview]; or

if ([level2SubView isKindOfClass:NSClassFromString(@"UISearchBarBackground")])
            {
                [level2SubView removeFromSuperview];
            }

Please remove this and see.

UISearchBar appearance issues in iOS 7


whats the best statistical method to analyse and compare four groups of intervention with follow up?

Question: I have recently conducted an experiment to compare the efficacy of 3 treatments and I had a whait-list group too.
I had three interventions and a I wanted to compare their efficacy on cognitive performance (I used 5 assessment tools to assess this) of elderly, Ive selected 100 people and randomly assigned them on these 4 groups. Ive conducted a pretest for baseline, a post test after the lasts session of interventions and a follow up test after 6 month.
my experiment design is like below:
where X are my interventions, and O1 is pretest, O2 is post test and O3 is follow-up
treatment1  O1 X1 O2 O3
treatment2  O1 X2 O2 O3
treatment3  O1 X3 O2 O3
wait-list   O1 - O2 O3
I want to compare the effect of these 3 interventions and see if each intervention is significant or not, and I want to see if the effect of interventions are lasted after 6 month in my follow up.
now whats my best option to analyze the collected data in SPSS?
I have used the repeated measures in general linear model section, but it has its shortcomings and don't give me the data I need.
I have attached the PAIRWISE COMPARISON by BONFERRONI, the problem is I want to know how each treatment worked and which treatment effect lasted best over time, in this table I just see that there are differences in time 1 vs time 2 and etc, but it wont give me the data based on each treatment.
can anyone help me with this please?
Thanks in advance
Comment: What does O1 X O2 O3 mean ? You said "I want to know how each group performed and which treatment effect lasted best over time" - what do you mean by "*how each group performed*" mean, and what does "*lasted best over time*" mean ? Also, please can you describe the study in more detail.
Comment: dear Robert, thanks for your reply, I've edited my original question and added more details about my research.
Answer: From the updated description, you have 4 groups of participants, where each group receives a different intervention (including 1 control group. Each participant was measured 3 times, the first being a baseline measure, and the other two following the intervention.
Interest is centred on the relative differences between the "treatment effects" of the groups as well as any difference(s) over time. The pairwise comparison model that you fitted will not answer these questions.
One way to analysis these data to help answer your research question is with a mixed effects model:

there are repeated measures within participants, so random intercepts should be specified for participant. This will control for the non-independence of measurements within participants.

treatment group and time should be fixed effects since these are the focus of the research question. The estimates for treatment group will provide inference about the mean outcome measure in the groups (similar to the model you fitted). The estimates for the time variable will provide inference for the change in the outcome measurement over time.

If there is interest in whether the change in the outcome measurement over time differs between the groups then you would also want to fit an interaction between the treatment group variable and the time variable.

SPSS has a mixed effects command, however I don't use SPSS - and I would advise you not to. A better approach, in my opinion is to use R or Python, both of which are free. In R, the model would look like this:
<code>outcome ~ group + time + (1|participant)
</code>
[this example does not fit the interaction]
Comment: I appreciate your taking the time to answer my questions.  It has really helped me. I'm trying to learn R, but I'm still a novice.
Comment: No problem, and you are welcome :) We are all still learning. One very good thing about R is that whatever the problem, you can probably find the answer fairly quickly, but if not then you can always ask on stackoverflow (if its purely about R) on on here if it is a statistical question involving R.


SSL certificate Error. IBM API Microgateway

Question: I have a node.js server on which I am running a microgateway using https. I am using a specific port. When i hit the url of the api gateway it produces a warning about the SSL certificate, After i accept the certificate it gives the error
"{"name":"PreFlowError","message":"unable to process the request"}"
API gateway is configured correctly as well as API.
what is the problem particularly ??
Answer: This is a generic error from your microgateway.
Verify logs at ˜/.apiconnect folder or enable a trace to catch your real problem.


Mudar valor do padrão americano para padrão brasileiro no Java Script

Question: Nesse código é solicitado que digite um número numa window.prompt.
Usei o replace para poder aceitar o padrão brasileiro com vírgula.
Minha dúvida é, como eu faço para ele converter para vírgula novamente quando for exibir o resultado da soma?

Exemplo:
A soma entre 3 e 3,5 é 6,5
quero que exiba assim com vírgula e não ponto.

var PrimeiroNúmero = window.prompt('Digite um número: ')
var SegundoNúmero = window.prompt('Digite outro número: ')
var n1 = parseFloat(PrimeiroNúmero.replace(',', '.'))
var n2 = parseFloat(SegundoNúmero.replace(',', '.'))
var soma = n1 + n2
window.alert(`A soma entre  ${n1} e ${n2} é ${soma}`)
Answer: Uma solução simples e portável, da mesma forma que fez na pergunta use String.prototype.replace() para a partir da string representando o resultado obtida com Number.prototype.toString() para substituir o ponto decimal por vírgula:

const primeiro = "3";
const segundo = "3,5";
const n1 = parseFloat(primeiro.replace(',', '.'));
const n2 = parseFloat(segundo.replace(',', '.'));
const soma = n1 + n2;

const resultado = soma.toString().replace('.', ',');     //Converte soma em String e usa o mesmo artificio usado na pergunta.

console.log(`A soma entre ${primeiro} e ${segundo} é ${resultado}`);

Aviso:
Quanto ao Node.js o código abaixo só funcionará adequadamente caso o
servidor esteja configurado com suporte a internacionalização adequado a linguagem.

Outra solução caso o seu código seja executado apenas em navegadores outra solução é utilizar o método Number.prototype.toLocaleString() que retorna uma string com uma representação de um número sensível a língua e cultura especificada, no caso por português brasileiro.

const primeiro = "3";
const segundo = "3,5";
const n1 = parseFloat(primeiro.replace(',', '.'));
const n2 = parseFloat(segundo.replace(',', '.'));
const soma = n1 + n2;

const resultado = soma.toLocaleString("pt-BR");     //Converte soma em String segundo a cultura pt-BR.

console.log(`A soma entre ${primeiro} e ${segundo} é ${resultado}`);

Outra alternativa que pode ser utilizada em navegadores modernos e o Node.js, sem o suporte a internacionalização específico, é personalizar a formatação usando o método Intl.NumberFormat.prototype.formatToParts() da API de Internacionalização.. Veja o exemplo:
const n = 35.81;
const f = new Intl.NumberFormat("en-US");
console.log(f.formatToParts(n));
/*[
 {"type": "integer", "value": "35"},
 {"type": "decimal", "value": "." },
 {"type": "fraction", "value": "81"}
]*/

O método formatToParts() é usado para formatação personalizada de strings numéricas pois retorna um Array de objetos contendo os componentes específicos da localidade a partir dos quais é possível construir strings personalizadas enquanto preserva as partes específicas da localidade.
Para solucionar o problema algoritmo é simples:

Crie um objeto de formatação numérica na localidade local com Intl.NumberFormat().
Quebre a representação numérica em um Array de suas componentes com Intl.NumberFormat.prototype.formatToParts().
Varra com Array.prototype.map() as componentes e as personalize.No caso caso foi personalizado a componente cujo type == "decimal" que define a  string separadora decimal ".".
Reconstrua a representação numérica a partir das componentes personalizadas usando Array.prototype.reduce().

const primeiro = "3";
const segundo = "3,5";
const n1 = parseFloat(primeiro.replace(',', '.'));
const n2 = parseFloat(segundo.replace(',', '.'));
const soma = n1 + n2;

const formatador = new Intl.NumberFormat();                //Cria um objeto de formatação numérica da localidade local(default).
const resultado = formatador.formatToParts(soma)           //Quebra a representação numérica em suas componentes.
 .map(({type, value}) => (type == "decimal")? "," : value) //Varre as componentes e caso type == "decimal" substitui o seu valor por virgula mantendo as outras componentes inalteradas.
 .reduce((str, part) => str + part);                       //Reconstrói a representação numérica.

console.log(`A soma entre ${primeiro} e ${segundo} é ${resultado}`);


how to resize partition on server 2003

Question: Yesterday, my system partition ran out of space (my OS is Windows Server 2003), and I need to resize it, how could I do this? Buy a new larger disk to replace it? I have searched GOOGLE, and found references to various partition resizing utilities.
How do I know which software is reliable and does its job properly? There data on my system is important, I do not want to risk the loss of it.
Comment: If you are worried about your job, it may be an idea to get yourself up to speed on the relevant technologies rather than trusting people on the internet to hold your hand.
Comment: Thanks for your suggestion, I just want to gather information, compare with them, then make the  decision.
Comment: Please note that your question has been edited to remove particular product references in order to conform to the [non-promotion policy](http://serverfault.com/faq/#promotion) on ServerFault.
Answer: The possible approaches are:

install a larger hard disk
perform a 1:1 copy of the data from the old disk - e.g. by mirroring the old disk using Windows Disk Management or employing a 3rd party Live CD
remove the old disk
expand the partitions / filesystems using 3rd party utilities (see below)

or

install a larger hard disk
copy the partitions expanding them simultaneously using some kind of 3rd party software (see below)
do not forget to copy the boot block and make sure your newly copied partitions carry the same attributes (especially the "Active" flag) and types as the old ones
remove the old disk

or

do a full backup (including system state) of your server system
install a new hard disk, remove the old one
create a new partitioning scheme suiting your current and future needs
restore from backup (this would involve installing a fresh instance of Windows Server 2003 first when you have used ntbackup to create the backup)

Windows Server 2003 does support the expansion of volumes but it does so for non-system volumes (i.e. not the one where your "WINDOWS" directory is) only. If you need to expand the system volume, you would need to resort to 3rd-party tools.
There is a number of commercial software packages for re-partitioning and partition / filesystem resize operations. There also are open-source Linux based LiveCD solutions like the GParted project with a pretty wide range in hardware (controller drivers) support and a broad feature set (resizing / moving partitions, resizing FAT/NTFS/extX filesystems).
If the system partition is the only (and thus the last) partition on your disk, you could use a Windows Server 2008 / Vista / Windows 7 DVD to start the recovery mode and use the command line to invoke "diskpart" to extend the volume as described in KB 325590, thus removing the need for involving non-Microsoft software in the process.
If the volume in question is on a FakeRAID device, you are very likely to encounter problems with any solution, so the recommended approach there would be creating a full backup and replaying it on a new installation.
In general, you should take the route you feel most comfortable and confident with. If you have never used partition editing utilities, you might prefer the backup/restore approach, although it would mean a longer downtime period and more manual work for the admin than the other two. Under no circumstances should you use partition editing utilities which have little prevalence in the market and thus have not been widely tested by a large number of users in most of the possible use cases.
Comment: Thanks for your Abundant information, I have tried the snap-in disk management, but there's no "Resize" function like what I can do in my Windows 7, therefore, I decide to buy a large disk and then image my source disk to it. To my surprise, unlike other clone software or image tool, Partition Assistant enable my to resize the target partition during the clone operation.
Comment: @user142676 as I noted, the "resize" option would only be available for non-system volumes with Windows Server 2003. Of course, most imaging / cloning utilities, including the free GParted which I suggested in my answer, would allow you to resize your destination volumes
Answer: Is there any free space on the same disk that could be used to extend system partition? If yes, you could refer to this article it contains the tutorial resize partition: http://www.extend-partition.com/resource/how-to-partition-a-hard-drive.html
If there no enough free space you have to buy a large hard disk and then replace it, if that you could also use this software Partition Assistant to migrate your OS to the new drive without data loss and reconfigure (reinstall) OS.

how to resize partition on server 2003


Firebase Queries don't Show Data in Adapter

Question: In my Application, I tried to get data in listview using simple queries with simple Adapters and FirebaseListAdapter, but the data ,which is selected, haven't shown in the listview, you can find FirebaseAdapter in comments in onCreateview, Code is as shown below:
package mainproject.mainroject.story;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;

import java.util.ArrayList;

import mainproject.mainroject.story.dummy.DummyContent.DummyItem;

/**
 * A fragment representing a list of Items.
 *

 * Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener}
 * interface.
 */
public class ItemFragment extends Fragment {

    // TODO: Customize parameter argument names
    private static final String ARG_COLUMN_COUNT = "column-count";
    // TODO: Customize parameters
    private int mColumnCount = 1;
    private ArrayList<String> musername = new ArrayList<>();
    private OnListFragmentInteractionListener mListener;

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public ItemFragment() {
    }

    // TODO: Customize parameter initialization
    @SuppressWarnings("unused")
    public static ItemFragment newInstance(int columnCount) {
        ItemFragment fragment = new ItemFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COLUMN_COUNT, columnCount);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
        public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_item_list, container, false);
        ListView recyclerView = (ListView) view.findViewById(R.id.list);

//        // Set the adapter
//        if (view instanceof RecyclerView) {
//            Context context = view.getContext();
//            if (mColumnCount <= 1) {
//                recyclerView.setLayoutManager(new LinearLayoutManager(context));
//            } else {
//                recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
//            }
//            recyclerView.setAdapter(new MyItemRecyclerViewAdapter(DummyContent.ITEMS, mListener));
////        }

        FirebaseDatabase mydatabase=FirebaseDatabase.getInstance();
        DatabaseReference myRef = mydatabase.getReference().child("UserDetail");
                Query query=FirebaseDatabase.getInstance().getReference().child("StoriesDetails").orderByChild("story_content").equalTo("story_content");

//The error said the constructor expected FirebaseListOptions - here you create them:
//        FirebaseListOptions<String> options = new FirebaseListOptions.Builder<String>()
//                .setQuery(query, String.class)
//                .setLayout(android.R.layout.simple_list_item_1)
//                .setLifecycleOwner(this)
//                .build();
//        FirebaseListAdapter<String> firebaseListAdapter = new FirebaseListAdapter<String>(options) {
//            @Override
//            protected void populateView(View v, String  model, int position) {
//                TextView text = (TextView)view.findViewById(R.id.id);
//                text.setText(model);
//            }
//        };
        musername.add(String.valueOf(query));
        final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getContext(),android.R.layout.simple_list_item_1, musername);
        recyclerView.setAdapter(arrayAdapter);

//        myRef.addChildEventListener(new ChildEventListener() {
//            @Override
//            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//                GenericTypeIndicator<Map<String, String>> genericTypeIndicator = new GenericTypeIndicator<Map<String, String>>() {};
//                Map<String,String> map=dataSnapshot.getValue(genericTypeIndicator);
//                String value =map.get("Name");
//
////                musername.add(value);
////                arrayAdapter.notifyDataSetChanged();
//            }
//
//            @Override
//            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
//
//            }
//
//            @Override
//            public void onChildRemoved(DataSnapshot dataSnapshot) {
//
//            }
//
//            @Override
//            public void onChildMoved(DataSnapshot dataSnapshot, String s) {
//
//            }
//
//            @Override
//            public void onCancelled(DatabaseError databaseError) {
//
//            }
//        });
       return view;
    }

//    @Override
//    public void onDetach() {
//        super.onDetach();
//        mListener = null;
//    }
//
    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     *

     * See the Android Training lesson Communicating with Other Fragments for more information.
     */
    public interface OnListFragmentInteractionListener {
        // TODO: Update argument type and name
        void onListFragmentInteraction(DummyItem item);
    }
}

layouts
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/list1"
    android:orientation="vertical">

    <TextView
        android:id="@+id/id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/text_margin"
        android:textAppearance="?attr/textAppearanceListItem" />

</LinearLayout>

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/list"
    android:name="mainproject.mainroject.story.ItemFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp"
    app:layoutManager="LinearLayoutManager"
    tools:context="mainproject.mainroject.story.ItemFragment"
    tools:listitem="@layout/fragment_item" />

Comment: I cannot see any listeners in your code. That's why you cannot display any data. But **[this](https://stackoverflow.com/questions/49383687/how-can-i-retrieve-data-from-firebase-to-my-adapter/49384849)** is how you can retrieve data from Firebase Realtime database and display it in a `RecyclerView` using `FirebaseRecyclerAdapter`.
Comment: you need to call `addChildEventListener` or any other listener on your `query` object and pass data into local list or directly set data to adapter
Comment: well, i thought i don't need listener ,if I used Query with FireBaseListAdapter and option.....at all, i have tried listener and showing same blank list.
Answer: when you get data from firebase database used below code ...
   Query query=FirebaseDatabase.getInstance().getReference().child("StoriesDetails").orderByChild("story_content").equalTo("story_content");
    query.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for (DataSnapshot issue : dataSnapshot.getChildren()) {

                musername.add(issue.getValue(User.class).name); // define your pojo class for getting firebase data.
            }
            final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getContext(),android.R.layout.simple_list_item_1, musername);
            recyclerView.setAdapter(arrayAdapter);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

Comment: so i still need to add listener even if i used FirebaseListAdapter as following
Comment: FirebaseListOptions options = new FirebaseListOptions.Builder()
//                .setQuery(query, String.class)
//                .setLayout(android.R.layout.simple_list_item_1)
//                .setLifecycleOwner(this)
//                .build();
//        FirebaseListAdapter firebaseListAdapter = new FirebaseListAdapter(options) {
//
Comment: why using FirebaseListAdapter only used simple ArrayAdapter above code correct for adding data into recyclerview. First check your data comeing on sever or not.
Comment: tip: it isn't recycler that is just name of listview was recycler then i changed it to list>>>>>>>>>>
Comment: that is the data i was going to retrieve data from StoriesDetails
 gigkxkg
 Author:

 LogoSrc:

 story_content:

 story_price:
Comment: and here it's rule {
  "rules": {
    ".read": "auth == null",
    ".write": "auth != null"
  }
}


Ragtime - Pedal or not to pedal?

Question: I would like to know if you would usually use the pedal for the stride bass in ragtime songs or not?
I heard that some people pedal the stride bass to make the jumps more fluent and others don't do it, to give it a more staccato feel.
But since the pedal is never notated in ragtime scores, I wanted to know if there is a 'right or common' way how to approach it, or if it's just a matter of taste?
Comment: I'd actually read it as a typo/malaprop for 'stride'.
Comment: As an aside, ragtime isn't always played in swing, so would the answer change for non-swing renditions of ragtime bass?
Comment: I'd hate to put this in an answer - I'm sure I'd get downvoted to death... but dare I say "it depends how good you are"... I would pedal. I know one player who never does, unless it's for intent/effect [YouTube links available on request]. Needless to say he's a million times better than me ;-)
Comment: Well yea, I've been taught the term 'swing bass' for that style, because your hand is swinging back and forth between the bass note and the chord. But you probably know it as stride (bass).
Comment: There are always exceptions and mixes of style.  But 'Not swung' is a core definition of Ragtime.
Answer: It depends, not only on the piece, but also on the piano, the room's reverberation, and perhaps how rowdy the audience is.  Similarly inconclusive arguments rage about pedaling Bach, who didn't notate damper pedal because he was writing for keyboard instruments without one.
Answer: As with any piano music, it depends on the piece, and your interpretation of it.  Pedaling is personal to each performer.  The result is what matters and if you do or don't use the pedal to achieve that result, the choice is yours (unless the score has specified one way or the other).

Ragtime - Pedal or not to pedal?


If $K = \lim_{i \to \infty}\frac{x_i}{y_i}$ and $\lim_{i \to \infty} x_i = 0 $, then $\lim_{i \to \infty} y_i =0$?

Question: If $$K = \lim_{i \to \infty}\frac{x_i}{y_i}$$
with $0<K<\infty$
and $$\lim_{i \to \infty} x_i = 0 $$
then will it be the case that
$$\lim_{i \to \infty} y_i =0$$
? I tried to prove this using different properties of limit, but so far I found no way. L'hopital's rule applies only when we can assume limits of both denominator and numerator exists or are infinite...
Edit: the main problem I observe in proving and disproving is eliminating/confirming possibility where the limit of $y_i$ as $i$ goes to infinity does not exist.
Answer: Since $\lim_{i \to \infty}\frac{x_i}{y_i} = K$ and $0 < K < \infty$ we have that $\lim_{i \to \infty}\frac{y_i}{x_i} = \frac{1}{K} = L$, where $0 < L < \infty$
Then we have:
$$\lim_{i \to \infty} y_i = \lim_{i \to \infty} \frac{y_i}{x_i} \cdot \lim_{i \to \infty} x_i = L \cdot 0 = 0$$
Comment: But what about possibility where the limit of $y_i$ as i goes to infinity does not exist? How would we eliminate this possibility?
Comment: @griedman See now. Maybe the new answer would be more clear to you.
Answer: $$\frac{x_i}{y_i}\to K\implies \left\vert\frac{x_i}{y_i}-K \right\vert<\frac{K}{2} \text{ eventually}  \implies \left\vert\frac{x_i}{y_i}\right\vert>\frac{K}{2}\implies \vert y_i \vert<\frac{2}{K}\vert x_i\vert\to0$$
So, $y_i\to0$ also.


$\ker(f\otimes g)=\langle\{a\otimes b:(a\in \ker f \text{ or }(b\in\ker g)\}\rangle$

Question: There's a theorem that if $f:A\to B$ and $g:A'\to B'$ are epimorphisms, then their tensor product's kernel is given as
$$\ker(f\otimes g)=\langle\{a\otimes b:(a\in \ker f )\ or\ (b\in\ker g)\}\rangle$$
where $<A>$ denotes the module generated by the set $A$.
But if I define $\widetilde{f}:A\to Im(f)$ as $\widetilde{f}(a)=f(a)$ for all $a$ in $A$, $\widetilde{f}$ is an epimorphism. And also, $\ker(\widetilde{f}\otimes g)=\ker(f\otimes g)$ since if
$$t\in A\otimes B$$
then there exist $a_i$and $b_i$ such that
$$t=\sum_{i} a_i\otimes b_i$$
so
$$(f\otimes g)(t)=\sum_{i} f(a_i)\otimes g(b_i)$$
$$=\sum_{i} \widetilde{f}(a_i)\otimes g(b_i)$$
$$=(\widetilde{f}\otimes g)(t)$$
which yields
$$(\widetilde{f}\otimes g)(t)=0 \iff (f\otimes g)(t)=0$$
Then I can say
$$\ker(f\otimes g)=\langle\{a\otimes b:(a\in \ker f )\ or\ (b\in\ker g)\}\rangle$$
for any $f$ even if it is not an epimorphism. At this point it is apparent that I made mistake, but I cannot see it. I made this mistake in proving that $-\otimes F$ preserves every short exact sequence, where F is an arbitrary free module. Can anyone point out what I did wrong? Thank you.
Comment: This is a common misconception, say, I have $A, B$ are both $R-$modules (one on the right, and the other on the left), and $A'$ is a submodule of $A$, then $A' \otimes B$ needs not be a subgroup of $A \otimes B$. If you wants to know why this happens, you should trace back to how the tensor product of $A \otimes B$ is built. What I mean is, the "structure" of $\mbox{Im} f\otimes B'$, and $A' \otimes B'$ has nothing to do with each other. They are completely different. Hence $f \otimes g$, and $\tilde{f} \otimes g$ are 2 different morphisms.
Answer: Let's take a closer look: when you write $(f\otimes g)(t)=(\widetilde{f}\otimes g)(t)$ you are assuming that LHS and RHS lie in the same module — i.e. that the natural map $\operatorname{Im}f\otimes B\to A\otimes B$ is a monomorphism. Of course the map $\operatorname{Im}f\to A$ is a monomorphism, but it's tensor product with $B$ needn't be.
Comment: @dielectric I'm not sure I understand the question correctly. Is $Kef(f\otimes g)=\langle...\rangle$ if $f$ is mono (and $g$ is epi)? No, take, for example, $f:x\mapsto ax,\mathbb Z\to\mathbb Z$, $g:\mathbb Z\to\mathbb Z/b$
Comment: Thank you, but I have a minor additional question; does $f$'s being monomorphism change the result?


Passar uma variável que está em um arquivo javascript para uma $_SESSION e pegar em uma página php

Question: Bom noite amigos.
Seguinte estou precisando passar uma variável de um arquivo .js para uma Session e pra pegar em outra página com php.
A função javascript retorna o primeiro horário disponível para marcação de uma consulta, e preciso deixar isso setado inicialmente em outra página.
var hr = now.getHours();
var min = now.getMinutes();
var time_format = hr + ":" + min;
//document.write ("
 Hoje é " + hr + ":" + min + ".
");
//$('#next_time').html('28 de dezembro (sexta-feira) - 14:00 horas');
var seconds = now.getTime() / 1000;
var doctor_id = $('#doctor_id').val();
var clinic_id = $('#clinic_id').val();
$.ajax({
  type: "GET",
  url: base_url+"Searchdoctor/doctor_availability?"+"date="+seconds+"&doctor_id="+$('#doctor_id').val()+"&offset=0&clinic_id="+$('#clinic_id').val(),
  success: function(result){
        if(result.data.time_interval.length>0)
        {
          $('#schedule-consult-timeslot').html('<option disabled selected>'+'Horarios disponiveis'+'</option>');
          $.each(result.data.time_interval, function (i, item) {
            if(item.length != 0){
                var split = item.time.split('-');
                if(compararHora(time_format,split[0])){
                   $('#next_time').html(now.getDate ()+ ' de '+ monName[now.getMonth()]+ ' ('+dayName[now.getDay()]+') '+ '- '+ split[0]+ ' horas');
                   return false;
                }
            }

          })
        }else{
           recursiveDate(1);
           //console.log( adicionarDiasData(3) );
        }
    },
    error: function(xhr, status, error) {
        var err = eval("(" + xhr.responseText + ")");
        alert(err.Message);
    }

  });

  function compararHora(hora1, hora2)
{
    hora1 = hora1.split(":");
    hora2 = hora2.split(":");

    var d = new Date();
    var data1 = new Date(d.getFullYear(), d.getMonth(), d.getDate(), hora1[0], hora1[1]);
    var data2 = new Date(d.getFullYear(), d.getMonth(), d.getDate(), hora2[0], hora2[1]);

    return data1 < data2;
}

function recursiveDate(cont){
    /*if(cont == 5){
        console.log('parou');
    }else{
        console.log(cont);
        cont = cont + 1;
        recursiveDate(cont);
    }*/
    var seconds = adicionarDiasData(cont);
    $.ajax({
      type: "GET",
      url: base_url+"Searchdoctor/doctor_availability?"+"date="+seconds+"&doctor_id="+doctor_id+"&offset=0&clinic_id="+clinic_id,
      success: function(result){
            if(result.data.time_interval.length>0)
            {
              $('#schedule-consult-timeslot').html('<option disabled selected>'+'Horarios disponiveis'+'</option>');
              $.each(result.data.time_interval, function (i, item) {
                if(item.length != 0){
                    var split = item.time.split('-');
                       date = getDateFormat(cont);
                       $('#next_time').html(date.getDate ()+ ' de '+ monName[date.getMonth()]+ ' ('+dayName[date.getDay()]+') '+ '- '+ split[0]+ ' horas');
                       //colocar a session com todos os dados acima;
                       return false;
                }
              })
            }else{
              cont = cont + 1;
              recursiveDate(cont);
            }
        },
        error: function(xhr, status, error) {

            console.log(error);
        }

      });
}

function adicionarDiasData(dias){
  var hoje        = new Date();
  var dataVenc    = new Date(hoje.getTime() + (dias * 24 * 60 * 60 * 1000));
  return dataVenc.getTime() / 1000;
  //return dataVenc.getDate() + "/" + (dataVenc.getMonth() + 1) + "/" + dataVenc.getFullYear();
}

function getDateFormat(dias){
  var hoje = new Date();
  return new Date(hoje.getTime() + (dias * 24 * 60 * 60 * 1000));
}

o que eu estou precisando passar para uma SESSION é exatamente o que está dentro do id #next_time. Pois preciso pegar em outra página php.
ISSO ->
date.getDate ()+ ' de '+ monName[date.getMonth()]+ ' ('+dayName[date.getDay()]+') '+ '- '+ split[0]+ ' horas');
Obrigado :)
Comment: Talvez uma `sessionStorage` do próprio JS possa lhe atender. Veja nesta resposta como é simples criar uma e recuperar o valor: https://pt.stackoverflow.com/a/357226/8063
Comment: Acredito que esse post possa te ajudar: https://stackoverflow.com/questions/35091757/parse-javascript-fetch-in-php basicamente é fazer um fetch no js passando no body a variavel e recuperando ela no php.
Answer: O que eu faria é o seguinte...
if(compararHora(time_format,split[0])){
    var ndate = now.getDate ();
    var nmonth = monName[now.getMonth()];
    var nday = dayName[now.getDay()];
    var nhour = split[0];

    $.ajax({
        type: "POST",
        data: {ndate:ndate, nmonth:nmonth, nday:nday, nhour:nhour},
        url: BASE_URL + "Searchdoctor/set_date",
        success: function(data) {
            ('#next_time').html(now.getDate ()+ ' de '+ monName[now.getMonth()]+ ' ('+dayName[now.getDay()]+') '+ '- '+ split[0]+ ' horas');
        }
    });

    return false;
}

A função dentro do controller Searchdoctor -> set_date:
function set_date(){
    $set_date['ndate'] = ($this->input->post('ndate')) ? $this->input->post('ndate') : '';
    $set_date['nmonth'] = ($this->input->post('nmonth')) ? $this->input->post('nmonth') : '';
    $set_date['nday'] = ($this->input->post('nday')) ? $this->input->post('nday') : '';
    $set_date['nhour'] = ($this->input->post('ndate')) ? $this->input->post('nhour') : '';

    return $this->session->set_userdata('search_return', $set_date);
}

E para exibir, na sua view:
echo $this->session->userdata('search_return')->ndate . 'de' . $this->session->userdata('search_return')->nmonth . ' ' . $this->session->userdata('search_return')->nday . ' ' . $this->session->userdata('search_return')->nhour . 'horas';

Comment: Obrigado amigo, eu vou tentar fazer dessa forma e posto o resultado.


Change private dns on AWS?

Question: Is there a way to change the private DNS of an EC2 server?
I want to be able to communicate between my servers with something like myserver.example.com rather than ip-22.214.171.124-uswest-aws-internal.  I'm new to the sysadmin role as well as networking. I tried to play around with DHCP options sets in the VPC but couldn't get it to work.
EDIT #1
To clarify what I'm trying to achieve...I'm setting up Jenkins that will run slaves on numerous servers.  I wanted to be able to use my own assigned addresses instead of arbitrary ones so it makes more sense that it depends on which machine's a job is running on.
I'm also sure it would make other inter-server communications easier in the future as well.  Like I said I'm new to sysadmin, so if there is an easier method I'm missing, let me know.
Comment: assigning addresses limits many of the benefits of AWS and makes your network design more complex. make sure you've got a very good reason before going down this path.
Answer: If you want to access your servers by my-dns-name you'll need to setup your own DNS server.
By default AWS VPC handles DHCP for you and comes with Amazon's DNS server.
You can read up on the options for supplying your own DNS Server here:
http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_DHCP_Options.html

DHCP Option Name: domain-name-servers
The IP addresses of up to four domain name servers, or
  AmazonProvidedDNS. The default DHCP option set specifies
  AmazonProvidedDNS.
DHCP Option Name: domain-name
If you're using AmazonProvidedDNS in US East (Northern
  Virginia) Region, specify compute-1.amazonaws.com. If you're using
  AmazonProvidedDNS in another region, specify
  region.compute.amazonaws.com. Otherwise, specify a domain name (for
  example, MyCompany.com).

Other related notes:
If you want to use a FQDN (myserver.example.com) to communicate, you can do that without your own DNS server, your domains are already publicly accessible.
You can communicate with IP Address', Private or Public, you can change private IPs at the OS level, change hostnames at the OS level and take advantage of /etc/hosts to have a kind of poor-mans DNS.
You might always want to look into ElasticIPs, Elastic Network Interface, and Elastic Load Balancers which all play in the same space as your qestion.
It all depends on what you're trying to achieve, and how you want to do it!
Comment: Thanks for your response, I see I would have to use my own DNS server.  I clarified what I'm looking to do above.
Answer: You can't change it, unless you deploy your own name servers, but you can easily reference it with another name, by creating a CNAME record, which will have the desired effect.
In your "example.com" DNS zone, whether it's in Route 53, or hosted with another DNS hosting provider, you should be able to create create CNAME records:
myserver IN CNAME ip-126.96.36.199-uswest-aws-internal.

When a machine tries to resolve "myserver.example.com" it will be, essentially, told by the "example.com" DNS servers that it should instead look up the "real" internal hostname (the "canonical name") .  If the machine is inside your EC2 deployment, it will ask the EC2 dns resolver to look this up, and the EC2 resolver will in turn return the internal IP address... leading to the behavior that you want -- you can access your internal machines by your desired hostnames.
If a system outside your EC2 deployment looks up this hostname, it will fail, which is the correct behavior, since the machine isn't accessible from outside (if it only has a private IP).
Conversely, if you have a machine with a public IP and a corresponding public hostname, like ec2-x-x-x-x.us-west-2.compute.amazonaws.com using that hostname as the CNAME target will do the same thing.  When queried from inside your EC2 deployment, the result will be the internal IP address via some DNS magic that EC2 does transparently... or from outside, it will return the external public IP address.
https://stackoverflow.com/a/19148569/1695906
Clarification:
There are two kinds of DNS server behavior -- "authoritative" servers will answer a request from any host for any resource record for which they are authoritative ... and recursive "resolvers," which query the global DNS on behalf of their authorized clients.  It is also possible for a DNS server to perform both functions.
Your EC2 instances (by default) use the AWS resolver servers to look up any hostname, inside ir outside, that your instances try to access, and return an IP address... but the AWS resolver is also authoritative for the ".internal" pseudo-domain, so when instances try to look up ".internal" hosts, the correct internal IP is returned.
Now, suppose you configure internal hostnames as CNAME targets in the external "example.com" DNS servers, and then try to internally look up "myserver.example.com" ... the AWS resolver consults the global DNS hierarchy and ends up asking one of the authoritative name servers for "myserver.example.com."  The response will essentially say "all I know is that to find myserver.example.com, you should look up  ip-184.108.40.206-uswest-aws-internal" ... the AWS resolver realizes that it does not need to consult an external entity to answer this new question, because it is authoritative for the fake internal domain, simply responds with the correct answer, which it already knows.
The external "example.com" doesn't need to or try to validate the CNAME target, since that's not its job.
Now, if the CNAME refers to the external hostname, the process is the same and the result is the same, because the AWS resolver (which handles all DNS queries made by your internal machines) does not try to actually look up the true and correct IP address from the DNS servers that are authoritative for the "compute.amazonaws.com" domain... instead, it once again believes, because of its design, that it already knows the IP address of your external hostname... but the answer will again be your internal private IP address.
The AWS resolver I'm speaking of, above, is a virtual entity that is only accessible to your instances.  The information it contains about public hostname to private IP mapping is only accessible to your instances when they query it.  It is not externally accessible.
If you provision an internal hostname as a CNAME target, external queries will get the "internal" answer, which for them will be a dead end.  If you provision external hostnames as the CNAME target, they will end up with the public IP, because finding the CNAME will direct them to the public authoritative DNS servers, not the private internal resolver that only your instances can access.
This is actually all very simple in practice, though not quite so simple to explain here, because so many of the fundamentals of DNS need to be understood, first... but this ultimately works because the "example.com" DNS servers simply don't care whether you configure them with a CNAME they understand.  It isn't their problem to understand it -- the burden is on the resolver that's looking for an answer to make ultimate sense of the intermediate answer appearing in the CNAME.
Comment: That answers how I would set it up if my AWS was my dns host.  Unfortunately it is external and I want to keep those servers closed.  I should probably look to migrate my host though.
Comment: No, this does not require AWS to host your DNS.  It works with *any* DNS provider.  Create `CNAME` records referring to the internal AWS auto-generated hostname *in your external DNS provider's management console* and the magic will follow.
Comment: I'm confused. If I set the private AWS name in the DNS, won't it reject or not resolve since the external AWS host is not part of the same subnet?  Wouldn't I need to put in the public name?
Comment: A CNAME should only need to be syntactically valid, for the external DNS server to return it as an answer.  It is then the original resolver's problem to understand it. The AWS resolver will understand it. Subnets are not relevant to this topic.  Please try configuring different CNAME records referencing internal and external hostnames... then try to resolve them with `dig` or `nslookup` or even `ping` ...from different locations, internal and external, and see what you observe. Added "clarification" section to answer.
Answer: I had the exact same problem.  Although my domains are managed outside of Amazon, I used Amazon Route 53  to create a private hosted name and added a CNAME record, pointing it towards the private AWS DNS name of the instance.  The problem was although this solved things for subdomains, it did not work for the root "example.com" as that breaks CNAME rules.
I have since deleted the CNAME entry, and replaced it with two A-records (example.com and *.example.com) pointing towards my public IP.  I used a public Elastic IP as in my usage case that will always be the same, but your situation may differ.  You ought to be able to use your private IP but I did not test this.
I should point out my servers were Windows based, though this shouldn't make a difference.  I found using NSLOOKUP example.com at a command prompt useful for monitoring changes as suggested by other posts here.  I also considered it vital that any changes you make have a very low TTL value so that changes apply as quickly as possible... Amazon Route 53 smallest preset is 60 seconds but may go lower.  I'm sure setting the A-record was one of the first things I tried, but it didn't propagate straight away so then spent hours going down blind alleys.
Answer: You can easily achieve this with private hosted zone in route 53
http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/hosted-zones-private.html
Answer:
You need your own DNS server such as named.
Look at http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_DHCP_Options.html. domain-name-servers option is the one to change.

Change private dns on AWS?


Usage of render and render partial

Question: For rendering a partial I can use
render 'partial_name' or render partial: 'partial_name'
I came to know that render is the shorthand syntax of render partial and render will not accept additional local variables for the partial from this SO answer
I would like to know if there is any performance issue when using render instead of render partial
Comment: You should look at both methods in the rails source and report back the source code. We can help you look at the difference but at least provide a little more research...
Answer: In Rails, the render action

"Renders the content that will be returned to the browser as the
  response body."

It is possible to render an action, text, the contents of a file, and other things, including a partial view.
render :action => "Create"
render :file => "/path/to/file/foo.erb", :layout => true, :status => 404
render :partial =>...

Using the partial label explicitly, disambiguates the render action for Rails ActionController.
As far as performance, I haven't done the test to confirm, but I think it's reasonable to expect it is more efficient to use render :partial for the above reasons.
When I'm looking for the nuts & bolts underlying Rails logic, this is an excellent detailed technical reference.

Usage of render and render partial


How to install patched Paypal module in Drupal Commerce?

Question: I am not an expert of Drupal, but I am trying to configure a site with Drupal Commerce, and in particular, the PayPal module.
I need the following two patches:
https://www.drupal.org/node/2415489
https://www.drupal.org/node/2415501
that, if I understood correctly they are not merged into the paypal module yet.
So, what I did is to manually download the PayPal module, manually apply the patches (unfortunately they conflict each other, so I applied one with the patch command and the other by manually diff the files) and I tar.gz everything.
The resultant module is here: https://dl.dropboxusercontent.com/u/7968745/commerce_paypal-7.x.2.3.tar.gz
Now, if I try to install this module I get the following error:
Unable to create directory 'temporary://update-extraction-bde81194/.'

But if I try to install any other module, it works.
BTW: I don't know if this is relevant or not. Before installing my custom-made module, I disabled and uninstalled the PayPal module, but if now I look for the modules in my Drupal installation I still find the PayPal module (but disabled)
Answer: You have to make sure that the temporary directory is configured at admin/config/media/file-system is writable.
In my case /tmp is writable, as per the settings in the screenshot below.
Comment: Shouldn't this apply also to "official" modules, i.e. the one I copy the link directly from the Drupal website? because they work. Furthermore, I tried to move from `/tmp` to `tmp` as I'm using an hosting provider
Comment: Any ideas? Should I wait that those patches get integrated into the main code, so I can directly update the module? Official modules get installed without any problem, so I don't think it is a problem of file system permisssion


Input 0 of layer "dense" is incompatible with the layer: expected min_ndim=2, found ndim=1. Full shape received: (1,)

Question: I am trying to use Dense function from keras to train neural network. However, I keep getting this error message

Input 0 of layer "dense" is incompatible with the layer: expected min_ndim=2, found ndim=1. Full shape received: (1,)

my input is 1 dimensional (for example [1,2,3,4]). is there any way to solve this?
Answer: The Dense function
output = activation(dot(input, kernel) + bias)
requires both input and kernel, so its parameter must have at least 2nd rank (have 2 dimensions).
Answer: That is easy just use input_shape=(1,)
For example this is a simple for a classification problem with only 1 input dimension.
<code>X = np.random.randn(1000,) #create some dummy data
y = np.random.randint(0,3,(1000,)) #create some dummy data
model = tf.keras.models.Sequential([
    tf.keras.layers.Dense(64, activation='relu', input_shape=(1,)),
    tf.keras.layers.Dense(32, activation='relu'),
    tf.keras.layers.Dense(3, activation='softmax')
])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# Fit your model
model.fit(X,y, epochs=100)
</code>


Expressao dentro da ng-disabled

Question: Tenho um problema com expressão no angular
Assim não funciona !checked || !checked2

        Click me to toggle:
        <input type="checkbox" ng-model="checked">

        <input type="checkbox" ng-model="checked2">

    <button ng-model="button" ng-disabled="!checked || !checked2">Button</button>

Assim funciona checked || checked2

        Click me to toggle:
        <input type="checkbox" ng-model="checked">

        <input type="checkbox" ng-model="checked2">

    <button ng-model="button" ng-disabled="!checked || !checked2">Button</button>

preciso de 2 checkboxs que a medida que seleciono um dos dois, certo campo será habilitado, seria isso um bug?
Comment: Essa pergunta não se encaixa na tag regex
Comment: Quando um checkbox está marcado, ele automaticamente se torna **TRUE**, a condição " !checked || !checked2 " não vai funcionar porque ele diz: *"Só funcione se algum dos checkbox estiverem False (desmarcados)"*
Comment: Eu não entendi onde você está identificando possível Bug aí, as condições estão corretas. O Ng-Disable só funciona se a condição dentro dele ter output TRUE
Comment: Não sei se encaixa como bug, mas desta maneira funcionou
!(controle || controle2)

A ideia aqui é que, com checkbox marcado o retorno seria true, negando isso o retorno seria false, negando o ng-disabled do campo

lembrando que testei a expressão !controle || !controle2 dentro de um ng-checked e funcionou, não precisei alterar para  !(controle || controle2), apenas dentro do ng-disabled que não funcionou.
Comment: Vou responder abaixo para você entender melhor.
Answer: Como mencionado pelo usuário Jackson:

Quando um checkbox está marcado, ele automaticamente se torna TRUE

Do jeito que você fez ela só funcionará caso um dos dois checkbox estiverem desmarcados, pois você usou o token de negação ! antes de controle e controle2.
O que acho que você quer fazer é colocar por fora da parte (controle || controle2), resultando em !(controle || controle2) ou voltar a usar ng-checked como você mencionou no comentário.
Answer: Isso está certo. Vou fazer em booleans para você entender.
Output do NG-Disable desabilita o elemento quando o output dele é True.

Na sua dúvida de !(controle1 || controle2) seria !( true || true )

Essa expressão inicia com os dois controles FALSE, então...
!(false || false) => true
Se você marca um ou dois, ele irá desabilitar o botão, porque...
!(true || true) => false
!(false || true) => false

É igual matemática, execute o que há dentro do parenteses, para depois executar o que está fora.
Comment: Vlw cara percebi msm,Confundi na lógica msm.

!controle1 || !controle2 assim apenas se os dois estivessem como true, para saída ser false, desabilitando o disabled.

!controle1 || !controle2   <>  !(controle1 || controle2)
Comment: boa explicação +1!
Answer: A diretiva ng-disabled, se receber um valor false, vai liberar o botão, se receber um valor true vai bloquear o botão, então, a lógica sua pode ser analisada por uma função, que ao final deve negar o resultado, exemplo:

var app = angular.module("app", []);
app.controller("ctrl", function($scope) {
  $scope.checked = false;
  $scope.checked2 = false;
  $scope.btnStatus = function()
  {
    return !($scope.checked || $scope.checked2);
  }
});

        Click me to toggle:
        <input type="checkbox" ng-model="checked">

        <input type="checkbox" ng-model="checked2">

  <button ng-model="button"
    ng-disabled="btnStatus()">Button</button>

Referencia: ng-disabled

Expressao dentro da ng-disabled


Como evitar que uma Activity seja criada novamente? É chamá-lá uma única vez?

Question: Estou fazendo um formulário e quando eu termino de preencher o formulário eu preciso mudar a cor do item de um ListView com o nome do formulário que acabei de preencher e deixar a cor lá independente se estou navegando pelo aplicativo e passando pela activity várias vezes, alguém sabe como fazer isso? deixa o onCreate ser chamado apenas uma vez.
Comment: Coloque o seu código na pergunta para a gente entender melhor o problema.
Comment: Acho que não tem muito jeito de conseguir isso... O ideal seria persistir essa cor como um valor no `SharedPreferences` e buscar sempre que precisar.
Answer: Acredito que você tentar alterar o ciclo de vida da Activity não terá muito sucesso.
O que você pode fazer é salvar as suas informações em uma variável estática, assim independente da Activity ser criada ou não o valor será sempre o mesmo.
Exemplo:
public static ArrayAdapter meu_adapter;

Assim seu Adapter manterá as informações sempre, independente se a Activity for destruída e criada.
Caso haja a necessidade de manter os cores apos o fechamento da App recomendo salvar em um banco de dados SQLite os registros.
Answer: Você pode fazer o seguinte, sempre que terminar de preencher o formulário você altera o seu adapter do listView e chama o método meu_adapter.notifyDataSetChanged().
Eu respondi algo semelhante aqui
https://pt.stackoverflow.com/a/81604/16057


How do I prove this determinant reduction?

Question: How do I prove the following ?
$$
(\alpha \delta - \beta \gamma)
\begin{vmatrix}
x_1 & y_1 & 1 \\
x_2 & y_2 & 1 \\
x_3 &  y_3 & 1
\end{vmatrix}
=\begin{vmatrix}
\alpha x_1 + \beta y_1 & \gamma x_1+ \delta y_1 & 1 \\
\alpha x_2 + \beta y_2 &\gamma x_2+ \delta y_2  & 1 \\
\alpha x_3+ \beta y_3 &  \gamma x_3+ \delta y_3  & 1
\end{vmatrix}
$$
I am getting $(\alpha \delta + \beta \gamma)$ instead of $(\alpha \delta - \beta \gamma)$. Any hints ?
Answer: Let
$$A=\begin{pmatrix} x_1&y_1&1\cr
x_2&y_2&1\cr
x_3&y_3&1\cr\end{pmatrix} $$
and
$$B=\begin{pmatrix} \alpha& \gamma&0\cr
\beta&\delta&0\cr
0&0&1\cr \end{pmatrix}$$
Compute $AB$.


How to find the appropriate model to apply (GAMLSS)/Approving statistical thinking

Question: I need to compute percentile curves using the LMS method (from the GAMLSS package/models) with Age and Height as predictors.
What is the best way to determine which equation (with which transformation and type of spline) is the most appropriate? I attempted to consider various models before comparing GAIC to select the best one. However, it takes a long time to consider various scenarios regarding whether either sigma, nu,tau should be constant or not. or the type of transformation that should be used. So any suggestions for finding the best model would be greatly appreciated.
<code>library(tidyverse)

df=read.csv("https://raw.githubusercontent.com/kinokoberuji/R-Tutorials/master/LMSmodelGAMLSS.csv", sep=";")%>%as_tibble()
m1 <- gamlss(TLC ~ Height + pb(Age), sigma.fo =~pb(Age), nu.fo =~pb(Age), family = BCCGo(mu.link = "log"), data=df)
m2 <- gamlss(TLC ~ Height + pb(log(Age)), sigma.fo =~pb(log(Age)), nu.fo =~pb(log(Age)), family = BCCGo(mu.link = "log"), data=df)
m3 <- gamlss(TLC ~ log(Height) + pb(Age), sigma.fo =~pb(Age), nu.fo =~pb(Age), family = BCCGo(mu.link = "log"), data=df)

m1.1 <- gamlss(TLC ~ Height + pb(Age), sigma.fo =~pb(Age), nu.fo =~1, family = BCCGo(mu.link = "log"), data=df)
m2.1 <- gamlss(TLC ~ Height + pb(log(Age)), sigma.fo =~pb(log(Age)), nu.fo =~1, family = BCCGo(mu.link = "log"), data=df)
m3.1 <- gamlss(TLC ~ log(Height) + pb(Age), sigma.fo =~pb(Age), nu.fo =~1, family = BCCGo(mu.link = "log"), data=df)

m1.2 <- gamlss(TLC ~ Height + pb(Age), sigma.fo =~pb(Age), nu.fo =~pb(Age), tau.fo=~(Age), family = BCPE(mu.link = "log"), data=df)
m2.2 <- gamlss(TLC ~ Height + pb(log(Age)), sigma.fo =~pb(log(Age)), nu.fo =~pb(log(Age)), tau.fo=~log(Age), family = BCPE(mu.link = "log"), data=df)
m3.2 <- gamlss(TLC ~ log(Height) + pb(Age), sigma.fo =~pb(Age), nu.fo =~pb(Age), tau.fo=~Age, family = BCPE(mu.link = "log"), data=df)

m1.2 <- gamlss(TLC ~ Height + pb(Age), sigma.fo =~pb(Age), nu.fo =~Age, tau.fo=~Age, family = BCPE(mu.link = "log"), data=df)
m2.2 <- gamlss(TLC ~ Height + pb(log(Age)), sigma.fo =~pb(log(Age)), nu.fo =~log(Age), tau.fo=~log(Age), family = BCPE(mu.link = "log"), data=df)
m3.2 <- gamlss(TLC ~ log(Height) + pb(Age), sigma.fo =~pb(Age), nu.fo =~Age, tau.fo=~Age, family = BCPE(mu.link = "log"), data=df)

etc.

GAIC(m1, m2,m3,m4,........,k=log(length(DAT1.F$y)))
</code>
Answer: There is an example of centile estimation for head circumference
using 2 explanatory variables (age and height)
in Rigby et al. (2019) page 100-108.
Comment: Please add a proper reference to Rigby et al. (2019) page 100-108.


Register a module theme implementations

Question: I have created a simple module to display frequently asked questions (FAQ). The output (faq content) can be customize in mymodule-template.tpl.php file located in a module directory.
I'd like to create an additional template file suggestion for the theme directory e.g: sites/all/themes/mytheme/templates/mymodule-template.tpl.php
So, the main goal is to add two template file suggestions.

[my module path]/mymodule-template.tpl.php
[active theme path]/templates/mymodule-template.tpl.php

To achieve #1 I have implemented this hook.
<code>/**
 * Implements hook_theme()
 * @return
 *  An array with the name of template file and variables
 */
function simple_faq_theme($existing, $type, $theme, $path) {
    // get faq content
    $records     = get_faq_content();   // categories, questions, answers
    $description = get_faq_info('intro');   // faq description

    return array(
        'faq_template'  => array(
          'template'    => 'simple_faq',
          'variables'   => array('records' => $records, 'description' => $description),
        )
    );
}

/**
 * FAQ Page content
 *
 * @return
 *  HTML created by template file
 */
function simple_faq_page() {
    return theme('faq_template');
}
</code>
It works, but I can't figure out how to create an additional suggestion, which allows users to theme the output without changing anything within module files.
Any idea?
Comment: So your template file is simple_faq.tpl.php? It should works out of the box, try to copy this file to theme directory. To add suggestions, use `template_preprocess_faq_template(&$variables)` and add it there like `$variables['theme_hook_suggestions'] = array('simple_faq__' . current_path());`
Comment: yes, suggestion is: simple_fag__faq so the filename should be: simple-faq--faq.tpl.php - I've tried with underscores as well, but with no results. Well, at least I'm on the right way.
Comment: Yes, and it works, but is there any way to do that in module? without preprocess functions?
Comment: This function should be in your module if You want provide template suggestions, like any other modules do, look eg. to field, node, etc., all of these have function `template_preprocess_theme`
Comment: Copy your `simple_faq.tpl.php` file to current theme's templates folder and it should work.
Comment: @malcolm - template_preprocess function did what I needs. It works, but unfortunately I've got stuck again.. I have my new suggestion file name (simple_fag_faq) in theme_hook_suggestions array, but the output is still generated by the default template file (simple_fag). Any idea what's missing?
Comment: Can be filename problem. When you add `simple_fag_faq` your template file should be `simple-fag-faq`.
Answer: Your hook_theme implementation is not being done in the usual way.
It should only have default values for the variables, like this:
<code>/**
 * Implements hook_theme()
 * @return
 *  An array with the name of template file and variables
 */
function simple_faq_theme($existing, $type, $theme, $path) {
  return array(
    'faq_template' => array(
      'template' => 'simple_faq',
      'variables' => array('records' => array(), 'description' => ''),
    )
  );
}
</code>
Then when you call the theme function is where you send the actual values in, like this:
<code>/**
 * FAQ Page content
 *
 * @return
 *  HTML created by template file
 */
 function simple_faq_page() {
   // Get faq content.
   // Categories, questions, answers.
   $records = get_faq_content();
   // faq description.
   $description = get_faq_info('intro');
   return theme('faq_template', array('records' => $records, 'description' => $description));
 }
</code>
As far as I know you can't give 2 values for the template file, however what you want to do should already be possible.
All you have to do is tell it where the original template file is in your module, then drupal will automatically find ones that are in any themes (the defining module doesn't have to set up anything for the theme).
Comment: I've tried to learn why the variables defined in hook_theme() should contain only default NULL values, but I haven't found any explanation about that. I tried to define them once, in hook_theme(), and they works, however, it seems the right way to do that is exactly like you wrote. Thank you very much.
Comment: The reason is that they are just default values that are used in the case that no value is passed in when calling theme(). If these default values weren't there then there would be lots of undefined index/variable errors if you omitted any variables when calling theme(). This means that theme functions don't need to check for the existence of the variable, they can just rely on the fact it will be there, even if it is just the default value.

Register a module theme implementations


Extract data based on condition

Question: I have the following dataset (sample) from which I have to extract dataframe based on a condition. The dataset consists of machines (over 1000), the downtime in hours, the status, and the downtime reason. There are many instances of each machine in the dataset (at least 1000). The condition for extraction is the dataframe must only contain those machines that have been active for the past 7 days consecutively (including the date). The dataset does not contain records for every day for each machine. Some days have been skipped. For those days, I'm not sure if the machine was active or not. I'm trying to do it on a rolling basis, for example, for  the date in each row, I'm trying to check if that unique machine has been active for the past 7 days (pd.Timedelta(days = 6)). I think there is a neater and more organized way to achieve this but so far, I've not been able to come up with an algorithm. I'm pretty much a novice programmer in Python. Is there someway I can organize the machines and then check for each date. I would also like to be able to keep track of those machines for which records for some days have been skipped. I don't need the code in Python. I'd just greatly appreciate if someone could help me come up with an effective algorithm through which I can achieve the new dataframe.
Thank you very much in advance and happy holidays! :)

DATE
MACHINE
DT_IN_H
MACHINE_STATUS
DT_REASON

11/5/2021
710
0
ACTIVE
In Service

8/1/2020
847
0
ACTIVE
In Service

2/4/2020
1334
0
ACTIVE
In Service

5/16/2020
855
24
ACTIVE
Under mgmt

1/4/2019
669
0
ACTIVE
In Service

7/24/2021
1831
0
ACTIVE
In Service

10/19/2018
134
24
ACTIVE
Under mgmt

8/18/2019
395
0
ACTIVE
In Service

1/19/2019
499
24
ACTIVE
Under mgmt

7/24/2020
2085
0
ACTIVE
In Service
Comment: To allow responders to test their ideas, Stackoverflow much prefers example data to be added as text rather than an image.
Comment: Thank you @DarrylG, I'll amend my question now
Comment: A MACHINE only occurs once in your dataset.  Consequently, no machine appeaers ACTIVE on successive days which makes it harder to check ideas for your desired output.
Comment: If the dataset is large you could use a cloud link to a fuller dataset using a service such as pastebin.com, or many others.
Comment: Don't forget to add a link to the online data.
Comment: Hi @DarrylG, here's the pastebin link https://pastebin.com/QwkJXK7f
Comment: In the larger dataset I'm not finding machines that are active for 7 consecutive days.  By consecutive you mean the same machine with no gaps in the date.  The most I find is 4 days.  An example is MAHINE_NO = 588 found for the four consecutive dates: 2019-05-04, 2019-05-05, 2021-11-03, 2021-11-03 .
Comment: Hi @DarrylG, I'm including another dataset. This is a dataset of one machine. I'm still trying to figure out how to determine if this machine had been in service for 7 consecutive days. Thank you so much for helping! :) https://pastebin.com/L0GSYrjf
Comment: yes, this machine has been in service.  I'll post some code that will help you identify when this is True.
Answer: Approach
Adapting method from How to group by date and find consecutive day count we proceed as follows

Take Dataframe rows only where MACHINE_STATUS is ACTIVE
convert DATE column from string to DATE
Sort by DATE (ascending)
Add a unique identifier for each group of ascending dates per MACHINE
Filter to obtain only when group size >= 7

Code
df = pd.read_csv("https://pastebin.com/raw/L0GSYrjf")    # Read data from url
df = df[df.MACHINE_STATUS == "ACTIVE"]                   # 1 when machine is ACTIVE

df["DATE"] = pd.to_datetime(df.DATE)                     # 2 Convert data field from string to date
df = df.sort_values(by='DATE', ascending=True)           # 3 sort by date
df['successive'] = df.groupby(["MACHINE"]).DATE.transform(func = lambda x: x.diff().dt.days.ne(1).cumsum()) # 4 add unique identifier

# 5 Filter keeping only groups of 7 or more active
df2 = df.groupby(["MACHINE", "successive"]).filter(lambda g: len(g) >= 7)

print(df2.groupby(['successive']).size())
# Output (shows only 1 group of length 1471, which means machine was active for 1471 successive days)
successive
1    1471
dtype: int64

print(df2.head(10))
# Output

       DATE  MACHINE  DT_IN_H MACHINE_STATUS   DT_REASON  successive
0 2018-01-01     1887      0.0         ACTIVE  In Service           1
1 2018-01-02     1887      0.0         ACTIVE  In Service           1
2 2018-01-03     1887      0.0         ACTIVE  In Service           1
3 2018-01-04     1887      0.0         ACTIVE  In Service           1
4 2018-01-05     1887      0.0         ACTIVE  In Service           1
5 2018-01-06     1887      0.0         ACTIVE  In Service           1
6 2018-01-07     1887      0.0         ACTIVE  In Service           1
7 2018-01-08     1887      0.0         ACTIVE  In Service           1
8 2018-01-09     1887      0.0         ACTIVE  In Service           1
9 2018-01-10     1887      0.0         ACTIVE  In Service           1

**Using DT_REASON **
df = pd.read_csv("https://pastebin.com/raw/L0GSYrjf")
df = df[df.DT_REASON == "In Service"]                   # 1 when machine is ACTIVE
df["DATE"] = pd.to_datetime(df.DATE)                    # 2 Convert data field from string to date
df = df.sort_values(by='DATE', ascending=True)          # 3 sort by date
df['successive'] = df.groupby(["MACHINE"]).DATE.transform(func = lambda x: x.diff().dt.days.ne(1).cumsum()) # 4 add unique identifier

df2 = df.groupby(["MACHINE", "successive"]).filter(lambda g: len(g) >= 7)

    df2.head(10)
    # Output shows first 10 of first group
    DATE    MACHINE DT_IN_H MACHINE_STATUS  DT_REASON   successive
0   2018-01-01  1887    0.0 ACTIVE  In Service  1
1   2018-01-02  1887    0.0 ACTIVE  In Service  1
2   2018-01-03  1887    0.0 ACTIVE  In Service  1
3   2018-01-04  1887    0.0 ACTIVE  In Service  1
4   2018-01-05  1887    0.0 ACTIVE  In Service  1
5   2018-01-06  1887    0.0 ACTIVE  In Service  1
6   2018-01-07  1887    0.0 ACTIVE  In Service  1
7   2018-01-08  1887    0.0 ACTIVE  In Service  1
8   2018-01-09  1887    0.0 ACTIVE  In Service  1
9   2018-01-10  1887    0.0 ACTIVE  In Service  1

df2.groupby(['successive']).size()
# Shows there are groups
successive
1     20
3    113
4    151
5     58
6    386
7    437
8    292
dtype: int64

Comment: Hi @DarrylG, thank you so much for sharing the code itself with me. The column I'm trying to filter by is 'DT_REASON' and when I run the code changing just that one value, I get an empty dataframe. :/
Comment: Hi @DarrylG, I came up with another, perhaps more primitive method. I'm adding a column at the end of the dataframe that contains all the dates for the past week. I guess my idea was to see if the dates in the list are in the present in the column 'DATE', then I'd mark 'TRUE' in another column 'IS_IN_SERVICE'. I'm including that dataset below. I guess my problem here is how can I check the 'DATE' column against a list of dates? https://pastebin.com/049WKWFB
Comment: @Wasp10 -- I'm not sure if I understand how the extra column solves your problem.  I thought you wanted to check if a machine has been continuously active for the past week.  Regarding DT_REASON, were you trying to change from checking if MACHINE_STATUS == ACTIVE to check if DT_REASON = "In Service"?  I don't get an empty dataframe when I do this.
Comment: @Wasp10 -- in above code using DT_REASON instead of MACHINE_STATUS I get 8 different groups of continuous 7 or more days.
Comment: Hi @DarrylG, When I add this statement, I get an empty dataframe -> data = data[data['MACHINE_STATUS'] == 'In Service'] Also, I'm not an advanced programmer in Python. :/ I looked up the functions you used and I'm kind of lost, especially with this statement -> df['successive'] = df.groupby(["MACHINE"]).DATE.transform(func = lambda x: x.diff().dt.days.ne(1).cumsum()) # 4 add unique identifier. I get that it's creating a new column 'Successive' and I've looked up the functions individually but what is the unique identifier?
Comment: I get the 8 groups when I omit this statement -> data = data[data['MACHINE_STATUS'] == 'In Service']
Comment: `code #data = data[data['DT_REASON'] == 'In Service']
data['successive'] = data.groupby(["DT_REASON"]).DATE.transform(func = lambda x: x.diff().dt.days.ne(1).cumsum()) # 4 add unique identifier

# 5 Filter keeping only groups of 7 or more active
df2 = data.groupby(["MACHINE", "successive"]).filter(lambda g: len(g) >= 7)

print(df2.groupby(['successive']).size())

print(df2.head(10)) `
Comment: @Wasp10 - updated by code to use DT_REASON.  In your code example, you didn't sort the values by date.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/241264/discussion-between-darrylg-and-wasp10).

Extract data based on condition