Why is my neck pickup quieter when playing with both pickups?

Question: I have an Epiphone Les Paul and have noticed that when the pickup selector is set to both pickups, my guitar plays very softly from the neck pickup.
When I play from the pickups separately the volume is similar.
Is it designed to be this way? Or do I need to have this fixed?
If so can I fix this myself or is it complex?
Comment: When the Pickup toggle is in middle position is the tone noticeably thinner or nasally sounding?
Comment: Couple of issues here. Can you clarify this: "pickup selector is set to both pickups, my guitar plays very softly from the neck pickup." If you are playing with both pickups engaged, how do you know it's the neck pickup that's playing "softer?" If you are losing volume at the middle position on the switch then you could have a wiring issue that's not related to the circuit (i.e. series/parallel). Did you purchase the guitar new? Do you know if it has any modifications or is the wiring stock?
Comment: I have this same guitar and I've had to fix my pickup switch twice.  It would only play the neck pickup when in the middle position.  I corrected this by bending the little contact so that it would not shut off the bridge pick up.
Answer: It's possible the pickup selector switch has a dirty contact for the front-pickup when in the middle position. I have an old Ibanez that does the same thing sometimes when I switch to the neck pickup.
I haven't seen what type of switch Epiphone guitars use, but my Les Pauls had an open-back switch, so it was possible to take off the switch cover and carefully squirt some contact cleaner on the contacts.
Contact cleaner can be found at electronic and hardware stores. It's a very light lubricant that helps to flush out dirt or debris that can affect potentiometers and switches. It is NOT the stuff you'd use to clean your contacts that go in your eyes.
Comment: Yes unfortunately. Some companies use horrible switches and pots. Heck, Gibson used cheap pots and switches in the old days, but at least they were CTS so they were relatively sturdy. The good thing is its easy to replace them with a little bit of good soldering technique.
Comment: All the Epiphone's I have worked on use open back three ways as well. Unfortunately they are usually cheaply made--that's one place where it's easy to skimp and not get caught.
Answer: It could be that the pickups are wired out of phase with each other, so when you have both selected there is a fair amount of cancellation. This tends to present itself as a much tinnier sound, with less middle and bass.
Or you have a bad switch - as per @theTinMan's post.
Comment: @Jason - that sounds much more like a switch contacts issue. Otherwise as you turned the bridge pickup volume down you would expect neck pickup volume to increase.
Comment: Then if it is this then you are saying it's not a problem just a different sound? ( I don't this so as it is very very soft only from the front pickup (when the bridge is set to 0 volume) meaning no cancellation is going on)
Answer: I'll hit the "is it complex?" question.
This is the Seymour Duncan schematic for Les Paul wiring. Pickup -> volume & tone -> switch -> jack. 4 wires connecting to the switch and one is ground. If phase is reversed, one or the other pickup should have the lead and ground wires reversed. If the switch has to be replaced and not just cleaned, it's 4 wires.
This may be more than you want to take on, but in terms of electronics, this is about as simple as it gets.
Answer: Its designed to split the "captation" for each pickup equally.
I think you should go to a luthier and fix that.
Comment: What is captation? google doesn't tell me what you mean...
Comment: He might mean capacitance, but it's unclear.
Comment: The word for "pick-up" (in a guitar context) in Portuguese and Spanish is "captador" (meaning "something that captures [sound]"). I think he got caught in a false cognate and he actually meant the "pickupiness" (if there was such a word) is split. This sentence would make a lot of sense in PT or SPN, but I'd rewrite it in English as "[The middle pickup position] is designed to have the output signal be a mix of the outputs of both pickups."


Are whole notes/rests really used to signify variable lengths of time?

Question: I saw this answer and I thought the guy was absolutely crazy for assuming that a whole note automatically equaled one measure regardless of time signature. However, there does appear to be more than one person who believes this. On a comment to this question,  Matthew Read states:

Personally I would use a whole rest, which ought to be understood thanks to the fact that it is already variable (used to represent the length of a bar irrespective of the time signature in most cases), but I don't think that's common practice.

Now my biggest issue with this idea stems more from a logical standpoint than a musical standpoint since most of the other notes/rests are defined as a fraction of the whole note. For example, the half note is generally defined as half a whole note:

half note
noun, Music.

a note equivalent in time value to one half of a whole note; minim.
— Dictionary.com

half note
noun
a musical note equal in time to ½ of a whole note
— Merriam-Webster

Half note
In music, a half note (American) or minim (British) is a note played for half the duration of a whole note (or semibreve) and twice the duration of a quarter note (or crotchet).
— Wikipedia

Now for example in 2/4 time that would somehow make all of the following true:

The half note is equal to a full measure
The whole note is equal to a full measure
The half note is equal to 1/2 of the whole note (even though they are both equal to a full measure).

So my question is: Is the whole note/rest really used as a note of variable length? If so, how common of a practice is it and how could this possibly be justified?
NOTE: I specifically mention notes in the question, but I am asking about the standpoint on both notes and rests since I normally think of individual rests as having a specific note that they are equal to in terms of length (if this is an incorrect way of thinking please correct me).
Comment: Well, yes. Absolutely. Look at any relevant music score - for instance. the beginning of Beethoven's 8th. The first page is crawling with whole rests that are actually 3/4 rests.
Comment: The note, no. The rest, yes. (If I were allowed to speculate why, it's probably to do with the fact that people are more willing to spend a bit of effort getting the detailed notation right for something that sounds than for something that doesn't.)
Comment: This is the most usual practice (I've sometimes seen dotted whole rests in 3/2 time, especially with dotted whole notes running around), and yes, it does apply only to the whole rest.  @KilianFoth: in my speculation, a whole rest just means ignore that measure in that staff.  Much easier to read than having different sorts of rests that would add up to the same thing.
Comment: Interesting. So you are saying it is an accepted practice that applies only to the rest?
Comment: @KilianFoth various notes *were* however used to specify different periods of time in mensural notation.
Answer: The other answers are using terminology which is common, but confusing. I think it's better to realize there are two different things here.

A whole-bar rest. This is always the same symbol whatever the length of the bar, and it is always positioned horizontally in the middle of the bar.

A whole-note rest. This has the same length as a whole-note. and is positioned horizontally in the same place as the note would be written, just like any other rest.

The apparent confusion comes from the fact that both 1 and 2 use the same symbol (but written in different places horizontally), and also that whole-note rests are very rare, because the only "common" time signatures where a bar is longer than a whole note are 3/2 and 4/2, and those have not been used much since about 1800.
Really, this is no more confusing that writing a dot after a note to add a half to its duration, and writing a dot above or below a note to shorten it (staccato). The same symbol means different things, depending on where it is written.
Comment: One caveat -- a whole-bar rest is always positioned in the middle of the bar in good modern typesetting. If you play from 19th c. or earlier scores, you will often find no distinction made in the positioning of whole-note rests and whole-bar rests.
Comment: @MichaelScottAsatoCuthbert but this would only be a problem for bars that are longer than a whole note but shorter than two whole notes (e.g., 3/2) because at 4/2 or longer they should start using breve rests for the whole-bar rest instead of semibreve rests.
Comment: @phoog -- You're right that it only causes a visual problem in those cases, but when a performer is used to reading modern scores, seeing a whole rest at the beginning of the bar in 3/4 in an old edition can throw them off temporarily.
Answer: Semibreve (whole note) rests are always used as measure rests, except occasionally for time signatures like 4/2, where a breve rest might be used instead. It's actually pretty simple: you know how many beats are in a given measure, so getting finicky about the actual time interval is a bit of a waste of energy when that voice isn't playing anything anyway. In most cases, a semibreve is greater than or equal to an entire measure, so a semibreve rest tells you quite succinctly that you've got an empty measure.
I would not use a semibreve rest to complete a measure - Matthew's comment that it might not be common practice is entirely correct. The rests that fill out the rest of the measure need to fill it exactly. In situations (like 4/2) where a semibreve is a division of the measure, semibreve rests will then be used according to their exact metric value.
I might add that this really is the conventional notation, and has been for centuries now.
Edit: you will not fill a measure with a semibreve note, however, except where the metre warrants it, i.e., 4/4, 2/2. If you have a note that holds for an entire measure of 3/4, for instance, you will use a dotted minim (half note). It is only for measure rests that the semibreve value carries the extra signification.
Comment: I assume that convention is somewhat based on the "old system for notating multirests" found on wikipedia *https://en.wikipedia.org/wiki/Rest_(music)*?
Comment: Actually, I expect so. The "old system" goes back quite a ways, to mensural notation. _Longa_ and _maxima_ rests had *two* ways of being notated, depending on whether they represented 2 beats or 3 beats, and semibreves functioned very much like quavers (eighth notes) do now. Semibreves being such a small unit, they didn't have multiple forms of rest, but as time progressed, music saw smaller and smaller subdivisions, and the unit of beat became smaller and smaller to match. See  https://en.wikipedia.org/wiki/Mensural_notation.
Comment: Do you know if this is still an accepted practice? I would have thought that by now they would have gone towards something that doesn't also have another meaning... If it were me I would probably vote just to use a multimeasure rest (if I'm choosing not to use the rests that correspond to the correct number of beats in the measure)...
Comment: Multi-measure rests now mainly take the form of the wide rest with the number of measures over it. Single measure rests, however, are still semibreve rests. That's in part because they still see use in polyphonic music where one voice in a stave might be active while another rests (i.e., multiple voices in one stave - this is still very common in keyboard music). Semibreve rests are very tidy in these situations.
Comment: Occasionally, mind you, you will see a multi-measure rest with a "**1**" over it in piano music when there is a measure of silence in all voices. I _think_ (I can't say for sure) that this is more common with French publishing houses. I saw such a score the other day, but I'll be damned if I can remember which piece of music it was.
Answer: Semibreve rest symbols centered in a bar are commonly used as whole-bar rest.  The equivalent of bordun notes that fill a bar with syllables in comparatively free meter (Monteverdi's Vespers contains quite a few prominent examples) is also notated in mid-bar but uses a brevis note (a double whole note), not a semibrevis (whole note).  This kind of notation has gone out of fashion since, so the discrepancy between whole bar rests and whole bar notes in their choice of symbol is rare to encounter these days.
Answer: The whole note symbol is generally used for whole bar rests written horizontally centered in the bar regardless of bar length (exception: 4/2 and similar meters that could cause confusion).
There is a similar centered note used for filling a whole bar with text (cf the falsoborduno recitatives in the "Dixit Dominus" of Monteverdi's vespers) on the same pitch, but the note glyph being used for that purpose is a brevis (nominally double the length of a whole note, a semibrevis).
This use is exceptional, however, as opposed to whole-bar rests which are ubiquitous.
Comment: Are you the same person as [user70671](https://music.stackexchange.com/a/101558/2257)?
Comment: You wrote: QUOTE: (exception: 4/2 and similar meters that could cause confusion). UNQUOTE No I disagree. The rest is placed in the middle of the bar. That makes it clear that it is a whole bar rest.
Answer: This is a very common misconception due to how the notes are named. All notes take up a very specific length of a measure as defined by the time signature.
In the most common time signature 4/4, which is also refereed to as common time, a whole note and rest both take the value of 4 quarter notes so it takes up the whole measure in 4/4. The half note and rest both  take the value of 2 quarter notes so it takes up half of the measure. The quarter note take the value of 1 quarter note and rest both so it takes up a quarter of the measure. This pattern continues in both directions as there are even values bigger then a whole note like the double whole note shown below.

So the naming scheme is build around 4/4 and it works perfectly there and makes sense, however when using it with other time signatures conceptual problems can arise and informally people will use a whole note rest for a whole measure. Just looking at the measure you can tell that you rest for the whole measure, but theoretically it is incorrect and should be avoided.
Comment: The very last sentence of your answer says: "Theoretically it is incorrect..."  This is your opinion, which you are intitled to, but you have several hundred years worth of accepted practice to argue with. Probably readers want to know the standard way music is written, not the way Dom thinks it ought to be written. Have you tried checking any standard reference works on this?
Comment: I wouldn't characterize as informal the use of a whole rest to mean rest for an entire measure, since at least 99% of all formal music notation uses it this way.  Furthermore, I wouldn't avoid it either.  It is far and away the most readable notation.
Comment: It is not entirely clear whether you are talking about notes or rests: if notes, then you are right. But if rests, then you are wrong. The semibreve, or "whole-note" rest is the standard notation used for a rest for the whole duration of a bar. So I marked you down, but if you like to edit so it is clear you are only talking about notes, we could mark you up again.
Comment: @BrianChandler Theoretically, both rests and notes always the same duration. Informally a whole rest _can_ mean rest for a whole measure just like if were to write _u_ instead of _you_ people would understand what's going on, but it does not mean it's the right thing to put which is what I say in the last paragraph.


How to set up head in Next.js?

Question: I added some themekit CSS to Next.js head, but browser console raise warning, what is wrong?
Expected server HTML to contain a matching  in
.

const Layout = ({ children, isNavbarTransparent }: Props) => {
    return (
        <>

                <link rel="stylesheet" href="themekit/css/bootstrap-grid.css" />
                <link rel="stylesheet" href="themekit/css/style.css" />

Answer: You seem to be using HTML head. Instead use Head component from Next.js, as they suggest in their documentation.

We expose a built-in component for appending elements to the head of the page.

import Head from "next/head";

const Layout = ({ children, isNavbarTransparent }: Props) => {
  return (
    <>

        <link rel="stylesheet" href="themekit/css/bootstrap-grid.css" />
        <link rel="stylesheet" href="themekit/css/style.css" />

How to set up head in Next.js?


how to stop current transaction in Jmeter on sampler error?

Question: In my Test Plan , i have multiple transactions(not related). Is there a way to stop just the current transaction only on a sampler error. If I use the setting to stop thread/ continue next thread , it just drops the thread for each transactions, which is not very helpful for what i want to achieve. Any help please. Thanks
Answer: What do you mean by "transaction"?
"Sample error" can be caught by If Controller using <code>${JMeterThread.last_sample_ok}</code> pre-defined variable as the condition and from there you can:

Add Flow Control Action sampler and use one of below 3 actions:

Or add a Module Controller pointing to a Test Fragment holding the actions which you would like to execute on Sampler's error. See Easily Write a GOTO Statement in JMeter article for more details.
Comment: by transactions i mean I have multiple transactional controller in my thread group


How to translate a header in drupal 7

Question: I have a drupal 7 site I inherited to manage.  There is a view I can edit at /newsletters#overlay=admin/structure/views/view/newsletters/edit and it has a section titled "header" that I can't figure out how to enable for translations.  The section below it,"content", is showing up properly translated on the front end.
The menu for Header looks like this:

Clicking Edit Global: Text area reveals this:

What do I have to do to translate this and display it properly?
Comment: A quick alternative would be create a simple custom block and display it above where you view is shown. Then its easily translated via a block
Answer: The "global" header and "global" footer built in Drupal Views isn't treated as a separate translatable entity like a node is.
One recommended approach (that will also avoid giving content managers access to edit views) is to setup a single custom content type for view headers and footers and then with the Entity API module enabled, set/embed an entity reference to the specific node in the view header (and/or footer). A breakdown of steps for this approach is below:

Make sure your site has the Entity API module installed and enabled.
Create a custom content type (it can be just a body field and title.  NOTE:  the title will render in the embedded entity in the view, so you may want to utilize it for the view page title/H1 in lieu of the specific "title" field on the specific display of the view. Otherwise you can preprocess the node type to exclude the title or use css to hide it.
Enable internationalization/translations for the new content type.
Create a node for each specific view header or view footer where you need manageable/translatable content, noting the node ID upon save.
Export a backup of the views impacted.
Edit the desired views; be sure to be editing the specific "view display" that applies to your block or page.  In the "Header" or "Footer" section of the view edit/config page (where you currently have a global textarea), click "ADD".
In the modal, make sure the selector in the top left corner is set to apply changes to "This Page"/"This Block"/etc and not "All Displays".  Select Entity: Rendered Entity and click Apply (this display).
Input the node ID and choose the desired display mode (full node should suffice as outlined, unless you need a custom display mode setup on the node/content type).
Remove the Global Text object in the View Header or View Footer.  After applying this change (and assuming you have no other custom objects in the view header or footer), you should only see the referenced entity in the View Header or View Footer section.
Save and test the page where the view appears.
If you decide to revert, import the backed up copy of the view as Admin1 to restore it.

How to translate a header in drupal 7


Solving implicit function and passing in three arguments

Question:
In the equation above I want to solve for f and pass in Re, D, and epsilon. Here is my code below:
import math
from scipy.optimize import fsolve

# Colebrook Turbulent Friction Factor Correlation
def colebrook(Re, D, eps):
    return fsolve(-(1 / math.sqrt(f)) - 2 * math.log10(((eps / D) / 3.7) + (2.51 / Re * math.sqrt(f))), f)

Would I use fsolve() or solve()? I read up on fsolve() on Python's main site, however I don't understand some of the inputs it wants. Thank you in advance!
Also, I am using Spyder (Python 3.6)
Answer: The wikipedia page on "Darcy friction factor formulae" has a section on the Colebrook equation, and shows how f can be expressed in terms of the other parameters using the Lambert W function.
SciPy has an implementation of the Lambert W function, so you can use that to compute f without using a numerical solver:
import math
from scipy.special import lambertw

def colebrook(Re, D, eps):
    """
    Solve the Colebrook equation for f, given Re, D and eps.

    See
        https://en.wikipedia.org/wiki/Darcy_friction_factor_formulae#Colebrook%E2%80%93White_equation
    for more information.
    """
    a = 2.51 / Re
    b = eps / (3.7*D)
    p = 1/math.sqrt(10)
    lnp = math.log(p)
    x = -lambertw(-lnp/a * math.pow(p, -b/a))/lnp - b/a
    if x.imag != 0:
        raise ValueError('x is complex')
    f = 1/x.real**2
    return f

For example,
In [84]: colebrook(125000, 0.315, 0.00015)
Out[84]: 0.019664137795383934

For comparison, the calculator at https://www.engineeringtoolbox.com/colebrook-equation-d_1031.html gives 0.0197.
Comment: Okay, thanks for the information regarding SciPy. It was very helpful.
Comment: Can you please explain to me what this line of code is doing? x = -lambertw(-lnp/a * math.pow(p, -b/a))/lnp - b/a


How to fix legato errors on repeats

Question: I'd like to fix two errors with legato appearance near the repeat sign.

I'd like the legato before the repeat (inside the 1st volta) to extend slightly to the right from the A note to emphasize that it connects to the beginning of the repeat.
I'd like the slur (that I created with \repeatTie command) to be up not down, however, I do not understand how to control it.

This is the code:
\version "2.22.2"

upper = \relative c' {
  \clef treble
  \key a \minor
  \time 4/4
  \tempo "Moderato" 4 = 94

  r1 |
  r2 r4 e8( a |
  \repeat volta 2 {
  b2. c4 |
  a2) r4 e8( a |
  b2. e4 |
  c2) r4 e4( |
  b2) r4 r8 c8( |
  }
  \alternative {
  { a2) r2 |
    r2 r4 \slurUp e8( a) |
  }
  { a2\repeatTie r4. g8( |
    b2) r2 |
  }
  }

  % Part B
  e8( a, c e f d e c) |
  e8( a, c e f d e c) |
}

\score {
  \new PianoStaff \with { instrumentName = "Piano" }
  <<
    \new Staff = "upper" \upper
    %\new Staff = "lower" \lower
  >>
  \layout { }
  \midi { }
}

Answer: Controlling the direction of a single tie or slur etc. is better done with ^ for up, and _ for down.
You can control the shapes of these curves with the \shape command, (see modifying shapes).  The pairs of numbers specify the coordinates of the "control points" of Bézier curves, (play around with these to see what they do).
If you upgrade to v2.23 (which I'd generally recommend) you can use \vshape to see exactly where these control points are, (see modifying shapes, v2.23). This helps in choose the best coordinates, but is not necessary.
You should get something like this:
...
\alternative {
    {
        a2) r2 |
        r2 r4
        \shape #'((0 . 0) (0 . 0) (2 . 0) (2 . 0)) Slur
            e8^( a) |
    }
    {
        \shape #'((0 . 3) (0 . 3) (0.5 . 3) (0.5 . 3)) RepeatTie
            a2^\repeatTie r4 r8 g8( |
        b2) r2 |
    }
}
...

Comment: Heh, I'm glad to see that \vshape (which I added) is seeing some use :-)
Comment: @ABOUSAMRAJean Thank you _so_ much. Bézier curves really are a lot easier to work with when you can actually _see_ the control points.
Comment: You'll probably want to get the repeat-tie under the 2. to look like the slur under the 1., so you'll have to adjust the control points a bit.

How to fix legato errors on repeats


I cannot run silverlight Developer run time

Question: I am suddenly unable to run any of my Silverlight projects. When I try to I get a message "You need to install the latest Silverlight Developer runtime before opening Silverlight project . It next brings up a Window that says Install Silverlight 5 for Developers. When I click "Install Now". I get a message Unable to Install Silverlight, followed by another message in smaller type "A 64-bit version of Silverlight is already installed". I tried uninstalling and reinstalling Silverlight and Silverlight of Visual Studio to no avail.
Comment: Stinks.  Not much anybody can do for you. Sounds like some bad corruption in your installs.  Probably a good time to do a system refresh.
Answer: I got it working. I'm not sure but I think there is a 32 and 64 bit version of the Developer kit. It is not obvious when you look at the installed programs.
This is the key
Silverlight_Developer_x64.exe
I am editing my own answer because I was premature it saying I had fixed my problem. I want to provide as many clues as possible to anyone who follows this thread if the future. I tried a bunch of different installs until I got it to work ok. See below to what I finally ended by with.

Also I found that I needed to change my Default provider from IE to Firefox in order to be able to step through my code.


Element whose value is smallest in a given row and highest in the corresponding column

Question: If a square matrix has element whose value is smallest in a given row and highest in the corresponding column then it's symmetric matrix has the same property.
As an example the statement holds true for this matrix and its symmetric. The largest element of the first column is the smallest element of the first row, and for it's symmetric, the largest element of the second column is the smallest of the corresponding row.
$$\begin{bmatrix}
6 & 7 \\
5 & 4
\end{bmatrix}$$
\begin{bmatrix}
6 & 5 \\
7 & 4
\end{bmatrix}
I believe this statement to be true, since I've done some case work for $2 \times 2$ matrices, but it gets pretty tedious for the higher order. In the case the matrix $A$ is $3 \times 3$ then the entries of the matrix $A$ and it's symmetric matrix $B$ look  like:
$$A=\begin{bmatrix}
a & b & c \\
d & e & f \\
g & h & i \\
\end{bmatrix}
$$
$$B=\begin{bmatrix}
a & d & g \\
b & e & h \\
c & f & i \\
\end{bmatrix}
$$
The largest elements of each column for $A$ are
$\max \{a,d,g\}, \max \{b,e,h\}, \max \{c,f,i\}$
while the smallest of each row are $\min \{a,b,c\}, \min \{b,e,h\}, \min \{c,f,i\}$
For it's symmetric matrix, the functions $\min$ and $\max$ are reversed:
$\min \{a,d,g\}, \min \{b,e,h\}, \min \{c,f,i\}$ are the smallest of each row while $\max \{a,b,c\}, \max \{b,e,h\}, \max \{c,f,i\}$ are largest of each column.
Now, we could choose something like $\max \{a,d,g\}=\min \{a,b,c \}=a$ and do bunch of casework to prove that $B$ also has the same property but this doesn't seem like a great idea.
I wonder if there is a clean method, perhaps something obvious I am missing that can be used to prove at least the simpler cases , and possibly even generalize it for any dimension of the square matrix $A$.
Note that I don't know if this holds true for every square matrix, so a counter example would also help.
Answer: The property is true for $2\times 2$ matrices, for $n=3$ take $\begin{pmatrix}10&11&12\\9&8&6\\8&9&5\end{pmatrix}$


Conservative confidence interval

Question: One month before the election, a poll of a large number of randomly selected voters showed 65% planning to vote for a certain candidate. The newspaper article reported a 90% conservative margin of error of 4 percentage points.
Use the above information to construct a 90% conservative confidence interval for the population proportion of all voters planning to vote for this candidate.
Can someone please explain why the answer is 0.65 +/- 0.04?
Comment: Perhaps the thread at http://stats.stackexchange.com/questions/16413/how-to-interpret-the-margin-of-error-in-a-poll will shed some light on this question.
Comment: Is the confidence interval defined as mean +/- margin of error?
Answer: The margin of error is usually defined as a particular way of expressing a confidence interval - see Wikipedia's definition, for example.  So you are not really being asked to do anything other than re-express what the newspaper has already stated.  By changing from 65% plus or minus 4 percentage points to 0.65 plus or minus 0.04 you have only changed it from percentages to proportions, by dividing by 100 (which obviously has no importance).
Looking again at your question I suspect it is actually exactly this relationship between a percentage and a proportion that is being tested here (as it is several months old I don't mind giving the answer away), not really the confidence interval issue.
Exactly what a "confidence interval" means is another matter (see @gung's comment).  The usual explanation is that if you performed this exercise (sampling a large number of voters etc) many times and used the same technique each time to estimate your confidence interval, 90% of the time the confidence interval would include the true but unknown value.
BTW if only newspapers were as clear as this, stating that the margin of error is a certain number of "percentage points" - all too often they omit the crucial "points", which leaves a significant ambiguity in meaning.

Conservative confidence interval


Use git with Media Temple Grid Service

Question: I've recently got some new Hosting after needing to move away from a Github hosted website as I need to run some Jekyll plugins that I obviously can't run on a git hosted site.
I got myself a media temple (grid)server. I've been trying to go through a guide they've put together here: https://kb.mediatemple.net/questions/1594/Using+Git#gs - However I've found (through being a Windows user, perhaps?), that these steps don't seem to work for me.
It states:

The following steps (1-6) are performed on your local machine:

It's when I hit step 5 that I'm lost. I've installed Putty so that I can gain SSH access to my server. But if this is supposedly local, how can I follow the commands if Windows doesn't have built in SSH capabilities?
scp -r example.git firstname.lastname@example.com:domains/git.example.com/html/example.git

As they don't offer support to actually use this, I'm really hoping some of you magnificent folk can help me out. I'd also like to understand exactly what the above line of code is doing, as I only understand part of it.
Answer: PuTTY includes an scp analog called pscp. Once you've got that installed, you should be able to use the exact command from your question, simply replacing scp with pscp.
Depending on how you installed PuTTY, this may already be available on the command line. In particular, if you used the installer, pscp.exe should be in your installation directory. If not, download it from the source and put it somewhere logical.
Alternatively, many graphical FTP clients support SCP as an alternative transport. Filezilla or WinSCP should be able to do what you want.

Use git with Media Temple Grid Service


I am unable to install module for my Drupal 7

Question: I am a newbie to Drupal and was trying to develop a website. I am in need of modules to enhance and when trying to install them , it throws the following error.

Warning: ftp_login(): Login incorrect. in FileTransferFTPExtension->connect() (line 59 of ..)
  Check Username and Password

My username and password are perfect. Can someone please help??
Comment: Are you trying to do that on a local computer, or on a remote server? Are you sure you are entering the credentials for the FTP server, and not the credentials for your Drupal account?
Answer: The alternate way to install module is to download the module and untar/unzip the files under /drupal/sites/all/modules/
Using Admin UI you can enable the module.


Contacting a moderator

Question: How do you contact a moderator? We obviously can't send messages. I know they can send messages to users but not the other way around.
I know they are extremely busy, if I could bring something to their attention not posting it in an open forum.
If I need to I will post it here for all to read but it is preferable not to.
Comment: I saw your message. Taking a look.
Comment: Thanks, someone responded mentioning that action was taken.
Comment: I raised the issue again, it got rejected with nothing to support. Have another look: No Action Needed, No Action Needed, Reject, Close, No Action Needed, No Action Needed, No Action Needed, No Action Needed, No Action Needed and on and on.
Answer: Flags.
That's your way to privately contact the moderators.
If you want to report something related to a user just flag any post of that user, select 'other' as reason and fill in your message.
If it's not user related just flag something posted by one moderator and do the same as described above.
Comment: As usual, thank you Marius :)

Contacting a moderator


Lang's Linear Algebra: what's next?

Question: I've completed the study of Lang's Linear Algebra ($3^\text{rd}$ edition). To put it simply, I have enjoyed the subject and I would like to know "what's next".
In other words, I would like to know

what are the "more advanced" topics in linear algebra that are not covered by Lang's (update: or Roman's) book and where to study them;
what are the "modern research topics" in "pure" linear algebra.
Comment: I think this is hard to answer. The snappy response to your last sentence is that there are none, but the more positive viewpoint is that most all modern research uses linear algebra so you had better narrow it down; that's going to be hard to do in this space. I don't think making pure linear algebra the cause of your life is really practical (maybe some people familiar with numerical methods should chime in; I'm sure there's work there). If you think you're drawn to algebraic thinking maybe the next step is to read a book with a broad view of the subject like M. Artin's *Algebra*.
Comment: Related math stackexchange questions: [What's a good book on advanced linear algebra?](http://math.stackexchange.com/questions/461275/whats-a-good-book-on-advanced-linear-algebra) and [High-level linear algebra book](http://math.stackexchange.com/questions/433858/high-level-linear-algebra-book?)
Answer: I would go for some later chapters of Advanced Linear Algebra, from Steven Roman, and Linear Algebra and Geometry, from Kostrikin and Manin. About open problems in Linear Algebra, you can take a look at the comments in this question: Are there open problems in Linear Algebra?. Particularly, I find it difficult to find open problems in linear algebra, since (in my point of view) a great part of this is mainly language for more advanced topics such as functional analysis, differential geometry, etc.
Answer: I'd recommend learning about other topics in mathematics that strongly employ the language and techniques of linear algebra.  The two clearest examples to me are functional analysis and differential geometry.  In functional analysis you get to see the ideas of vector spaces, except these are expanded to the cases of infinite-dimensional Banach and Hilbert spaces, the latter of which is fundamental to the structure of quantum mechanics.  In differential geometry linear algebra is needed to understand tangent spaces and the derivatives of multidimensional maps between manifolds, etc.
As others have stated above, it's probably difficult to find modern "pure" linear algebra research, and the "more advanced" topics you're looking for might be found in other areas of mathematics that strongly employ linear algebra.  You may also want to learn about representation theory as well.
Answer: Let me concisely but properly address your questions.
1) Learn about tensor products and multilinear algebra in general. (Since you mention that you read Lang's linear algebra book, there is a more advanced algebra book by Lang, called - guess what - Algebra; it is a standard reference.) These things are totally crucial in e.g. commutative algebra, algebraic geometry, algebraic topology, mathematical physics, etc. They also allow you to give more canonical definitions and viewpoints on classical topics such as the determinant or the trace. Lang's treatment uses modules (over commutative rings), which are the natural generalization of vector spaces, and I strongly recommend you to learn about module theory (also from Lang's Algebra). Then the natural way to proceed is to learn about homological algebra (Lang's Algebra contains an introduction, but there is a lot more to learn). (A professor of mine called homological algebra "smart linear algebra", which is in some sense true.)
2) I actually asked this question myself; a professor of mine responded by saying that "linear algebra is trivial and not a subject of current research", so I can only leave you with this. Note that this is what he says and not what I think; personally I think that there are probably not a lot of people who consider themselves "pure linear algebraists" (in the same way that probably hardly any professional mathematician would described his field of research as "calculus" in the narrow sense), but quite a few who study numerical linear algebra.
Answer: I really like Introduction to Matrix Analysis by Richard Bellman.
Comment: Would you comment on why you like it?
Answer: Have you studied abstract algebra? I believe it is a natural step after learning linear algebra, as a vector space is often one of the (if not the) first abstract algebraic structure a student encounters. Perhaps take a look at Dummit and Foote's text. It also covers much of what an "advanced" linear algebra text might, and much more.
Answer: As someone mentioned above, your question is really difficult to answer, especially the modern topics in "pure" linear algebra. It is hard to say whether some topics are "pure". Anyway, I think Brian C. Hall's book (maybe GTM222) about matrix lie group, somehow may help you.

Lang's Linear Algebra: what's next?


Subsets $Y$ of a partially ordered set $L$ need not have least upper bounds nor greatest lower bounds

Question: I am currently studying the textbook Principles of Program Analysis by Flemming Nielson, Hanne R. Nielson, and Chris Hankin. Appendix A Partially Ordered Sets says the following:

Partially ordered set. A partial ordering is a relation $\sqsubseteq : L \times L \rightarrow \{ \text{true}, \text{false} \}$ that is reflexive (i.e. $\forall l : l \sqsubseteq l$), transitive (i.e. $\forall l_1, l_2, l_3 : l_1 \sqsubseteq l_2 \land l_2 \sqsubseteq l_3 \Rightarrow l_1 \sqsubseteq l_3$), and anti-symmetric (i.e. $\forall l_1, l_2 : l_1 \sqsubseteq l_2 \land l_2 \sqsubseteq l_1 \Rightarrow l_1 = l_2$). A partially ordered set $(L, \sqsubseteq)$ is a set $L$ equipped with a partial ordering $\sqsubseteq$ (sometimes written $\sqsubseteq_L$). We shall write $l_2 \sqsupseteq l_1$ for $l_1 \sqsubseteq l_2$ and $l_1 \sqsubset l_2$ for $l_1 \sqsubseteq l_2 \land l_1 \not= l_2$.
A subset $Y$ of $L$ has $l \in L$ as an upper bound if $\forall l^\prime \in Y : l^\prime \sqsubseteq l$ and as a lower bound if $\forall l^\prime \in Y : l^\prime \sqsupseteq l$. A least upper bound $l$ of $Y$ is an upper bound of $Y$ that satisfies $l \sqsubseteq l_0$ whenever $l_0$ is another upper bound of $Y$; similarly, a greatest lower bound $l$ of $Y$ is a lower bound of $Y$ that satisfies $l_0 \sqsubseteq l$ whenever $l_0$ is another lower bound of $Y$. Note that subsets $Y$ of a partially ordered set $L$ need not have least upper bounds nor greatest lower bounds but when they exist they are unique (since $\sqsubseteq$ is anti-symmetric) and they are denoted $\bigsqcup Y$ and $\sqcap Y$, respectively.

It is this part that I am unsure about:

Note that subsets $Y$ of a partially ordered set $L$ need not have least upper bounds nor greatest lower bounds but when they exist they are unique (since $\sqsubseteq$ is anti-symmetric) and they are denoted $\bigsqcup Y$ and $\sqcap Y$, respectively.

This isn't obvious to me. Would someone please explain/clarify this?
Comment: Consider $(0, \infty) \subseteq \mathbb{R}$, which has no upper bound, and $(-\infty, 0)$, which has no lower bound. Also consider the signed integers $\mathbb{Z} \subseteq \mathbb{R}$, which has neither.
Comment: @BrianO This is the only response that has been informative.
Comment: @ ThePointer Thanks, glad you found the examples useful. Note, the comment by @amrsa is correct: $=$ is "trivially" antisymmetric, because for all $x, y \in X$, if $x = y$ and $y = x$ then surely $x = y$.
Comment: Consider the set $\{1,2,3,12,18,72,108,216\}$ ordered by the relation "$x$ divides $y$". The set $\{12,18\}$ has no least upper bound and no greatest lower bound.
Comment: Also, if $X$ is a set with two elements or more, then $(X,=)$ is a poset where for two different elements $a,b$ there is neither their glb not their lub (it's called an anti-chain).
Comment: @bof you'll have to explain this further, since it isn't clear to me how the set has no least upper bound and no greatest lower bound.
Comment: @BrianO Oh, ok. Thanks for the clarification. Is my comment to rpl19's answer correct?
Comment: @ThePointer Regrettably, no, it isn't :) (See my reply.)
Answer: To see that there are posets without least upper bounds nor greatest lower bounds consider $L = [-1,0) \cup (0,1) \cup (1,2]$ and $Y = (0,1)$. Let your partial order be the usual total order on $\mathbb{R}$. Then there is no least upper bound or greatest lower bound of $Y$ in $L$.
To prove this explicitly for the least upper bound case: suppose some $l \in L$ were a least upper bound of $Y$. Then we can select any $l_0 \in (1,l)$ and $l_0 < l$ is another upper bound for $Y$, but it's less than $l$. This is a contradiction, so no least upper bound can exist.
A similar argument works for the greatest lower bound.
For the uniqueness aspect, given existence, suppose both $l$ and $l^\prime$ were a least upper bound for $Y$ in $L$. Then this means in particular that they are both an upper bound. So $l \sqsubseteq l^\prime$ because $l$ is a least upper bound. But, $l^\prime \sqsubseteq l$ since $l'$ is also a least upper bound. By anti-symmetry this means we must have $l = l^\prime$.
A similar argument works for uniqueness of a greatest lower bound given its existence.
Comment: @ThePointer It's not clear what I could clarify further, but time permitting I'll attempt it.
Comment: $<$ is not anti-symmetric, and therefore it is not a POSET.
Comment: @ThePointer $<$ is the strict version of the usual $\le$ relation on reals, which of course *is* a partial order, as is its restriction to the answer's set $L$. This set is just $[-1, 2]$ with the points $0$ and $1$ removed. It should be clear that its subset $(0, 1)$ has no lub and no glb, though it's bounded above and below in $L$.
Comment: @ThePointer As BrianO pointed out, this is a poset. The difference between a partial order and a total order is convexity. That is, total orders are indeed anti-symmetric (and have all the other properties of a partial order), and have the additional property that you can compare any two elements. The example I gave is taking the closed set $[-1,2]$ with this partial order and removing two points that would be the upper and lower bounds of the subset $(0,1)$. Please let me know if my answer is still unclear.
Comment: Thanks again for the clarification. I don't understand this one. If we have $L = [-1,0) \cup (0,1) \cup (1,2]$ and $Y = (0,1)$, then how do we reason about the least upper bound and greatest lower bound? Furthermore, I don't understand why the answer is switching between $<$ and $\sqsubseteq$.
Comment: @BrianO Do you want to post a clearer answer for the bounty, by any chance?
Comment: @BrianO Great, thanks. Just an answer that gives a clear example and clearly explains it (for instance, an elaboration of your comment to the main post). The example given by this answer is just unclear to me.


Does anyone know why Take() isn't working here

Question: i have the following code using Nhibernate.Linq
<code>   var apps = Session.Linq<History>().OrderByDescending(r => r.LastUpdated).Take(50);
   Console.Write(apps.Count());
</code>
the count returns 1000 (NOT 50 which is what i would have expected)
any ideas why the .Take() is not working?
Answer: It looks like a bug in the Linq provider (you are using the old one, I tried the new one too and it still doesn't work).
You should open an issue in http://jira.nhforge.org/
As a workaround, use <code>.ToList()</code> in the assignment to apps.
Comment: You should either attach the classes and mappings, or use some of the existing ones in the test project, and create a proper unit test that fails. Look at the examples in the source code.


How to create a read only access key for Container Registry Azure

Question: I'm on the basic account type on Azure.
I have: A private registry with only one Access Key (Admin one)
I want: To be able to create more access keys with read only (acrpull) access.
Question: Am I reading correct from here: https://learn.microsoft.com/en-us/azure/container-registry/container-registry-skus#sku-feature-matrix that this is not allowed (only in the premium account)?
Isn't there a way to create another token with acrpull access only on a basic account?
Regards,
Comment: you have azure ad?
Comment: No, I don't have
Comment: az ad user list - it is displaying a users so I think I have it acctually - most probably the basic one
Answer: Of course, you can. It uses a service principal to do the authentication. You need to create a service principal assigned with the role acrpull for the ACR.
Here is an example script which uses the CLI command:
<code>#!/bin/bash

# Modify for your environment.
# ACR_NAME: The name of your Azure Container Registry
# SERVICE_PRINCIPAL_NAME: Must be unique within your AD tenant
ACR_NAME=<container-registry-name>
SERVICE_PRINCIPAL_NAME=acr-service-principal

# Obtain the full registry ID for subsequent command args
ACR_REGISTRY_ID=$(az acr show --name $ACR_NAME --query id --output tsv)

# Create the service principal with rights scoped to the registry.
# Default permissions are for docker pull access. Modify the '--role'
# argument value as desired:
# acrpull:     pull only
# acrpush:     push and pull
# owner:       push, pull, and assign roles
SP_PASSWD=$(az ad sp create-for-rbac --name http://$SERVICE_PRINCIPAL_NAME --scopes $ACR_REGISTRY_ID --role acrpull --query password --output tsv)
SP_APP_ID=$(az ad sp show --id http://$SERVICE_PRINCIPAL_NAME --query appId --output tsv)

# Output the service principal's credentials; use these in your services and
# applications to authenticate to the container registry.
echo "Service principal ID: $SP_APP_ID"
echo "Service principal password: $SP_PASSWD"
</code>
You can get more details in Azure Container Registry authentication with service principals, and also you can choose an appropriate role as you need when you take a look at Azure Container Registry roles and permissions.
Comment: My goodness! Excellent answer, with a minor touchup on the query for the APP ID for me.

The line works for SP_APP_ID with an updated query as:
`USER_NAME=$(az ad sp list --display-name $SERVICE_PRINCIPAL_NAME --query "[].appId" --output tsv)`


Simple group of order 168

Question: Let $G$ be a simple group of order 168, I have to show that it has at least 14 elements of order 3.
Using Sylow's theorems I proved that if $n_3$ is the number of 3-Sylows then $n_3\in\{4,7,28\}$, but now I don't know how to continue, I have to exclude the possibility of $n_3=4$, could you help me?
Reading this question Prove there is no element of order 6 in a simple group of order 168 I saw that actually $n_3=28$ could you explain me why?
Comment: If there were $4$ $3$-Sylow groups, your simple group $G$ would act on them by conjutation, giving a map $G\to S_4$. Can you get a contradiction from this?
Comment: related: http://math.stackexchange.com/a/1402/
Answer: The group $G$ acts by conjugation on the set of its own $3$-Sylow subgroups. That means that there is a homomorphism from $G$ into $S_{n_3}$, whose image is a transitive subgroup of $S_{n_3}$. Since $G$ is simple, the kernel of this map must be trivial, so $n_3!$ must be at least $168 = 2^3\times 3\times 7$.
This observation rules out $n_3=4$.
Comment: Eliminating the case of $7$ Sylow 3-groups can be done a variety of ways.  If there were $7$, you get a homomorphism into $S_7$, where an element of order $3$ looks like $(123)(456)$.  Now what does an element of order $2$ which centralizes this look like?
Comment: Dear Alex, please ask that *in the question body*. The comments to an answer is not the correct place where to ask a question!
Comment: @Mariano: To be fair, that is also in the body (third paragraph).
Comment: how can I rule out also the case $n_3=7$?

Simple group of order 168


How to think about the Lebesgue measure on the Gaussian Unitary Ensemble

Question: I am attempting to understand random matrices better, in particular the measure associated the Gaussian ensembles. It seems very different from standard measure theory. I do not even know how to think of the Lebesgue measure on the strange GUE space.
For this I am currently reading: https://arxiv.org/pdf/1510.04430.pdf and I am particularly stuck on page $17$ on the section about measures:
By definition, the Gaussian Unitary Ensemble (GUE) consists of the consists of the set of complex Hermitian matrices. For the GUE with matrices of size $n$, it is stated that a Lebesgue measure $dM$ exists. Furthermore, it is stated that it is a product of all the real components of the matrix. This is done in the following way: denoting the real components of $M_{i,j}$ as $M_{i,j}^{(\alpha)}$, we may thus define the Lebesgue measure as
$$ dM = \prod\limits_{i}dM_{i,i}\prod\limits_{i < j}dM_{i,j}^{(0)}dM_{i,j}^{(1)}\; \; (*)$$
Any idea of how to think of Lebesgue measure $dM$ in such a complex space GUE and dies $dM_{i,j}^{\alpha}$ simply stand for the "simple" Lebesgue measure on the complex plane?
I would be grateful for some intuition. Thanks!
Answer: A $n\times n$ Hermitian matrix, $M$, is determined by its entries along its diagonal and above its diagonal. Therefore only the entries $\left(M_{ij}\right)_{1\leq i \leq j \leq n}$ along and above the diagonal have to be specified. Furthermore since $M_{ii} = \overline{M}_{ii}$, i.e. the diagonal entries are equal to there complex conjugate, they are real. There are no further constraints on the entries thus the entries $\left(\left(M_{ii}\right)_{1\leq i \leq n}, \left(M_{ij}\right)_{1\leq i < j \leq n}\right)$ take values in $\mathbb{R}^n \times \mathbb{C}^{n(n-1)/2}$. Writing the real and imaginary parts of $M_{ij}$ as respectively, $M_{ij}^{(0)}$ and $M_{ij}^{(1)}$, $M$ is equivalent to a real vector $\left(\left(M_{ii}\right)_{1\leq i \leq n}, \left(\left(M_{ij}^{(0)}, M_{ij}^{(1)}\right)\right)_{1\leq i < j \leq n}\right)$ in $\mathbb{R}^n \times \left(\mathbb{R}^2\right)^{n(n-1)/2} \cong \mathbb{R}^{n^2}$.
$dM$ is the Lebesgue measure on $\mathbb{R}^2$ written in such a way as to make explicit the dependence on the components of $M$.


Header column border not matching with cell border - groupable header

Question: I added groupable from stack overflow to achieve the header column span but the border are not in align. I am trying to align the borders with the cells of the row . Can someone please help me to resolve it
The alignment of the header border stake net is slightly moved which is not visibly good in table:

I have posted all the code below which i am using in the project.
''' ColumnGroup :
<code>  public class ColumnGroup {
  protected TableCellRenderer renderer;
  protected Vector v;
  protected String text;
  protected int margin=0;

  public ColumnGroup(String text) {
    this(null,text);
  }

  public ColumnGroup(TableCellRenderer renderer,String text) {
    if (renderer == null) {
      this.renderer = new DefaultTableCellRenderer() {
  public Component getTableCellRendererComponent(JTable table, Object value,
                         boolean isSelected, boolean hasFocus, int row, int column) {
    JTableHeader header = table.getTableHeader();
    if (header != null) {
      setForeground(header.getForeground());
      setBackground(header.getBackground());
      setFont(header.getFont());
    }
          setHorizontalAlignment(JLabel.CENTER);
          setText((value == null) ? "" : value.toString());
    setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    return this;
        }
      };
    } else {
      this.renderer = renderer;
    }
    this.text = text;
    v = new Vector();
  }

  /**
   * @param obj    TableColumn or ColumnGroup
   */
  public void add(Object obj) {
    if (obj == null) { return; }
    v.addElement(obj);
  }

  /**
   * @param c    TableColumn
   * @param v    ColumnGroups
   */
  public Vector getColumnGroups(TableColumn c, Vector g) {
    g.addElement(this);
    if (v.contains(c)) return g;
    Enumeration e = v.elements();
    while (e.hasMoreElements()) {
      Object obj = e.nextElement();
      if (obj instanceof ColumnGroup) {
        Vector groups =
          (Vector)((ColumnGroup)obj).getColumnGroups(c,(Vector)g.clone());
        if (groups != null) return groups;
      }
    }
    return null;
  }

  public TableCellRenderer getHeaderRenderer() {
    return renderer;
  }

  public void setHeaderRenderer(TableCellRenderer renderer) {
    if (renderer != null) {
      this.renderer = renderer;
    }
  }

  public Object getHeaderValue() {
    return text;
  }

  public Dimension getSize(JTable table) {
    Component comp = renderer.getTableCellRendererComponent(
        table, getHeaderValue(), false, false,-1, -1);
    int height = comp.getPreferredSize().height;
    int width  = 0;
    Enumeration e = v.elements();
    while (e.hasMoreElements()) {
      Object obj = e.nextElement();
      if (obj instanceof TableColumn) {
        TableColumn aColumn = (TableColumn)obj;
        width += aColumn.getWidth();
        width += margin;
      } else {
        width += ((ColumnGroup)obj).getSize(table).width;
      }
    }
    return new Dimension(width, height);
  }

  public void setColumnMargin(int margin) {
    this.margin = margin;
    Enumeration e = v.elements();
    while (e.hasMoreElements()) {
      Object obj = e.nextElement();
      if (obj instanceof ColumnGroup) {
        ((ColumnGroup)obj).setColumnMargin(margin);
      }
    }
  }
}
</code>
GroupableTableHeader :
<code>  public class GroupableTableHeader extends JTableHeader {
  private static final String uiClassID = "GroupableTableHeaderUI";
  protected Vector columnGroups = null;

  public GroupableTableHeader(TableColumnModel model) {
    super(model);
    setUI(new GroupableTableHeaderUI());
    setReorderingAllowed(false);
  }
  public void updateUI(){
   setUI(new GroupableTableHeaderUI());
  }

  public void setReorderingAllowed(boolean b) {
    reorderingAllowed = false;
  }

  public void addColumnGroup(ColumnGroup g) {
    if (columnGroups == null) {
      columnGroups = new Vector();
    }
    columnGroups.addElement(g);
  }

  public Enumeration getColumnGroups(TableColumn col) {
    if (columnGroups == null) return null;
    Enumeration e = columnGroups.elements();
    while (e.hasMoreElements()) {
      ColumnGroup cGroup = (ColumnGroup)e.nextElement();
      Vector v_ret = (Vector)cGroup.getColumnGroups(col,new Vector());
      if (v_ret != null) {
  return v_ret.elements();
      }
    }
    return null;
  }

  public void setColumnMargin() {
    if (columnGroups == null) return;
    int columnMargin = getColumnModel().getColumnMargin();
    Enumeration e = columnGroups.elements();
    while (e.hasMoreElements()) {
      ColumnGroup cGroup = (ColumnGroup)e.nextElement();
      cGroup.setColumnMargin(columnMargin);
    }
  }

}
</code>
GroupableTableHeaderUI :
<code>    public void paint(Graphics g, JComponent c) {
    Rectangle clipBounds = g.getClipBounds();
    if (header.getColumnModel() == null) return;
    ((GroupableTableHeader)header).setColumnMargin();
    int column = 0;
    Dimension size = header.getSize();
    Rectangle cellRect  = new Rectangle(0, 0, size.width, size.height);
    Hashtable h = new Hashtable();
    int columnMargin = header.getColumnModel().getColumnMargin();

    Enumeration enumeration = header.getColumnModel().getColumns();
    while (enumeration.hasMoreElements()) {
      cellRect.height = size.height;
      cellRect.y      = 0;
      TableColumn aColumn = (TableColumn)enumeration.nextElement();
      Enumeration cGroups = ((GroupableTableHeader)header).getColumnGroups(aColumn);
      if (cGroups != null) {
        int groupHeight = 0;
        while (cGroups.hasMoreElements()) {
          ColumnGroup cGroup = (ColumnGroup)cGroups.nextElement();
          Rectangle groupRect = (Rectangle)h.get(cGroup);
          if (groupRect == null) {
            groupRect = new Rectangle(cellRect);
            Dimension d = cGroup.getSize(header.getTable());
            groupRect.width  = d.width;
            groupRect.height = d.height;
            h.put(cGroup, groupRect);
          }
          paintCell(g, groupRect, cGroup);
          groupHeight += groupRect.height;
          cellRect.height = size.height - groupHeight;
          cellRect.y      = groupHeight;
        }
      }
      cellRect.width = aColumn.getWidth() + columnMargin;
      if (cellRect.intersects(clipBounds)) {
        paintCell(g, cellRect, column);
      }
      cellRect.x += cellRect.width;
      column++;
    }
  }

  private void paintCell(Graphics g, Rectangle cellRect, int columnIndex) {
    TableColumn aColumn = header.getColumnModel().getColumn(columnIndex);
    TableCellRenderer renderer = aColumn.getHeaderRenderer();

    renderer = new DefaultTableCellRenderer(){
        public Component getTableCellRendererComponent(JTable table, Object value, boolean
         isSelected, boolean hasFocus, int row, int column) {
          JLabel header = new JLabel();
            header.setForeground(table.getTableHeader().getForeground());
            header.setBackground(table.getTableHeader().getBackground());
            header.setFont(table.getTableHeader().getFont());

          header.setHorizontalAlignment(JLabel.CENTER);
          header.setText(value.toString());
          header.setBorder(UIManager.getBorder("TableHeader.cellBorder"));
            return header;
        }

    };
    Component c = renderer.getTableCellRendererComponent(
        header.getTable(), aColumn.getHeaderValue(),false, false, -1, columnIndex);

        c.setBackground(UIManager.getColor("control"));

    rendererPane.add(c);
    rendererPane.paintComponent(g, c, header, cellRect.x, cellRect.y,
        cellRect.width, cellRect.height, true);
  }

  private void paintCell(Graphics g, Rectangle cellRect,ColumnGroup cGroup) {
    TableCellRenderer renderer = cGroup.getHeaderRenderer();

    Component component = renderer.getTableCellRendererComponent(
      header.getTable(), cGroup.getHeaderValue(),false, false, -1, -1);
    rendererPane.add(component);
    rendererPane.paintComponent(g, component, header, cellRect.x, cellRect.y,
        cellRect.width, cellRect.height, true);
  }

  private int getHeaderHeight() {
    int height = 0;
    TableColumnModel columnModel = header.getColumnModel();
    for(int column = 0; column < columnModel.getColumnCount(); column++) {
      TableColumn aColumn = columnModel.getColumn(column);
      TableCellRenderer renderer = aColumn.getHeaderRenderer();

      if(renderer == null){
      return 40;
      }

      Component comp = renderer.getTableCellRendererComponent(
        header.getTable(), aColumn.getHeaderValue(), false, false,-1, column);
      int cHeight = comp.getPreferredSize().height;
      Enumeration e = ((GroupableTableHeader)header).getColumnGroups(aColumn);
      if (e != null) {
        while (e.hasMoreElements()) {
          ColumnGroup cGroup = (ColumnGroup)e.nextElement();
          cHeight += cGroup.getSize(header.getTable()).height;
        }
      }
      height = Math.max(height, cHeight);
    }
    return height;
  }

  private Dimension createHeaderSize(long width) {
    TableColumnModel columnModel = header.getColumnModel();
    width += columnModel.getColumnMargin() * columnModel.getColumnCount();
    if (width > Integer.MAX_VALUE) {
      width = Integer.MAX_VALUE;
    }
    return new Dimension((int)width, getHeaderHeight());
  }

  public Dimension getPreferredSize(JComponent c) {
    long width = 0;
    Enumeration enumeration = header.getColumnModel().getColumns();
    while (enumeration.hasMoreElements()) {
      TableColumn aColumn = (TableColumn)enumeration.nextElement();
      width = width + aColumn.getPreferredWidth();
    }
    return createHeaderSize(width);
  }
</code>
}
Main class : JTable
<code>        DefaultTableModel dm = new DefaultTableModel();

        DefaultTableModel tableModel = new DefaultTableModel();

       for(int i=0;i<15;i++){
           if(i%2==0){
               dm.addColumn("Net");
           }else {
               dm.addColumn("Stake");
           }

       }

        for(ModelForLimitCategory model : singleCategoryList){
            dm.addRow(model.getVector());
        }

         table = new JTable( dm ) {
          protected JTableHeader createDefaultTableHeader() {
              return new GroupableTableHeader(columnModel);
          }
        };

        TableColumnModel cm = table.getColumnModel();

        ColumnGroup g_black = new ColumnGroup("Blaclist");
        g_black.add(cm.getColumn(1));
        g_black.add(cm.getColumn(2));
        ColumnGroup g_default = new ColumnGroup("Default");
        g_default.add(cm.getColumn(3));
        g_default.add(cm.getColumn(4));
        ColumnGroup g_silver = new ColumnGroup("Silver");
        g_silver.add(cm.getColumn(5));
        g_silver.add(cm.getColumn(6));
        ColumnGroup g_gold = new ColumnGroup("Gold");
        g_gold.add(cm.getColumn(7));
        g_gold.add(cm.getColumn(8));
        ColumnGroup g_platinum = new ColumnGroup("Platinum");
        g_platinum.add(cm.getColumn(9));
        g_platinum.add(cm.getColumn(10));
        ColumnGroup g_online = new ColumnGroup("online");
        g_online.add(cm.getColumn(11));
        g_online.add(cm.getColumn(12));
        ColumnGroup g_elite = new ColumnGroup("Elite");
        g_elite.add(cm.getColumn(13));
       g_elite.add(cm.getColumn(14));
       // ColumnGroup g_other = new ColumnGroup("Others");
       // g_other.add(cm.getColumn(5));
        //g_other.add(cm.getColumn(6));
        //g_lang.add(g_other);

        GroupableTableHeader header = (GroupableTableHeader)table.getTableHeader();
        header.addColumnGroup(g_black);
        header.addColumnGroup(g_default);
        header.addColumnGroup(g_silver);
        header.addColumnGroup(g_gold);
        header.addColumnGroup(g_platinum);
        header.addColumnGroup(g_online);
        header.addColumnGroup(g_elite); '''

</code>
Answer: I did the code change which helped me to resolve the issue . Hope its helps you
In class : GroupableTableHeaderUI
cellRect.width = aColumn.getWidth() + columnMargin; // Remove the column margin which is adding 1px to the width of the header column
New line will have : cellRect.width = aColumn.getWidth()
In class : ColumnGroup
comment line :  // width += margin; // margin add 1px width to header
Removing those two will align with the Jtable column borders
This has helped me to align the table columns and the header column . Please find below image enter image description here


Solution of Wave Equation initial conditions

Question: A vibrating string fixed at $ x=0 $ and $ x=L $ undergoes oscillations described by the wave equation $ \frac{\partial^2u}{\partial x^2} = \frac{1}{c^2} \frac{\partial^2u}{\partial t^2} $ where $ u(x,t) $ represents the displacement from equilibrium of the string. Initially, the profile of the string is $ u(x,0) = \sin(\frac{4 \pi}{L}x) $ and its initial velocity is $ u_t(x,0)=8 \pi \sin( \frac{4 \pi}{L} x ) $.
My attempt at a solution:
Take $ u(x,t) = [ A \cos(kx) + B \sin(kx) ][ C \cos (kct) + D \sin(kct) ] $
$ u(x,0) = [A \cos(kx) + B \sin(kx)] \times C = \sin( \frac{4 \pi}{L} x) $.
So, $ A = 0; k = \frac{4 \pi}{L} $
Then, $ B \sin({ \frac{4 \pi}{L} x})[ C \cos (\frac{4 \pi}{L} ct) + D \sin( \frac{4 \pi}{L} ct )] $
$ u_t(x,t) = B \sin( \frac{4 \pi}{L} x)[ \frac{4 \pi}{L}c \times C \times -\sin( \frac{4 \pi}{L}ct) + \frac{4 \pi}{L} \times D \times  \cos( \frac{4 \pi}{L} ct) ] $
$ u_t(x,0) = \frac{4 \pi}{L} c BD \sin( \frac{4 \pi}{L} x ) = 8 \pi \sin ( \frac{8 \pi}{L}x ) $
How do I solve this? Can I take $ BD = \frac{L}{c} \times 4 \cos( \frac{4 \pi}{L} x ) $
Answer: You won't get $\sin(\frac{8\pi}{L}x)$. You are actually dealing with $\cos(\frac{4\pi}{L}c 0)=1$.
Update: I see that you may have a typo in the initial velocity condition which should have contained $\sin(\frac{8\pi}{L}x)$.
To handle that begin with the solutions as $\sum_n a_n e^{i\frac{2\pi n}{L}(x-ct)}+b_ne^{i\frac{2\pi n}{L}(x+ct)}$. With the initial conditions you can easily recognize the only coefficients left would be $a_2,b_2,a_4,b_4$. With the constraints of getting real solutions, you can see it is
$\frac12 \sin(\frac{4\pi}{L}(x-ct))+\frac12\sin(\frac{4\pi}{L}(x-ct) + \frac{L}{2c}\cos(\frac{8\pi}{L}(x-ct))-\frac{L}{2c}\cos(\frac{8\pi}{L}(x+ct)).$


How to use Numeric[T] to represent zero of any numeric type

Question: I have a piece of Scala code that I'd like to make more generic. I know that Numeric[T] exists, but I'm not sure how to use it.
  def sumMaps[A](m1: Map[A, Long], m2: Map[A, Long]): Map[A, Long] = {
    m1 ++ m2.map { case (k, v) => k -> (v + m1.getOrElse(k, 0L)) }
  }

  def sumMaps[A](m1: Map[A, Int], m2: Map[A, Int]): Map[A, Int] = {
    m1 ++ m2.map { case (k, v) => k -> (v + m1.getOrElse(k, 0)) }
  }

  def sumMaps[A](m1: Map[A, Double], m2: Map[A, Double]): Map[A, Double] = {
    m1 ++ m2.map { case (k, v) => k -> (v + m1.getOrElse(k, 0)) }
  }

I'd like to write something like this (just once), where the zero value gets auto-converted to a B type.
  def sumMaps[A, B: Numeric[?]](m1: Map[A, B], m2: Map[A, B]): Map[A, B] = {
    m1 ++ m2.map { case (k, v) => k -> (v + m1.getOrElse(k, 0)) }
  }

Answer: Try
def sumMaps[A, B](m1: Map[A, B], m2: Map[A, B])(implicit num: Numeric[B]): Map[A, B] = {
  m1 ++ m2.map { case (k, v) => k -> num.plus(v, m1.getOrElse(k, num.zero)) }
}

or
import Numeric.Implicits._
def sumMaps[A, B](m1: Map[A, B], m2: Map[A, B])(implicit num: Numeric[B]): Map[A, B] = {
  m1 ++ m2.map { case (k, v) => k -> (v + m1.getOrElse(k, num.zero)) }
}

or
def sumMaps[A, B: Numeric](m1: Map[A, B], m2: Map[A, B]): Map[A, B] = {
  val num = implicitly[Numeric[B]]
  import num._
  m1 ++ m2.map { case (k, v) => k -> (v + m1.getOrElse(k, zero)) }
}

The imports provide implicit conversion infixNumericOps
m1 ++ m2.map { case (k, v) => k -> (infixNumericOps(v) + m1.getOrElse(k, num.zero)) }

so we do not have to explicitly use Numeric.plus like in the first example.
Comment: No, that is perfectly fine, I was referring is that I do not see any value in using context bounds when one has to use `implicitly` to summon the implicit. But that is just a style preference of myself, thus I would just use an implicit parameter to have it named and call the import as you did.
Comment: @LuisMiguelMejíaSuárez Is `import num._` style discouraged? I have seen this style often in macros, for example, `import c.universe._`.
Comment: @LuisMiguelMejíaSuárez I found a decent argument for not naming implicits on [slide 26](https://image.slidesharecdn.com/scala-3-by-example-better-semigroup-and-monoid-200106140918/95/scala-3-by-example-better-semigroup-and-monoid-26-638.jpg?cb=1578320042) of [Scala 3 by Example - better Semigroup and Monoid](https://www.slideshare.net/pjschwarz/scala-3-by-example-better-semigroup-and-monoid) by Philip Schwarz, where it is stated _"The point of givens or implicits is that the compiler will produce them for you, so why should you bother giving them a name?"_
Comment: Interesting. However, that slide refers more when creating the implicit rather than when using it, in which case, I agree that not having to name them on **Scala 3** will be great. Now, in the context of a method / function. I do think that if all **typeclasses** provide a summoner like `Monoid[T]` _(and apply in the companion)_ then it would a good argument for just use context bounds. But since many doesn't have such and the `implicitly` is too verbose for me, I prefer to just use plain implicit parameters.


Number on-line users on ASP.NET site

Question: Currently, writing an application in ASP.NET How to calculate and display the main form of on-line users or the number of running Web sites if run on your computer.
Answer: You'd normally store an application variable and then in your global increment / decrement on session start / session end respectively.
Failing that, this is an even better approach: http://blog.sb2.fr/post/2008/12/01/HowTo-Get-Current-Online-Users-Count-and-Infos-with-ASPNET.aspx
Duplicate: Get currently online users?

Number on-line users on ASP.NET site


Form Submit without module

Question: Is a module required to submit a form ?
I get a standard form from our designer and try to send it as follow:
<form action="/kontakt" class="sky-form" method="POST" name="kontakt">
  ...
  <input type="submit" class="btn btn-u btn-u-lg" value="Nachricht absenden">
</form>

I have tried different function calls without success
MYTHEME_form_submit(array &$form, FormStateInterface $form_state)
contact_form(array &$form, FormStateInterface $form_state)
contact_form_submit(array &$form, FormStateInterface $form_state)
MYTHEME_contact_form_submit(array &$form, FormStateInterface $form_state)
...

i have to say, that i am a beginner in Drupal 8, so help is very appreciated.
thank you.
Answer: Two ways to approach this.
One way is to use the Webform module. If this is just a simple contact form, you can get this done with Webform in five minutes.
The second way is create a custom module that implements a route, Form class and related methods. Wouldn't take an intermediate long, but a beginner should try Webform first.
You cannot simply paste form HTML into a twig file and expect it do anything. Drupal is ignorant to its existence and therefore no hooks will work, as you already saw.
https://www.drupal.org/project/webform
Comment: Kevin, thank you, i'll give it a try. The problem is, there are dependicies on some checkboxes. They should show some other fieldsets. I'll see.

Form Submit without module


Show that $ \operatorname{Hom}(K[s]/I, A)$ is isomorphic to $Z(I;A)$

Question: We have a field $K$, and an ideal $I \subseteq K[s],$ $s=(s_1,..., s_n)$ . The exercise requires me to prove that for any $A$ algebra over $K$,
$Z(I; A) = \operatorname{Hom}(K[s]/I, A),$ and here $Z(I; A)$ is the zero set of $I$ ideal in $A^n$.
I understand what zeros are for $I$ in a ring but what does it mean for an ideal to have zeros in an algebra?
Answer: Recall the universal property of the polynomial ring $K[X_1,...,X_n]$. It says, given a $K$-algebra $A$ and a function $\phi:\{1,...,n\} \rightarrow A$ there is a unique $K$-algebra homomorphism $\Phi: K[X_1,...,X_n] \rightarrow A$ satisfying $\Phi(X_i) = \phi(i)$. Hence we can evaluate a polynomial $f\in K[X_1,...,X_n]$ at a point $(a_1,...,a_n)\in A^n$ by considering the image of $f$ under the map $\Phi$ induced by the map $\phi(i)=a_i$. So in other words every point $a\in A^n$ induces a unique homomorphism
$$\begin{array}{rcl}
\operatorname{ev}_a: K[X_1,...,X_n] & \longrightarrow & A\\
f & \longmapsto & f(a_1,...,a_n)
\end{array}$$
and every homomorphism $\Phi: K[X_1,...,X_n] \rightarrow A$ yields a point $(\Phi(X_1),...,\Phi(X_n))\in A^n$. Thus we have mutually inverse maps
$$\begin{array}{rcl}
\operatorname{Hom}(K[X_1,...,X_n],A) & \longleftrightarrow & A^n\\
\Phi & \longmapsto & (\Phi(X_1),...,\Phi(X_n))\\
\operatorname{ev}_a & \leftmapsto & a=(a_1,...,a_n)
\end{array}$$
Now if we restrict this bijection to
$$Z(I;A)=\{(a_1,...,a_n) \in A^n \mid \forall f\in I: f(a_1,...,a_n)=0\}$$ on the right side, which set of homomorphisms do we get on the left? For this we will need another universal mapping property, namely that of the quotient ring. Let $I$ be an ideal in some ring $R$. Given any $R$-module $M$ we have that any morphism $\psi: R \rightarrow M$ satisfying $\psi\vert_I = 0$ induces a unique morphism $\Psi: R/I \rightarrow M$ satisfying $\Psi \circ \pi = \psi$ (where $\pi: R \rightarrow R/I$ denotes the quotient map). In other words we have mutually inverse maps
$$\begin{array}{rcl}
\operatorname{Hom}(R/I, M) & \longleftrightarrow & \{\psi \in \operatorname{Hom}(R,M)\mid \psi\vert_I =0\}\\
\Psi & \longmapsto & \Psi\circ \pi\\
\Psi & \mapsfrom & \psi
\end{array}$$
Can you see how this helps you with the exercise?
Comment: Thank you! I feel like I'm getting the hang of it but I struggle to write down the isomorphic map. So if I define $Φ : K[s]/I ⟶ A$ with $f(a_1,...,a_n)⟼(a_1,...,a_n) and $a: Hom(K[s]/I,A) ⟶ Z(I;A)$ with $a(Φ)=Φ(a_1,...,a_n)$, and show it's bijective, would this work?
Comment: Something along these lines, yes, but if I understand your comment correctly it is not the maps you mention. I will edit for more information.


Getting rid of commas in a list

Question: Here is my program:
def Prob2( rows, columns ):
for i in range(1, rows+1):
    print(list(range(i, (columns*i)+1, i)))

Prob2( rows = int(input("Enter number of rows here: ")), columns = int(input("Enter number of columns here: ")))

Essentially, it takes a user input of rows and columns and, based on those inputs, makes lists of multiples starting with 1.
For example, if the user typed in 4 rows and 5 columns, the program would output something like this:
[1, 2, 3, 4, 5]
[2, 4, 6, 8, 10]
[3, 6, 9, 12, 15]
[4, 8, 12, 16, 20]

The problem I have is that I need to get rid of the commas and only have spaces between the numbers. Is this possible?
Comment: There are a million duplicates of this...
Comment: `print(' '.join(str(x) for x in range(i, (columns*i)+1, i)))`.
Comment: You can convert the list to a string and call str.replace(',', '') before you print it.
Answer: As your title specifies :

Getting rid of commas in a list

I'll give the general version of it.
>>> l = [1,2,3,4]
>>> l
[1, 2, 3, 4]

>>> s = ' '.join(str(x) for x in l)
>>> s
'1 2 3 4'

Here since the list contains int, we use list comprehension to convert each individual into str before joining.
Suppose the list contained str, we can directly do :
>>> l = ['1','2','3','4']
>>> l
['1', '2', '3', '4']

>>> s = ' '.join(l)
>>> s
'1 2 3 4'

Comment: Sure, glad to help
Answer: Could just convert your lists to strings and remove your commas with the re.sub() method.
import re

def Prob2(rows, columns):
    for i in range(1, rows + 1):
        numbers = re.sub(",", "", str(range(i, (columns * i) + 1, i)))
        print(numbers)

Prob2(rows=int(input("Enter number of rows here: ")),
      columns=int(input("Enter number of columns here: ")))

Output:
[1 2 3 4 5]
[2 4 6 8 10]
[3 6 9 12 15]
[4 8 12 16 20]

Answer: You can do it like so:
def Prob2( rows, columns ):
    for i in range(1, rows+1):
        print('['+', '.join(map(str, list(range(i, (columns*i)+1, i))))+']')

Prob2( rows = int(input("Enter number of rows here: ")), columns = int(input("Enter number of columns here: ")))

Using ' '.join() is a trick that allows you to convert a list to a string where map(str, <list>) iterates over each value in that list and apply the str() function on it.
Answer: def Prob2( rows, columns ):
    for i in range(1, rows+1):
        print('['+' '.join(str(val) for val in range(i, (columns*i)+1, i))+']')

Prob2( rows = int(input("Enter number of rows here: ")), columns = int(input("Enter number of columns here: ")))

output:
[1 2 3 4 5]
[2 4 6 8 10]
[3 6 9 12 15]
[4 8 12 16 20]

Getting rid of commas in a list


re.search in python, return a list of integers separated by comma

Question: I have a list of strings as follows:
my_list = ['array("i", [12694499, 12855016, 123457])',
'array("i", [12694499, 12865016, 123457])',
'array("i", [12694499, 12855016])',
'array("i", [12699749, 12877477])',
'array("i", [12828285, 12868277])',
'array("i", [-1])',
'array("i", [-1])',
'array("i", [-1])']

I am a newbie using regular expressions in python and I'm trying to use re.search to extract the values in brackets and separated by commas. As follows:
[12694499, 12855016, 123457]
[12694499, 12865016, 123457]
[12694499, 12855016]
[12699749, 12877477]
[12828285, 12868277]
[-1]
[-1]
[-1]

I have tried this:
for value in my_list:
    coords = re.search(r"\[[0-9]+,\s[0-9]+\]", value)
    print(coords)

but I get this:
None
None
None
None
None
None
None
None

I know I can use split() to get the numbers, but I'm really interested in understand how RE works in python.
Any suggestion would be much appreciated!
Comment: I don't get that result. I get 2 None, 3 matches, then 3 None. Your regexp only matches when there are exactly 2 numbers in the brackets.
Comment: Your regexp also doesn't match negative numbers.
Answer: Your code actually has a match for the 3rd, 4th and 5th item.
But if you want to get all the matches, you can use an optional hyphen -? and optionally repeat the part with the comma and the digits (?:,\s-?[0-9]+)*
Then first check the result of re.search and print the value with .group()
for value in my_list:
    coords = re.search(r"\[-?[0-9]+(?:,\s-?[0-9]+)*]", value)
    if coords:
        print(coords.group())

Output
[12694499, 12855016, 123457]
[12694499, 12865016, 123457]
[12694499, 12855016]
[12699749, 12877477]
[12828285, 12868277]
[-1]
[-1]
[-1]

See a Python demo.


How to add an additional theme to a Bootstrap web project?

Question: I am using a theme from Bootstrap and would like to add a new un-styled theme page from the same site, which comes with it's own files:
css
--bootstrap.css
--bootstrap.min.css
--style.css
js
--bootstrap.js
--bootstrap.min.js
--jquery-1.11.0.js
newpage.html

As far as I can tell, only the newpage.html and the style.css files are different from what I already have from the current theme. I added the newpage.html and the style.css to my project. However, when I open the new page, the content is there, but it seems to be missing all of the css and the js components. I suspect it might be a path issue.
My project structure with the new files, looks like this (simplified):
css
--style.css
js
pages
--newpage.html
index.html

In the newpage.html file, the css and the js are linked like so:
<link href="/css/bootstrap.min.css" rel="stylesheet">
<link href="/css/style.css" rel="stylesheet">

All of these files are there and accounted for. When I linked to the new page, I had to use this path: "./pages/newpage.html" What am I doing wrong?
Answer: Try traversing up the directory with all the paths you are trying to include, traversing is denoted as '..'
Example:
<link href="../css/style.css" rel="stylesheet">

Comment: This was it! Thanks #arinh


Spock's groovy test fails with ArrayIndexOutOfBoundsException at Stub()

Question: I have a java class AgentConverter as which implements
org.springframework.core.convert.converter.Converter -
public class AgentConverter implements Converter<RequestWrapper, TicketingAgent> {

    public TicketingAgent convert(RequestWrapper wrapper) {

        TicketingAgent agent = new TicketingAgent();
        ....
        ....

Then I have java class which is using above AgentConverter as -
public class BuildTicketingDocumentRequest implements BuildRequest<TicketingDocumentRequest> {

    private final PosConverter posConverter;
    private final AgentConverter agentConverter;    //here it is ..
    private final TransactionInfoConverter transactionInfoConverter;
    private final BuildRequestComponent<TicketingDocument> buildRequestComponent;

I have written Groovy test case where I am stubbing the AgentConverter class -
class ConversionStrategyForDocCreateTest extends EdiSimulator  {

    def "Master Test for Build Conversion Strategy to create TicketingDocumentRequest"() {

        given:"Mocked Classes"
        AgentConverter agentConverter = Stub(AgentConverter.class)     // this line exception comes
        agentConverter.convert(wrapper) >> new TicketingAgent()
        .....
        .....

Now when above test case - I am getting:
java.lang.ArrayIndexOutOfBoundsException: 45569

    at net.sf.cglib.proxy.BridgeMethodResolver.resolveAll(BridgeMethodResolver.java:61)
    at net.sf.cglib.proxy.Enhancer.emitMethods(Enhancer.java:911)
    at net.sf.cglib.proxy.Enhancer.generateClass(Enhancer.java:498)
    at net.sf.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
    at net.sf.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216)
    at net.sf.cglib.proxy.Enhancer.createHelper(Enhancer.java:377)
    at net.sf.cglib.proxy.Enhancer.createClass(Enhancer.java:317)
    at org.spockframework.mock.runtime.ProxyBasedMockFactory$CglibMockFactory.createMock(ProxyBasedMockFactory.java:91)
    at org.spockframework.mock.runtime.ProxyBasedMockFactory.create(ProxyBasedMockFactory.java:49)
    at org.spockframework.mock.runtime.JavaMockFactory.create(JavaMockFactory.java:51)
    at org.spockframework.mock.runtime.CompositeMockFactory.create(CompositeMockFactory.java:44)
    at org.spockframework.lang.SpecInternals.createMock(SpecInternals.java:45)
    at org.spockframework.lang.SpecInternals.createMockImpl(SpecInternals.java:281)
    at org.spockframework.lang.SpecInternals.StubImpl(SpecInternals.java:131)
    at com.sabre.ticketing.hub.converter.startegy.ConversionStrategyForDocCreateMasterTest.Master Test for Build Conversion Strategy to create TicketingDocumentRequest(ConversionStrategyForDocCreateMasterTest.groovy:35)

While hit & trial I found if I remove AgentConverter's  implements Converter like below -
public class AgentConverter {             // Here i have removed "implements Converter"

    public TicketingAgent convert(RequestWrapper wrapper) {

        TicketingAgent agent = new TicketingAgent();

then things start working and there is no java.lang.ArrayIndexOutOfBoundsException. I am trying to understand what is the relation between Stub() in Spock framework AND stubbed class's interface implementation. Couldn't find in google so posted here... Any help is appreciated.
Here is my POM snippet for spock & groovy versions :
  <dependency>
       <groupId>org.spockframework</groupId>
       <artifactId>spock-core</artifactId>
       <version>1.0-groovy-2.4</version>
       <scope>test</scope>
   </dependency>
   <dependency>
       <groupId>org.codehaus.groovy</groupId>
       <artifactId>groovy-all</artifactId>
       <version>2.4.4</version>
       <scope>test</scope>
   </dependency>

Comment: Check your code with Spock 1.3 (or 2.0-M3) and Byte Buddy. Spock 1.0 has been released over 5 years ago. Number of bugs has been fixed since then.
Answer: Disclaimer: I used spock ~ 1.5 years ago, maybe things have changed since then...
Anyway:
Are you running with Java 9?
If so, check this cglib issue:
All-in-all cglib seems to have an issue, you can try to use bytebuddy instead as suggested in this thread.
Another possible solution is refactoring:
Maybe BuildTicketingDocumentRequest can depend on interface rather than concrete implementation like AgentConverter. When the mock is created out of the interface, it should work.


Interseção entre tempo

Question: Estou em duvida sobre o que utilizar na criação de um projeto de simulação de cinema. Até o momento tenho uma classe Sessao:
package entidades;

import java.time.Duration;
import java.time.LocalTime;

public class Sessao {
    private String nomeFilme;
    private LocalTime horarioDoFilme;
    private Duration duracaoDoFilme;

    public Sessao(String nome, LocalTime horario, Duration duracao) {
        this.nomeFilme = nome;
        this.horarioDoFilme = horario;
        this.duracaoDoFilme = duracao;
    }

    public Duration getDuracaoDoFilme() {

        return duracaoDoFilme;
    }

    public void setDuracaoDoFilme(Duration duracaoDoFilme) {

        this.duracaoDoFilme = duracaoDoFilme;
    }

    public String getNomeFilme() {

        return nomeFilme;
    }

    public void setNomeFilme(String nomeFilme) {

        this.nomeFilme = nomeFilme;
    }

    public LocalTime getHorarioDoFilme() {

        return horarioDoFilme;
    }

    public void setHorarioDoFilme(LocalTime tempoFilme) {

        this.horarioDoFilme = tempoFilme;
    }

    public String toString() {
        return "\nFilme: " + nomeFilme +
                "\nHorário: " + horarioDoFilme +
                "\nDuração: " + duracaoDoFilme;
    }
}

Em uma outra classe do projeto tenho o método adicionarSessao(). O mesmo recebe um id de uma sala e obviamente uma nova sessão. Porém, só posso adicionar uma sessão após testar se a duração de uma nova sessão não interfere na outra.
Gostaria de uma ajuda na hora de descobrir se há interseção, pois não estou conseguindo pensar em uma logica pra isso.
Answer: A ideia básica é obter o horário que a sessão termina (somando a duração com o horário inicial), e verificar se o término é depois do início da outra sessão (se for, elas interferem uma na outra).
Então na classe Sessao você pode adicionar um método que faz essa verificação:
public class Sessao {
    public boolean interfere(Sessao outra) {
        Sessao antes, depois;
        if (this.horarioDoFilme.isBefore(outra.horarioDoFilme)) {
            antes = this;
            depois = outra;
        } else {
            antes = outra;
            depois = this;
        }

        return antes
            // calcula horário de término = horário de início + duração
            .horarioDoFilme.plus(antes.duracaoDoFilme)
            // verifica se o término é depois do início da sessão seguinte
            .isAfter(depois.horarioDoFilme);
    }
}

Primeiro eu vejo qual sessão começa antes, usando o método isBefore.
Em seguida, eu calculo o horário de término da sessão que começa antes (usando o método plus para somar a duração com o horário inicial) e verifico se esse término ocorre depois que a outra sessão já começou (com o método isAfter).
Caso a primeira sessão termine depois que a outra já começou, é porque elas interferem uma na outra (e nesse caso, o método interfere retorna true). Testando:
// filme com 2 horas de duração, começa as 14h
Sessao s1 = new Sessao("A", LocalTime.of(14, 0), Duration.ofHours(2));
// filme com 2 horas de duração, começa as 15h
Sessao s2 = new Sessao("B", LocalTime.of(15, 0), Duration.ofHours(2));
// filme com 2 horas de duração, começa as 17h
Sessao s3 = new Sessao("C", LocalTime.of(17, 0), Duration.ofHours(2));

System.out.println(s1.interfere(s2)); // true
System.out.println(s1.interfere(s3)); // false
System.out.println(s2.interfere(s3)); // false

Repare que s2 termina às 17h, que é o mesmo horário que s3 começa. O algoritmo acima considera que se termina exatamente no mesmo horário, então não há interferência.
Mas se quiser considerar que "exatamente o mesmo horário" também é interferência, basta mudar o retorno do método interfere para:
return ! antes
    // calcula horário de término = horário de início + duração
    .horarioDoFilme.plus(antes.duracaoDoFilme)
    // verifica se o término é depois do início da sessão seguinte
    .isBefore(depois.horarioDoFilme);

Agora eu uso ! (que é o operador de negação) e troquei a chamada para isBefore. Ou seja, agora a lógica é verificar se a primeira sessão não termina antes do início da outra (o que quer dizer que ou ela termina no mesmo horário, ou depois). Usando esta implementação, s2.interfere(s3) retorna true.

No caso, para adicionar uma nova sessão, você teria que verificar se ela não interfere em nenhuma outra (ou seja, teria que chamar o método intefere várias vezes, comparando a nova sessão com todas as outras já existentes).
Outro detalhe é que um LocalTime só possui informações sobre o horário, mas não sobre a data. Ou seja, se a sessão começar próxima da meia-noite, ela pode terminar na madrugada do dia seguinte, e as comparações acima falham. Ex: se começa 11 da noite e tem duração de 2 horas, o código acima falha, pois o horário de término é 1 da manhã, que um LocalTime considera que é antes de onze da noite, já que esta classe não leva em conta o dia.
Se quiser considerar também esses casos, eu sugiro mudar os horários da sessão para LocalDateTime (que possui data e hora, assim ao somar a duração, as datas são corretamente ajustadas para o dia seguinte, caso necessário), ou ainda ZonedDateTime, se quiser considerar também o fuso horário e casos mais complicados, como as mudanças de horário de verão. Ambos possuem os métodos plus para somar uma duração, e isAfter e isBefore para fazer comparações.
Comment: Muito obrigado, me ajudou bastante.
Comment: O Java adotou alguma coisa da JodaTIme?
Comment: @Maniero Segundo o próprio Stephen Colebourne, algumas ideias e conceitos foram aproveitados, mas outras coisas que ele considerava "erradas" ou ruins, ele aproveitou para corrigir. Tem mais detalhes no blog dele, [aqui](http://blog.joda.org/2009/11/why-jsr-310-isn-joda-time_4941.html) e [aqui](http://blog.joda.org/2014/11/converting-from-joda-time-to-javatime.html). Ele mesmo diz que a API `java.time` seria mais "inspirada" no Joda-Time, do que uma simples cópia...

Interseção entre tempo


Formatar cor da table CSS

Question: Gostaria de que minha tabela estivesse com esse visual.

mas ao adicionar o conteúdo nela ele fica com essa visual não estou conseguindo deixa-la como a table de cima.

function listarProdutos(){
    var conteudo="
";
     conteudo+="
";
    conteudo+="

Indice

"
    conteudo+="

Nome

"
     conteudo+="
";
    //pos contator
    for(var pos=1;pos<indice.length;pos++){
        conteudo+="
";
        conteudo+=""+indice[pos]+"	";
        conteudo+=""+nomes[pos]+"	";
        conteudo+="
";
    }
    conteudo+="
";
    document.getElementById("txtrelatorio").innerHTML=conteudo;
}

.indice, .nome{

        font-size: 15pt;
        font-weight: 700px;
        background-color: #000066;
    }

    tr,td{
        font-size: 14pt;
        background-color: #000066;
        color: #CCCCCC;
    }

Comment: Você esta declarando tr e td com o mesmo visual, separe um css para tr e outro para td, afinal TR é linha e TD é coluna. Logo, você está dando o mesmo css para toda a table
Answer:

table thead{
    background: #2980b9;
    color: #FFF;
}

table tbody{
    background: #3498db;
    color: #FFF;
}

table thead tr td{
    padding: 5px;
    text-align: center;
}

table tbody tr td{
    padding: 5px;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title></title>

                Indice
                Nome

                Conteudo Primeiro
                Conteudo Segundo

Assim?
Answer: Basta utilizar este código que sua tabela ficará com o cabeçalho diferente do corpo

                <title>TODO supply a title</title>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">

                            Índice
                            Nome

                          1
                          Paula

                          2
                          Luisa

Formatar cor da table CSS


How is the a value in Laguerre's method calculated?

Question: How is it calculated? I cannot find the value of a as in the method.
Comment: Do you mean Laguerre's method for polynomial root approximation? Your second sentence is unintelligible, please correct and add detail. What value exactly is your problem?
Comment: @Dr.LutzLehmann Yes, it is for root approximation. I updated the question so you can easily see the a value, which I am having difficulty to obtain like that equation. Thank you for warning!
Answer: You should also have copied the context of the wikipedia Laguerre article where $a=x-x_1$ is the root update we seek and all other roots are far away and considered the same, so that $x-x_k\approx b$ and
\begin{align}
G&=\frac1{x-x_1}+\sum_{k=2}^n\frac1{x-x_k}\approx\frac1a+\frac{n-1}b\\
H&=\frac1{(x-x_1)^2}+\sum_{k=2}^n\frac1{(x-x_k)^2}\approx\frac1{a^2}+\frac{n-1}{b^2}
\\\hline
\frac{n-1}b&=G-\frac1a\\
(n-1)H&=\frac{n-1}{a^2}+\left(G-\frac1a\right)^2=\frac{n}{a^2}-\frac{2G}a+G^2
\end{align}
and now solve this quadratic equation for $a$, or rather first for $\frac na$,
$$
n(n-1)H=\frac{n^2}{a^2}-2\frac{n}a G+nG^2=\left(\frac na-G\right)^2+(n-1)G^2,\text{ etc.}
$$
Then insert that $G$ and $H$ can be expressed in the polynomial's derivatives at $x$ and you end up with an implementation like the following, where dd_evaluate(x) evaluates the value, first and second derivative at $x$ and store them in global variables pol, dpol, ddpol.
double complex laguerre_update(){
  double complex root;

  dd_evaluate(zero);

  root=((DEG-1)*(DEG-1))*(dpol*dpol)-(DEG*(DEG-1))*(ddpol*pol);

  root = csqrt(root);

  if( creal(dpol*~root)<0 )
    root=-root;

  return -(DEG*pol)/(dpol+root);
}

This is from working (if somewhat minimalist) code, it produced images like the one below illustrating the basins of attraction (same color domains) of the roots (white circles) and the number of steps to reach them (shades of the colors).


check if aio_write finished

Question: Is there any way to check if there are no AIO writes to a given file? Im making an project on my Unix course which will be a context free (based on UDP) chess server and all data has to be stored in files. Application will be single proccess and single threaded (expect for AIO functions). My problem is that:
1)Player One sends some data which triggers aio_write operation to files and the process goes
2)Player Two requests current board state which should be read from that file, but if previous aio_write hasnt finished yet then this file is not final and so I should not read yet but wait for aio_write to end.
Problem is that as it is context free I dont have aiocb structure from aio_write call.
Also there could be aio_writes from other games (which use diffrent files) on which I dont need to care, only if specific file is currently on write.
Answer: Why are you using AIO for this? The purpose of AIO is not synchronization between processes. It's purely to prevent your process from sleeping in kernelspace when a read or write can't be satisfied immediately due to disk load (reading) or cache pressure (writing). On such small transactions as a chess game will be working with, AIO should behave exactly the same as normal read and write IO: all operations will complete immediately, albeit with moderately more overhead.
If your goal is to synchronize file access, you could perhaps use fcntl locking, or mmap your files and include a mutex or semaphore somewhere in the file.
Comment: I'd like to add that, as usual, NFS is Weird, and you can't rely on synchronisation to work properly with it. (Although I think it's OK if both processes are on the same machine.)
Comment: As I wrote is for UNIX Course and one of the requirements is to use Asynchronous Input-Output only :/
Comment: *Sigh*... Why are instructors teaching the most horribly misdesigned and useless interface in POSIX? I don't think AIO can help you achieve the synchronization you need, as it is not a synchronization method...
Comment: After spending more time on lecture notes and other I think that the way to acomplish it should be file locks...
Answer: The fact that it's context-free shouldn't stop you from keeping some state information.
You could keep the context (I mean the io_context) and just reuse it (send a read request and wait for it - io_getevents). io_submit says it pushes requests in a queue so I believe it will preserve the order of operations.
Alternatively, (if you find out that io_submit doesn't preserve the order) you could keep enough state to know that a write operation is pending and wait using io_getevents. Then reading will be safe.
I hope I didn't misread your question.
EDIT
It seems I did misread your question. You are likely talking about POSIX aio(7). I was talking about true asynchronous I/O (libaio.h). POSIX aio is usually implemented using threads (which kind of sucks).
Either way, if you can wait for events (which I think you can) you can still do it: keep some state to declare a write is pending, and when someone wants to read wait for the write to complete.
Comment: You can wait for your own events, but I don't know any way to wait for an event triggered by another application. Pretty much all POSIX AIO does, conceptually, is a blocking read or write in a new thread with a notification signal or callback when it finishes... with a horribly ugly API. This is not a primitive that can be used to build inter-process synchronization.
Comment: @R.. I think he's using the same process - a server that receives UDP messages from clients.
Comment: OK I think I get it. The server is just using AIO waits to synchronize with itself. In reality, all AIO ops will take place immediately and waits will all immediately return. This is a really useless exercise...

check if aio_write finished