Obscuring squares of Rubik's cube

Question: This is a combinatorial question related to Rubik's cube $3\times3\times3$ (and, in the end, its generalizations $n\times n\times n$). I assume that the readers are familiar with this puzzle. Let's recall some basic terminology and conventions to rule out possible ambiguities. In the following, we use the words state and configuration interchangeably, as exact synonyms.
We are only interested in configurations of Rubik's cube where it has the shape of a cube (so, we consider rotations of its layers by an angle of $90^\circ$ as atomic transformations, and no incomplete rotations are allowed). Also, we consider configurations that can be obtained from one another by solid rotations of the cube as a whole (without any relative movements of its parts) as identical.
The cube has $6$ faces, each one of them is a $3\times3$ grid of squares — $9$ squares per face, and $54$ squares in total. Each square is of a solid color. Orientation of every single square is irrelevant (in fact, this rule has significance only for central squares). There are $6$ different colors, and there are $9$ squares of each color. There is a single selected state where each face consists of all squares of the same color — this state is called the solved state. A state that can be reached from the solved state by a sequence of valid rotations of layers is called a valid state (the solved state, of course, is a valid state too).
As a side note, if we allowed disassembling the cube into its parts and reassemling them, then we would get the number of possible states $12$ times larger than the set of valid states (this larger set would be a disjoint union of $12$ equivalence classes under valid rotations, each of the classes called an orbit). We are only interested in valid states in the following.
Usually, it is assumed that colors of all squares on the cube are visible. Let's consider a possibility that some squares may be obscured (e.g. completely covered by an opaque colorless sticker), so that their colors are not visible.
In general, obscuring some squares can result in some states becoming visually indistinguishable. As trivial examples, obscuring all $54$ squares makes all states indistinguishable, but obscuring only $1$ square (no matter which one) does not make any states indistinguishable.

What maximal number of squares in Rubik's cube $3\times3\times3$ can be obscured without making any states indistinguishable?

What maximal number of squares in Rubik's cube $2\times 2\times 2$ can be obscured without making any states indistinguishable?

What maximal number of squares in Rubik's cube $n\times n\times n$ can be obscured without making any states indistinguishable? Can we find a general formula, recurrence relation, etc. to compute it for every $n\in\mathbb N$?
Comment: I started working on this but then wondered, are you considering that the color scheme is known before peeling/obscuring off the stickers/squares? Because this will affect how many you can peel off since it gives some extra information.
Comment: This question reminds me a lot of trying to find the minimum number of clues necessary in a game of Sudoku, except instead of numbers you filly the squares with colors (which could be labelled arbitrarily as $1$ to $6$, making it even more like Sudoku)
Comment: To establish a simple lower bound we can reason as follows. Suppose we obscured $9$ squares, all of the same color (say, red). By inspection, we can see that $9$ red squares are not visible anywhere, but there are $9$ obscured squared. So, we can deduce that all obscured squares are red. Hence, no information is lost, and no states were made indistinguishable. We can furthermore obscure a non-red square on a corner cubie with a red square. By inspection of other corner cubies, we can find what color has been obscured, and the last visible square is enough to infer the orientation of the cubie.
Comment: @Matta Yes, we can assume the color scheme is known.
Comment: According to google there are 43,252,003,274,489,856,000 rubik's cube states (which I think you find using burnside's lemma).  Each color you read can reduce the state by at most a factor of 6.  So a lowerbound on colored edges is log(43,252,003,274,489,856,000) / log(6) $\approx$ 25.2 so you can uncolor no more than $6 \times 9 - 26 = 28$ tiles.  This might generalize to getting a lose lowerbound on larger cases.
Answer: Disclaimer: This is an old incomplete answer, now aged multiple years. I started this before I had any formal math education and I never came back to finish this.

To make our lives easier, we can separate the pieces by 3 types:
Edges (3 stickers)
Sides (2 stickers)
Centers (1 sticker)
Also note that im observing a cube with Yellow and Black( I call it White later on) colors for the top and bottom sides as my default color scheme.
 (Other pieces follow Red, Blue, Orange, Green)

For the $3\times3\times3$ Rubik's cube, first we can solve for the middle parts.
We can conclude that if the color scheme is known, that all obscured centers can be determined if we have at least 2 neighbour ones.
 This means we can peel off 4 centers if we keep 2 neighbour ones. This can be checked by playing with its own cube or simply by following the laws of legal positions and using something like a solver help you out. (This is because centers can't be really switched, but the pieces around them can so that it looks that way)
Then lets see how many stickers from the edge pieces can be obscured or peeled off, since any configuration of $n\times n\times n$ always has exactly 8 edges.
We can list them by the colors they contain:
 (Red, Blue, Green, Orange, Yellow, White)
$$ R,G,Y $$
$$ R,G,W $$
$$ R,B,Y $$
$$ R,B,W $$
$$ O,G,Y $$
$$ O,G,W $$
$$ O,B,Y $$
$$ O,B,W $$
If you want to know how many stickers can be peeled off and still be able to identify each corner, you can ask yourself; How many stickers you can take so that when putting them back, you have only one possible way to do so?
I have found out the maximum number of 12 out of 24 stickers; by taking all R or O, then all B or G and finally all Y or W.
 Here is an example:
$$ -,-,- $$
$$ -,-,W $$
$$ -,B,- $$
$$ -,B,W $$
$$ O,-,- $$
$$ O,-,W $$
$$ O,B,- $$
$$ O,B,W $$
Now by shuflling the order and rotation of all 8 edges in every way possible, there will be only one way to stick the removed stickers, thus you still can identify the pieces.
Now the Side pieces, which might be a bit tricky.
 On the $3\times3\times3$ Rubik's cube, there are 12 Edge pieces:
$$ G,R $$
$$ R,B $$
$$ B,O $$
$$ O,G $$
$$ Y,G $$
$$ G,W $$
$$ W,B $$
$$ B,Y $$
$$ R,W $$
$$ W,O $$
$$ O,Y $$
$$ Y,R $$
Now you can try to do the same thing.
 Firstly I tried to remove all White stickers, then it allows me to take one color from $Y,?$ pieces other than yellow, and after that nothing more can be taken without providing multiple solutions for the edges; so that was 5 stickers.
 Then after other failed attempts, I found you can remove 6 stickers; one of each color so that there aren't multiple stickers of the same color standing without their second color, and I'm kinda sure it can't be done with more than 6 here.
 If someone can do better here, please let me know.
 So if I haven't made a mistake, for the $3\times3\times3$ Rubik's cube you can remove total of $12+6+4 = 22$ out of 54 stickers top (following the things I pointed out) without losing any information about the cube's states.
The $2\times2\times2$ Rubik's cube is made of only 8 edge pieces, so 12 out of 24 stickers can be removed here.

We can now try to generalize this to other $n\times n\times n$ cubes.
We now know that we can for;
 $n=2$ take 12 out of 24
 $n=3$ take 22 out of 54
For any $n\times n\times n$ cube, we always have 8 edges, so thats $+12$ obscured stickers.
For the side pieces, we have $n$ of each piece (sorted set of pieces):
$$ W,R $$
$$ W,B $$
$$ W,G $$
$$ W,O $$
$$ Y,R $$
$$ Y,B $$
$$ Y,G $$
$$ Y,O $$
$$ R,B $$
$$ R,G $$
$$ O,B $$
$$ O,G $$
There is nothing more to do here than apply the same thing I did in $3\times 3\times 3$ cube;
 Remove 6 stickers, one of each color so that there aren't multiple stickers of the same color standing without their second color and do that for each new set of the side pieces.
 This provides us with $6\times(n-2)$ pieces more to obscure.
 Again, if you can do better with the sorted set I provided, please let me know.

So far then, the number of stickers we can obscure is: $$12+6\times(n-2)+C$$
Where $C$ is the number of "mobile" and "immobile" centers we can obscure, that appear after $n>3$ and have yet to be figured out.
 (when $n=3$ then $c=4$ )

So now, the center pieces at $4\times 4\times 4$ cube and every other with $2k$ sides ($k>1$) are different than every $2k+1$ sided cubes;
The $2k+1$ like our standart $3\times3\times3$ cube have 6 "real centers" which are immobile and $4$ out of $6$ can be obscured, the rest one-sticker centers here are "mobile" and behave differently when being rotated.
 Same goes for all of centers which are all "mobile" in $2k$ cubes.
How many of these mobile centers can be obscured? I would say for a starting bound, all of one color which is then:
 $C = (n-2)^2$ for $n>3$
 And gives us finally:
$$12+6\times(n-2)+(n-2)^2$$
Pieces we can surely obscure.
I haven't yet started checked if more can be obscured on these centers, but thats because its now end of the day and I don't have any more time, and now decided to post my progress so far.
I think you could take it from here to finish up the generalization and try to see if it is possible to obscure more than $(n-2)^2$ stickers using the color scheme and legal permutations, so maybe separate formulas for $2k$ and $2k+1$ can be found.
Update
Actually I don't think the mobile centers should provide us with any additional problems, thus we can take for $C$ that it is: $ = (n-2)^2 \times 4$ Since we need only 2 full center colors that will tell us the rest, most easily after solving the cube to its solved state.
Then we have: $$12+6\times(n-2)+4\times(n-2)^2$$
I have classes to be on early tomorrow morning now, so good night.

Edit: This should be computed and checked to make sure I haven't made
a mistake somewhere.
Comment: I'm assuming the color scheme is known, as you stated. So just pull the W sticker off the OBW corner piece. Compare it to the other OB piece. You can still tell which is which and deduce which one originally had a W sticker. Alternatively, without taking the stickers off, try to put the OBY corner in the place where the OBW corner should be, oriented so the O and B stickers are on the same faces as the O and B center stickers. It can't be done, because the O and B stickers are placed differently on that corner.
Comment: The side pieces are a little trickier since any of the B side pieces with the other sticker removed actually appear identical. But I think there might be a way to have two pieces with on the B sticker remaining and know which is which due to the fact that 11 of 12 configurations of the small cubes are not reachable from the solved state.
Comment: Any corner piece's identity and orientation can be determined by just two stickers; two corners with one sticker removed from each, and two remaining stickers of the same two colors, are mirror images of each other. So you can remove at least 13 corner stickers.
Comment: @DavidK I'm not sure what you are saying, but does this still imply when the corners and all other pieces are scrambled? How would you then decide which corner is a mirror image of which? Could you show a example for your 13 out of 24 of the corner stickers? (and explain why the corners in your example can have only one solution which then means you know for sure the identity of each piece) By using something like my 12 out of 24 example? That would make your statement very much more clear.
Comment: I see it now, haven't seen that by myself. I guess this could too be applied to the side pieces too in a similar way. This increases the total number of stickers that can be peeled off. I'll update my answer considering mirrored pieces for both side and corner pieces when I find some free time for this. Meanwhile you could also post an answer yourself if you want, considering the mirrored pieces as you pointed out.
Answer: format of terms used in this answer:
removal = obscuring (hiding a sticker)
piece = mini-cube
face = side of a piece =equiv sticker
$n$ = one 1-dimensional face unit
side = whole face of the rubik's cube
cube = entire rubik's cube
state = configuration
type = which form of piece (corner-proper, edge-proper, or edgeless  face)
c = corner_piece (starts with $3C_v$ = three visible faces)
e = edge-without-corner_piece (starts with $2E_v$)
f = face-without-edge_piece (starts with $1F_v$)
$C$ = an individual c face
$C_r$ = a C removed
$C_v$ = a visible C
$C_A$ = all c faces combined
${C_A}_v$ = all visible c faces
$E_A$ = all e faces combined
$F_A$ = all f faces combined
$T_v$ = all visible faces combined ($C_v$+$E_v$+$F_v$)
$X_A$ = all deducible faces
$({X_A})_n$ = arbitrary # deducible faces for $n^3$ cube
(⇒ solve $∀x=r:$ max$[{(X_A)}_n]$ = ${(T_A)}_n$-min$[{(T_v)}_n]$)

This question (well, three questions to the same end) boils down to two considerations: What is minimal stickers required to know what the solved state is supposed to look like, and minimal stickers needed to retain the identities of them all. Considering the first part without the second, as few as two diagonally opposite corner pieces would suffice ($2c$, establishing every color's/side's correct alignment to every other). Of course, this defies the second necessity, since not only the other 6 corner pieces' but all the other pieces' identities would become indistinguishable. Considering the second part (which mostly if not wholly absorbs the first), one can afford one piece of each type getting stripped of its 1, 2, and 3 stickers ($6$ so far). Of course there is a lowerbound of $n^2$ (one whole face, 9n for a 3×3×3 cube), but we can do better than that for the n=3 cube (edit bolded for emphasis). For n≥[some integer ≥4], the general maximal formula will include n^2; this formula might be able to fit for smaller n values despite that the particular algorithms for determining the actual faces to remove from smallish differs from what the formula implies. Consider n=50 cube.
To what extent depends upon which variation of 2^2=4 possible ways to interpret the problem as originally presented: do we know correct color-scheme alignment (medium outside information, reasonable supposition since already know how to play the puzzlegame and have access to internet, and confirmed in response to Vepir's question); do we know a particular pattern to how the faces were removed (heftier outside information, mostly absorbing preceding knowledge); do we know both of these info (heftiest outside information); or de we know none of these info (minimum outside information).
I will approach this problem assuming minimal outside information to start, because considering the difference affordable from there upward seems easier to me, and I am curious how the up to four different general formulas would differ.

Since any valid state with all stickers visible can be deduced as such (by solving it, even if achieving that from a random state might be computationally pricey), they convey the same information; so one sensible way to think of this problem is as subtracting stickers from the solved state. Besides the straightforward description, the response to Vepir's question confirming knowledge of the color scheme may and likely will increase the maximal count by allowing for more removals of non-corner edge pieces. To start, however, I will ignore this fact. Another possible consideration for n>3 (and possibly even n<4) is if you can presuppose knowledge of pattern to which faces you hid. When I get to the part of formulating a general pattern, I will assume initially that the obfuscated cube is to be decipherable by a stranger.
Any piece within a rubik's cube of of side n length 3 or greater can be separated into three disjoint categories: corner [3 different colors], edge without corner [2 different colors], and face without either [1 color]. In the case of 2×2×2 cube, each type shares the same category (is not disjoint). The number of total faces (visible or not) as a function of integer n is equal to 6⋅(n^2). These might be helpful later in constructing a general formula.
Focusing now on the 3×3×3 cube, with all 8⋅3=24 corner stickers removed you could still ascertain what state$_{[solved]}$ should look like by using $c_a$=${(c_a)}_v$ to track a course around the cube. But that would also make those 8 c indistinguishable, so 8⋅2=16 removals allowed. Remove the remaining face from one of the c making it blank and 1 from a single f = 16+2=18 removals allowed (lower bound), since these single "extra" oddball removals from two different types of the three does not by itself prevent deduction of solved state. That leaves the 10 untouched e and 7 one-sticker c pieces to consider. Well, at least one e could be totally removed, so 18+1=19 removals lower_bound for the 3×3×3 cube.
Here is a good place to pause to calculate the formulas for the different types of pieces (by how many original faces contained) as equations based on n.
corners: 8 (constant); $c_n$=8. non-corner edges: as few as 0, for n={1,2}. For every n beyond that, it increases by 10; $e_n$=10(n-2). non-edge/corner faces: all the rest. For n={1,2}, 0. For every n beyond that, it increases by faces times square of two less than n: $f_n$=6(n-2)^2. Any beyond 1 from this category becomes indistinguishable with its only sticker removed, so +1 should be the only effect to the general formula from this type.
Back to optimizing the 3×3×3 cube. None of the remaining 7 C could get removed, since that would make those c indistinguishable. That leaves the nine remaining e to focus on, or possibly all ten if it can ensure a greater maximum (past lowerbound of 20 or alternative removals). Focusing on the 9 is simpler than 10 and likely the correct path so I shall. Every c piece serves for this purpose also as an e piece, but with all of them out for use except for one serving now as an f piece, the remaining e pieces are the only pieces showing more than 1 side/color. The question now is how many of the eight two-side relationships can be removed from the cube before the full identities of the removed (non-corner) ones cannot be deduced. I believe the answer is 4: two on opposite sides of and sharing a side, the other two on reverse side diagonal from the first 2, allowing for an unobstructed route linking all six sides (contiguous, since every side is contiguous). One of these is accounted for already. So long as the other absent face of that piece is considered (rather than preserving it still on) when deciding the remaining 3 to remove, which I believe means choosing the same "obverse" side (as opposed to the opposite "reverse" side) as the first two mentioned (proving this is another task), it should work out. That results in 19+3 = 22 removals from the 3×3×3 cube's 54 faces without knowing the color scheme. If you know the color scheme, then one whole side could be "removed" (possibly better), so long doesn't cost an existing deduction, which I think it wouldn't if you did so unto the remaining "reverse" side: 22+2 = 24 removals from the 3×3×3 with prior knowledge of the color scheme.
This brings up an important consideration for a general formula. While for n<4 a majority of the removals came from corner pieces, as n increases the corner pieces remains constant whereas the edge pieces increases linearly. As such, for higher n values the majority of faux "data-hiding" will be unto non-corner edge pieces, in alternating half-visible fashion. To formulate a general equation, at first I will suppose no prior knowledge of the color scheme nor methodology to the removals. Considering for a moment the particular case of a 4×4×4, there are 20⋅2=40 E, compared to 8⋅3 = 24 C. Since the corner-pieces reveal more information about the whole cube (particularly without prior info), retaining most of them in favor removing all of the non-corner edgepiece stickers likely yields higher value of lossless data-compression. I'm not sure yet how to formulate this into a general equation without if/else-style verbiage included, though it is probably possible. I will come up with a general formula and post it as a comment or update this post, but for now I'll leave with a summary of some relationships to n-width to consider:
corner stickers = ${(C_A)}_n = 3{c_a}  = 3⋅8$
edge stickers = ${(E_A)}_n = 2{(e_a)}_{n-2} = 2[10(n-2)]$
face stickers = ${(F_A)}_n = 1{(f_a)}_{n-2} = 1[6(n-2)^2]$
total stickers = ${(T_A)}_n = 6*{(F_A)}_n = 6⋅n^2$
Considering lower n^3 cubes (to help figure out a general pattern and answer second question):
For n=1, no prior knowledge, 1 face could get removed. With prior knowledge of correct scheme, presumably all except two = 4  of the six could get removed.
For n=2, no prior knowledge, trickier. $T_2$ = ${(C_A)}_2$ = 24. A maximum bound entails linking all sides, from 3 C with 2 c each ⇒ max$[{(X_A)}_2]$ = ${(T_A)}_2$-min$[{(T_v)}_2$] = max$[{(X_A)}_2]$ = $24-(2⋅3)$ = 18. For n=2 with prior knowledge of color scheme: ..

For n=4, no prior knowledge: min$[{(E_v)}_4]$ = min$[{(e_v)}_4]$÷2-1 =20÷2-1=9 ⇒ max$[{(E_r)}_4]$=${(E_A)}_4$-9 = 40-9 =31. max$[{(F_r)}_4]$=1. max$[{C_r}_4]$=8⋅2+1=17. Assuming no contradictions (noting  thatn=4 is even, n=5 is odd,..) max${(X_A)}_4$=${(T_r)}_4$ = max$[{C_r}_4]$+max$[{(E_r)}_4]$+max$[{(F_r)}_n]$ = 17+31+1 = {49 = upperbound}.
$∀n∈N:$upperbound$[{(X_A)}_n]$ = max$[{(C_r)}_n]$+max$[{(E_r)}_n]$+max$[{(F_r)}_n]$,
⇒ max$[{(X_A)}_n] ≤ 17+(½{(E_A)}_n+1)+1$
⇒ max$[{(X_A)}_n] ≤ 17+1+(½(2[10(n-2)])+1)$
⇒ max$[{(X_A)}_n] ≤ (10n-20+1)+18$
⇒ max$[{(X_A)}_n] $?$=$?$ 10n-2$ doesn't fit; too high
but $[{(X_A)}_n]=10n-9$ seems pretty close for n<4

large n value: n=50
lowerbound[max$[{(X_A)}_n]$ = ${f_n}^2+3C_v+2E_v$ = $n^2+3+2$
lowerbound[max$[{(X_A)}_50]$ = $50^2+5$: one whole side removed plus one whole opposite corner and one whole middle edge piece (these latter 5 removals might not all apply, but are guaranteed in a simple quadratic lowerbound). So what other faces can get removed (and still get ascertained by a stranger familiar with the rules of the puzzle but not the color scheme used)?

Obscuring squares of Rubik's cube


How can I see how much bandwidth each Apache Virtual Host is using?

Question: I have Apache set up to serve several Virtual Hosts, and I would like to see how much bandwidth each site uses.  I can see how much the entire server uses, but I would like more detailed reports.
Most of the things I have found out there are for limiting bandwidth to virtual hosts, but I don't want to do that; I just want to see which sites are using how much bandwidth.
This isn't for billing purposes, just for information.
Is there an apache module I should use?  Or is there some other way to do this?
Answer: The information you're after is all in the logs, so you should look at a log analyzer such as AWStats.  The other option is to use Google Analytics.
For analyzing the logs, here's a rough example which you can use to tell you how many MB of traffic a log file reports from the command line:
cat /var/log/apache/access.log | awk '{SUM+=$10}END{print SUM/1024/1024}'

Comment: useless use of cat: awk '...' /var/log/apache/access.log works too
Comment: Yes.  But be careful that you dont sum up the response codes by accident.  I realised my counts were way too low because for me $10 is the http response code.  For my apache custom log I needed to use {SUM+=$11} instead.
Comment: Will the suggested way(s) calculate the traffic sent from some web page(s) to the Internet (outbound traffic)?
Answer: I suggest you use the wonderful apache logging mechanism and its less known %I and %O flags:
Define the format:

LogFormat "%t %a %v %U%q %I %O" IOFormat

Use it in your main httpd.conf:

CustomLog /var/log/apache2/all-bw.log IOFormat

The values are probably not accounting all headers information, but are quite accurate to have a precise idea of VirtualHost traffic.
Scan the logs with a perl script to aggregate per virtual host every n minutes (5 for example) and send this to cacti.
These flags are provided by mod_logio which is probably built in your Apache (as it for my Debian's Apache).
Comment: Hum, also as quoted in Apache 2.0 documentation:

Note that in httpd 2.0, unlike 1.3, the %b and %B format strings do not represent the number of bytes sent to the client, but simply the size in bytes of the HTTP response (which will differ, for instance, if the connection is aborted, or if SSL is used). The %O format provided by mod_logio will log the actual number of bytes sent over the network.
Comment: As of apache 2.4.7 there is now `%S` which is total bytes transferred, sum of both `%I` and `%O` https://httpd.apache.org/docs/trunk/mod/mod_logio.html
Answer: Awstats is one way to do this but probably not the best
Answer: If you decide to use awstats with Apache, out of the box it will show you aggregated bandwidth for your entire server.
To see bandwidth on a per virtual host basis, I recommend installing vlogger.
Vlogger will actually gather Apache access log information for each of your virtual hosts that you set up to do so in separate directories/files.
For example if your Apache log file is in /var/log/apache2, typical vlogger installation will create something like this for your virtual hosts (e.g. vhost1.com vhost2.com):
/var/log/apache2/vhost1.com/access.log
/var/log/apache2/vhost2.com/access.log

Vlogger gives you the option to rotate these logs for you, provides a way to change the naming template of the access log file (e.g. add a date), and claims it handles a large number of log files better than Apache.
One down side to this is that you won't have an aggregated server view anymore (you'll need to aggregate logs separately or perhaps use an additional apache setting or perhaps some other method?).
I would caution against using google analytics (or any javascript based tracking) for server bandwidth monitoring as you are relying on the client to report via the javascript. GA does not report to you people who have their javascript disabled as well as any crawlers/spiders/bots.
Answer: Here is some regex to parse the log format proposed by Xerxes.
\[([0-9]+)/(\w+)/([0-9]{4})[^\]]+\]\s(\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})\s([^/]+)[^\s]+\s(\d+)\s(\d+)
Example log:
[12/Jan/2011:14:25:04 +0000] 220.127.116.11 files.hjaltijakobsson.com / 581 669
[12/Jan/2011:14:25:04 +0000] 184.108.40.206 files.hjaltijakobsson.com / 624 747
[12/Jan/2011:14:25:04 +0000] 220.127.116.11 files.hjaltijakobsson.com /icons/blank.gif 687 186
[12/Jan/2011:14:25:04 +0000] 220.127.116.11 files.hjaltijakobsson.com /icons/compressed.gif 693 188
[12/Jan/2011:14:25:04 +0000] 220.127.116.11 files.hjaltijakobsson.com /favicon.ico 592 512
Matches:
Subpattern 1 (day of month): 12
Subpattern 2 (abbr. month): Jan
Subpattern 3 (year): 2011
Subpattern 4 (visitor host): 18.104.22.168
Subpattern 5 (virtual host): files.hjaltijakobsson.com
Subpattern 6 (incoming bytes): 581
Subpattern 7 (outgoing bytes): 669
Cheers.
Answer: Slight tweak on the accepted answer assuming there is actually multiple vhosts on the server (and therefore multiple site.com.access_log 's). This will sort and list each vhost
for f in *.access_log ; do echo `awk '{SUM+=$10}END{print SUM/1024/1024}' $f` $f ; done | sort -rn | more

and for a directory of gzipped logs
for f in *.access_log.*.gz ; do echo `zcat $f|awk '{SUM+=$10}END{print SUM/1024/1024}'` $f `stat -c%z $f`; done | sort -rn | more

Answer: Hmm, you could get evil with IPTables and string matching to log the packets for later reporting. Will only work for non SSL connections though.
Or something protocol and session aware like Snort could be shoe horned into use ...
Answer: Correct. Filtering the log is a good idea. I also want to get the bandwidth of my Apache server when download files.
LogFormat "%h %l %t %u \"%r\" %>s %b/%D**" combined

Calculates the %b and %d output, which will give you the bandwidth of current.


How many different names can be created by using the letters...?

Question: Consider the name: AABBC DEF ACK
I want to find how many different name combinations with 3 words I can come up with. I know there exists $\frac{11!}{3!2!2!}$ different permutations. But, what is the best way to partition these into three words. (Words must be at least 2 words length it is the only rule.)
My attempt:
I have three spaces and 3 different partitions can be obtained:
<code>                      _ _ _
                      2 2 7
                      2 3 6
                      2 4 5
</code>
Result = $\frac{11!}{3!2!2!}$$*$[$\binom{11}{2}$$\binom{9}{2}$$\binom{7}{2}$$*$$\frac{3!}{2!}$$+$$\binom{11}{2}$$\binom{9}{3}$$\binom{6}{6}$$*$$3!$$+$$\binom{11}{2}$$\binom{9}{4}$$\binom{5}{5}$$*$$3!$$]$
Is this answer true and is it the best way to solve this problem?
Best
Answer: Hint: First, find out all permutations of those letters, i.e. all 11-letter word.
Then, you need to add three spaces between those letters. The rule means that the first space must not be in the first position, there must be two letters between the two consecutive spaces and the last space can be after the 11 letters.
It should not be hard if you think of the question in this way.
You can think of the partitions in this way. Consider all letters are the same, say T. Then, combine two T's with each space. Then, find the permutations of the rest T's and the combined blocks. That will be the number of partitions you can make.
Comment: There will be no repetitions. As the order of the 11 letters are fixed in the first place. What you do is inserting spaces according to the rules. Your answer should be modified because there are acturally 5 stars and 2 bars. Because 4 stars are combined with 2 bars already in order to satisfy the rules and the last two stars are fixed, no bars can be inserted in.
Comment: You are right. Somehow I thought I needed to use all the letters. So according to your remark, for example in this question, after fixing 2 letters for each words, I will have 5 letters left. Then I need to partition those letters. I may or may not use all of them. But what I could not figure out is how to eliminate the same permutations. I have letters occuring more than once, simplest solution seems to be fixing the letters occurring only once like AB | CD | EF and then partitioning the left letters. But is it right? I do not feel comfortable.
Comment: Also if I had to use all the letters, then could I think this question as a stars&bars question right? (I have 11 stars and 2 bars (since I have 3 words) so the result would be equal to $\frac{11!}{3!2!2!}$$\binom{11+3-1}{3-1}$ )


Confused about calling default, no arg constructor

Question: From Bates and Sierra:
class Top {
    public Top(String s) {
        System.out.print("B");
    }
}

public class Bottom2 extends Top {
    public Bottom2(String s) {
        System.out.print("D");
    }

    public static void main(String[] args) {
        new Bottom2("C");
        System.out.println(" ");
    }
}

The choices are:
A. BD
B. DB
C. BDC
D. DBC
E. Compilation fails
Answer:
® ✓ E is correct. The implied super() call in Bottom2's constructor cannot be satisfied because there isn't a no-arg constructor in Top. A default, no-arg constructor is generated by the compiler only if the class has no constructor defined explicitly.
But I'm confused. Isn't "public Top(String s) { System.out.print("B"); } " a constructor defined explicitly? Where am I going wrong?
I've seen this question here but didn't really understand the answers.
Answer: The implicit call tries to call super with no parameters. Top does not have a no-arg constructor, so the call to super is trying to call a method that doesn't exist. When you want to call a non no-arg constructor, you need to do it explicitly. Bottom2's constructor should call super(s) to call Top's 1-arg constructor.
Answer: Yes, this constructor is defined in the base class. But you also have to call it from the sub class.
In every sub-class constructor, you must call a base-class constructor.  The only exception is if there is a base-class constructor without arguments.  This constructor is called by default.
That means your code should look like this:
public Bottom2(String s) {
    super(s);
    // ...
}

As an alternative, you could add a Top() constructor the the base class.
Comment: "But you also have to call it from the sub class."                                                                                That's where I've been going wrong. Solved with one sentence!!! Great! Thanks.
Answer: Whenever you write your own constructor which is parameterized, it replaces the default constructor provided by Java unless you define the no-arg constructor by yourself again.
Now, in Top, there is a parameterized constructor and the default no-arg constructor is gone unless you explicitly define one. Hence, just calling super() won't work. You need to pass in a String argument and call super(string).
Try writing a default constructor for Top and then call super() in the Bottom class. It won't flash that error =)
Try this:
class Top {
    public Top() { System.out.println("No-arg constructor in Top"); }
    public Top(String s) {
        System.out.print("B");
    }
}

public class Bottom2 extends Top {
    public Bottom2(String s) {
        System.out.print("D");
    }

    public static void main(String[] args) {
        new Bottom2("C");
        System.out.println(" ");
    }
}

Answer:
But I'm confused. Isn't "public Top(String s) { System.out.print("B");
  } " a constructor defined explicitly? Where am I going wrong?

public Top(String s) is a constructor defined explicitly. As the correct answer said, A default no-arg constructor is generated by the compiler only if the class has no constructor defined explicitly
Answer: Solution
1.you are creating object of base class that is new Bottom2() and passing argument as string that is "C" then as per the calling, call get to the Bottom2(String s) constructor and print "D".
2.at same time Bottom2() extends Top class so "B" need to print but Top(String s) constructor having string as parameter and in main class there is no parameter passing to Top(String s) constructor.
3.that why compiler give us an error
4.below giving solution over this problem
    class Top {
    public Top() {
        System.out.println("B");
    }
}
public class Bottom2 extends Top {
    public Bottom2(String s) {
        System.out.println("D");
    }
public static void main(String args[]) {
        new Bottom2("C");
        System.out.println(" ");
    }
}


NGINX cache based on cookies

Question: Is there a way for NGINX to have a different cache depending on the value of a cookie?
In my case, I have a website (in my case, a plugin) that creates a cookie called devicePixelRatio. This is 1 in most cases but if you have a high-DPI display then it will be equal to 2 (or more). Basically the server-side generates the website differently depending on the value of this cookie (either it is 1 or something else). Basically I would need two caches, one for devicePixelRatio=1 and one for any other value of devicePixelRatio.
Is that possible?
Thanks a lot.
Answer: Yes, that is possible.
https://stackoverflow.com/questions/26128412/how-to-extract-some-value-from-cookie-in-nginx
http://nginx.org/en/docs/http/ngx_http_core_module.html#variables
Use the client request headers to evaluate the cookie contents. Build your cache access logic around that.
More info: https://serversforhackers.com/nginx-caching/
Here is a starting point:
http://syshero.org/post/50053543196/disable-nginx-cache-based-on-cookies
You could, for example, place the proxy_cache_path in an if statement evaluating the cookie content. Pseudo code:
<code>if $cookie_devicePixelRatio = 2
proxy_cache_path = /retina/;
(or fastcgi_cache_path)
else
proxy_cache_path = /sd/;
(or fastcgi_cache_path)
</code>

NGINX cache based on cookies


Bootstrap - Classe .table-striped não funciona corretamente dentro de um while

Question: Estou usando o Bootstrap para fazer um sistema. Na hora de listar as linhas do meu select usando while as linhas não sem zebradas corretamente, saem todas escuras, como se todas as linhas fossem a primeira da tabela (acho que é isso que o Bootstrap está entendendo), porém a exclusão e a edição de cada linha está funcionando perfeitamente, é apenas visual. Segue o trecho do código:
$query = mysql_query(" SELECT * FROM USUARIOS ");
                            echo
                            "

                                    Nome
                                    E-mail

";
                          while($row = mysql_fetch_array($query)){
                                echo
                                "

                                ".$row['nome']."
                                ".$row['email']."

                                <button type='button' class='btn btn-info btn-xs' title='Detalhes' data-toggle='modal' data-target='#modalAlteracaoUsuario' data-whatever-nome='".$row['nome']."' data-whatever-email='".$row['email']."'></button>
                                <button type='button' class='btn btn-warning btn-xs' title='Trocar Senha' data-toggle='modal' data-target='#modalAlteracaoSenha' data-whatever-nome='".$row['nome']."' data-whatever-email='".$row['email']."'></button>
                                <button type='button' class='btn btn-primary btn-xs' data-toggle='modal' data-target='#modalAlteracaoUsuario' data-whatever-id='".$row['id']."' data-whatever-nome='".$row['nome']."' data-whatever-email='".$row['email']."'>Editar</button>
                                Excluir

";
                                }
                            echo
                            "

";

O que posso fazer para concertar isso?
Desde já agradeço!
Comment: Cara você teria ai o código final que ele gera?
Answer: Você está confundindo abertura de tag com fechamento.
Para abrir uma tag usa-se <tag> e para fechar </tag>.
No seu código você estava fechando uma tag e depois abrindo, como no trecho:

    Nome
    E-mail

Ficou assim: (ocultei o código dos botões para não ficar muito feio)

            Nome
            E-mail
            ...

        <?php
            $c =1;
            $row = array('nome' => 'nome', 'email' => 'email', 'id' => 0);

            echo "
\n";

            while($c < 5)
            {
                echo "\t\t\t".$row['nome']."	\n\t";
                echo "\t\t".$row['email']."	\n\t";
                echo "\t\tExcluir	\n\t";
                echo "\t
\n\n\t\t
\n";
                $c ++;
            }
            ?>

Dica, muito echo em html puro fica feio, mescle HTML com PHP.
Outra coisa que notei foi que no while não parecia ter noção nenhum do que estava fazendo a abrir e fechar linhas, então adaptei colocando uma lógica que sempre uso nas minhas aplicações, no código fonte resultante você pode ver que sobre uma linha a mais (

) mas não atrapalha em nada.
Para ficar funcional no PC de qualquer membro coloquei um while sem necessidade de banco de dados, apenas para exemplo.
Finalizando, \n(quebra de linha) e \t (tabulação, famoso TAB) usados no echo foram apenas para identar o código fonte no navegador para que você possa ver a estrutura de uma tabela e pode entender melhor.
Comment: Muito Obrigado!
Com o copiar e colar acabei me confundindo com as tags! No meio do código acaba ficando difícil visualizar esse tipo de erro.
Obrigado também pelas dicas!
Sucesso pra você!


Relationship between topological and Quillen's K-theory

Question: Up until now, I've taken it for granted that the topological k-theory of a space $X$ is equal to the K-theory of vector bundles on $X$. $K_0$'s of both coincide (Serre-Swan) however, is it the case that $K_i(\text{Vect}(X)) \cong K_{top}^i(X)$? ($\text{Vect}(X)$ being the category of (real/complex) vector bundles over $X$.)
I'm doubting this now, however, and I can't seem to find anything written up explicitly on the relationship between the two.

In what way, if at all, is topological K-theory a special case of Quillen's K-theory? What is the relationship?
Comment: Here's a reference: looks like the algebraic $K$-theory of $C^*$-algebras is not well-understood beyond $K_0$ or finite coefficients. http://www.math.uiuc.edu/K-theory/0128/Kregularity.pdf
Comment: Topological $K$-theory is a special case of the $K$-theory of operator algebras. Algebraic $K$-theory doesn't have Bott periodicity, so the higher $K$-groups needn't agree. I don't know whether the algebraic and operator algebraic $K_1$s are the same.
Comment: Rephrased the question.
Comment: Thanks, Kevin. We wouldn't need a Bott periodicity for algebraic K-theory in general, just one for the class of rings of functions on spaces. I couldn't initally why this couldn't be, a priori. In any case though, you're right that this doesn't work. As we can take $X$ to be a point. There's a theorem of Suslin (I think) that desrcibes the alg K-theory of an algebraically closed field of char 0 and it has that K_2 is uniquely divisible, which can't be the case for X=point, in which which we're comparing the algebraic K-theory of $\mathbb{C}$ with the top K-theory of a point.
Comment: (Somewhat) related: [Topological vs. Algebraic K-Theory](http://math.stackexchange.com/q/11393/)
Answer:
I've taken it for granted that the topological K-theory of a space X is equal to the K-theory of vector bundles on X

This is not true even for a point: $K_1^{alg}(\mathrm{Vect}(pt))=K_1^{alg}(\mathbb C)=\mathbb C ^\times$.
(Of course, there is a map from $GL(\mathbb C)$ with discrete topology to 'ordinary' $GL(\mathbb C)$ inducing a map $K^{\text{alg}}(\mathbb C)\to K^{\text{top}}(pt)$; but this map is far from being isomorphism. That's how I think about the difference in general case: in algebraic K-theory we forget about non-trivial topology [on our group]…)

Looks like some results in the direction you want are discussed in Michael Paluch. Algebraic K-theory and topological spaces K-theory:

In this note we discuss the algebraic and topological K-theories of an admissible space X and demonstrate how one may recover the connective topological K-theory of X from the algebraic K-theory of a simplicial ring which encodes the topological structure of the Fréchet algebra of continuous functions on X (...)
Comment: Thank you for the response. I apologise for taking as long as I did to get back to you. School has been hectic and I probably won't be able to look into this for a while. But I certainly will revisit this answer.


Dúvidas sobre geração de programa executável no VBA/Excel

Question: Compilei um programa em VBA que interage com uma planilha do Excel. Após não ter mais falhas apontadas ao compilar, a compilação é executada e nenhuma ação é apresentada ao final.
Não localizei o programa executável em nenhuma pasta (caso ele tenha sido gerado).
Ao pesquisar sobre o assunto, fiquei com mais dúvidas:
É possível gerar o programa executável do VBA que faz uso de planilhas do Excel? Há indicações que nestes casos um Excel de versão compatível tem de estar instalado em cada computador em que irá ser executado, justamente por fazer uso da planilha e necessitar do Excel.
Se a compilação gerou o programa executável, onde está sendo salvo o arquivo? Há indicações de nomes de diretórios que não localizei, por exemplo, "BIN".
Gostaria de saber o que de fato ocorre e como devo proceder para gerar e instalar em outros computadores o programa gerado.
Answer: O VBA, que significa Visual Basic for Applications, é uma linguagem interpretada criada pela Microsoft para permitir a automação de alguns processos em suas aplicações (dai o nome Visual Basic para Aplicações). Por ser uma linguagem interpretada, não há a geração de executável. Um módulo específico, compartilhado por todas as aplicações que utilizam o VBA, é responsável por interpretar o código escrito nessa linguagem, diretamente a partir da aplicação que o utiliza. Por isso o VBA tem as instruções/comandos genéricas(os) e os(as) específicos(as) de cada aplicação (no Excel, há classes para manipular planilhas, no Word, pra manipular estilos de texto, no Powerpoint para manipular formas e slides, etc).
Eu desconheço se há algum compilador VBA robusto ou que funcione bem, mas desconfio que se houver serão poucos. Afinal, se a sua idéia é fazer um executável, você pode usar qualquer outra linguagem (inclusive Visual Basic) pra acessar e/ou manipular arquivos do Office via bibliotecas específicas. O único uso para uma compilação de código VBA em executável que eu enxergo seria para dificultar o acesso ao seu código, mas mesmo assim é possível proteger os projetos dentro das ferramentas do Office e conseguir esse comportamento sem precisar gerar nada externo.
De todas as formas, ao fazer uma busca no Google encontrei algumas opções como esse tal de VbaCompiler (que parece gerar uma DLL a partir do código). Não o conheço, e não sei se funciona como esperado.
Comment: Obrigado pelo esclarecimento, vou verificar o que indicou.
Comment: Realmente há soluções para proteger o código por meio da geração de executável (por exemplo, o Secure++ VBA For Microsoft Office Excel & PowerPoint), mas eles necessitam do office para serem executados da mesma forma. Alguns comentam que além da proteção há o ganho de performance. Eu me interessei em passar a usar o VB em casos específicos, mas a dúvida é se o VB é uma linguagem que tem suporte e atualizações ou é como o VBA, que foi descontinuado (parece que a última versão do VB é de 2010). Quais seriam outras opções para substituir o VB se for o caso, pois li que o Delphi foi descontinuado.
Comment: O VB foi continuado por meio do .NET (como uma linguagem adicional para a construção do código). Dê uma pesquisada a respeito.
Comment: Ok. Vou ver. Grato


C++ compiler waring C26409 - avoid calling new and delete

Question: Here is my code that I'm getting (Warning C26409 Avoid calling new and delete explicitly, use std::make_unique instead (r.11).) after doing a Visual Studio 2019 Code Analysis:
#include <windows.h>
#include <strsafe.h>
int main()
{
    auto *sResult = new WCHAR[256];
    StringCchPrintfW(sResult, 256, L"this is a %s", L"test");
    delete[] sResult;
}

I was under the assumption to use new/delete instead of calloc/free, but now the compiler is telling me to use std::make_unique. I can't find any examples on how I can change my code to be compliant.
So my questions are:

how do I change my code so it doens't use new/delete

why should I not use new/delte vs std::make_unique?
Comment: In terms of "why should I not use new/delete", this is explained in numerous "introduction to smart pointers" guides on the web, such as this one: https://www.codeproject.com/Articles/541067/Cplusplus-Smart-Pointers
Comment: Btw. `(r.11)` references the item in the C++ core guidelines that is violated. [Here](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rr-newdelete) is the item with explanation. And [here](https://learn.microsoft.com/en-us/cpp/code-quality/c26409?view=msvc-160) is Microsoft's detailed explanation of the warning.
Comment: When asking about build errors or warnings, please always include a full and complete copy-paste (as text) of the build output. Not everyone knows by heart what `C26409` might be.
Answer: The warning is somewhat confusing, because it assumes that you need some direct memory allocation. If fact, you don't:
#include <windows.h>
#include <strsafe.h>
#include <vector>
int main()
{
    std::vector<WCHAR> sResult(256);
    StringCchPrintfW(sResult.data(), sResult.size(), L"this is a %s", L"test");
}

or
int main()
{
    WCHAR sResult[256];
    StringCchPrintfW(sResult, 256, L"this is a %s", L"test");
}

The idea is to use static storage when you can (small data) to be more efficient (no OS memory call), and use std::vector when you must allocate because the size is either unknown at compile time or too big for the stack and let STL do the work for you. The usage of std::make_unique is when you indeed need to call new directly or indirectly and have it auto-destruct later.
TL;DR: Read about modern C++ memory management.
Answer: Here's how you could rewrite this using std::unique_ptr. Note that the use of std::vector<WCHAR>, std::wstring or an array allocated on the stack would be preferable:
#include <memory>

...

{
    auto sResult = std::make_unique<WCHAR[]>(256);
    StringCchPrintfW(sResult.get(), 256, L"this is a %s", L"test");
} // exiting the scope frees the memory

Why should you do this (or use std::vector or similar?
It simplifies the code, since you don't need to think about how the function is exited; the compiler ensures the resources are freed. Otherwise you need to make sure for every execution path including ones that throw an exception or return early free all resources. The programming technique is called RAII (Resource Allocation Is Initialization) in C++.

Note: Given the small amount of memory you allocate, you may want to create the memory on the stack though. This should also get rid of the error by removing any dynamic memory allocations:
WCHAR sResult[256];
StringCchPrintfW(sResult, 256, L"this is a %s", L"test");

Comment: @JeffR it's part of the `memory` standard library header: https://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique
Comment: @Jeff `std::unique_ptr::get` gives access to the raw pointer. This is reading the value, but for array parameters `std::unique_ptr` implements the `[]` operator in addition to that. To replace the array, you'd use the move assignment operator or `reset()`. There's a good documentation of unique_ptr here: https://en.cppreference.com/w/cpp/memory/unique_ptr Doesn't teach you necessarily about how to use it though ;)
Comment: so a `.get()` is used to store the value into the variable (seems opposite), so what is the operator to "read" the value stored in sResult?


What happened to the wishbone?

Question: The top rushing teams in college football are running some form of the wishbone/triple-option and some are doing it with less size and speed (military academies). It doesn't appear that defenses have "figured it out". Why don't more teams run it?
Update: I would consider flex-bone in the same category as the true wishbone. Many spread teams are running some form of option including triple option.
Comment: At least four teams in the FBS run some variant of the triple option, and none of them is better than 7-4 this season.
Comment: @MichaelMyers - that is true, but do you expect any of the academies to be better than 7-4 with their scholarship/entrance limitations?
Comment: No one ran the wishbone better at quarterback than two of the first: James Street of Texas and Jack Mildren of Oklahoma. What made them so good was not just their ability to run the triple option, but also their knack for making big plays in the pass game, even though neither would be considered a high-completion percentage passer. The 1969 Texas-Arkansas and 1971 Oklahoma-Nebraska games show how they were able to overcome great defenses with the pass. It seems that wishbone qbs of the 1980s were not able to make those kind of passing plays.
Comment: Does Georgia Tech have severe limitations? Maybe their entrance requirements are stricter than at other schools; I don't know. The last major school to use the wishbone was probably Oklahoma in the early 1990s right after Barry Switzer was fired. They were pretty mediocre, but that could be due to the coach who inherited the offense.
Comment: @MichealMyers - Oklahoma got out of the bone during Switzer's tenure when they got Marcus Dupree.
Comment: Michael Myers, younger people cannot stand to face the fact that ANYthing was ever better before their righteous selves were born. Fact is, the Wishbone is the ONLY truly artistic formation in history, and your comments are dead on. Nothing was ever more fascinating than watching Texas, Oklahoma, and Alabama run that thing to one championship after another.
Comment: Folks, take a close look at Chip Kelly's offense at Oregon. It's got wishbone principles all over it.
Answer: Defenses have indeed, "figured it out". The top 4 rushing teams that run the Wishbone/Triple-Option—Georgia Tech, Air Force, Army, and Navy—are a combined 21-35.
However, they are successful running the ball with all four being in the top 6 in rushing in the FBS.
Teams approach this offense by containing the rush and funneling the play up the middle. This limits big gains and forces the offense to put together drives of 10-15 plays. Inevitably, a penalty or error derails a drive and they are left in a 3rd and long situation. This offense is not built to overcome long down and distances.
In response to comments below..
The legitimacy and effectiveness of an offensive system can be measured by the number of points it is able to produce. The object of the game, after all, is to score more points than your opponent. Wins and losses is an easy, but maybe too simple, way of judging this.
The four prominent Wishbone/Triple-Option teams have scored 1,334 points. That's good for 333 on average which would place them on the list of FBS scoring offense at 71 out of 134. Teams that have finished 71st in scoring offense in the past 5 years have combined for a win loss record of 29 - 33.
The last time a Wishbone led offense won a National Championship was in 1986.
Frankly, the speed of the game has made the Wishbone obsolete. Even ultra conservative teams like Alabama use offenses that look like a Spread in comparison to the Wishbone.
Comment: Not that I dispute your conclusions but all the service academies field teams that are physically smaller than the powerhouses and they are none the less moderately successful with the triple option. Personally, I suspect philosophical reasons for choosing a offense that puts a heavy emphasis on coordinated team action.
Comment: I can see where defenses have "figured it out" but how does a losing record from those teams translate to such? Quasi-legit answer, yet I don't think a losing record legitimately backs up how defenses have "figured it out."
Comment: I completely disagree with this entire answer.  The wishbone is used in the NFL.  If it were ineffective I wouldn't think it would be used for over 40 years.  Your PPG and yardage info are flawed.  It is PPP not PPG that measure an offense.  If your offensive drives are on average twice as long then of course you will have lower PPG.  Also you need to measure the teams against like teams (their conference is a good start) not the entire BCS.
Comment: Good point, doing some more homework to expand my answer.
Comment: I tried, but I'm not sure if my edits will satisfy you.
Comment: Not looking for satisfaction, just more context to back up your answer. With that said, good job with the extra research.
Comment: They aren't exactly playing powerhouses either. Army played three BCS teams this year, and they aren't exactly great football teams anyways: Wake Forest, Rutgers, and Boston College.
Comment: Georgia Southern is a national power at FCS. Although not the biggest league in college football, it's not exactly pee wee either.
Comment: What offense do you suggest the academies run that is going to turn their win-loss records around?
Answer: There are an awful lot of contributing reasons that the wishbone is not used more often.  Here are a few top reasons:

Quarterbacks take a lot of hits in the wishbone.  The offense requires the QB to run with the ball on outside options and take hits from linebackers/lineman even when they pitch the ball.  For this reason, QB's get hurt often in the wishbone.
Related to #1, with most pro-offenses being pass heavy spread or west coast style, QB's are reluctant to be featured in the wishbone as it hurts their chances of advancing to the NFL.
Related to #2, because QB's are reluctant to be wishbone QB's, college teams are reluctant to feature the offense as it could damage recruiting.  This effect runs down to the high school levels as well.
The wishbone excelled in a time where linebackers were considerably slower than today.  Without hard 40 time stats, it is generally accepted that defensive linebackers move much better today than in previous eras.  The wishbone requires the QB and RB to get to the corner in many of their bread and butter plays in order to force a DE to choose the QB or RB, and then have the QB or RB beat the corner back for large plays.  Faster linebackers require more blocking on the outside, and spoil the top plays of the wishbone.
There are few stars in a wishbone offense. The QB may be the biggest benefactor stats wise (and we covered why they don't want to be featured in the offense) and the remaining skill players spread touches more than in modern day offenses.
Time.  If you fall behind in a game, the wishbone takes a long time to score points.  Most plays are running plays, and a team with a weak defense will find themselves with no plays in the arsenal (and perhaps not the right talent to execute even if they did) to catch up against large deficits.
Comment: What about spread teams that rely heavily on the option including the triple option? Points 1-4 don't really hold up. Denard Robinson carries the ball a lot in Michigan's offense and took quite a beating.
Answer: Wishbone requires a tough quarterback. Like stated earlier, they get hit A LOT.  The offense can still work with smart disciplined offense players. My high school ran it sometimes and it opens up play-action passes quite well. Play to your strengths. If you have big road-grader lineman, a big tough fullback, a smart QB with speed, along with a fast HB, you can run it effectively. We always put our fast and more athletic guys on defense and hoped to win 14-7 or something similar to that.  Definitely not a sexy offense but it can be effective still if run right.  Maybe I'm just old school but I still think there's room for it in football.
Comment: I disagree about the need for good lineman. It is just the opposite. Hawaii was a great triple option team (rushing yardage, not necessarily wins) with hardly any quality lineman. You get angles, double-teams, and a quick-hitting fullback (no need to hold blocks). Combine that with some defenders not getting blocked at all (dive & pitch read) and you can have success with an inferior line.
Answer: Some of the other answers make valid points but I would like to give you a coach's take on this.  (And I disagree with the effectiveness of the wishbone scheme being ineffective - seriously at least 4-5 NFL teams run wishbone packages)
Given that I have a set of football players at a good high school level or college level, they have been coached for 4-10 years.  The chances that these kids were ever taught to drive-block correctly are almost 0%.
The wishbone offense basically lumps a good deal of players close to the ball.  It is predicated on mis-direction and offensive lineman getting the defensive players going backwards.  So a good wishbone team will have offensive lineman push defensive lineman back.  The d-backs not assigned a blocker (most linebackers would be assigned a blocker on most wishbone plays) would get caught up in the scrum of the blocked players.  In fact if you watch 8-10 year-old pee-wee teams that run the wishbone this is exactly what happens.
So from a coach's perspective I would have to reteach all of my offensive lineman to quit playing paddy-cake and throw a shoulder into their man and drive block.  This can be done but this would take total commitment and a lot of time.
Would the wishbone work?  God yes.  If Alabama switched to the wishbone right now they would be unstoppable.  They have the offensive lineman and the talent at the RB position to do it.  They would be just as good or better.  The fact is teams that practice against the spread weekly and don't hit as much at practice would get brutalized.  There are several top high school programs reverting back to the wishbone, wing, or heavy power I concepts trying to go against the grain.
However...  At the college level you need to recruit kids.  If Nick Saban decides to go wishbone say goodbye to getting any top WR or QB to commit to his school.  Sure he will still do OK but not nearly as well as he did.  Remember that more than half the skill position players - QB, RB, WR, FB, and TE are usually recruited based on offensive skills but will be converted to defense over time.  So if you cannot recruit top WRs because of the wishbone then your CB/S depth will be far worse.
Comment: Relative to the other SEC schools, Bama is barely in the middle when it comes to QB ranking especially when it comes to NFL potential. Agree on the WR area. I disagree with the Oline play. The academies are not driving anyone off the ball which is an advantage of the Triple Option.
Comment: @JeffO They are compared to who they play against.  You are missing the point.  The talent is relative.
Comment: Navy has beaten Notre Dame. They don't play just guppies.
Answer: Wishbone style attacks require patience and discipline. That's why the service academies often excel at it. Unfortunately, they don't have the personnel to compete with the big boys. The last great triple option team was actually the 1997 Nebraska team with Scott Frost at QB. They run it from the I formation.
Comment: I disagree that Nebraska was a triple option team. Double, zone and trap option were their form of the option over the years. Oklahoma under Switzer may have been the last.
Answer: The reason it's not used is because coaches are no longer a pillars of their institution.  They are always looking for better opportunities and they don't wish to appear like a dinosaur who is isn't up on the latest offensive theory
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: Will Cole's point #3 is the closest to an accurate answer. Marketing. College sports is all about the money and the players make it for the college U-Marts. So teams do what they believe will attract talent.
The stupid argument about players being faster nowadays is the same one the pros tried to use for the past fifty years. Joke's on them as SF used a variant of wishbone football all the way to the Super Bowl this year. Georgia Tech has been a scoring machine running the wishbone but their defense was horrible.
Any offense will work with the proper execution and superior talent. Coaches are slaves to fashion and since the wishbone isn't in vogue they don't want to appear out of the loop. So they sheeple on.
Nothing in football looks as artistic as a properly executed triple option. Nothing.
Incessant passing is boring. Nothing as ugly as an incomplete or even completed out route.

What happened to the wishbone?


Fazer um input receber um valor menor que outro

Question:

<input type="number" name="total" value="25" required>
<input type="number" name="valor-em-dinheiro" class="form-control text-right" required>

Tenho dois input aonde o primeiro receber o valor de 25, queria saber como fazer o segundo não receber um valor menor que o primeiro.
Answer: Use o atributo [min][1].

<input type="number" name="total" value="25" required>
<input type="number" name="valor-em-dinheiro" class="form-control text-right" required min="25">
Comment: Mas o valor do primeiro e dinâmico
Comment: Você pode alterar o valor mínimo com JS também, fazendo `document.getElementById("elemento").min = "25";`, por exemplo.
Answer: Se for fazer isso de forma dinâmica, utilize JavaScript com o evento blur, igualando o valor caso seja menor.
O min pode ser usado para efeito de validação se você está utilizando um formulário a ser submetido.
Se não for este o caso, pode utilizar o evento blur abaixo:

document.querySelector("[name=valor-em-dinheiro]").onblur = function(){

   // valor do primeiro input. Se for vazio vira 0
   var total = document.querySelector("[name=total]").value || 0;

   // valor do segundo input
   var dindin = this.value;

   // se o segundo for menor que o primeiro, iguala
   if(Number(dindin) < total) this.value = total;
}
<input type="number" name="total" value="25" required>

Digite um valor menor e tecle TAB:
<input type="number" name="valor-em-dinheiro" class="form-control text-right" required>

Se for submeter o formulário, pode alterar o min de forma dinâmica:

document.querySelector("[name=total]").oninput = function(){
   // altera o min do segundo input de acordo com o valor digitado
   document.querySelector("[name=valor-em-dinheiro]").min = this.value;
}

document.querySelector("[name=valor-em-dinheiro]").oninput = function(){

   // seleciona o primeiro input
   var total = document.querySelector("[name=total]");

   // altera o min de acordo com o valor de total
   this.min = total.value;

}
<form>
   <input type="number" name="total" value="25" required>
   <input type="number" name="valor-em-dinheiro" class="form-control text-right" required>

   <button>Enviar</button>
</form>
Comment: mas e pra proibir o usuário de digitar um numero menor essa função de digitar o tab pra poder ativa a função não ficaria legal pra mim.
Comment: Entendo. Vc vai submeter esse formulário?
Comment: Sim, irei submeter
Comment: O problema é o seguinte: se o cara quiser digitar "200", é maior que 25, só que ao digitar o número "2" inicial, é menor que 25. Por isso tem que ter algum evento final para saber que valor o cara digitou. Quando ele faz um blur, é porque ele já digitou o valor que queria e saiu no input.
Comment: Ele não tem que teclar em TAB. O TAB foi só um exemplo para sair do campo.
Comment: ahhh entendi, agr se eu quisesse fazer isso com uma div in vez do input
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/86745/discussion-between-vision-development-and-sam).
Comment: Costumo colocar o gatilho no evento `change`. Independente do cara sair do campo (blur) ou submeter o formulário (submit), o `change` será executado.
Comment: @LipESprY O problema é que o change só tem efeito nas setas, e olha que o IE nem seta tem. Então ele terá o mesmo efeito que o blur, porque o change só é disparado quando tira o foco do campo.
Comment: @Sam Sempre usei o change. Fiquei curioso com sua resposta e fui testar! Coloquei 2 gatilhos em um input: change e blur. Editei o input e pressionei Enter (submit). No Chrome foi disparado apenas o change. No IE foram disparados ambos...
Answer:

document.querySelector('[name=valor-em-dinheiro]').onchange = function() {
    console.log('change disparado');
    if(this.value < document.querySelector('[name=total]').value) {
        alert('Valor em dinheiro deve ser maior ou igual ao total!');
        // ...
    }
}
// No Chrome (atualizado) não é acionado o blur caso o usuário pressione "enter" para submeter o formulário.
//document.querySelector('[name=valor-em-dinheiro]').onblur = function() {
//    console.log('blur disparado');
//}
document.querySelector('[id=formul]').onsubmit = function(ev) {
    if(document.querySelector('[name=valor-em-dinheiro]').value < document.querySelector('[name=total]').value) {
        ev.preventDefault();
        console.log('submit interrompido');
    } else {
        ev.preventDefault(); // LEMBRE-SE DE COMENTAR ESTA LINHA APÓS TESTAR.
        console.log('submit não interrompido');
    }
}
  <form action="/dev" method="get" id="formul">
      <input type="number" name="total" value="25" required>
      <input type="number" name="valor-em-dinheiro" class="form-control text-right" required>
      <input type="submit" value="Submit">
  </form>

Use como exemplo. Altere conforme sua necessidade. A fim de testar, coloquei um alert() e um preventDefault() caso o usuário tente submeter o formulário com o valor menor.
Dessa forma (onchange), o gatilho será acionado até mesmo quando o usuário pressionar enter após definir o valor do segundo campo.


enet() works but not when run via caret::train()

Question: I'm trying to run an elastic net.  Starting with LASSO and going from there.  I can get it to run directly but it fails when I try to run the same parameters using train in the caret package.  I'd like to get train working so that I can use it to evaluate model parameters.
# Works
test <- enet( x=x, y=y, lambda=0, trace=TRUE, normalize=FALSE, intercept=FALSE )
# Doesn't
enetGrid <- data.frame(.lambda=0,.fraction=c(.01,.001,.0005,.0001))
ctrl <- trainControl( method="repeatedcv", repeats=5 )
> test2 <- train( x, y, method="enet", tuneGrid=enetGrid, trControl=ctrl, preProc=NULL )
  fraction lambda RMSE Rsquared RMSESD RsquaredSD
1    1e-04      0  NaN      NaN     NA         NA
2    5e-04      0  NaN      NaN     NA         NA
3    1e-03      0  NaN      NaN     NA         NA
4    1e-02      0  NaN      NaN     NA         NA
Error in train.default(x, y, method = "enet", tuneGrid = enetGrid, trControl = ctrl,  :
  final tuning parameters could not be determined
In addition: There were 50 or more warnings (use warnings() to see the first 50)
> warnings()
...
50: In eval(expr, envir, enclos) :
  model fit failed for Fold10.Rep5: lambda=0, fraction=0.01 Error in enet(as.matrix(trainX), trainY, lambda = lmbda) :
  Some of the columns of x have zero variance

Note that any collinearity in the above example is just a result of subsetting down for a reproducible example (1,000 rows vs. 208,000 in the real dataset).
I've checked the full dataset in various ways, including findLinearCombos.  Note that a few hundred of the variables are dummied out from clinical diagnoses and thus are binary with a low proportion of 1's.
How do I get train(...,method="enet") to run using the exact same settings asenet()`?
Data for reproducibility, sesionInfo, etc.
Sample data x and y are available here.
Results of sessionInfo():
R version 3.0.1 (2013-05-16)
Platform: x86_64-pc-linux-gnu (64-bit)

locale:
 [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C         LC_TIME=C            LC_COLLATE=C         LC_MONETARY=C        LC_MESSAGES=C        LC_PAPER=C
 [8] LC_NAME=C            LC_ADDRESS=C         LC_TELEPHONE=C       LC_MEASUREMENT=C     LC_IDENTIFICATION=C

attached base packages:
 [1] parallel  splines   grid      stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] scales_0.2.3        elasticnet_1.1      fscaret_0.8.5.3     gsubfn_0.6-5        proto_0.3-10        lars_1.2            caret_5.17-7
 [8] foreach_1.4.1       cluster_1.14.4      lubridate_1.3.0     HH_2.3-37           reshape_0.8.4       latticeExtra_0.6-24 leaps_2.9
[15] multcomp_1.2-18     perturb_2.05        Zelig_4.2-0         sandwich_2.2-10     zoo_1.7-10          survey_3.29-5       Hmisc_3.12-2
[22] survival_2.37-4     lme4_0.999999-2     bayesm_2.2-5        stargazer_4.0       pscl_1.04.4         vcd_1.2-13          colorspace_1.2-2
[29] mvtnorm_0.9-9995    car_2.0-18          nnet_7.3-7          gdata_2.13.2        gtools_3.0.0        spBayes_0.3-7       Formula_1.1-1
[36] magic_1.5-4         abind_1.4-0         MapGAM_0.6-2        gam_1.08            fields_6.7.6        maps_2.3-2          spam_0.29-3
[43] FNN_1.0             spatstat_1.31-3     mgcv_1.7-24         rgeos_0.2-19        RArcInfo_0.4-12     automap_1.0-12      gstat_1.0-16
[50] SDMTools_1.1-13     rgdal_0.8-10        spdep_0.5-60        coda_0.16-1         deldir_0.0-22       maptools_0.8-25     nlme_3.1-110
[57] MASS_7.3-27         Matrix_1.0-12       lattice_0.20-15     boot_1.3-9          data.table_1.8.8    xtable_1.7-1        RCurl_1.95-4.1
[64] bitops_1.0-5        RColorBrewer_1.0-5  testthat_0.7.1      codetools_0.2-8     devtools_1.3        stringr_0.6.2       foreign_0.8-54
[71] ggplot2_0.9.3.1     sp_1.0-11           taRifx_1.0.5        reshape2_1.2.2      plyr_1.8            functional_0.4      R.utils_1.25.2
[78] R.oo_1.13.9         R.methodsS3_1.4.4

loaded via a namespace (and not attached):
 [1] LearnBayes_2.12  compiler_3.0.1   dichromat_2.0-0  digest_0.6.3     evaluate_0.4.4   gtable_0.1.2     httr_0.2         intervals_0.14.0 iterators_1.0.6
[10] labeling_0.2     memoise_0.1      munsell_0.4.2    rpart_4.1-1      spacetime_1.0-5  stats4_3.0.1     tcltk_3.0.1      tools_3.0.1      whisker_0.3-2
[19] xts_0.9-5

Update
Run on a 15% sample of the dataset:
Warning in eval(expr, envir, enclos) :
  model fit failed for Fold10.Rep1: lambda=0, fraction=0.005
... (more of the same warning messages) ...
Warning in nominalTrainWorkflow(dat = trainData, info = trainInfo, method = met\
hod,  :
  There were missing values in resampled performance measures.
Error in if (lambda > 0) { : argument is of length zero
Calls: train ... train.default -> system.time -> createModel -> enet

There are 806 columns of the X matrix, 801 of them dummies.  Many of these dummies are extremely sparse (1-3 observations out of 25k or so rows), others have 0.1-5% of their values as TRUE.  In total, there are 108867 TRUE's and 21mm FALSE's.
Comment: It is the problem of subsampling. When the crossvalidation is running, some samples are drawn such way that some columns become constant. In whole data that is used by enet there no constant columns, so enet() goes fine. But in samples used for crossvalidation they are.
Comment: @GavinSimpson I was thinking it would be more appropriate here, but I guess not.  Flagged for migration to SO.
Comment: This question appears to be off-topic because it is about coaxing R to do what you want or using a package and not a statistical issue.
Comment: Did you get any error message running `train()` ?
Comment: If the main problem is collinearity, one of possible approaches is to add small (relatively to columns' standard deviations) random error to data before running `train()`
Comment: The same should work with zero variance as well
Comment: @O_Devinyak Why would `enet` work when run directly then?
Comment: @O_Devinyak Plus I don't think it had that problem when I ran it on the full dataset.  Just an artifact of having a sample dataset
Comment: @O_Devinyak But 20% of 200k observations is still 40k observations.  If `enet` can run on 1000 observations, why can't `train` run it on a subsample?
Comment: In the example both methods are run with the same `x`. Do the really used different: `enet` on 1000 but `train` on 200k?. In any case it is good to check whether there are many duplicated values in some column. Like `sapply(x,function(column){max(table(column))}`
Comment: @O_Devinyak Noted in the question: the example dataset (`enet` and `train` both run on) has 1k observations, but the real dataset (`enet` and `train` both run on) has 208k.  Problem still occurs in real dataset, without the warnings().
Comment: I've checked the full dataset in various ways, including findLinearCombos. Note that a few hundred of the variables are dummied out from clinical diagnoses and thus are binary with a low proportion of 1's.
Comment: The given warning says that in case of 1k observations the fail is caused by sampling of nearly constant column. The cause why the whole data run fails as well is not so straightforward since there were no warnings. The ways to test that fact are 1)delete that binaries and check `train()` 2) Add random error to these columns 3) Write your own crossvalidation function with splitting that is stratified by given columns
Comment: @O_Devinyak Ok.  I'm running on the full dataset now to confirm the warning is still there, and I'll try to implement some of your suggestions and see how it goes.  Thanks.
Comment: To decrease the running time you may pass `repeats=1` to `trainControl()`. Note, that you are running not five-fold crossvalidation, but 5 independent iterations of ten-fold. For testing 1 iteration is enough. I hope my suggestions will help.
Comment: @O_Devinyak Thanks.  Stopped the 5x and trying the 1x.
Answer: Just to bring some resolution to this, I have it working now.  I dropped all columns with less than 20 TRUE's (remember, this is out of almost 200k observations) as simply having insufficient information to contribute.  This wound up being about half of them.
I will have to be cautious that these sparse columns don't contribute too much bias, etc. as I move forward, but I am hoping that by using a method that does variable selection (lasso, RF, etc.) that will be less of a problem.
Thanks to @O_Devinyak for the help.


How can I make clusters with highly right skewed data?

Question: My histogram of expected income is as below.
As you can see, income is highly right skewed. I want to divide individuals with regard to income - for example into Low, Middle, and High, and then I want to compare the other properties of individuals in each of the three groups.
Any idea about dividing into groups with highly right skewed data?
Comment: Take the logarithm of **x** and then plot that.
Answer: Use a non-linear function. Functions such as $\log x$, $e^x$ and $\sqrt{x}$ change skewedness of your data.
The exact "correct" scaling depends on your data, and can often only be guessed.
For income data, $\log(x)$ or $\log(x+1)$ might work.


Exercise regarding distance between a given point and the kernel of a particular linear functional

Question: Let $\mathcal{X} =\{ x \in \mathbb{R}^\mathbb{N} : \lim x_n = 0\}$, with the sup norm, and $f: \mathcal{X} \to \mathbb{R}$ be a linear functional defined by $f(x) = \sum_{k = 1}^\infty 2^{-k+1}x_k$. The functional is continuous, with norm $||f|| \leq 2$.
Consider $\alpha \in \mathcal{X} \setminus \ker(f)$. Prove that there is not a point $x \in \ker(f)$ such that $||x - \alpha|| = dist(\alpha, \ker(f))$. I tried using the fact that $dist(\alpha, \ker(f)) = \frac{|f(\alpha)|}{||f||}$ - but to no avail.
Can anyone help me?
Comment: Is the $n$ in the definition of $f$ actually a $k$?
Comment: https://math.stackexchange.com/questions/253953/distance-between-point-and-linear-space has a nice proof of this fact.
Comment: That's very nice actually!
Comment: If it is a $k$ then by choosing vectors $x_n$ from $X$ with first $n$ elements equal 1 and the rest zeroes you can see that $f(x_n)\to 2$ as $n\to\infty$ and therefore $\|f\|=2$.
Comment: Why is $\text{dist}(\alpha, \ker(f)) = \lVert f(\alpha)\rVert/\lVert f\rVert$?
Answer: If there were some such $x$, then $\lVert x - \alpha\rVert = \frac{\lVert f(\alpha)\rVert}{\lVert f\rVert}$.
We'd have:
$$\begin{align}
\lVert f(\alpha)\rVert
&=
\lVert f(x - \alpha)\rVert
\\&\leqslant
\lVert f\rVert \lVert x - \alpha\rVert
= \lVert f(\alpha)\rVert
\end{align}$$
In other words, $\lVert f\rVert = \frac{\lVert f(x - \alpha)\rVert}{\lVert x - \alpha\rVert}$, so the operator norm is attained.
Hint: Is this possible for this operator?
Super Hint:

 Remember that $\lVert f \rVert = \sup\{ \lVert f(v)\rVert\,;\, \lVert v \rVert = 1\}$ and consider the sequence $v = (1,1,1,\dots)$.

It does not lie in $\mathcal X$, but it can be approximated by elements of $\mathcal X$. Can any $x\in \mathcal X$ do as good as $v$, with respect to attaining $\lVert f\rVert$?


How to find the ID of a webform?

Question: I am working with webform module , I have added two different forms in my website.
I have customized the forms according to my convenience, as I have changed the css. These changes are reflected in the two forms.
Now i need to get the id of these forms so i can further customize one of them.
I have added this css code for form
<code>.form-text,
.form-textarea {
   width: 100%;
}
</code>
Comment: ues firebug addon on firefox to find the id of your form
Answer: Try the Get Form ID module:

By hovering over any form you will see a contextual link
  available. By expanding the link you will see the form ID. Click
  on the link and you will see a modal window with copyable form id and
  hook_form_FORM_ID_alter() hook suggestion.

Step 1: hover over the form.

Step 2: expanding the contextual link.

Step 3: Click on the link and a new window will open with copyable form id and hook_form_FORM_ID_alter() hook suggestion
Answer: You can get the form id from the form_id hidden field of the webform. Go to source view of the form from your browser and search for form_id.
Answer: Just another method. If you use Devel module, you can add this code snippet to your custom module to view the form id.
<code>function [module_name]_form_alter(&$form, &$form_state, $form_id){
  dpm($form_id);
}
</code>
Answer: You can use firebug

Just right click the FORM using Chrome Browser and click Inspect Element

Select form tag,  you can see the FORM ID inside ID attribute
Answer: Webform forms usually have the id webform_client_form_nid. Where nid is your node id.

How to find the ID of a webform?


Adding Tracer beans in Spring Boot with OpenTelemetry

Question: Context:
I have to rewrite a parent library from Java EE to a more modern one in Spring Boot. For example, it has got some deprecated dependencies and CDI parts, Microprofiles that are not Spring compatible.
Problem:
I have hardly used OpenTelemetry and OpenTracing. I understand only the high-level concepts but I have never coded such things. I have trouble rewriting a part that involves OpenTracing. I know OpenTracing is deprecated and I should use OpenTelemetry. There is a dependency called 'Tracer Resolver'.
Its description from Github: Resolver API for OpenTracing Tracer implementations. NOTE: The Tracer Resolver mechanism is only intended to be used at application startup/initialization time. This responsibility should be handled by the application, possibly using some runtime-specific support (e.g. providing a Tracer @Bean in Spring Boot, or a CDI producer). Framework integrations used to instrument-specific technologies should not use this library, but should allow a Tracer to be injected instead, with fallback to the GlobalTracer.
In the code the only OpenTracing dependency:
<dependency>
    <groupId>io.opentracing.contrib</groupId>
    <artifactId>opentracing-tracerresolver</artifactId>
    <version>0.1.8</version>
</dependency>

And I found the usage in the code as:
@ApplicationScoped
public class OpenTraceResolver {

    @Inject
    private Instance<Tracer> tracerInstance;

...

or
@Provider
public class OpenTraceErrorResponseFilter implements ContainerResponseFilter {

    @Inject
    private Tracer configuredTracer;

...

How should I do the same with OpenTelemetry? Is there a way to use it in such a simple way?
Thank you for your help!
Answer: First of all, Spring uses Spring Cloud Sleuth project for implementing distributed tracing and you need to add it to your project before configuring open telemetry. By default, Spring Cloud Sleuth uses OpenZipkin Brave, which is different from OpenTelemetry (Otel) implementation.
To configure your project to use OpenTelemetry you need to decide if you will go with auto-instrumentation which is more straightforward (using agents on not) or with manual instrumentation, with gives you more flexibility.
With auto-instrumentation, you can use the java agent with some properties like the example below
java -javaagent:opentelemetry-java-agent-all.jar -Dotel.exporter.otlp.traces.endpoint=http://yourTraceServerEndpointUrl yourApp.jar

to your app execution script (ie. Dockerfile). More info on https://github.com/open-telemetry/opentelemetry-java-instrumentation
or change your pom.xml and configure an exporter backend in your application.yaml and it will automatically generate and export the traces for you.
application.yaml
spring.sleuth.otel.exporter.otlp.endpoint=[URL TO YOUR OTEL BACKEND]

you can send the traces to zipkin, grafana tempo and etc..
pom.xml

<properties>
  <spring-cloud.version>2021.0.0-M2</spring-cloud.version>
  <spring-cloud-sleuth-otel.version>1.1.0-M3</spring-cloud-sleuth-otel.version>
  <opentelemetry-exporter-otlp>1.7.0</opentelemetry-exporter-otlp>
  <grpc-netty-shaded>1.41.0</grpc-netty-shaded>
</properties>

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-dependencies</artifactId>
      <version>${spring-cloud.version}</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-sleuth-otel-dependencies</artifactId>
      <version>${spring-cloud-sleuth-otel.version}</version>
      <scope>import</scope>
      <type>pom</type>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-sleuth</artifactId>
  <exclusions>

    <exclusion>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-sleuth-brave</artifactId>
    </exclusion>
  </exclusions>
</dependency>

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-sleuth-otel-autoconfigure</artifactId>
</dependency>

<dependency>
  <groupId>io.opentelemetry</groupId>
  <artifactId>opentelemetry-exporter-otlp</artifactId>
  <version>${opentelemetry-exporter-otlp}</version>
</dependency>

<dependency>
  <groupId>io.grpc</groupId>
  <artifactId>grpc-netty-shaded</artifactId>
  <version>${grpc-netty-shaded}</version>
</dependency>

<repositories>
  <repository>
    <id>spring-snapshots</id>
    <url>https://repo.spring.io/snapshot</url>
    <snapshots>
      <enabled>true</enabled>
    </snapshots>
  </repository>
  <repository>
    <id>spring-milestones</id>
    <url>https://repo.spring.io/milestone</url>
  </repository>
</repositories>
<pluginRepositories>
  <pluginRepository>
    <id>spring-snapshots</id>
    <url>https://repo.spring.io/snapshot</url>
  </pluginRepository>
  <pluginRepository>
    <id>spring-milestones</id>
    <url>https://repo.spring.io/milestone</url>
  </pluginRepository>
</pluginRepositories>

More references

https://github.com/open-telemetry/opentelemetry-java-instrumentation
https://opentelemetry.io/docs/instrumentation/java/
https://github.com/spring-projects-experimental/spring-cloud-sleuth-otel
Comment: just a small note, that Sleuth is being deprecated in Spring 3, so this is not the preferred way to initialize otel in new projects.
Comment: Spring 3 now uses new distributed tracing support with Micrometer Tracing (formerly Spring Cloud Sleuth) More info on https://spring.io/blog/2022/10/12/observability-with-spring-boot-3


Need Reference: Product over invertible elements of finite fields is -1

Question: so there's the following fact: For all finite fields $K$, it holds that
$$\prod\limits_{k \in K^*} k = -1.$$ I know how to prove it, but I'd really like to just include a reference. However, for the life of me I somehow cannot find this fact as a theorem or similar in any of my Algebra books. Can anybody tell me whether this fact has a name, or give me a reference to some book that proves it?
Thanks!
Answer: The product of an invertible element with its inverse is $1$. If we just break this product up into pairs of elements $x, x^{-1}$, then the product of each pair will be $1$, so the whole product should be $1$, right?
This argument fails precisely when $x = x^{-1}$. When is that? $x^2 - 1$ is a degree $2$ polynomial, so it has at most two roots. Indeed, they are precisely $+1$ and $-1$. So the product breaks up into one $1$, one $-1$, and a bunch of pairs that multiply to $1$.


How to install zip extension for PHP 7.4 compiled from scratch on CentOS 7?

Question: I have a PHP 7.4.2 installation, which is installed by compiling from the scratch. The configure command I used is as given below :
'./configure' '--with-apxs2=/usr/bin/apxs' '--with-curl=/usr' '--with-gd' '--with-gettext' '--with-jpeg-dir=/usr' '--with-freetype-dir=/usr' '--with-openssl' '--with-mcrypt=/usr/local/lib' '--with-mhash' '--with-mysql=mysqlnd' '--with-mysqli=mysqlnd' '--with-pcre-regex' '--with-pear' '--with-png-dir=/usr' '--with-xsl' '--with-zlib' '--with-zlib-dir=/usr' '--with-iconv' '--enable-bcmath' '--enable-calendar' '--enable-exif' '--enable-ftp' '--enable-gd-native-ttf' '--enable-soap' '--enable-sockets' '--enable-zip'

Now when I tried to use the ZipArchive class, I realized that the zip extension is not installed or enabled. It is not showing in my phpinfo() and the code is showing an error
Fatal error: Class 'ZipArchive' not found
I think the configure option for adding the zip extension has been changed in PHP 7.4 versions and I should have used --with-zip instead of --enable-zip.
I tried using pecl to install the extension and it is returning in the following error:
checking libzip... yes
checking PHP version... 7.4
checking for pkg-config... /bin/pkg-config
checking for libzip... not found
configure: error: Please reinstall the libzip distribution
I tried to install the extension from the pecl archive and the configure command returned in the same error. I am doing this on CentOS 7 and some posts are suggesting to install libzip-devel package. But it is only available as part of third party repository. As this is a production environment I can't do that either.
If I reinstall PHP from scratch running the configure command again, will it install the extension ? Will it affect any of my existing setups ? I have installed and enabled SVN extnsion
Comment: Why not simply recompile PHP with built-in ZIP support?
Comment: According to https://centos.pkgs.org/7/centos-x86_64/libzip-devel-0.10.1-8.el7.x86_64.rpm.html it should be just `yum install libzip-devel`
Comment: Why building from sources when well maintained packages exist ?
https://rpms.remirepo.net/wizard/
Answer: The zip extension requires the libzip library. So you can compile it from source. However the libzip library requires the zlib library. To make sure that you won't miss anything important, the best if I show you how I'm doing it.
This is how I compile 7.4 from source on our centos 7 servers
First I'm installing package update and installing the missing packages:
sudo yum update
sudo yum -y install lzip oniguruma oniguruma-devel

# OR if you cant find the packages you can use RPMs - example:
curl https://dl.fedoraproject.org/pub/epel/7/x86_64/Packages/o/oniguruma-5.9.5-3.el7.x86_64.rpm --output oniguruma-5.9.5-3.el7.x86_64.rpm
rpm -Uvh oniguruma-5.9.5-3.el7.x86_64.rpm

Installing the CMake:
cd
# installing compiled cmake
wget -c https://cmake.org/files/LatestRelease/cmake-3.16.0-Linux-x86_64.tar.gz
tar zxvf cmake-3.*

# OR install it from source:
curl -OL https://github.com/Kitware/CMake/archive/v3.16.5.tar.gz
tar zxvf v3.16.5.tar.gz

cd CMake-3.*
./bootstrap --prefix=/usr/local
sudo make -j2
sudo make install
# maybe this is not required:
sudo cp ~/CMake-3.16.5/bin/cmake /usr/bin/

Compile the zlib:
wget -c http://www.zlib.net/zlib-1.2.11.tar.gz
tar zxvf zlib-1.2.11.tar.gz
cd zlib-1.2.11
./configure
sudo make -j2
sudo make install

Compile the libzip for the zip extension:
cd
wget -c https://libzip.org/download/libzip-1.6.1.tar.gz
tar zxvf libzip-1.6.1.tar.gz
cd libzip*
mkdir build
cd build
cmake ..
sudo make -j2
make test
sudo make install

Copy the built file and add it to the variables
sudo cp /home/centos/libzip-1.6.1/build/libzip.pc /usr/local/lib64/pkgconfig/libzip.pc

# Also add this to the env variables for each session - later in the guide
export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib64/pkgconfig/

Compiling php:
if php is already installed through a package installer, then delete it.
sudo yum-config-manager --disable remi-php74
sudo yum remove php php-cli php-common php-opcache php-mcrypt php-gd php-curl php-fpm php-dom php-intl php-pecl-mongodb php-mbstring php-xml php-pear php-devel php-pecl-zip

Extra info for compiling: https://shaunfreeman.name/compiling-php-7-on-centos
# for some reason libzip-last wont do what you need, so you need to compile it as it's written above
sudo yum install httpd-devel git gcc gcc-c++ readline-devel libxml2-devel libzip-last libxslt-devel pkgconfig openssl-devel bzip2-devel curl-devel libpng-devel libjpeg-devel libXpm-devel freetype-devel gmp-devel libmcrypt-devel mariadb-devel aspell-devel recode-devel autoconf bison re2c libicu-devel
sudo mkdir /usr/local/php7
cd

# OPTION A
git clone https://github.com/php/php-src.git
cd php-src
git checkout PHP-7.4.5

# OPTION B
# use the release tar instead of the source branch
curl -OL https://github.com/php/php-src/archive/php-7.4.5.tar.gz
tar zxvf php-7.4.5.tar.gz

cd php-src-php-7.4.5
./buildconf --force
./configure --prefix=/usr/local/php7 \
    --with-config-file-path=/usr/local/php7/etc \
    --with-config-file-scan-dir=/usr/local/php7/etc/conf.d \
    --with-apxs2=/usr/bin/apxs \
    --enable-bcmath \
    --enable-fpm \
    --with-bz2 \
    --with-curl \
    --disable-phpdbg \
    --disable-phpdbg-webhelper \
    --enable-filter \
    --enable-gd \
    --with-freetype \
    --with-jpeg \
    --enable-intl \
    --with-mysql-sock=/var/lib/mysql/mysql.sock \
    --with-openssl \
    --enable-simplexml \
    --enable-xmlreader \
    --enable-xmlwriter \
    --enable-pcntl \
    --enable-shmop \
    --enable-sysvmsg \
    --enable-sysvsem \
    --enable-sysvshm \
    --with-xsl \
    --enable-opcache \
    --enable-calendar \
    --enable-sockets \
    --enable-mbstring \
    --with-readline \
    --with-zlib=~/libzip-1.6.1/build/ \
    --with-zip \
    --enable-exif \
    --with-gettext \
    --without-sqlite3 \
    --with-mhash \
    --enable-maintainer-zts
sudo make -j2
sudo make install
sudo mkdir /usr/local/php7/etc/conf.d
sudo cp -v ./php.ini-production /usr/local/php7/lib/php.ini
sudo cp -v ./sapi/fpm/www.conf /usr/local/php7/etc/php-fpm.d/www.conf
sudo cp -v ./sapi/fpm/php-fpm.conf /usr/local/php7/etc/php-fpm.conf
sudo vim /usr/local/php7/etc/conf.d/modules.ini

the make -j2 defines how much core threads you would like to use to compile.
The other line you should notice is this one:
--with-zlib=~/libzip-1.6.1/build/ \

During the configuration use the package of your own need.
php is running primarily from here: /usr/bin/php
And your built php will be located here: /usr/local/php7/bin/php
so you might will need overwrite it:
sudo mv /usr/local/php7/bin/php /usr/bin/php
That's not all, but it covers every important part with the zip extension.
Answer: Give a try on this:
yum install php74-libzip.x86_64
yum install php-pecl-zip

Answer: In CentOS you have yum
You can do the following and it should work. I just texted it in a fresh CentOS with PHP 7.4.
You don't need to reinstall PHP, you just need to add the extension.
Install dependencies (you will need to run as root)
yum install pcre-devel gcc zlib zlib-devel  libzip-devel make

Install zip using PECL
pecl install zip

Edit /etc/php.ini to register the new module
(you will need to open as root)
extension=zip.so;


Why is my form_state being reset after submission?

Question: I have a menu item with page callback:
function my_menu() {
  $items = array();
  $items['my/action/%ctools_js'] = array(
    'title' => 'do something',
    'page callback' => 'my_action',
    'page arguments' => array(2,3),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
}

function my_action($js = NULL, $nid = NULL) {
  $form_state = array('nid' => $nid);
  if(!$js) {
    drupal_build_form('my_action_form', $form_state);
  }
  ctools_include('modal');
  ctools_include('ajax');
  $form_state['ajax'] = $js;
  $form_state['title'] = t('Form Title');
  $output = drupal_build_form('my_action_form', $form_state);
  $commands = array();
  if (!empty($form_state['finished'])) {
    $commands[] = ctools_modal_command_dismiss();
    $commands[] = ctools_ajax_command_redirect('challenges');
  } else {
    ctools_modal_form_render($form_state, $output);
  }
  print ajax_render($commands);
  exit;
}

function my_action_form($form, &$form_state) {
  // form fields defined here
}

function my_action_form_validate($form, &$form_state) {
  // $form_state['finished'] = true;
}

function my_action_form_submit($form, &$form_state) {
  $form_state['finished'] = true;
}

If I uncomment out the line in my_action_form_validate The modal form dismisses and the redirect works. But with that line commented out when I try to set the $form_state var in submit, the modal doesn't dismiss and doesn't redirect. The form submit code executes (calls to drupal_set_message work fine), but by the time it gets back to the conditional (line 11) in my_action, $form_state has been set to default and a blank form reappears in the modal popup. How can I dismiss the modal window after submission?
Answer: The issue was in the callback frunction my_action(). I was using the ctools_modal_form_render() function wrong. In the end I replaced the call to ctools_modal_form_render() with ctools_modal_form_wrapper():
function my_action($js = NULL, $nid = NULL) {
  if(!$js) {
    $form_state = array( 'nid' => $nid );
    return drupal_build_form('my_action_form', $form_state);
  }
  ctools_include('modal');
  ctools_include('ajax');
  $form_state = array(
    'title' => t('My Action Form'),
    'ajax' => TRUE,
    'nid' => $nid
  );
  $output = ctools_modal_form_wrapper('my_action_form', $form_state);
  if ( !empty($form_state['executed']) ) {
    $output = array();
    $output[] = ctools_modal_command_dismiss();
  }
  print ajax_render($output);
  exit;
}