To check if a given string start with A-Z in Perl

Question: I had an programming interview few days ago, I am required to write a piece of code in Perl with the functionality described in the title, after a while, I came up with the following solution:
sub startWithUppercaseLetter {
    return @_[0] =~ m/^[A-Z]/;
}

The interviewer seems unhappy with this solution, can anybody give a better one? thanks
Comment: I presume the interviewer's worry was with you accessing an array element with `@`. The first element of `@_` is `$_[0]`. Or you could use `shift`.
Comment: Or perhaps it's *words* that start with a letter, implying the word boundary: `\b`...
Comment: Maybe he wanted lowercase, too, either by adding `a-z` to the character class, or via the `i` switch. I don't know Perl, but the regex seems solid (for uppercase).
Comment: @aliteralmind could you be more specific by providing an example? thanks :)
Comment: @aliteralmind Do you mean the string could start with characters like +,* and so on? I tested the code with strings such as " ", "+A", which could start with a non-word character, it all return 0.
Comment: `\b`=word-boundary, `[A-Za-z]`=Any letter, uppercase or lowercase, `+`=one or more of.
Answer: I would write
sub starts_with_capital {
  shift =~ /^[A-Z]/;
}

Your own solution doesn't survive use warnings, giving
Scalar value @_[0] better written as $_[0]

and it is bad practice to use upper case letters in local identifiers.
Answer: I would really think this is not a good use of the title since your regular expression will return empty  matches or matches (what do you want as a definition of the problem to solve).  The person could also imagine having type this function name over and over again to check if something has a Capital.
So many ways to do it in Perl.
return @_[0] if /^[A-Z]/;

return;

The m really is not needed as you only want the start of the string and any new lines etc, as you are concerned only if first character starts.  Your way, yes can have an empty match and works the same; make it readable for interviews or provide two examples : long hand as above and then short hand.
Comment: Why do you say *"your regular expression will return empty matches or matches"*?
Comment: Yes, I should be more specific, it will return a 1 for match or nothing for a match. I tested the code in the shell and this is the result, no match , returns blank , match returns 1.
Comment: @alexmac I tested it before, I think it will return 0 if not match.:D
Comment: I admire your answer though no need for the m, just for your interview try to be very clear even if you have to dumb it down for the interviewer; he may also think he has dumb staff members who would not be smart enough to read your answer.  Being able to maintain the code afterwards is key.


Can a simple difference in Python3 variable names alter the way code runs?

Question: This code...
class Person:
    num_of_people = 0

    def __init__(self, name):
        self.name = name
        Person.num_of_people += 1

    def __del__(self):
        Person.num_of_people -= 1

    def __str__(self):
        return 'Hello, my name is ' + self.name

cb = Person('Corey')
kb = Person('Katie')
v = Person('Val')

Produces the following error...
Exception AttributeError: "'NoneType' object has no attribute 'num_of_people'" in <bound method Person.__del__ of <__main__.Person object at 0x7f5593632590>> ignored

But this code does not.
class Person:
    num_of_people = 0

    def __init__(self, name):
        self.name = name
        Person.num_of_people += 1

    def __del__(self):
        Person.num_of_people -= 1

    def __str__(self):
        return 'Hello, my name is ' + self.name

cb = Person('Corey')
kb = Person('Katie')
vb = Person('Val')

The only difference I see is the last variable name is "vb" vs. "v".
I am leaning Python and am working on the OOP stuff now.
Comment: The first code does not produce that exception. Show your full traceback. (Correction: it doesn't produce that exception in Python 3.3 or higher. In 3.2 it does.)
Comment: @Wooble: Last but not least, you certainly won't see this error in CPython 3.4, as it has a new [safe object finalization codepath](https://docs.python.org/3/whatsnew/3.4.html#whatsnew-pep-442) that removes the reason for this error altogether.
Comment: @Wooble: That's because dictionary hashing for strings is randomized in 3.3. It'll happen in 3.3 too, when the stars align just right for the keys to collide in the right order. In other words, re-run your test several times and you'll see it happen on **some** runs.
Comment: @StevenRumbalski: In short, yes. But only at interpreter exit.
Comment: @Wooble Nah! That's what i was missing..
Comment: Note: I wouldn't say that what you see is an "error". It's a **ignored** exception, and it is also a *correctly* ignored exception, and as such I'd say it's a *warning* more then an error. If you didn't mess with `__del__` you wouldn't have this problem, and I believe the code you have written is *misusing* `__del__`. In fact in python<3.4 you could easily create some cycles of references so that your `num_of_people` counter is off.
Comment: Not just Python3. In Python 2.7.3 I get two such errors for the first example and one for the second.
Answer: Yes, although it is not the so much the variable name that causes this, not directly.
When Python exits, all modules are deleted too. The way modules are cleaned up is by setting all globals in a module to None (so those references no longer refer to the original objects). Those globals are keys in a dictionary object, and as dictionaries are ordered arbitrarily, renaming one variable can change the order in which variables are cleared.
When you renamed v to vb, you altered the order in which variables are cleared, and now Person is cleared last.
One work-around is to use type(self).num_of_people -= 1 in the __del__ method instead:
def __del__(self):
    type(self).num_of_people -= 1

because the instance will always have a reference to the class still, or test if Person is not set to None:
def __del__(self):
    if Person is not None:
        Person.num_of_people -= 1

Two notes:

CPython 3.4 no longer sets globals to None (in most cases), as per Safe Object Finalization; see PEP 442.
CPython 3.3 automatically applies a randomized hash salt to the str keys used in a globals dictionary; this makes the behaviour you observed even more random, merely re-running your code several times may or may not trigger the error message.
Comment: @aIKid: When Python exits, (or if you delete the module by removing all references to it and deleting it from `sys.modules`, but that's not often done), the module `__del__` is called, which then proceeds by first clearing all globals in the module by rebinding their names to `None`.
Comment: @sds: finalization is finicky; by setting globals to `None` many common circular references are broken properly without invoking (slow and entirely unneeded) resizes of the `globals` dictionaries. The finally did find a better way for Python 3.4, so this whole thing is no longer a problem with that version.
Comment: Ugh.. The answer is brilliant, but I don't really understand this. What do you mean by 'on intepreter exit'? Can you please explain?
Comment: @Corey: there isn't really a higher level here; the bottom line is that during finalization, globals like `Person` and `v` and `vb` have `None` assigned to them, so you cannot count on `Person` being the class still in `__del__`.
Comment: @aIKid: this should only happen when you exit the interpreter, *or* you delete the module explicitly.
Comment: This kind of stuff is why I love StackOverflow.  +1, very interesting.
Comment: So the exception is only raised when we exit the interpreter.. <- That's false, right?
Comment: Wow. I don't know there's such thing! Well, thanks!
Comment: great technical answer, could you summarize it at a higher level for me?


Como fazer uma barra de progresso circular para web?

Question: Como essa da imagem anexada abaixo
Comment: Da uma olhada nesse site, analisando o fonte vai notar que é bem simples criar com css puro. http://www.cssscript.com/demo/pure-css-circular-percentage-bar/
Comment: @LucasLima este exemplo usa propriedades depreciadas do css por exemplo a propriedade clip
Comment: Fica a dica pra por os detalhes nas próximas, pq imaginemos que a resposta dele não te servisse por algum detalhe, ai seria tempo perdido das duas partes. Quanto mais detalhes nas próximas, melhor. Que bom que nesse caso deu certo.
Comment: Queira postar o que tentou fazer e a dificuldade exata.
Comment: Seria bom tambem um trecho de código e um contexto onde vai ser usado isso, para que a resposta possa resolver o problema de fato.
Comment: Olá, Bacco. O Lennon já respondeu o que eu queria saber.
Comment: Entendo, obrigado pela dica.
Answer: Vou contribuir..

var el = document.getElementById('graph'); // get canvas

var options = {
    percent:  el.getAttribute('data-percent') || 25,
    size: el.getAttribute('data-size') || 220,
    lineWidth: el.getAttribute('data-line') || 15,
    rotate: el.getAttribute('data-rotate') || 0
}

var canvas = document.createElement('canvas');
var span = document.createElement('span');
span.textContent = options.percent + '%';

if (typeof(G_vmlCanvasManager) !== 'undefined') {
    G_vmlCanvasManager.initElement(canvas);
}

var ctx = canvas.getContext('2d');
canvas.width = canvas.height = options.size;

el.appendChild(span);
el.appendChild(canvas);

ctx.translate(options.size / 2, options.size / 2); // change center
ctx.rotate((-1 / 2 + options.rotate / 180) * Math.PI); // rotate -90 deg

//imd = ctx.getImageData(0, 0, 240, 24a0);
var radius = (options.size - options.lineWidth) / 2;

var drawCircle = function(color, lineWidth, percent) {
  percent = Math.min(Math.max(0, percent || 1), 1);
  ctx.beginPath();
  ctx.arc(0, 0, radius, 0, Math.PI * 2 * percent, false);
  ctx.strokeStyle = color;
        ctx.lineCap = 'round'; // butt, round or square
  ctx.lineWidth = lineWidth
  ctx.stroke();
};

drawCircle('#efefef', options.lineWidth, 100 / 100);
drawCircle('#555555', options.lineWidth, options.percent / 100);
div {
    position:relative;
    margin:80px;
    width:220px; height:220px;
}
canvas {
    display: block;
    position:absolute;
    top:0;
    left:0;
}
span {
    color:#555;
    display:block;
    line-height:220px;
    text-align:center;
    width:220px;
    font-family:sans-serif;
    font-size:40px;
    font-weight:100;
    margin-left:5px;
}

input {
    width: 200px;
}

span {

}

Agora só alterar o atributo data-percent para a porcentagem que você quiser.
Comment: Obrigado, Lennon.


Video player shows black border

Question: I use a HTML5 video player and it works, but it shows a 1/2 pixel border on the right side.
I already checked if it was because the video itself and I tried to set
border:solid 0px black;

but that didn't help.
My current code:
<video id="video" autoplay>
  <source src="intro.mp4" type="video/mp4" id="video">
  Your browser does not support the HTML5 player.
</video>

and the style
#video{
    width:80%; right: 0; top: 0;
    display:none;
    border:solid 0px black;
}

results in

If someone could help me out, I would be really happy :D
Thanks
Comment: http://stackoverflow.com/questions/10203437/html5-video-in-ie9-is-showing-a-black-border-on-its-both-sides
Comment: why not if you share your code
Comment: @Mihai I tried that, but it leaves a long border trough my text underneath it. And border:none results the same
Comment: Is it the same on all browsers?
Comment: @Mihai No in IE11 it shows a green screen ( which is due my video card? ) but when I use the effect to resize it it shows black borders on both sides. Chrome ( the picture ) shows just one border on the right.
Answer: I found the following to be the best solution for removing the 1px border:
video {
    clip-path: inset(1px 1px);
}

Comment: Hi, I have the same issue and this solution works in Chromium browsers but not in Firefox.
Comment: This worked for me on both Chrome and FF. Thanks!
Comment: No probs @SamAssoum
Comment: Thank you @timbari!! Works like a charm. Tested in Chrome, Opera, Firefox and Edge.
Comment: Glad it helped @RichardKühleis - thank you for testing across browsers :)
Answer: NONE of this is right. This is a focus thing. You need to do:
video:focus { outline:none; }

// or choose a color or transparent or something other if you are needing the focus for ADA/WCAG compliance.
Comment: Check your selector and make sure they match. This is explained elsewhere on here. This is the correct method. https://stackoverflow.com/questions/57608693/how-to-remove-the-outline-on-my-video-player
Comment: This should be selected as an answer! Works perfectly, looks like chrome ads some outline to the video element on :focus.
Answer: it actually a quite known issue. a fix of hide it a bit solves it ->
Give the parent element, who wraps the video overflow: hidden
and the video (position relative/absolute) left:1px.
Like this:
Html:
<div class="video-wrapper"
  <video id="video" autoplay>
    <source src="intro.mp4" type="video/mp4" id="video">
    Your browser does not support the HTML5 player.
  </video>
</div

Css:
.video-wrapper{
    overflow: hidden
}

.video-wrapper #video{
    position: relative; /* could be absolute if needed */
    left: 1px;
}

Comment: that works, thanks. You also forget to close a tag : class="video-wrapper" ***-> > <----***
Answer: From this (black video borders):

To This (no black borders):

By adding:
<video width="103%" style="margin-left: -3px">

Answer: To improve timbari's solution - if using border radius, borders go out of shape. To fix that, lower the inset values
In react it would look like this:
clipPath: 'inset(0.01px 0.01px)'

Answer: How about:
border: none !important;

If this doesn't work try adding as well:
border-right: none !important;

If these don't help please show us your site
Comment: It could also be a box shadow too... so try adding: `box-shadow: none !important;`
Answer: I've had this issue as well and I can't figure out why it's happening. What I did to get around it was something like this:

  <video>
    <source>
  </video>

.container {
    overflow: hidden;
}
.container video {
    display: block;
    width: 100%;
    transform: scale(1.01)
}

I don't know if this is the best way of solving it, but it works.
Answer: It have worked on my side to avoid black and white borders.
margin: -1px;
clip-path: inset(0px);

Video player shows black border


Finite Group with Nilpotent Subgroup of Prime Power Index is Solvable

Question: Let $G$ be a finite group, and assume that $H$ is a nilpotent subgroup whose index is a prime power. WLOG, we can say that the index of $H$ is the highest power of $p$ which divides the order of $G$.
I want to show that $G$ is solvable, and I'm allowed to use Burnside's $p^aq^b$ theorem, as well as Hall's Theorem (which states that if every Sylow-$p$ subgroup has a complement, then $G$ is solvable).
So say $|G|=p^aq_1^{\alpha_1}\cdots q_n^{\alpha_n}$. Then since $H$ is nilpotent, it's the direct product of its Sylow subgroups, so $H=Q_1\times\cdots\times Q_n$. $H$ is obviously a complement for $G$'s Sylow-$p$ subgroup $P$, so I'll be done if I can show there's a complement to $Q_i$, the Sylow-$q_i$. Now, if we let $H_1=H/Q_i$, my first idea is to consider $PH_i$, which has the desired order, but of course there's no guarantee that this is a subgroup, since neither of the two subgroups need to be normal.
I also tried assuming that $G$ is a minimal counterexample and thus simple and showing that some nontrivial proper subgroup is normal, but since $p$ does not have to be the largest prime, I can't argue that the action of $P$ on the $Q_i$'s by conjugation is trivial.
Are either of these avenues fruitful, or should I try something else?
Comment: Well there is a theorem of Kegel that a finite group that is a product of two nilpotent subgroups is solvable, so it follows from that. But you are talking about what you are allowed to use, so is this an exercise? If so, it might be helpful to give more context, such as what were the earlier exercises.
Comment: This is from Dummit and Foote, and it's a Representation Theory section that used Character Theory to prove Burnside's Theorem and then used standard Group Theory plus Burnside to prove Hall's Theorem.

The other exercises were to prove that a finite group all of whose maximal subgroups have prime or prime squared index is solvable, to prove the problem in the OP for "abelian" instead of "nilpotent," and to prove Burnside's Theorem when the Sylow $p$ and $q$ subgroups are abelian.
Comment: Does the theorem of Kegel have an easier proof when one of the groups is a $p$ group?
Answer: The main argument in the character theoretic proof of Burnside's $p^aq^b$ theorem actually proves that a finite simple group cannot have a conjugacy class of prime power order bigger than $1$. In your problem, $H$ is nilpotent, so it has nontrivial centre. Then, for $1 \ne h \in Z(H)$, either $h \in Z(G)$, in which case $G$ is not simple, or $|{\rm Cl}_G(h)|$ is a nontrivial power of $p$, so again $G$ is not simple. Hence, by induction, $G$ is solvable.
Comment: Ah, I missed that lemma...just to be sure, does the hypothesis of there being a nilpotent subgroup of prime power index still hold when we quotient out by a normal subgroup?
Comment: Yes, $HN/N$ is a quotient of a nilpotent group, so it's still nilpotent, and $|G/N:HN/N| = |G:HN|$ is still a power of $p$. (It could be $p^0=1$, but then $G/N$ would be nilpotent.)
Comment: And if $G/N$ is nilpotent, then since $N$ is also, both are solvable, and thus $G$ is solvable. Thanks!


Sql Server 2008 with Small Business Server external connector license

Question:
Possible Duplicate:
Can you help me with my software licensing question?

Is it possible to license Microsoft Small Business Server and add an external connector license to be able to use Sql Server with a public website?
Comment: closing already answered questions with that incredibly lame "Can you help me with my software licensing question?" well played. not.
Answer: Sorry, the EC license does not apply to SBS.
See here http://www.microsoft.com/windowsserver2008/en/us/external-connectors.aspx


Web socket stops responding after awhile

Question: I have a windows service that uses a websocket (from http://sta.github.io/websocket-sharp/) to conenct to Slack and monitor messages.
My connection code looks something like this:
ws = new WebSocket(connection.Url);

ws.OnMessage += async (sender, e) =>
{
    var msg = JsonConvert.DeserializeObject<MessageFromSlack>(e.Data);
    if (msg.Type == "message" && msg.Text != null && msg.User != UserId)
    {
        if (userMatcher.IsMatch(msg.Text))
        {
            await ProcessDirectMessage(msg);
        }
        await ProcessMessage(msg);
    }
    if (msg.Type == "channel_joined")
    {
        await ChannelJoined(msg.ChannelModel.Id);
    }
};

ws.OnClose += (sender, e) =>
{
    var reason = e.Reason;
    var code = e.Code;
    System.Diagnostics.Debug.WriteLine($"{code}:{reason}");
};

ws.Connect();

Basically it waits for a message and then if it's directed @ my bot, it'll call ProcessDirectMessage and if not it'll call ProcessMessage. The details of those functions are, I think, unimportant (they do some matching looking for key phrases and respond by sending a message back).
This all works fine. For a while. But after some period of time (usually more than a day), it just stops responding altogether. My OnMessage handler never gets hit. I thought that maybe what is happening is the websocket is getting closed on the server side, so I added the OnClose handler, but that never seems to get hit either.
Does anybody have an idea what might be happening here? Is there a way to keep the connection alive, or else reconnect it when it dies?
Comment: Did you confirure your websocket to send ping requests?
Comment: @Evk as far as I can tell, the library is supposed to take care of that itself. In so far as there doesn't appear to be a place to configure it.
Answer: By the nature of TCP connection - the only reliable way to detect its gone is to write something to it. If you are just reading (waiting for data to arrive) - you can do that for a very long time while the other side is long time dead. That happens if that other side did not close connection gracefully (which involves an exchange of some TCP packets).
Web socket protocol defines special Ping frame, and corresponding Pong frame, which you should use to avoid situation described in the question. From time to time you should send Ping frame and wait (for a certain timeout) for server to respond with Pong frame. If it did not respond in given timeout - assume connection is dead and reconnect.
As far as I know - library you use does not automatically send ping requests on your behalf. However, it allows you to do that via Ping method.
You need to configure timeout with
ws.WaitTime = TimeSpan.FromSeconds(5);

And then, from time to time (for example - when you did not receive any new messages in last X seconds), do:
bool isAlive = ws.Ping();

There is also boolean property which does the same:
bool isAlive = ws.IsAlive;

This is a blocking call (both of the above). It will return true if server replied with Pong during ws.WaitTime interval, and false otherwise. Then you can act accordingly.
Comment: Thanks, I'll play around with that and see if it fixes the problem
Comment: I'd suggest to test by running your own websocket service in separate console app. It can send message to client every second, and then you can kill it in process explorer and observe the result.


Continuity of a multivariate CDF at a point

Question: I want to show that if $(X_1,X_2,\dots,X_n)$ is an $n$-variate random variable, then its CDF is continuous at a point $\vec a$ iff $$P\left(\bigcup_{k=1}^n\{X_k= a_k, X_j\le a_j\:\forall\:j\ne k\}\right)=0$$
I don't understand how to show this result. If I use the usual definition of continuity, then it would be very difficult to handle balls (because they are spherical, and we are working with CDFs). If we consider rectangles instead of spherical balls, then $F$ is continuous at $\vec a$ iff for every $2\varepsilon$ sided square centered at $F(\vec a)$, we have a $2\delta$ sided square centered at $\vec a$ whose $F$-image lies in the former square.
And I don't know what to do then.
Answer: Write $\mathbf{X}=(X_1,\ldots, X_n)$ for an arbitrary random variable with distribution function $F.$  By definition, the value of $F$ at any point $\mathbf a = (a_1,a_2,\ldots, a_n)$ is
$$F(\mathbf a ) = \Pr(X_1\le a_1, X_2\le a_2, \ldots, X_n\le a_n) = \Pr(\max_i(X_i-a_i)\le 0).$$
For any point $\mathbf{a}\in\mathbb{R}^n$ and any number $\delta$ define the events
$$\mathcal{M}(\mathbf a, \delta) = \{\mathbf X\mid \max_i(X_i - a_i) \le \delta\}.$$

Here, in $n=2$ dimensions, is shown $\mathcal{M}(\mathbf a, 0)$ relative to $\mathbf a.$  It is a buffer of width $\delta$ around all points to the left and below $\mathbf a.$
The demonstration below will analyze the region between two such buffers: an outer buffer and an inner buffer, as shown.

These buffers are relevant to the question because the boundary of $\mathcal{M}(\mathbf a, 0),$ written $\partial\mathcal{M}(\mathbf a, 0),$ is the event described in the question and their set difference is a buffer of radius $\delta$ around that event.

Let
$$F_{\mathbf a}(\delta) = \Pr(\mathcal{M}(\mathbf a, \delta)) = F\left(\mathbf a + \delta(1,1,\ldots, 1)\right).$$
Since
$$\mathcal{M}(0) = \bigcap_{n=1}^\infty \mathcal{M}\left(\mathbf a, \frac{1}{n}\right),$$
computing probabilities gives
$$F(\mathbf a) = \Pr(\mathcal{M}(0)) = \inf_n\, \Pr(\mathcal{M}\left(\mathbf a, \frac{1}{n}\right) = \inf_n\, F_{\mathbf{a}}\left(\frac{1}{n}\right) = \lim_{n\to \infty} F_{\mathbf a}\left(\frac{1}{n}\right).\tag{*}$$
Similarly, we can fill up the interior of $\mathcal{M}(\mathbf a, 0)$ with a union of sets that are disjoint from the boundary, so that their probabilities (of the interior and of the boundary) add:
$$\mathcal{M}(\mathbf a, 0)  = \partial \mathcal{M}(\mathbf a, 0)\, \cup\, \bigcup_{n=1}^\infty \mathcal{M}\left(\mathbf a, -\frac{1}{n}\right)$$
implies
$$F(\mathbf a) = \Pr\left(\partial \mathcal{M}(\mathbf a, 0)\right) + \lim_{n\to \infty} F\left(\mathbf a, -\frac{1}{n}\right).\tag{**}$$
In these terms, the statement to be proven is that

$F$ is continuous (as a function) at $\mathbf a$ if and only if $\Pr\left(\partial \mathcal{M}(\mathbf a, 0)\right) = 0.$

Forward direction
Suppose $F$ is continuous at $\mathbf a.$  This means that for any $\epsilon \gt 0,$ there is some ball (say of radius $R(\epsilon)$ around $\mathbf{a},$ written $B(\mathbf a, R(\epsilon))$) for which the image of $F$ is close to $F(\mathbf a):$ namely,
$$F\left(B(\mathbf a, R(\epsilon))\right) \subseteq [F(\mathbf{a})-\epsilon/2, F(\mathbf{a})+\epsilon/2].$$
When $\delta \le R(\epsilon)/\sqrt{n},$ the rectangle $[a_1-\delta,a_1+\delta]\times \cdots \times [a_n-\delta,a_n+\delta]$ lies entirely within this ball.  But, because $F$ cannot decrease when any of its arguments are increased, the largest value attained by $F$ on this rectangle is $F_{\mathbf a}(\delta)$ while the smallest is $F_{\mathbf a}(-\delta).$  Since
$$\partial\mathcal{M}(\mathbf a, 0) \subset \mathcal{M}(\mathbf a, \delta) \setminus \mathcal{M}(\mathbf a, -\delta),$$
we deduce
$$\Pr\left(\partial\mathcal{M}(\mathbf a, 0) \right) \le F_{\mathbf a}(\delta) - F_{\mathbf a}(-\delta) = F(\mathbf a) + \epsilon/2 - (F(\mathbf a) - \epsilon/2) = \epsilon.$$
The only probability less than or equal to all positive numbers $\epsilon$ is $0,$ which completes the demonstration of the forward direction.
Reverse direction
Given $\epsilon \gt 0,$ $(*)$ shows there exists an integer $n_+\gt 0$ for which $F_\mathbf{a}\left(\frac{1}{n_+}\right) - F(\mathbf a) \lt \epsilon.$  Similarly, assuming $\Pr\left(\partial\mathcal{M}(\mathbf a, 0) \right),$ $(**)$ shows there exists an integer $n_{-} \gt 0$ for which $F(\mathbf a) - F_\mathbf{a}\left(-\frac{1}{n_{-}}\right)  \lt \epsilon.$
Choosing any $\delta \gt 0$ smaller than $1/n_+$ and $1/n_{-}$  assures the values of $F$ on $B(\mathbf a, \delta)$ are within $\epsilon$ of $F(\mathbf{a}).$  Since $\epsilon\gt 0$ was arbitrary, this establishes the continuity of $F$ at $\mathbf a,$ QED.
Comment: Thanks a lot !!


Joining 100GB tables on Mysql

Question: I have 2 tables with 100gb data.
First table
+-------------+---------------+
| id          | code          |
+-------------+---------------+
| 10255911    |sample data    |
| 10255912    |sample data    |
| 10255913    |sample data    |
+-------------+---------------+

Second table
+-------------+---------------+
| id          | code2         |
+-------------+---------------+
| 10255911    |sample data    |
| 10255912    |sample data    |
| 10255913    |sample data    |
+-------------+---------------+

I need the fastest and optimal way to join tables for  creating view. With function UNION ALL very slooow. Table (VIEW) should be
+-------------+---------------+-------------+
| id          | code          | code2       |
+-------------+---------------+-------------+
| 10255911    |sample data    |sample data  |
| 10255912    |sample data    |sample data  |
| 10255913    |sample data    |sample data  |
+-------------+---------------+-------------+

Comment: You can create indexkey on column for performance.
Answer: CREATE INDEX on ID Column of both Tables.
SELECT table_1.id
    , table_1.code
    , table_2.code2
FROM table_1 INNER JOIN table_2
  ON table_1.id = table_2.id
  ;

Comment: Please post your explain plan .
Comment: CREATE OR REPLACE
VIEW stat AS
SELECT
table.id,
table.code,
table.text,
table2.code2
FROM table INNER JOIN table2
  ON table.id = table2.id
Comment: No, I meant fire the query with EXPLAIN appended first. You have posted the view definition which I already understand you want to achieve. The performance of the view will be dependent upon the performance of SELECT .
Answer: With 100 GBs of two tables, I don't think join is advisable. To run join query, you will need highest CPU, MEMORY, optimum mysql configuration etc. on your developer machine.
So better you merge these two tables into one. With this advantage, you may have to change your php application code to a bit to insert data into new table accordingly.
e.g.
+-------------+---------------+-------------+
| id          | code          | code2       |
+-------------+---------------+-------------+
| 10255911    |sample data    |sample data  |
| 10255912    |sample data    |sample data  |
| 10255913    |sample data    |sample data  |
+-------------+---------------+-------------+

and then create index on Id field.

If code and code2 fields are going to be used into where clause,

create a index for each of them too.

Joining 100GB tables on Mysql


Adicionar filtro de usuário em uma função

Question: A função abaixo emite notas fiscais automaticamente usando este plugin (Nota Fiscal Eletrônica WooCommerce) quando o status do pedido é concluído.
function issue_automatic_invoice( $order_id, $from, $to, $order ) {

    // Validate
    $option = apply_filters( 'nfe_issue_automatic', get_option('wc_settings_woocommercenfe_emissao_automatica') );
    if ( !$option ){
        return;
    }

    // Process
    if (
        $to == 'processing' && ($option == 1 || $option == 'yes') ||
        $to == 'completed' && $option == 2
    ){

        $nfes = get_post_meta( $order_id, 'nfe', true );

        if ( !empty($nfes) && is_array($nfes) ) {
            foreach ( $nfes as $nfe ) {
                if ( $nfe['status'] == 'aprovado' ) {
                    return;
                }
            }
        }

        $nf = new WooCommerceNFeIssue;
        $response = $nf->send( array( $order_id ) );

    }

    do_action( 'nfe_issued_automatic', $order_id, $to, $response );

}

Como seria possível adicionar um if para não emitir se o criador do pedido for admin?
Quero que a função seja executada apenas nos pedidos dos clientes e não nos meus.
Answer: Você pode buscar o CPF cadastrado no pedido a ser processado e executar a função apenas se o CPF for diferente do seu, por exemplo:
function issue_automatic_invoice( $order_id, $from, $to, $order ) {
    $format = new WooCommerceNFeFormat;
    $checaCPF = $format->format_number( get_post_meta( $order->get_id(), '_billing_cpf', true ) );
    if ( $checaCPF != 12345678900){

        // Validate
        $option = apply_filters( 'nfe_issue_automatic', get_option('wc_settings_woocommercenfe_emissao_automatica') );
        if ( !$option ){
            return;
        }

        // Process
        if (
            $to == 'processing' && ($option == 1 || $option == 'yes') ||
            $to == 'completed' && $option == 2
        ){

            $nfes = get_post_meta( $order_id, 'nfe', true );

            if ( !empty($nfes) && is_array($nfes) ) {
                foreach ( $nfes as $nfe ) {
                    if ( $nfe['status'] == 'aprovado' ) {
                        return;
                    }
                }
            }

            $nf = new WooCommerceNFeIssue;
            $response = $nf->send( array( $order_id ) );

        }

        do_action( 'nfe_issued_automatic', $order_id, $to, $response );     }
}

Answer: Voce pode fazer um if antes de chamar a função:
if(cliente) {
    issue_automatic_invoice( $order_id, $from, $to, $order )
} else {
    die('admin')
}

espero ter ajudado


How does Apache interpret multiple SSLRandomSeed sources

Question: In my Apache configuration I have these lines:
SSLRandomSeed connect builtin
SSLRandomSeed connect file:/dev/random
SSLRandomSeed connect file:/dev/urandom 1024

How, exactly, does Apache interpret this? Does it first try builtin and then move to /dev/random if that fails? If it uses /dev/random, and /dev/random then runs out of entropy, does it automatically switch to /dev/urandom? Is there an Apache document somewhere that explains all this?
Answer: It is not stated in Apache docs, but looking at ssl_engine_rand.c (apache 2.2.21 here) you can see that the function ssl_rand_seed iterates over all the defined SSLRandomSeed sources, ultimately calling the OpenSSL RAND_seed function unless there is a failure.
Refering to the OpenSSL man page for RAND_seed, every successful call to it will add entropy to the state of the PRNG.
At the end, it asks OpenSSL if seeding is sufficient trough RAND_status.
So, if you define many sources, it will use all of these that work, and combine their entropy.
Comment: Thanks for the pointer to file `ssl_engine_rand.c`; it does indeed show that all supplied methods are used and combined.


Validate json Payload before passing It

Question: HI there I am making post call using karate And for that I am passing json Payload but before i pass it i want to validate is there any null or empty string present and if yes then Abort the post call and print message empty string or null values cant be accepted.
Thanks in advance!
peter thomas Thank you in advance
Answer: This doesn't make sense to me, because if you are preparing this payload yourself, you never need to validate it.
That said, you can run a match anytime.
* def body = { myKey: 'myValue' }
* match body == { myKey: '#string' }

* url 'https://httpbin.org/anything'
* request body
* method post
* status 200
* match response contains deep { json: { myKey: 'myValue' } }

See how the second line does a validation.
Also refer this answer to see how you can programmatically run karate.match() for advanced use-cases: https://stackoverflow.com/a/50350442/143475

Validate json Payload before passing It


How would one prove, or disprove, that as $n$ goes to $0$, the curve described by $x^n + y^n = 2$ approaches that of $xy = 1$?

Question: I was playing around with $n$-norms a few years ago, and wondered, if the limit as $n\rightarrow\infty$ of the curve given by $x^n + y^n = 2$ was equivalent to $max(x,y) = 1$, how the curve would behave as we approached different values of $n$, such as zero or $-\infty$. Interestingly enough, the limit as it approaches $-\infty$ seems to be $min(x,y) = 1$, which was easy enough to guess based on observation, and even more interestingly, the limit as it approaches $0$ appears to be $xy=1$, which I also guessed by simple observation.
How would one go about proving or disproving these conjectures? (For those who are interested, I made an animation of the curve as $n$ varies from $-\infty$ to $\infty$, which is available here: https://youtu.be/WwrsmpjU1Y0)
Edit: I should have mentioned, I'm only considering the curve for $x,y\geq 0$.
Comment: I think you mean max(x,y)=1 respectively min(x,y)=1?
Comment: @KlaasvanAarsen yes of course, my mistake! I've edited the question.
Answer: Yes, your conjecture that the curve $x^n+y^n=2$ tends to $xy=1$ as $n\to 0$ is correct. Note that $x^n+y^n=2$ if and only if $y=(2-x^n)^{1/n}$. The question at hand here is whether or not this is the same as $1/x$ as $n\to 0$. This is equivalent to the question of whether or not the limit of their ratios is $1$. Well,
$$\begin{split}
\lim_{n\to0}\frac{(2-x^n)^{1/n}}{1/x}&=\lim_{n\to\infty}x\left(2-x^{1/n}\right)^n\\&=x\underbrace{\lim_{n\to\infty}\left(2-x^{1/n}\right)^n}_{L(x)}.
\end{split}$$
It turns out that this limit $L(x)$ is actually $1/x$, so the result is indeed true. To show this, take the logarithm and write the limit as
$$\log L(x)=\lim_{n\to\infty}\frac{\log(2-x^{1/n})}{1/n}, $$
then employ L'Hospital's rule to show that $\log L(x)=-\log x$. I'll leave this to you.
Comment: @YiFan Wow, this is much simpler than I thought! Thank you.
Comment: The guy that have put the downvote, for honesty, if he has it, he should cancel that downvote.
Comment: What if $2-x^n$ is negative though e.g., $x=1.5$ and $n>10$ is an even integer? Then what is $((2-x^n)^{1/n})^n$ again?
Comment: @YiFan for the revised question yes, I was going with mx$(x,y)=2$ which is how it was originally written
Comment: @Mike, yes, I see your point. Although the part about the curve $x^n+y^n=2$ approaching $xy=1$ was always in the question, and that was the part my answer is based upon.
Answer: The first conjecture is false. For even integers $n>10$ and $x > 1.5$ there is no $y$ satisfying $x^n+y^n < 2$.
So is the 2nd conjecture. For even integers $n > 10$ and any $x>2$, the value of $y$ cannot be any larger than 1.
Your conjectures would be true for curve
$\left(x^n+y^n\right)^{\frac{1}{n}} = 2$ though [restricted to $x,y >0$]. We show the first modified conjecture. Assuming WLOG that $x \ge y$, we show that $x$ must approach 2 from below. Indeed, for positive $n$ the string of inequalities hold:
$$x = (x^n)^{\frac{1}{n}} \le  2 = \left(x^n+y^n\right)^{1/n} \le (2x^{n})^{1/n} \le x(1+2/n)$$
How would you show the modified second conjecture.
Comment: Why was this downvoted? This is right
Comment: "For even integers $n>10$ and $x>1.5$ there is no $y$ satisfying $x^n+y^n<2$". Of course not. How is this even relevant to the question?
Comment: Well, if your conjecture that max($x,y) =2$ were true, then this would indeed imply an $x> 1.5$ and $n>10$ s.t. there is a $y$ .t $x^n+y^n \le 2$. Again that was the way you wrote the question originally.
Comment: I apologize for the original typo.


Using a NAS to store user files over iSCSI/NFS?

Question: I have an environment with servers (5-6) virtualized and hosted locally on the hypervisor.
They act as file servers, so am thinking of moving the files out to a NAS (TheCUS or QNAP) and share over iSCSI or NFS.
Both the vendors are "vmware" certified and can do iSCSI, but I am concern about the performance given that the server is virtualized, and the NAS is 2GB ram only (e.g. QNAP 809U-RP).
or should I stick to NFS? which is file based sharing...
Answer: I'd stick to NFS but not because of anything you've said.
In general iSCSI performance inside VMs is ok, certainly no enormous drop in IO rates but what does worry me is how you'd manage the clustered file system you'd be creating by mounting these iSCSI block-level disks inside two or more VMs. You don't mention your VM OS but few file systems that ship natively with ANY OS are cluster-aware, meaning almost instant data corruption. If you do choose to go down that route then for Windows I'd recommend using either Veritas Storage Foundation or Microsoft's own Cluster Services; for Linux I like Oracle's OCFS2 - either way don't use raw-NTFS or ext2/3/4.
So to conclude I think you'll have less complexity and therefore better supportability just using NFS.
Comment: My concern would be performance, for NFS.

For iSCSI, in this particular scenario, it would definitely be 1 iSCSI LUN to one VM, thats for sure.

If that is assured, will you suggest iSCSI then?

Thanks :)
Comment: I think either would be fine and although one would perform better than the other I wouldn't like to guess which of iSCSI or NFS it would be without knowing a lot more about your setup - either way there shouldn't be that much difference in speed.
Comment: I see :)

Well, thanks for the input :)


Duplicate nodes returned from a module's SQL query

Question: I'm in a spot of bother customizing the calendar block module for my needs. I've written a custom module that queries my database for published nodes that possess a specific taxonomy term. This works as desired; 3 node objects are returned as an array. However, this array is returned a total of 35 times. When I execute the query in my SQL manager the 3 rows are returned without repetition. Is there anything blatantly amiss in my code I haven't been able to spot?
/*
*
* Implementation of hook_calendar_block
*
*/

function calendar_block_mod_calendar_block(&$calendar, &$date, $op) {
  switch($op) {

   case 'alter':
                $sql = "SELECT DISTINCT node.nid AS nid
                                FROM {node}
                                INNER JOIN term_node term_node ON node.vid = term_node.vid
                                WHERE (node.status <> 0) AND (term_node.tid = 5)";

                $results = db_query($sql);

        while ($node = db_fetch_object($results))
        {
          $events[] = node_load(array('nid' => $node->nid));
        }

        foreach ($events as $var){
                $thisPath = $var->path;
                                $nodeTitle = $var->title;
                $thisDate = substr($var->field_event_date[0]['value'],0,10);
                                $realDay = substr($thisDate, 8,2);
                $realDate = substr($thisDate, 5, 2) . "-" . ( $realDay < 10 ? substr($realDay, 1,1) : $realDay ) ."-". substr($thisDate, 0, 4);

                                //$dayInfo[] = array ('date' => $realDate, 'title' => $nodeTitle,  'path' => $thisPath );

                                if ($date->date == $realDate) {

                                    $date->content = ''. l($date->day, $thisPath) .'';
                                    $date->content .= '
'. l($nodeTitle, $thisPath) .'
';

                                }
                            }
          break;

        case 'load':

        // Change the weekday's format and set the first day of the week to sunday.
        $calendar->weekdays =  array(
            'su' => 'S',
            'mo' => 'M',
            'tu' => 'T',
            'we' => 'W',
            'th' => 'T',
            'fr' => 'F',
            'sa' => 'S',
        );

        break;
  }

}

Edited to include all the code from my module - If anything I hope this can give others a similar starting point. if the code looks like a mess it's because it's my first module.
The code works: nodes with the desired taxonomy term are pulled from the database and each date on the calendar becomes a link to its corresponding node. However on closer inspection the 3 rows are returned 35 times, so doing anything beyond this (e.g. a choice of nodes if there are multiple ones on a single date) becomes a challenge / impossible.
Comment: Could it be that you run your code on every operation $op in the hook? Is there a `if($op=='foo')` or a `switch - case` anywhere in the hook?
Comment: In Drupal, you should write the table name between curly brackets.
Comment: Which hook is, exactly? I ask because it's not clear to me when you say that the code works and it returns an array with 3 objects, but the array is returned 35 times. It seems the code is executed 35 times, then.
Comment: Is the code executed inside a hook or a function that is invoked from a hook?
Comment: The code's executed inside the hook function I believe
Comment: Sorry - It's hook_calendar_block() which is provided by calendar_block module in order to alter the dates and presentation of the calendar. Edit: I can provide further code if it helps.
Comment: If you provide the full code of the hook you implemented, that would surely help.
Comment: node_load shouldn't use the 'nid' as parameter because this forces the module not to use the cached version of the node and load it all the times
Answer: I just took a quick look at the calendar_block module. From what I can tell, hook_calendar_block op alter is called for every single day in the calendar. I guess this makes sense at it allows you to alter the appearance of any day.
My guess is that the calendar on your site has 35 days in it which is why your query is run 35 times.
You could make use of a static variable to only do your stuff once or save the query etc.
Something like this could work:
function calendar_block_mod_calendar_block(&$calendar, &$date, $op) {
  switch($op) {
    case 'alter':
      static $events;
      if (empty($events)) {
        $sql = "SELECT DISTINCT node.nid AS nid
              FROM {node}
              INNER JOIN term_node term_node ON node.vid = term_node.vid
              WHERE (node.status <> 0) AND (term_node.tid = 5)";

        $results = db_query($sql);

        while ($node = db_fetch_object($results)) {
          $events[] = node_load(array('nid' => $node->nid));
        }
      }
      ....
  }
}

The above code doesn't catch the case where there is no result and is just meant as a proof of concept.
Update:
If you only want to run the entire code once, you could do something like this:
function calendar_block_mod_calendar_block(&$calendar, &$date, $op) {
  switch($op) {
    case 'alter':
      static $code_executed;
      if (!$code_executed) {
        ...
        $code_executed = TRUE;
      }
  }
}

Comment: Thanks googletorp :).. I should have noticed that the number of executions correlated to the number of days shown on each calendar month. The query is now executed only once and successfully returns the correct results, however my foreach statement is again executed 35 times.
Comment: @Steve you only need to run the entire code once, you can just put all if it in an if statement.


Sending data via href get Route Methode

Question: I build get Methode route to store data via controller in a mysql database.
Here you can see a part of my view
@foreach($groupsrequest as $grouprequest)
         $grouprequest->idgroup, 'iduser' => $grouprequest->iduser]) }}">
            Gruppe {{$grouprequest->group_name}} Anfrage von User {{$grouprequest->username}}

@endforeach

And this is my web route file which pass the data to controller where the data is going to store into the mysql db.
Route::get('/home/groupmgmt/approvel', 'GroupController@setGroupApprovel')->name('mgmtgroups_approvel');

Now my problem, after i clicked on the a href button I get the following url
http://localhost:8000/home/groupmgmt/approvel?idgroup=18445&iduser=123

and i can change the url parameter and press enter and then data will be stored. But this cannot be correct, because I am able to store fake data in the db. I can for example create userid which not exist. How to do this in the right way that this is not possible and only data which are shown in the view before can be stored in the db?
Comment: Use a POST route instead of a GET route
Answer: You can use exists validation type of laravel to validate existence of user ID.
BTW, if the ID is ID of logged in user then you don't need to pass it via query parameters, you can just get it using Auth::id() function of laravel.
Also I suggest you to use POST method instead of GET and add csrf token to the request to improve the security. Also you should validate the request to make sure nobody can insert invalid data to the database. For example if this is a registration approval script, you should make sure that the given ID is requested for registration on group otherwise you should show an error to the user.

Sending data via href get Route Methode


Rotation matrix in spherical coordinates

Question: When given arbitrary point on a unit sphere $a = (\theta, \phi)$ and an arbitrary axis $\vec{A}=(\Theta, \Phi)$, can we have an algebraic expression for $a_1=(\theta_1, \phi_1)$ which is a rotation of $a$ around $\vec{A}$ to the angle $\beta$?
Points and axes are not on the coordinate planes, values are not trivial: $\theta \neq 0$, $\phi \neq 0$, $\Theta \neq 0$, $\Phi \neq 0$, $\beta \neq 0$.
Can this be done without transformation through Cartesian? Otherwise the analytic form becomes too complicated. If there is a particular case for $\Phi \rightarrow 0$ ($\sin{\Phi} \approx \Phi$, but not for the other values) it is also fine.
Thanks
Comment: I find the exponential notation (ie in terms of the Lie group elements for the system in question) to be the most enlightening.
Answer: I think what you might be looking for is Rodrigues' Rotation Formula. Using spherical coordinates:
Your arbitrary point on the unit sphere is:
$$
\mathbf{a} = (\sin\theta\cos\phi, \sin\theta\sin\phi, \cos\theta)
$$
Your arbitrary axis is represented by the unit vector:
$$
\hat{\mathbf{k}} = (\sin\Theta\cos\Phi, \sin\Theta\sin\Phi, \cos\Theta)
$$
Then the result of rotating $\mathbf{a}$ around $\hat{\mathbf{k}}$ by the angle $\beta$, using the right-hand-rule, is given by

$$
\mathbf{b} = \cos\beta\,\mathbf{a} + \sin\beta\,(\hat{\mathbf{k}} \times \mathbf{a}) + (\hat{\mathbf{k}}\cdot\mathbf{a})(1-\cos\beta)\,\hat{\mathbf{k}}
$$

Of course, now $\mathbf{b}$'s Cartesian coordinates need to be converted to spherical:
$$
\tan\phi' = \frac{b_y}{b_x}
\qquad\mbox{and}\qquad
\tan\theta' = \frac{\sqrt{b_x^2 + b_y^2}}{b_z}
$$
so that
$$
\mathbf{b} = (\sin\theta'\cos\phi', \sin\theta'\sin\phi', \cos\theta')
$$
The same article on Rodrigues' Formula also discusses a matrix representation of the rotation operation in question.
Comment: Thanks a lot, exactly what I needed. The matrix representation is much cleaner, IMO.
Answer: Rotations in spherical coordinates are affine transformations so there isn't a matrix to represent this on the standard basis $(\theta,\phi)$, you'll need to introduce another coefficient here: $(\theta,\phi,1)$, the rotation matrix in the $\theta$ direction is then, for example, rotating by $\alpha$ is;
$R(\alpha) = \left( \begin{array}{ccc}
1 & 0 & \alpha \\
0 & 1 & 0 \\
0 & 0 & 1 \end{array} \right) $
Comment: Ok, thanks, and what about the axis of rotation? shoudn't it go somehow into the matrix terms?
Answer: In this post I explain how to deal when the rotation axis is one of the Cartesian axes.
For an abritrary rotation axis $\vec{A}=(\Theta,\Phi)$, using the same notations, the formula is
$$
(\theta', \phi') = (Q^{-1} \circ R_{\vec{A}}(\beta) \circ Q)(\theta,\phi)
$$
where the rotation operator $R_{\vec{A}}(\beta)$ is
$$
R_{\vec{A}}(\beta) = R_z(\Phi)R_y(\Theta)R_z(\beta){R_y(\Theta)}^\dagger{R_z(\Phi)}^\dagger
$$
("${}^\dagger$" is the notation for the conjugate transpose).


2020-10-16 21:53:19 [scrapy.core.scraper] ERROR: Spider must return request, item, or None, got 'str' in

Question: I am try to extract some quotes from  here using Scrapy but I am running into some kind of problem. here is my code.
import scrapy
start_urls=['https://www.goodreads.com/quotes']
for number in range(1,11):
  start_urls.append('https://www.goodreads.com/{}'.format(str(number)))

class quotes(scrapy.Spider):
name='goodreads_quotes'
def start_requests(self):
    urls=start_urls
    for url in urls:
        yield scrapy.Request(url=url,callback=self.parse)

def parse(self,response):
    quotes=response.css('div .quoteText::text').extract()
    for quote in quotes:
        if len(quote)>10:
           yield quote

Every time I try to run it in scrapy shell, I get the following error
2020-10-16 21:53:16 [scrapy.core.engine] INFO: Spider opened
2020-10-16 21:53:16 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0
items (at 0 items/min)
2020-10-16 21:53:16 [scrapy.extensions.telnet] INFO: Telnet console listening on 127.0.0.1:6023
2020-10-16 21:53:17 [scrapy.core.engine] DEBUG: Crawled (200) <GET
https://www.goodreads.com/robots.txt> (referer: None)
2020-10-16 21:53:19 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.goodreads.com/quotes>
(referer: None)
2020-10-16 21:53:19 [scrapy.core.engine] DEBUG: Crawled (404) <GET https://www.goodreads.com/7>
 (referer: None)
2020-10-16 21:53:19 [scrapy.core.engine] DEBUG: Crawled (404) <GET https://www.goodreads.com/2>
(referer: None)
2020-10-16 21:53:19 [scrapy.core.engine] DEBUG: Crawled (404) <GET https://www.goodreads.com/5>
(referer: None)
2020-10-16 21:53:19 [scrapy.core.engine] DEBUG: Crawled (404) <GET https://www.goodreads.com/3>
(referer: None)
2020-10-16 21:53:19 [scrapy.core.scraper] ERROR: Spider must return request, item, or None, got 'str'
in <GET https://www.goodreads.com/quotes>
2020-10-16 21:53:19 [scrapy.core.engine] DEBUG: Crawled (404) <GET https://www.goodreads.com/6>
(referer: None)
2020-10-16 21:53:19 [scrapy.core.engine] DEBUG: Crawled (404) <GET https://www.goodreads.com/4>
(referer: None)
2020-10-16 21:53:19 [scrapy.core.engine] DEBUG: Crawled (404) <GET https://www.goodreads.com/1>
(referer: None)
2020-10-16 21:53:19 [scrapy.spidermiddlewares.httperror] INFO: Ignoring response <404
https://www.goodreads.com/7>: HTTP status code is not handled or not allowed
2020-10-16 21:53:19 [scrapy.core.scraper] ERROR: Spider must return request, item, or None, got 'str'
in <GET https://www.goodreads.com/quotes>
2020-10-16 21:53:19 [scrapy.core.scraper] ERROR: Spider must return request, item, or None, got 'str'
in <GET https://www.goodreads.com/quotes>
2020-10-16 21:53:19 [scrapy.core.scraper] ERROR: Spider must return request, item, or None, got 'str'
in <GET https://www.goodreads.com/quotes>
2020-10-16 21:53:19 [scrapy.core.scraper] ERROR: Spider must return request, item, or None, got 'str'
in <GET https://www.goodreads.com/quotes>
2020-10-16 21:53:19 [scrapy.core.scraper] ERROR: Spider must return request, item, or None, got 'str'
in <GET https://www.goodreads.com/quotes>
2020-10-16 21:53:19 [scrapy.core.scraper] ERROR: Spider must return request, item, or None, got 'str'
in <GET https://www.goodreads.com/quotes>

2020-10-16 21:53:19 [scrapy.spidermiddlewares.httperror] INFO: Ignoring response <404
https://www.goodreads.com/9>: HTTP status code is not handled or not allowed
2020-10-16 21:53:19 [scrapy.core.engine] INFO: Closing spider (finished)

Does anybody have any suggestions, that can help me successfully scrape the site?
Answer: As the error points out, a parse function must return a request, item, or None.  It errors because you are trying to return a str.  Instead of returning a str, you can solve this by creating a class that inherits from scrapy.Item and holds the data you want:
# Create a scrapy.Item class which will hold all the scraped data
class Quote(scrapy.Item):
    text = scrapy.Field()
    # any additional info you want to put in a quote...

class QuoteSpider(scrapy.Spider):
    ...

    def parse(self, response):
        quotes = response.css('div .quoteText::text').extract()
        for quote in quotes:
            if len(quote) > 10:
               # We return a Quote scrapy.Item instead of a string!
               yield Quote(text=quote)

Answer: It looks like you forgot to define the fields. Go to items.py file and paste the code written below inside the class:
 quotes = scrapy.Field()


add light box effect to login, create account form

Question: How to add light box effect to login, account creation, forget password and password reset forms?
Comment: Could you please show at least _some_ effort yourself? It's bad form to try to use this site to get people to do your work for you; your current low-quality "do it for me" approach will always be met with negative responses. Instead of writing a single, high-level specification for someone to fill in for you, you need to write a proper question that describes the background of your situation, and, importantly, what you've tried yourself. Please see the [help center](http://drupal.stackexchange.com/help) if you need more details on what this site is about, and the quality we expect here. Thanks
Comment: Sorry Clive, I searched on google regarding this. But I didn't get result. That's why asked question directly. I will go through the help centre. Thanks for guide.
Comment: That might've sounded a bit harsh actually - not my intent at all, so sorry if that's the case. We're trying to build a repository of high quality Q+A here, so every question/answer comes under a certain amount of scrutiny. The quality/scope requirements may seem a bit pedantic at first, but it really does make for a better quality of overall site when that logic is applied over a good period of time. Thanks for your understanding
Answer: Go to admin/config/lightbox2 and then expand the Modal form settings and check the first option.

or you can try Ajax Login/Register module see the demo.

This module provides a smooth way for the user to login, register and
  request new password via AJAX at any Drupal site.

or you can try Popup module and don't forgot to read the documentation

The popup suite allows builders to popup tooltip-like text, nodes,
  blocks, menus, forms, views and php-generated content.
Comment: I used lightbox2 module as you pointed out with bartik theme and it is not working for me.
Comment: @dhinesh what happen when you click on the login link ?
Comment: @dhinesh it will work on clicking the login link, not on viewing the login page, when you are in example.com/user/login
Comment: @dhinesh make an anchor tag like this "Login" and check if it is open as popup, if not let me know.
Comment: Did you try 'https://drupal.org/project/modal_forms' module. It will not show the user login form with lightbox library but will display in modal window.
Comment: @JayendraKainthola always use notation before name like I done, otherwise he will not be intimated
Comment: @dhinesh, Did you try 'drupal.org/project/modal_forms'; module. It will not show the user login form with lightbox library but will display in modal window.
Comment: I entered user name and password and clicked on login button. I didn't see lightbox effect. Then I clicked on Create new account and Request new password links. Default account creation and request password page opened without any effect. After that I created a content, inside that I gave Login. When I click on Login I do not see lightbox effect but it redirects to login page. I'm not yet used Modal Forms but I currently using https://drupal.org/project/ajax_register module. Give me your suggestion please.
Comment: @dhinesh Ok try like this Login
Comment: I gave Login. Lightbox effect comes but username and password fields not showing up.
Comment: @dhinesh I updated my answer, since you are struggling to setup correctly the lightbox module, alternatively you can try the  Ajax Login/Register module, It will match your case exactly.


Drush 9 can't find installed module, yields CommandNotFoundException

Question: On my newly installed Drupal 8.4.4 sandbox installation, I've installed Drush 9 and the Devel module:
composer require drush/drush:^9
composer require drupal/devel

After running these commands, I installed the Devel module using the Extend tab in Drupal.
Drush seems be be installed correctly:
www-data@39e134dc7690:~/html$ /var/www/html/vendor/bin/drush version
Drush version : 9.1.0

The Devel modules seems to be installed correctly:
www-data@39e134dc7690:~/html$ grep -r devel-container-service /var/www/html/modules/contrib/devel/
/var/www/html/modules/contrib/devel/src/Commands/DevelCommands.php:   * @aliases devel-container-services,dcs,devel-services
/var/www/html/modules/contrib/devel/drush/devel.drush8.inc:  $items['devel-container-services'] = array(

But Drush doesn't seem to find the devel module:
www-data@39e134dc7690:~/html$ /var/www/html/vendor/bin/drush devel-container-services
[Symfony\Component\Console\Exception\CommandNotFoundException]
Command "devel-container-services" is not defined.

Are there any path settings I need to tweak to get Drush to find the Devel module?
Comment: `drush cc drush; composer dump-autoload; drush cr`. Any better after running that?
Comment: Thanks for the reply. I ran the commands you suggested, but unfortunately thing still fail:

    www-data@39e134dc7690:~/html$ export PATH=$PATH:/var/www/html/vendor/bin drush cc drush; composer dump-autoload; drush cr; drush devel-container-services
Generating autoload files
> Drupal\Core\Composer\Composer::preAutoloadDump
> Drupal\Core\Composer\Composer::ensureHtaccess
 [success] Cache rebuild complete.
  [Symfony\Component\Console\Exception\CommandNotFoundException]
  Command "devel-container-services" is not defined.
Answer: I looks like I simply had forgotten to enable (i.e install) the module in /admin/modules. I had just ran "composer require", but not actually enabled it.
Answer: I encountered this issue when attempting to port an older global Drush command. While following the porting instructions generated the necessary Drush code, the command was not discovered by drush because it wasn't part of an enabled module.
If this is your issue, either create a module_name.info.yml file manually, or run drush generate module, then enable the module in question. The drush command no longer threw a CommandNotFoundException.
Comment: Thanks for the reply, I'll test this when I get the chance. But before that I need to verify that I actually enabled (i.e. click "install" in the Drupal GUI) the Devel module in Drupal after installing it - it's possible I forgot to enable it.


Error loading svg data with html2canvas and jspdf

Question: I have a very simple svg

    test
    <svg height="100" width="100">
        <circle cx="50" cy="50" r="40" />
    </svg>

and trying to print it with html2canvas and jspdf. But whatever I do I get an error
Error loading svg data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20height%3D%22100%22%20width%3D%22100%22%20style%3D%22-webkit-writing-mode%3A%20horizontal-tb%3B%20-webkit-user-modify%3A%20read-only%3B%20-webkit-user-drag%3A%20auto%3B%20-web
Oe.error @ html2canvas-1.1.2.min.js:20

and test.pdf file with just word test in it.
I googled this for about 3 hours, and in every place people recommend settings width/height atributes. Which, as you can see, doesn't help in my case.
I've simplified it as much as I could. Here is the full index.html I use:
<!DOCTYPE html>

        test
        <svg height="100" width="100">
            <circle cx="50" cy="50" r="40" />
        </svg>

    <input type='submit'
            onclick='saveAsPDF();'
            value='save'>

I also tried all possible versions of html2canvas:
1.1.2
1.1.5
1.2.2
1.3.2
and two versions of jspdf:
2.1.1
2.3.1
And two browsers: Chrome and Opera.
What can be my issue?
Edit:
I managed to make html2canvas work on it's own with the document below. Now the question is how to make it work with jspdf together:

                this is circle:
            <svg height="100" width="100">
                <circle cx="50" cy="50" r="40" />
            </svg>

Image of above HTML content...

Answer: It looks like jspdf is not able to add svg as vector graphic to a page. There are three options:

Use svg2pdf instead of jspdf to convert svg to pdf on it's own.
Use addSvgAsImage function of jspdf to place an svg in the pdf page manually.
Convert svg to jpg first, then use jspdf.

I've chosen the 3rd option and wrote a function, which I run before saving canvas as pdf:
htmlToJpg: function()
{
    var canvas = document.querySelector('.to-print');
    screenWidth = parseFloat(window.getComputedStyle(canvas).width);

    var problematic = document.querySelectorAll('.convert-to-jpg');
    problematic.forEach(function(el) {
        html2canvas(el,
            {
                scale: 2480/screenWidth // 2480px - size for A4 paper, 300 dpi
            }
        )
        .then(function(canvas) {
            var img = canvas.toDataURL("image/jpeg");
            el.innerHTML = '';
        });
    });
}

Answer: import html2canvas from 'html2canvas';
import { jsPDF as JsPDF } from 'jspdf';
import { useCallback, useEffect } from 'react';

export const useDownloadPdf = (name: string, isReady: boolean) => {
 useEffect(() => {
   if (isReady) {
    const fileName = `${name}.pdf`;
    const pdf = new JsPDF({
    orientation: 'p',
    unit: 'mm',
    format: 'a4',
    putOnlyUsedFonts: true,
    });

    const convertElements = document.querySelectorAll('.convert-on-pdf');
    const elements = Array.from(convertElements) as HTMLElement[];

    if (elements.length > 0) {
      Promise.all(
        elements.map(async (element) => {
          const canvas = await html2canvas(element);
          element.replaceWith(canvas);
      }),
      ).then(() => {
        pdf.html(document.body, {
          callback: (generatedPdf) => {
            generatedPdf.save(fileName)
          },
        });
      });
    } else {
      pdf.html(document.body, {
        callback: (generatedPdf) => {
        generatedPdf
          .save(fileName)
        },
      });
    }
  }
}, [isReady, name, setAtribute]);}

Comment: Welcome to SO! Please don't post code-only answers but add a little textual explanation about how and why your approach works and what makes it different from the other answers given. You can find out more at our ["How to write a good answer"](https://stackoverflow.com/help/how-to-answer) page.


UIView appears when keyboard is displayed but then disappears when I start to type (swift)?

Question: I have a UIView container which holds a UITextField and two UIButtons (see image below).
I have written an extension which listens to a UIKeyboardWillShow notification and animates the  UIView so that it binds to the keyboard when it shows.
This works perfectly, but as soon as I start typing the UIView disappears again.
Extension usage:
sendMessageView.bindToKeyboard()

UIView extension:
extension UIView {

    func bindToKeyboard() {

        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

    }//end func

    @objc func keyboardWillShow(notification: NSNotification) {

        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double

        let curve = notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! UInt

        let beginningFrame = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue

        let endFrame = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue

        let deltaY = endFrame.origin.y - beginningFrame.origin.y

        UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIViewKeyframeAnimationOptions(rawValue: curve), animations: {
            self.frame.origin.y += deltaY
        }, completion: nil)

    }//end func

}//end extension

UIView binds to keyboard when it is displayed:

UIView disappears (I suspect behind the keyboard to its original location) when typing:
Comment: Can you throw a couple of print statements in there to see how many times your function is called? Also, I want to point out, as a friendly tip, that if you add observers, it's good practice to remove them as well. I would write an extension that does that on deinit or something.
Comment: I put a `print("bindToKeyboard() called...")` statement in my `bindToKeyboard()` function and it is called once only when `viewDidLoad()` runs. It is not called again even after I tap into the text field to bring up keyboard. ps: thanks for the tip re: removing notifications.
Comment: Did you place it in the `keyboardWillShow(notification: NSNotification)`
Comment: this time I did, I added `print("keyboardWillShow() called...")` and it is called once when I tap on the textfield, but as soon as I start to type the view disappears.
Comment: I was thinking that maybe your view position was recalculated when keyboardWillShow() was called and maybe it was being called multiple times. Keeping in mind that the top of the keyboard will change when the user types, I will keep checking around.
Comment: I have put constraints on the `UIView` via the storyboard to pin it left, right and bottom, would this be causing an issue perhaps, you think?
Comment: Most definitely. Especially if you've pinned the top and bottom to other objects. I found something that may give you the same effect that you are looking for. Maybe you could take a look.

https://stackoverflow.com/questions/35689528/add-a-view-on-top-of-the-keyboard-using-inputaccessoryview-swift
Answer: Don't put an extension for the UIView itself. Just add your textBox view as a subview and set the bottom constraint of your view to be updating according to the height of the keyboard. If keyboard is present, set the constant to the negative value of height of the keyboard else set it to zero.
    private func setupView() {
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardShown(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        self.view.backgroundColor = .white
        self.view.addSubview(textInputView)
        bottomConstraint = NSLayoutConstraint(item: textInputView, attribute: .bottom, relatedBy: .equal, toItem: view.safeAreaLayoutGuide, attribute: .bottom, multiplier: 1.0, constant: 0)
        NSLayoutConstraint.activate([
            //textBox.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0),
            //textInputView.heightAnchor.constraint(equalToConstant: UIFont.systemFontSize+14+10),
            textInputView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 0),
            textInputView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: 0)
        ])
        bottomConstraint.isActive = true
    }

    @objc private func keyBoardShown(_ notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
            print(keyboardSize.height)
            bottomConstraint.constant = -keyboardSize.height
            UIView.animate(withDuration: 0.5,
                           delay: TimeInterval(0),
                           options: .beginFromCurrentState,
                           animations: { self.view.layoutIfNeeded() },
                           completion: nil)
        }
    }


Is there any way to get the "center" channel having a stereo track?

Question: Context:
I am really beginner. I know about sample rates, bit depth, but practically never used any DAW. Now I've installed Audacity and Sonar.
To give a real life example:
I use Aebersold backing tracks. Bass pure left, drums pure center, piano pure right. I would like to render out the piano, and record my guitar track there.
The easy solution would be to split the stereo track to two mono tracks and take the left track. However I am not satisfied with this solution, because the drum level is somehow decreased, but more importantly the drum and the bass will share a mono track this way, which means wherever I will pan this track later they stuck together forever.
The ultimate goal I would like to achieve to having a bass left, drums center, but no piano.
Theoretic question
Is there any way to separate left, center, right to three separate tracks? (where those signals are really pure left, center, right with no echoes and center is real mono, with no phase difference fancies etc.)
If not, then end of story.
Practical question
If yes, then any practical help how to do this in Sonar will be appreciated.
Comment: similar to http://music.stackexchange.com/questions/6344/removing-human-voice-from-songs -- though this question is phrased a bit different in that it is about the stereo mix and not in terms of a specific instrument (which may or may not be uniquely assigned to a single stereo track).   Despite this difference, most of the issues/difficulties of this that problem apply to this one.
Comment: The theoretical problem falls in the class of "blind signal separation" https://en.wikipedia.org/wiki/Blind_signal_separation
Comment: not putting this as an answer because I'm not sure, but backing track apps like iReal Pro may have versions of most of the Aebersold tracks, and in iReal you can select playback of the different instruments, as well as export to wav, so selecting different source material may be best way to do it.
Answer: You asked (bold emphasis added):

Is there any way to separate left, center, right to three separate tracks? (where those signals are really pure left, center, right with no echoes and center is real mono, with no phase difference fancies etc.)

Pretty much no. The only way to separate the drums from the rest would be by comparing the left and right channels and either selecting or rejecting the information that matches, and even though that's done all the time, there will always be artifacts (e.g., phase differences, etc.) on both the resulting bass and drum tracks.


Lilypond: merging notes from two voices to one beam OR faking note length

Question: Chopin's Raindrop prelude, first measure.
The notes marked in red technically do not fit into their group (connected by the beam). If I define two voices however, they will be no longer connected to the beam. There are official editions out there that do separate those two note from the group, but I really prefer the way  shown in the picture.
But how would I do this? How do I connect both "wrong" notes to this beam? Can I just fake and override the duration of these notes? I did not find a way to do this. And merging notes – as far as I found – only deals with same notes but different types of heads at the same time.

Edit: As I continued to look for solutions I found a way to fake the duration:
\override NoteHead.duration-log = #1 <des' f'> \revert NoteHead.duration-log
But still: Is there an elegant or correct way to deal with this via voicings?
Answer: Lilypond does have this wonderful little macro \mergeDifferentlyHeadedOn. Using this we can easily achieve this:
\new PianoStaff <<
  \new Staff {
    \key des\major
    f''8. des''16 as'2 bes'4
  }
  \new Staff {
    \clef bass
    \key des\major
    \mergeDifferentlyHeadedOn
    <<
      {
        s4 <des' f'>2 4
      }
      \\
      {
        des8 as des' as as as des' as
      }
    >>
  }
>>

Note that this is technically slightly different from the engraving here, as this would gives us the (eighth) Db with a stem down and the (half) Db and F with a stem up. The engraving here does this reversely, so only the F has a stem up while both notes are on the stem down.
So the way Lilypond does this does make more sense musically. By the way in the autograph Chopin notated this without a stem up.
Comment: Works like a charm! And after re-readings your explanation about 20 times, I _think_ I _begin_ to understand what Lilypond does there. Thank you!


Is there a (linear) functional $f\in (C[-1,1])^*$ such that $f$ maps even continuous function to $0$ and odd continuous function to its infinite norm

Question: Is there a (linear) functional $f\in (C[-1,1])^*$ such that for any even function $g$ in $c[-1,1]$, $f(g)=0$, and for any odd fucntion  $h$ in $c[-1,1]$,  $f(h)=||h||_\infty$?
Comment: You call a function $g \in C([0,1])$ even or odd iff ...? If with $h$ also $-h$ is odd, then such an $f$ cannot be linear.
Comment: Even function is even symmetric w.r.t middle point of domain, To avoid $\frac{1}{2}$, I change the space.
Comment: But I still suspect that f is not linear on odd functions.
Comment: Do you mean "linear functional?" Because there are non-linear functionals.
Comment: @Thomas Andrews, Although I changed the problem, but I think there non-linear functionals, we don't consider them often.
Comment: @Shine Well, we use them all the time we we use norms, and the fact that a norm here is referenced means we might be talking non-linear. In particular, all linear functions that are not everywhere zero take negative values.
Answer: The question didn't originally  ask for a linear functional, merely a functional.
If $g\in C([-1,1])$ then define:
$$f(g)=\sup_{x\in[-1,1]} \left|\frac{g(x)-g(-x)}{2}\right|$$
is such a continuous but non-linear functional.
Comment: Yes, it Looks good.
Answer: If $h$ odd, then so is $-h$. So if such functional $f$ existed, then we would have
$$
f(h)=\|h\|_\infty=\|-h\|_\infty=f(-h),
$$
which would imply that $\|h\|_\infty=0$, for every odd function $h$ - a contradiction.
Comment: Yes, $f$ can't be linear on the collection of odd functions.
Comment: Do you think we can find such $f$ is we only demand that for one given odd function $h_0$,  $f(h_0)=||h_0||_\infty$ and $f$ maps even function to $o$?


ODE compartmental model: waiting time

Question: Here is a ODE compartmental model made of 3 equations :
$\frac{dX}{dt}=-\alpha X$
$\frac{dY}{dt}=\alpha X-\beta Y$
$\frac{dZ}{dt}=\beta Y$
$X$, $Y$, $Z$ represents, in my case, the total number of people being in the state/compartment/case $X$, $Y$ or $Z$ (it could be a SIR model) and we assume that each individual can move from $X$ to $Y$ and from $Y$ to $Z$ with the respective rates $\alpha$ and $\beta$.
Let's $w_{XY}$ be the average waiting time for an individual being in $X$ before moving to $Y$. This rate is often calculated/estimated as $w_{XY}=1/\alpha$.
First question: Is it an approximation or is the exact result? How is it obtained? Should we make more assumptions to find it?
Second question: Let's assume now that they are more exits that leave $X$. Will the waiting time $w_{XY}$ still be $w_{XY}=1/\alpha$? Again, how is it obtained?
Comment: Should the second equation be $$\dfrac{dY}{dt}$$
Comment: Yeah thanks, corrected now
Answer: Here's the kicker: we're operating under the assumption that the population of compartment $X$ is exponentially distributed, and that its rate of change (probability of change per unit time) is $\alpha.$ Its probability density function is $$f(t)=\begin{cases}\alpha e^{-\alpha t}&t\ge0,\\0&t<0.\end{cases}$$ This means that the probability of a member of that compartment leaving prior to time $T$ will be $$\int_{-\infty}^Tf(t)\,dt$$ in general. For positive $T,$ this will be $$\int_0^T\alpha e^{-\alpha t}\,dt=\left[-e^{-\alpha t}\right]_{t=0}^T=1-e^{-\alpha T},$$ but it will otherwise be $0.$
To find the average waiting time, we need the expected value: $$\int_{-\infty}^\infty tf(t)\,dt=\int_0^\infty\alpha t e^{-\alpha t}\,dt=\left[-\frac1\alpha(\alpha t+1)e^{-\alpha t}\right]_{t=0}^\infty=\frac1\alpha.$$

Now, if we're talking about a "population" of a compartment, we're probably dealing with a discrete case, in actuality, so this should be considered an approximation. If there are more exits, I'm not sure $w_{XY}$ even makes sense.

ODE compartmental model: waiting time


Control Show/Hide multiple DIV using CSS, Javascript, and Anchor without unique ID

Question: I have an older JavaScript/CSS file that used to (no longer works in current browsers) toggle the display properties for multiple divs by way of anchor tags. The CSS document.stylesheets would toggle based on value "rules", that required the style to be in a specific sequence to control the "none" to "block" toggling (or the reverse). Here is a link to the JSFiddle example:
JSFiddle
Here is the JavaScript:
function NorB(arg){
if (arg=="n") {
    document.styleSheets[0].rules[0].style.display=='block';
    document.styleSheets[0].rules[1].style.display=='none';
} else {
    document.styleSheets[0].rules[0].style.display=='none';
    document.styleSheets[0].rules[1].style.display=='block';
}

}
Here is the HTML:

Narrative >

List View >

Narrative text

List Item A

List Item B

List ITem C

Narrative 2>

List View 2>

Narrative 2 text

List 2 Item A

List 2 Item B

List 2 ITem C

And lastly, the CSS:
        .n {
        display:block;
    }
    .b {
        display:none;
    }
    .b ul {
        margin-left:3px;
        margin-top:0px;
        margin-right:10px;
        margin-bottom:-2px;
    }
    .b ul li {
        list-style-type:square;
        list-style-position:outside;
        line-height:12px;
    }
    .buttons {
        position:relative;
        width:300px;
    }
    .narButton {
        width:80px;
        float:left;
        padding:2px 0px 2px 5px;
    }
    .bulButton {
        width:80px;
        float:left;
        padding:2px 0px 2px 5px;
    }
    .bulButton a, .narButton a {
        font-size:14px;
        font-style:normal;
        text-decoration:none;
    }
    .narrativeContent {
        border-top:1px solid #CCC;
        border-bottom:1px solid #CCC;
        padding:5px;
    }

Since there is a large number of div/anchor elements on the page, the goal is to avoid creating unique IDs for each, and continue to use basic CSS/JavaScript (avoid using jQuery and the like). Thoughts on how to keep this simple?
Comment: This is usually done by changing classes of the elements, not by changing the CSS on the fly.
Answer: Append these CSS
.b-mode .b, .n-mode.n {
    display:block;
}
.b-mode .n, .n-mode.b {
    display:none;
}

Modify onclick action

Modify Javascript
function NorB(e, arg) {
    var wrapper = e.parents('.narrative');
    var rm = arg == 'n' ? 'b' : 'n';
    wrapper.classList.add(arg + '-mode');
    wrapper.classList.remove(rm + '-mode');
}
Object.prototype.parents = function (selector) {
    if (selector.length == 0) return;
    var prefix = selector.substr(0, 1);
    if (prefix != '#' && prefix != '.') return;
    var selector = selector.substr(1);
    var p = this.parentNode;
    while (p !== null) {
        switch (prefix) {
            case "#":
                if (p.getAttribute('id') == selector) return p;
                break;
            case ".":
                if (p.classList.contains(selector)) return p;
                break;
        }
        p = p.parentNode;
    }
    return null;
};

http://jsfiddle.net/ypnospae/
Comment: Not quite. Each row has two buttons that toggle between a short text messages and a set of list items. Each row works independently of all other rows, but in this jsfiddle clicking on one row toggles the other row as well. Since the class name is the same for each row, I would expect each occurrence to toggle across all the rows.
Comment: Most awesome! Thought I was going to be stuck using the DIV IDs to sort through and find the class specific to what was being toggled. Thank you so very much!
Answer: Parfait's script is exactly what was needed:
function NorB(e, arg) {
    var wrapper = e.parents('.narrative');
    var rm = arg == 'n' ? 'b' : 'n';
    wrapper.classList.add(arg + '-mode');
    wrapper.classList.remove(rm + '-mode');
}
Object.prototype.parents = function (selector) {
    if (selector.length == 0) return;
    var prefix = selector.substr(0, 1);
    if (prefix != '#' && prefix != '.') return;
    var selector = selector.substr(1);
    var p = this.parentNode;
    while (p !== null) {
        switch (prefix) {
            case "#":
                if (p.getAttribute('id') == selector) return p;
                break;
            case ".":
                if (p.classList.contains(selector)) return p;
                break;
        }
        p = p.parentNode;
    }
    return null;
};

Learning every day, and the mentoring is greatly appreciated!


Statistical significance for a dataset of males vs. females

Question: I have a dataset of about 100,000 individuals, each of which is assigned a score between 1 and 5. Let's assume half are male and half are female, so 50,000 each.
I find that the average score for males is 3.9 whereas the average score for women is 3.6. How do I determine if gender has a statistically significant role? For reference, the scores do not follow a normal distribution.
Would a chi-squared test be appropriate by comparing this to the expected case of the results being identical for males and females?
Comment: Something to be wary of: if you do find that men and women have a significantly different distribution of scores, don't then immediately conclude that it's because women are worse at whatever task they're being scored on. The distributions of men and women that you have may well be different for some confounding reason.
Comment: Is the question specifically about whether the population means differ, or is it something else (e.g. do the distributions differ? Is the probability that a random male scores more than a random female different from 50%?)...? Do you have anything more than the averages like the original data? (you can still work with only the information you have mentioned, but if you have the data it's easier to justify to other people without a lot of explanation)
Comment: @Dougal We should assume the experiment is non-biased, unless otherwise.
Comment: @StudentT I only meant the standard correlation-is-not-causation caveat, since this seems like a setting where misinterpretation of those results is easy.
Answer: This looks like a Wilcox rank sum test (Mann–Whitney U test) to me.

It's a non-parametric test
The null hypothesis is that the two samples come from the same population
Assuming your observations in male and female are independent
Your data is ordinal, for example 3.9 is better than 3.6

Please note with 50,000 sample size, you test will most likely be significant. You may want to take a smaller sample for the test.
Comment: If the scores are being averaged, they were already assumed to be at least interval when they were added together (since that treats 2+3 the same as 4+1 for example)
Answer: I would suggest using the Kolmogorov-Smirnov Test to determine if these two datasets differ significantly. It is non-parametric, so this suits your dataset.
An advantage of the K-S test is that you can plot the cumulative fraction of the two groups and view these graphically.
Answer: With approx n=50,000 in each sample, there's no point in a statistical test since it will most likely be statistically significant regardless of the meaning of the difference. Instead, I'd plot the two distributions (histograms and boxplots) and carefully consider what is the practical meaning of a difference of 0.3 between the two genders. Most importantly, the question is: what will this result be used for? Is it really the averages that you need to compare?


How to get Amazon ELB to handle large traffic ramps?

Question: We have a system that is currently in Amazon Ec2. I use Amazon ELB right now to load balance across 12 instances in 2 zones. I've been running some load tests with different characteristics:
1) a ramp of simultaneous users from 0 to 10,000 over 60 minutes.
2) a stepped ramp starting at 2,500 for 15 min, to 5,000 for 15 min, to 7,500 for 15 min, to 10,000 for 15 min.
On both, my servers sit around 20-30% cpu, 10-15% network and seem to perform nicely, our app logs everything as expected and is responding very quickly on the machine throughout the entire test. My traffic Requests per second on these machines seem to be pretty spikey and exhibits some weird behavior. One example being servers in zone 1 will drop 200-400 requests per second while servers in zone 2 will simultaneously jump up by 200-400 requests per second. All this while still responding just fine.
However, the results I see from the external load test are much different. I see a lot of timeouts and connection reset errors. Those timeouts and connection errors are somewhat spikey as well, meaning I'll go 5 minutes with no errors then get a little flood of them then back to nothing for awhile.
I'm suspecting the ELB may be rebalancing or something that is causing some of this behavior. I did try to move to just a really beefy hardware running HAPRoxy. That seemed to solve some of the issues on the lower end of the load test ramp, but then seemed to get network starved and couldn't go much beyond 5-6K requests per second.
I'm wondering if anyone has any insight into the Amazon ELB behavior? Also if there are any workarounds to this? That may include completely different solutions...
Thanks,
MikeD
Comment: See: http://www.tocker.ca/2013/05/01/benchmarking-and-prewarming-Amazon-ELBs.html
Answer: Answering my own question. I happened to come across this thread (https://forums.aws.amazon.com/thread.jspa?threadID=76834) that made an obscure reference to something called ELB Pre-Warm. I called up Amazon AWS Support and was told that it was indeed a service they offered, you just have to have a support plan (Gold level if you want to call them). They set everything up for me and I was able to run a successful load test with a ramp from 0-10K QPS in 5 minutes.


Is this key-oriented access-protection pattern a known idiom?

Question: Matthieu M. brought up a pattern for access-protection in this answer that i'd seen before, but never conciously considered a pattern:
class SomeKey {
    friend class Foo;
    SomeKey() {}
    // possibly make it non-copyable too
};

class Bar {
public:
    void protectedMethod(SomeKey);
};

Here only a friend of the key class has access to protectedMethod():
class Foo {
    void do_stuff(Bar& b) {
        b.protectedMethod(SomeKey()); // fine, Foo is friend of SomeKey
    }
};

class Baz {
    void do_stuff(Bar& b) {
        b.protectedMethod(SomeKey()); // error, SomeKey::SomeKey() is private
    }
};

It allows more fine-granular access-control than making Foo a friend of Bar and avoids more complicated proxying patterns.
Does anyone know whether this approach already has a name, i.e., is a known pattern?
Comment: It might be useful to make the key noncopyable, unless you want `Foo` to be able to delegate access to other classes (of course, delegation might be useful, depending on the circumstances).
Comment: Q: could it be defeated with the following hack? char* some_junk_object=new char[...]; SomeKey* p=(SomeKey*)(some_junk_object); b.protectedMethod(*p); If all you're doing is relying on the type system, this is trivial to subvert. (I've seen a similar key system fail spectacularly in a similar way.)
Comment: @Owen: If the copy-ctor is accessible, yes - but then again there is no way to protect against everything in C++, there is always some hack around it. We want to protect against mistakes, not deliberate abuse. If we don't want delegation and make the copy-ctor non-public, your hack wouldn't work.
Comment: Might be an idea to show how you would actually use those classes.
Comment: @Neil: Right, that may not be obvious.
Comment: Personally I don't like 'friend xxx' in general, but that's just me :-)
Comment: This is quite a neat idea for granting partial friendship... I don't have a C++ compiler handy, but I wonder if you could you make protectedMethod a template specialization, so that you don't even incur the cost of the SomeKey() construction...
Comment: @brone: Any decent compiler will optimize it away if the definition is visible. It only needs to behave *"as if"* it happened - which is pretty trivial for an empty class :)
Comment: Ah, yes, missed the copy – that will help. Just so long as you realize the extent to which your key may or may not protect you.
Comment: @Owen: I'm not sure that your question is really relevant. Of course you can (most probably) bypass it like you can bypass the normal access checks by doing stupid things like #define private public. As always it is the responsability of the programmer to use his tools correctly which is mostly what you said in your last comment.
Comment: @nick: I'm trying to pass along that I've seen schemes like this fail _without_ going to such lengths as altering the header's contents through editing or macro magic. It miffs me that you feel a caution on the idiom being described is irrelevant to the question, whether or not you think it's a _valid_ criticism, but do with this as you see fit.
Comment: I opened a [follow-up question on naming](http://stackoverflow.com/questions/3324248/how-to-name-this-key-oriented-access-protection-pattern).
Comment: [And a follow up on generalizing it.](http://stackoverflow.com/questions/3324898/can-we-increase-the-re-usability-of-this-key-oriented-access-protection-pattern)
Comment: Are there any anecdotes of this idiom being optimized into no-ops on GCC?
Comment: Wonderful idiom. Thanks!
Answer: Thanks to your other question it looks like this pattern is now known as the "passkey" pattern.
In C++11, it gets even cleaner, because instead of calling
b.protectedMethod(SomeKey());

you can just call:
b.protectedMethod({});

Comment: not sure, but without c++11 it could be an option to provide a `SomeKey` constructor that takes eg. an `int` to allow for a somewhat shorter `b.protectedMethod(0);`
Comment: Just a detail: The shorthand version `foo.bar({})` doesn't work with constructors e.g. `Foo foo({})` as it is ambiguous - the compiler doesn't know which constructor is being called, it could be a copy constructor. Or at least that's an explanation that seems reasonable to me, correct me if I'm wrong.
Comment: Can someone elaborate what means {} in
b.protectedMethod({});
Comment: @yako: `{}` for default construct first argument
Answer: It seems that this idiom like one mentioned in another SO question here. It is called Attorney-Client idiom and described in more details there.
Comment: I already linked to another answer to that question and the pattern above doesn't involve proxying through another class. There is no *"attorney"* we need to call through (they are expensive anyway), instead we simply get access by passing a *key* along.
Comment: @jeff: The point on expenses was meant to be a pun regarding hourly rates ;) Still, one has to manually forward in the attorney case - you have to write more.
Comment: @Georg: In what real sense are the attorney calls expensive?  If they are stateless, static inlines that merely forward arguments, how would any size or time penalty be introduced?
Comment: @Georg: sorry, read pun as double entente on the _call_ expense, not on method _definition_.  I generally agree, but I did make a comment in the other question's thread about actual runtime expense.
Answer: some boring man like me would make the fowllow code:
int FraudKey=0;
b.protectedMethod(reinterpret_cast<SomeKey&>(FraudKey));

Comment: That's not really surprising in C++ - this is not supposed to protect against malicious intent.
Comment: You have invoked undefined behavior. The bug exists in your code, as the caller of the function, because you are using `reinterpret_cast` to access an object by a type other than its actual type. From undefined behavior, absurdity follows.
Comment: That's why the `SomeKey` copy ctor has to be private as well. That ensures that this would fail to compile, while valid uses would succeed.
Comment: Maybe making `SomeKey` inner private to `Bar` would kind of protect against such uses - or at least restrict it to the `Bar` class. But then it would require to always use `protectedMethod({})`.
Answer: Its pretty close to this:
http://minorfs.wordpress.com/2013/01/18/raiicap-pattern-injected-singleton-alternative-for-c/
Basically if you consider a reference to an object of well designed class to be provide the
access control you need to implement any access control policy that actually makes sense, applying this pattern to anything other than the constructor does not seem to make that much sense.
So as the article states, if you use this key in conjunction with those constructors for what
access control might make sense, objects that represent significant parts of scares resources, that in C++ would generally be implemented as RAII objects, than the name RAIICap or RAII-Capability would indeed make sense.
http://www.eros-os.org/essays/capintro.html
Alternatively you could refer to it with a more general name like construct authority.
The implementation in the article is a bit to much main centered, that is, main needs to create all the authority keys. You can extend on it and make it more flexible by adding an additional public constructor for the key itself:
template <typename T>
class construct_authority {
  public:
    construct_authority(construct_authority<void> const&)
    friend int main(int,char **);
  private:
    construct_authority(){}
};

That way main could delegate the key creation to other parts of the program.
Personally I think the RAIICap name is quite appropriate for the useful part of this pattern.
A while ago I proposed that this simple template above could be added to the standard library.
https://groups.google.com/a/isocpp.org/forum/#!topic/std-proposals/p_v-aYIvO1E
Unfortunately there are issues with the idea that there can be one main fingerprint that constitutes a computational root, so something like this apparently can't have a place in the standard library. Having said this, at least for the use with the constructor of RAII classes, this pattern seems to be quite useful.


$(a_{1}+ a_{2} + ....+a_{k})^{n}$ where $k >2$, what does it generate?

Question: Binomial expansion generates the Pascal triangle but what does it generate when you have different amount of terms there?
You can see here the geometric generation with only 2 terms. I am interested to know if you have many terms.
Comment: Do you mean Pascal's triangle?  What is up with z and h?  How many terms are inside parentheses?  Do you mean something like $(a_1+a_2+\cdots+a_k)^n$ where $k$ is an integer greater than $2$?  You get multinomial coefficients: http://en.wikipedia.org/wiki/Multinomial_theorem.  Is that what you're looking for?
Comment: @Jonas Meyer: yes, thanks.
Comment: @hhh: feel free to edit the question!
Answer: See: multinomial theorem
http://en.wikipedia.org/wiki/Multinomial_theorem
Comment: In particular, see the section [Generalized Pascal's triangle](http://en.wikipedia.org/wiki/Multinomial_theorem#Generalized_Pascal.27s_triangle) and the articles linked there, [Pascal's pyramid](http://en.wikipedia.org/wiki/Pascal%27s_pyramid) and [Pascal's simplex](http://en.wikipedia.org/wiki/Pascal%27s_simplex)


Android - Should I use ViewGroup when close/null all views?

Question: I have one question about when closing my activity and letting it be destroyed.
I think, in my java class that is going to reference my views (for example, my java class references my buttons and textviews on the screen), is it ok for me to put all the view references into a ViewGroup for the purpose of closing them out 100% later?
Sorry for my poor English. Let me further explain:
I create (in java class) variables for my button, textview, and other screen items, and put them into a group so when I want to delete them (null them) later, I can tell Android to delete all the child of the group? Also, maybe I can use group of all my buttons to do loop later too.
Is this bad practice? Is this ok to do this or is this not the intention of the ViewGroup? I read document on ViewGroup, but it does not say about if this is also a use for View Group.
Thank you for all answers. I am learning every day.
Comment: If I understand you correctly, you are worried about memory leaks due to keeping references to View objects. Is this correct?
Comment: Yes I do worry about a memory leak. This worry is my number one worry.
Answer: When designing a view, you use layout xml typically. That's loaded into Activity's onCreate() as a view. So in layout xml, you're required to use any layout managers, like LinearLayout, RelativeLayout, FrameLayout etc. They're all child of ViewGroup. So by default, every view is contained in a ViewGroup already.
Regarding your question about destroying, if there's no special case that is retaining the view and its child views, Activity's default implementation will take care of destroying the view and letting it get garbage collected.
Have a look at document reference of onDestroy() funtion, also the method onDetachedFromWindow() is worth looking at.
If you've a special case, that's retaining the view, overriding the onDetachedFromWindow() is a good place to release those views.
Comment: Great, welcome to android development, and happy coding!
Comment: Thank you Adil. This gives me the understanding I look for. I did not know the buttons and other views were already child of ViewGroup. I will not make new group then, because then I have too many references for no reason. Thank you again.