How can I render HTML tags in a variable in a twig template?

Question: I have a variable in my twig template called description.
The variable is a string with an html em tag in it. When I go to the webpage to view the field, the html em tags are stripped out of the string.
I am on a Drupal 8 site and my variable was rendered through
\Drupal::service('renderer')->render() The twig autoescape parameter is set to false.
Using the twig debugger, I can see that my markup object includes the html em tags so I know that the problem is how twig is processing the string.
I've read in other posts to use the |raw tag but this has no effect.
What can I do to make the HTML in my twig variable render properly?
Update: I've included a screenshot of my output from {{ dump(description) }}
Comment: can you share the line you have used into your twig file to print that variable?
Comment: {% if description is not empty %}
    {{ description }}
{% endif %}
Comment: try to allow uses of  tag `{{ description|striptags('')|raw }}`
Comment: Just tried this but no difference. I know that my variable has the html em tags because I can see them when I run dump( description ).
Comment: can you share a screen of your dump results? try to update the post by adding your screenshot.
Comment: I've included the screenshot with the original question.
Comment: try `{{ description.string | raw }}` to access string property of description object
Comment: This causes the description variable to show no output.
Comment: so don't use `\Drupal::service('renderer')->render()` try to pass your variable directly to your template and print it directly as mentioned into Clive answer.
Answer:
my variable was rendered through
  \Drupal::service('renderer')->render()

Don't do that - Drupal sets Twig up to understand render arrays. Just use:
{{ original_description_render_array }}


How to use non-english language in code

Question: I'm italian and I've to develop a multilingual drupal site but english translations of strings (that should be added in code or templates) will be done in the future.
Is there a way to use in code a non-english language and use t() and other functions to translate them in english?
Answer: AFAIK core's does not support (and could take a while to do so) keyed based translation (like Symfony or other do). Theres an idea queued but seems to fall on deaf ears.

How to use non-english language in code


.htaccess mod_rewrite rule "works", but server sends 404 code!

Question: I have the following .htaccess file on my webroot:
<code>DirectoryIndex index.htm index.html index.php AddType application/x-httpd-php .htm .html
RewriteEngine On
RewriteBase /

RewriteCond %{ENV:REDIRECT_STATUS} 200 RewriteRule .* - [L]

RewriteCond $1 !\.(gif|jpe?g|png|ico|css|js|pdf|mp3|flv|swf)$
RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/(.+)\.htm$ /$1.php [nc,L,QSA]
</code>
The purpose of the Rewrite rule is to change any request for a page with a .htm extension to a request for the same filename with a .php extension (unless the file with .htm extension actually exists). This rule seems to "work" in the sense that if I ask for a page with a .htm extension, I get the PHP content. This is what I want, but at the same time HTTP header inspector tools report that the website is giving a 404 response. What's weird is that my tools report that in the body of THE SAME RESPONSE, the server returns the correct HTML generated by the PHP code. That seems like a contradiction: page not found, but here's the content you wanted anyway??
If I force the server to send a 200 code ([R=200]), I get an "Internal server error" response, and if I force it to send a 301 code ([R=301]), the result is that the browser makes 2 HTTP requests instead of 1, and the second one ends up being a 404 anyway (but I still get the desired HTML in the response body!). I'm confused!!!
Comment: You might get better answers at: http://webmasters.stackexchange.com/
Comment: It sounds like your PHP script has a call to `header()` somewhere that sends back a 404 response. What kinds of things are you doing in `mystery_file.php`?
Comment: You might be on to something, Tim. My PHP files are using a CMS to query page content stored in a database. I didn't write the CMS, so it might be sending a 404 header somewhere in the code but not exiting. As a test, I added a PHP page that did no backend querying, just a few lines of simple code. Then I requested that page with a .htm extension, got the correct PHP-generated content back, and no 404 this time.
Answer: Solved. The CMS software was sending a 404 header due to an error in the page code. Once I fixed that, I stopped getting a 404 code in the response header.
Comment: You may want to mark your answer as correct then.  Adding the CMS name as a tag on the question is also a good idea, as it helps people to find appropriate questions when looking for answers later.


Area of a section of the cylinder bounded by two planes

Question:
Compute the area of the region on the cylinder $x^2+y^2=R^2$ bounded by the planes $z=mx$ and $z=nx$ where $z\ge 0, m>n>0.$
source: Demidovich, task 2214

My attempt:
I considered the following injective and continuously differentiable map $F:Q=[0,1]^2\to\Bbb R^3$ given by $F(u,v)=(R\cos(\pi u),R\sin(\pi u),R(n+(m-n)v)\cos(\pi u))$ in order to use the formula $$\nu(F)=\int_Q\sqrt{\det\nabla F(\boldsymbol u)^T\nabla F(\boldsymbol u)}d\boldsymbol u.$$
I get the following:
$$\nabla F(u,v)=\begin{bmatrix}-R\pi\sin(\pi u)&0\\ R\pi\cos(\pi u)&0\\ -R\pi(n+(m-n)v)\sin(\pi u)& R(m-n)\cos(\pi u)\end{bmatrix}.$$
So $$\begin{aligned}\nabla F(u,v)^T\nabla F(u,v)&=\begin{bmatrix}-R\pi\sin(\pi u)& R\pi\cos(\pi u)&-R\pi(n+(m-n)v)\sin(\pi u)\\0&0& R(m-n)\cos(\pi u)\end{bmatrix}\cdot\begin{bmatrix}-R\pi\sin(\pi u)&0\\ R\pi\cos(\pi u)&0\\ -R\pi(n+(m-n)v)\sin(\pi u)& R(m-n)\cos(\pi u)\end{bmatrix}\\&=\begin{bmatrix}R^2\pi^2(1+(n+(m-n)v)^2\sin^2(\pi u))&-R^2\pi(n+(m-n)v)\sin(\pi u)\cos(\pi u)\\-R^2\pi(n+(m-n)v)\sin(\pi u)\cos(\pi u)& R^2(m-n)^2\cos^2(\pi u)\end{bmatrix}\end{aligned}$$ and $$\begin{aligned}\det\nabla F(u,v)^T\nabla F(u,v)&=R^4\pi^2(m-n)^2\cos^2(\pi u)+ R^4\pi^2(n+(m-n)v)\sin^2(\pi u)\cos^2(\pi u)-R^4\pi^2(n+(m-n)v)^2\sin^2(\pi u)\cos^2(\pi u)\\&=R^4\pi^2(m-n)^2\cos^2(\pi u)\\\implies \sqrt{\det\nabla F(u,v)^T F(u,v)}&= R^2\pi|\cos(\pi u)|\end{aligned}$$ and finally, I obtained the integral $$\begin{aligned}\nu(F)&=\int_0^1\int_0^1R^2\pi|\cos(\pi u)|dudv\\&=R^2\pi\left(\int_0^{1/2}\cos(\pi u)du-\int_{1/2}^1\cos(\pi u)\right)\\&=R^2\pi\left(\frac{\sin(\pi u)}\pi\Big|_0^{1/2}-\frac{\sin(\pi u)}\pi\Big|_{1/2}^1\right)\\&=2R^2(m-n),\end{aligned}$$ but, in the book, the solution is $4R^2(m-n),$ which is twice of mine. I checked again the condition $z\ge 0$ and I can't find my mistake. Is there anything wrong and is there anything illegitimate with the procedure itself?
Answer: It's correct. To verify, integrate the area below in cylindrical coordinates
$$\int_{-\pi/2}^{\pi/2} (z_m -z_n)R d\theta
= R^2 (m-n)\int_{-\pi/2}^{\pi/2} \cos\theta \ d\theta=2R^2(m-n)
$$
where $z_k = k x =kR\cos\theta$.
Comment: Thank you! I've now noticed I looked the angle from $0$ to $\pi$ instead of from $-\frac\pi2$ to $\frac\pi2,$ but that didn't affect the result.


What equipment do I need to Jam to my own recorded chord progression?

Question: I am following the Fretboard Theory book by Desi Serna. And when learning the pentatonic scale I thought it would be good if I could record some chord progression and try to play melodies in the pentatonic scale to better understand the patterns on the fretboard.
I currently have a classical guitar (doesn't have a preamp) and that's all I have :). What equipment would I need to achieve the above?
It would be great if you can tell me as much options as possible. For example with looping device/with preamp etc.. but still keep the process interesting (recording on the phone and playing it in my opinion is not very interesting). I am also thinking of buying an electro acoustic classical guitar so please tell me how I will be able to use that for the above purpose. (I am asking all the options because then I can choose the most economical but interesting one)
Thanks in advance!
Answer: I realize some people will probably not like this answer, but I am going to say it anyway:  I am a very strong believer in simplicity for recording short jams.  You need to have a method to get a rough draft recording down very quickly without much thought.
Therefore, I highly recommend simply starting out with a tape recorder, digital meeting/voice recorder, or even a recording app on your smartphone.  Practice your rhythm progression, turn on the metronome, and simply press play go for it.  I know, this probably isn't what you want to hear.  However, if you take my advice, you will quickly find that is actually takes much discipline, accuracy, and trial and error to record a halfway decent take using the tape recorder, which is all part of the learning process.  Once you become proficient at recording using this simple device, you can move on to more complicated and sophisticated recording measures -- but I would take a look at gear related websites for advice on where to start with that.
My friends and I have gone through many spectrums of recording, both analog and digital, and when we are trying to get a final, polished recording, of course we will use a Tascam, Pedal which features looping/recording, or record using our other gear into a DAW on the computer.  However, for small jams and bursts of inspiration (when improvising), you need a method that is simple, guarenteed, and easy.  In fact, I will usually at the start of a jam turn on my smart phone app just in case we miss anything or can't figure out exactly what was played that we liked so much.
Comment: Hey! Thanks for your answer. But are there tape recorders that allow looping? And also, what phone application do you use? The problem I had with phone looping app is that the sound might not be loud enough. Did you not come across this problem?
Comment: @Can'tTell, you can loop with the Micro-BR I link to in my answer.
Comment: The answers below are just as valid, just simply different pieces of gear for doing so.  If you are willing to make the investment, picking up one of those would be just as good (pretty much exactly the same thing) as using the smartphone app or digital voice recorder.  I forgot to mention specifically, I personally use a Sony ICD-AX412 (in addition to the smartphone app, I use this for meeting at work as well) and have been meaning to get one of the many plug-in-able microphones to increase the sound quality.
Answer: The Boss RC-30 is a very good looper that has an XLR input for a microphone and stereo/mono input for when you get your electro-acoustic. It is a dual track looper, with some effects, 99 memory slots, up to 3 hours recording. You can also connect this to your computer and save/load your loops. For putting down a phrase and then playing over it etc, I would totally recommend this.
I would still recommend recording your jam as well though, the output of the above could be connected to your computer or a separate recorder (Tascam DP-004/8 are really good, also the Zoom R8/16 or even a tape recorder). Depends how much you want to spend and what your commitment is. From my experience, a multi-track would be a good investment. The RC-30 would also plug straight into these multi-tracks.
In total (Sorry, only have prices in GBP), you are looking at £199 for the RC-30, about £180 if you went for the 4 track Tascam DP-004 and then extra for cables/microphone etc if you haven't already got them. This is probably the more expensive option, but if you are committed to what you are doing then it's more of an investment and I couldn't recommend the above enough.
Answer: I use a Boss Micro-BR for doing this kind of practice. (At the moment, I just select a random page from a Real Book, record the chords, and then use this backing to sight-read the melody over and practise some improvisation.)
The recording quality of the Micro-BR isn't that amazing, but the functionality is. Off the top of my head: 4 track multi-track recording; effects; tuner; drum machine; stereo/mono inputs. You can mix-down to WAV or MP3. You can store MP3s on it to play along with (and you can change the playback speed of these too…)
The Micro-BR has it's own microphone, so you can record acoustic or classical guitar. The quality of this microphone is, again, not amazing. But, it is much better than you'd expect. I use the microphone for recording classical guitar pupils all the time, so they can listen back to their playing after lessons.
It's really small and is very inexpensive (I just saw some new ones on eBay for $89).
I like these so much, I have one on my desk at home, and one in my teaching guitar case. I've recommended them to loads of pupils.


Replicating for...in loop with SpiderMonkey public API

Question: I am trying to probe some JavaScript in SpiderMonkey (the latest release version) with the public C JSAPI.
How do I replicate the behavior of the for...in loop with public JSAPI calls, such as JS_GetPropertyById, JS_LookupProperty, JS_Enumerate, and others? The documentation for JS_Enumerate says that it only returns enumerable properties on the target object; it does not search for properties in the object's prototype chain. I would like to replicate the exact behavior of the for...in loop, but avoid injecting code into the JS environment. It looks like JS_NewPropertyIterator may be deprecated, or is a strong candidate for deprecation.
Answer: My first impression is that this probably isn't a good thing to do. It is not something I would ever do because the behavior of for...in is kind of bizarre and idiosyncratic and I just don't think it's ever the right thing. But if this is really what you want, read on.
Internally, an actual for...in loop uses js::ValueToIterator, and that function doesn't appear to be exposed via the JSAPI (at least jsapi.cpp doesn't call it anywhere).  So you have two options:

Convince the Mozilla JS team to expose the for...in machinery via the JSAPI (if you were willing to help with the work, this is doable); or
Actually compile some JS code that has a for...in loop in it.

Option 2 will be quicker for you. You can use this function, for example:
function ForInResults(obj) {
    return [v for (v in obj)];
}

Or if you prefer an iterator:
function ForInIterator(obj) {
    for (var v in obj)
        yield v;
}

You can compile either of these functions using JS_CompileFunction, then call it using JS_CallFunctionValue. To get individual elements out of an array, use JS_GetArrayLength and JS_GetElement. Getting values out of an iterator is a little trickier, but it's more like a real for...in loop in the unusual case where properties are being added or deleted while you're looping.


Why are topologies that give different limits nonequivalent?

Question: I am reading an example that gives a sequence and show how two topologies on the vector space containing the sequence will give different limits of the sequence. They conclude without proof: "the two norms cannot be equivalent" (equivalent in the sense $C_1 \|\cdot\|_1 \leq \|\cdot\|_2 \leq C_2 \|\cdot\|_1$). I don't see why differing limits give in-equivalent topologies.
Note: Open Mapping Theorem has not been introduced yet (which I've read can be helpful here -- but am not sure), so I suspect there's some more elementary/topological argument.
Comment: Voting to re-open as the answers in the dupe target don't seem to address the particular question asked here. In particular, they show the converse: if the norms are not equivalent, then there is a sequence converging with respect to one norm, but not the other.
Comment: I concur with Theo's comment and vote.
Answer: Suppose $C_1 \| \cdot \|_1 \le \| \cdot \|_2 \le C_2 \| \cdot \|_1$, where $C_1, C_2 > 0$. If $x_n \to x$ with respect to $\| \cdot \|_1$, then
$$0 \le \|x_n - x\|_2 \le C_2 \|x_n - x\|_1 \to 0$$
in $\Bbb{R}$, so by squeeze theorem, $\|x_n - x\|_2 \to 0$. Note also that $\|x_n - x\|_2 \to 0$ in $\Bbb{R}$ is immediately equivalent to $x_n \to x$ with respect to $\|\cdot\|_2$.
Since $\| \cdot \|_1 \le C_1^{-1} \| \cdot \|_2$, we can see that, if $x_n \to x$ with respect to $\|\cdot\|_2$, then $x_n \to x$ with respect to $\| \cdot \|_1$.
Thus, equivalent norms perfectly preserve convergence (i.e. a convergent sequence in one norm will converge to the same limit in the other). Contrapositively, if two norms cause the same sequence to converge to different limits (or to diverge in one, but not the other), then the norms cannot be equivalent.
EDIT: Here's another way to think about the same proof. Since $\| \cdot \|_2 \le C_2 \| \cdot \|_1$, this means that the identity map $I : X \to X$ on our space $X$ is a bounded linear map from $(X, \|\cdot\|_1)$ to $(X, \|\cdot\|_2)$. In particular, $\|Ix\|_2 = \|x\|_2 \le C_2\|x\|_1$. Hence, $I$ is (sequentially) continuous. So, if $x_n \to x$ under $\| \cdot \|_1$, then $Ix_n \to Ix$ under $\|\cdot\|_2$, by sequential continuity.
Answer: A basic fact: if two norms are equivalent (in the $C_1-C_2$ sense you mentioned) then they have the same convergent sequences. (the proof is easy.) So the logical reformulation (contrapositive) is: if we have two sequences with different limits, then the norms cannot be equivalent. This, I think, explains the remark in your example.


Quantidade de casas decimais

Question: Estou fazendo a soma de um carrinho de compras com javascript porém quando o número não é exato me retorna muitas casas decimais.
para resolver isso eu usei o toFixed(2). porém agora quando dá um número exato, ele retorna com duas casas decimais a mais com 0 e não passa no teste pois o teste espera que quando for inteiro retorne apenas o valor.

const sum = priceItem.reduce((acc, curr) => acc + curr);
sumPlace.innerText = sum.toFixed(2);```

Answer: Não vai conseguir esse comportamento com uma função só, até porque o normal é querer um número fixo de casas decimais mesmo para valores inteiros (tipo um preço de 5 reais é expresso como R$ 5,00).
Teria de tratar você mesmo esta exceção, algo no estilo
if (sum === Math.floor(sum) {
    sumPlace.innerText = sum.toFixed(0);
} else {
    sumPlace.innerText = sum.toFixed(2);
}

Quantidade de casas decimais


Cube roots of complex numbers

Question: I need help with finding the cube roots of the complex number 27... I know that the obvious answer is three, but what is the less simple method to solving this?
Comment: Have you heard of [De Moivre's formula](http://en.wikipedia.org/wiki/De_Moivre%27s_formula)?
Answer: Tim's answer works, but another way to do it is using De Moivre's theorem. Using this theorem we find that the three complex roots of $27=27\left(\cos 0+i\sin 0\right)$ are given by:
\begin{equation}
\begin{aligned}
z_k&=\sqrt[3]{27}\left(\cos\frac{0+2\pi k}{3}+i\sin\frac{0+2\pi k}{3}\right)\\
&=3\left(\cos\frac{2\pi k}{3}+i\sin\frac{2\pi k}{3}\right)
\end{aligned}
\end{equation}
where $k=0,1,2$. This therefore gives us that the three cube roots of $27$ are:
\begin{equation}
\begin{aligned}
z_0=3\left(\cos\frac{2\pi\times 0}{3}+i\sin\frac{2\pi\times 0}{3}\right)&=3\\
z_1=3\left(\cos\frac{2\pi\times 1}{3}+i\sin\frac{2\pi\times 1}{3}\right)&=\frac{3\left(i\sqrt{3}-1\right)}{2}\\
z_2=3\left(\cos\frac{2\pi\times 2}{3}+i\sin\frac{2\pi\times 2}{3}\right)&=-\frac{3\left(i\sqrt{3}+1\right)}{2}
\end{aligned}
\end{equation}
Answer: From Euler formula you have:
$$
1=\cos(2k\pi)+i\sin(2k\pi)=e^{i2k\pi}
$$
Write: $27=27\times 1=27e^{i2k\pi}$ and find:
$$
\sqrt[3]{27e^{i2k\pi}}=3(e^{i2k\pi})^{\frac{1}{3}}=
3e^{\frac{i2k\pi}{3}}
$$
and for $k=1,2,3$ you find the three complex cubic roots of $27$.
Answer: Well you can solve the equation $x^3-27=0$
$$x^3-27=(x-3)(x^2+3x+9).$$
So, of course we get $3$ as a solution from the first factor.  To get the remaining solutions use the quadratic formula.

Cube roots of complex numbers


Plot multiple vertical lines using plotly facet grid

Question: I want to plot 2 vertical lines displaying two different means. This is again separated into different subplots using plotly facet grid.
With below, I'm displaying the cut in separate subplots. In each subplot, I have two different colors signifying val. For each subplot, I want to display the means for val and cut. But I'm only displaying the mean for cut at the moment.
import seaborn as sns
import plotly.express as px

diamonds = sns.load_dataset('diamonds')

diamonds['val'] = np.random.randint(1, 3, diamonds.shape[0])

grpval = diamonds.groupby(['cut','val'])['price'].mean()
print(grpval)

fig = px.histogram(data_frame=diamonds,
                   x='price',
                   facet_col='cut',
                   color = "val",
                   facet_col_wrap = 2,
                   )

for c,idx in zip(diamonds['cut'].unique(),[(1,1),(1,2),(2,1),(2,2),(3,1)]):
    df = diamonds[diamonds['cut'] == c]
    fig.add_vline(x=df['price'].tail(1).values[0], line_width=1, line_dash='solid', line_color='red', row=idx[0], col=idx[1])

fig.show()

I tried plotting both means but am only getting one.
Comment: I am a little confused as to your intent. If you want to add a vertical line of averages in units of the newly added val values, try the following code. `fig.add_vline(x=df.query('val == 1')['price'].mean(), line_width=1, line_dash='solid', line_color='blue', row=idx[0], col=idx[1]);fig.add_vline(x=df.query('val == 2')['price'].mean(), line_width=1, line_dash='solid', line_color='red', row=idx[0], col=idx[1])`
Answer: Here's how you could add two vertical mean lines to the plot:

import numpy as np
import seaborn as sns
import plotly.express as px

diamonds = sns.load_dataset("diamonds")

diamonds["val"] = np.random.randint(1, 3, diamonds.shape[0])

grpval = diamonds.groupby(["cut", "val"])["price"].mean()
# reshape the mean values into cut and val dimensions
grpval_per_cut = np.reshape(grpval.values, (diamonds["cut"].unique().size, -1))

# add color sequence to have same colors on histogram and lines
color_discrete_sequence = px.colors.qualitative.G10

fig = px.histogram(
    data_frame=diamonds,
    x="price",
    facet_col="cut",
    color="val",
    facet_col_wrap=2,
    color_discrete_sequence=color_discrete_sequence,
)

# iterate over mean values and subplots (I could not figure out a direct way
# to associate the subplot with the correct mean value, so I arranged it "by hand"
for mean_per_val, (row, col) in zip(
    grpval_per_cut, [(3, 1), (3, 2), (2, 2), (2, 1), (1, 1)]
):
    for val, line_color in zip(mean_per_val, color_discrete_sequence):
        fig.add_vline(
            x=val,
            line_width=1,
            line_dash="solid",
            line_color=line_color,
            row=row,
            col=col,
        )

fig.show()


Word VBA "Label Not Defined" If Bookmark exists command

Question: I am very new to VBA and just learning. Here's my situation and problem:
1) I created a working userform with text and comboboxes linking to bookmarks
2) Problem is that it doesn't work if some bookmarks don't exist (and the project will require this: the form will need to run on documents where not all bookmarks are present)
3) I would like the form stop giving me error messages if bookmarks arent there and just fill out the ones that are existing in that particular ocument
4) Here's the Code:
Private Sub cmdOK_Click()
    Application.ScreenUpdating = False
    With ActiveDocument
          If .Bookmarks.Exists("cboYourName") Then
        .Range.Text = cboYourName.Value
        Else: GoTo 28
    End If
         If .Bookmarks.Exists("cboYourPhone") Then
         .Range.Text = cboYourPhone.Value
         Else: GoTo 32
    End If
        If .Bookmarks.Exists("cboYourFax") Then
        .Range.Text = cboYourFax.Value
        Else: GoTo 36
    End If
         If .Bookmarks.Exists("cboYourEmail") Then
         .Range.Text = cboYourEmail.Value
        Else: GoTo 40
    End If
         If .Bookmarks.Exists("txtContractName") Then
         .Range.Text = txtContractName.Value
         Else: GoTo 44
    End If
          If .Bookmarks.Exists("txtContractNumber") Then
          .Range.Text = txtContractNumber.Value
          Else: End
    End If
    End With
    Application.ScreenUpdating = True
    Unload Me
End Sub

4) How do I get this to work?????????
Answer: I think you're close. First, avoid Goto statements. In your code, it's hard to tell what you mean to do. I think the errors are from the Goto statements. Its parameter is a label, not a line number. Second, avoid using End. It's better to have a closing routine. That said, the code works with any number of Exists statements.
Private Sub cmdOK_Click()
    Application.ScreenUpdating = False
    With ActiveDocument
        If .Bookmarks.Exists("cboYourName") Then
            .Range.Text = "cboYourName text."
        Else
            Debug.Print "Bookmark exists."
        End If

        If .Bookmarks.Exists("cboYourPhone") Then
           .Range.Text = "cboYourPhone text"
        Else
            Debug.Print "Bookmark does not exists."
        End If
    End With

    Application.ScreenUpdating = True
    Unload Me
End Sub

However, be aware that each found bookmark completely replaces the content of the document, including subsequently found bookmarks. Is that what you mean to do?


Creating a horizontal separator in xamDataGrid

Question: I want some way of indicating a separation or line between two records whose dataitems are known, in a XamDataGrid. Currently I'm doing this by adding a background brush to the rows that contains a gradient (the top row has solid red near the bottom, the bottom row has solid red near the top), resulting in the appearance of a nice-looking red line between the two rows. A converter checks the dataitems against fields containing the special dataitems, and if they match, it applies the brush. However, now I need to add actual backgrounds to the rows.

So is there a way to apply two LinearGradientBrushes to the same row? Alternatively, I tried adding the StopCollections for the two border gradients to the normal background brushes, but this means for every normal background, there's 3 possible brushes (simple, red at top, red at bottom), which quickly adds up when you have 12 possible backgrounds.
On a different tangent, is it maybe possible to add a line or show a separator in a xamDataGrid in any other way than this background hack? Maybe a border hack or an actual way to insert visual elements into the grid at a location specified by row indexes?
Answer: You could add a style for the DataRecordCellArea to show the border below the cells.  For example:
<code><Style TargetType="{x:Type igDP:DataRecordCellArea}">
    <Setter Property="BorderBrush" Value="Red"/>
    <Setter Property="BorderThickness" Value="0,0,0,2"/>
</Style>
</code>
Note that you would still need to add the logic that you have to use this conditionally.


Paying back for shared costs among a group

Question: After celebrating the new year, me and my pals wanted to split the costs of our mischief. I started wondering about the best way to toss money around, i.e. a way to systematically minimise the amount of transactions. So the problem is that everyone should pay equally, even though one or few have already payed for the bills.
The obvious worst case scenario is that for $p$ people out of $n$ that have payed for something, the other $n-1$ pay for their share, $p$ times. If a single person pays for everything, the solution is easy enough: everyone pays for their share. For 2 out of $n$ people my best guess is this. First we total the money spent. Then one of the two pays the other such that they only pay for their share. The others pay the first guy as previously. This can be generalised. For $p$ out of $n$ that do the spending, let's choose 1 that is the hub of all transactions. Again, let's combine the total costs of everything, and let the chosen hub equalise the loss or win of those that payed something. Finally $n-p$ people simply pay for their share.
Is this the optimal strategy?
In a special case, where for example the non-hub spender spent 16 € and the share is 8 €, one of the people can pay their share to the non-hub, eliminating a transaction with the hub. But any amount that doesn't exactly get the spending of a non-hub equal to the share doesn't help.
I know this is neither the trickiest of questions nor one of utmost importance, but I thought someone might enjoy giving it a go. Happy New Year!
Comment: See also https://math.stackexchange.com/q/3046139/177399
Answer: Your question is quite confusingly worded, but I think I know what you are asking.
Each person should end up paying the proper share, and there should be as few transactions as possible - that minimizes "tossing money around".
The problem seems to be that some people have already paid the full bill at some of the establishments you visited, and now you have to even up.
Figure out the amount owed (the total of the bills divided by the number of people).
Clearly you might need one transaction for each of the $n$ people who aren't even. Here's a way to do that. Among the people not even there must be at least one who has paid less than their fair share. Let one of those people hand the balance owed to anyone else. Now that payer is even (all paid up). If you're still not all even, do it again.
This will take at most $n$ transactions, fewer if by chance someone receiving money was evened up along the way. At each stage you can look for such a coincidence and take advantage of it.
Comment: Thanks for the answer! I edited the question slightly to confirm your interpretation of the question, sorry. But to your answer. It takes at most $n$ transactions. I reckon the hub solution I proposed also takes that amount, and now looking at it, no less should be expected beyond the special cases. But this does have the advantage of not piling the transactions onto one hub. Cheers!


mapbox layer fill-color based on TEXT property

Question: Is is possible to set the fill-color stops, based on a text property rather than a numeric value
e.g fill based on province name
My input dataset has a property/Column called PROV_ID and contains a 2 letter ID for each state/Province
So I am aiming toward something in the lines of: 'stops': [['GP', 'YELLOW']]
The code however does not render any fill-colors when when implemented as shown below, I have replaced my PROV_ID in the code below with the Primary key property [numeric] to test, and that works fine
I guess the question is really then if fill-color stops is limited to numeric properties only?
map.addLayer({
        'id': 'countiesLayer',
        'type': 'fill',    /*define the type of layer fill, line, point, fill-extrusion, background, raster, circle*/
        'source': 'mySrcName',
        'source-layer': '3_Fields-83vr21',
        'layout': {
          'visibility': 'visible'
        },

        /*there are many options for styling - this is a simple style*/
        'paint': {
          'fill-color': {
            'property': 'PROV_ID',
            'stops': [['GP', 'YELLOW']]
          },
          'fill-outline-color': 'white'
        }
      });

Answer: I think you need an expression with the function match.
The code would be (not tested):
map.addLayer({
    'id': 'countiesLayer',
    'type': 'fill',    /*define the type of layer fill, line, point, fill-extrusion, background, raster, circle*/
    'source': 'mySrcName',
    'source-layer': '3_Fields-83vr21',
    'layout': {
      'visibility': 'visible'
    },

    /*there are many options for styling - this is a simple style*/
    'paint': {
      'fill-color': ['match', ['get', 'PROV_ID'], // get the property
                     'GP', 'yellow',              // if 'GP' then yellow
                     'XX', 'black',               // if 'XX' then black
                     'white']                     // white otherwise
      },
      'fill-outline-color': 'white'
    }
  });

From the docs:

match
Selects the output whose label value matches the input value, or
  the fallback value if no match is found. The input can be any string
  or number expression (e.g. ["get", "building_type"]). Each label can
  either be a single literal value or an array of values.
["match",
input: InputType (number or string),
label_1: InputType | [InputType, InputType, ...], output_1: OutputType,
label_n: InputType | [InputType, InputType, ...], output_n: OutputType, ...,
default: OutputType ]: OutputType


In meantone temperaments, do A sharp and B flat have different frequencies?

Question: In Pythagorean and Just tuning, according to Wikipedia, there are different frequencies for flat and sharp notes. Most notably, there is a tritone of which there seem to be 2 quite different versions.
In equal temperament, there are just 12 semitones.
In meantone temperaments, like Werckmeister's, is there a difference in frequency between A♯ and B♭? Or do they, like equal temperament, just have 12 notes?
I know a violin may be playing a different frequency for A♯ and B♭, and it may sound better, but if they do, are they technically outside the bounds of both equal and meantone temperaments?
EDIT
As per comments below, Werckmeister's is NOT a 'meantone temperament' but a 'well temperament'. Meantone happened early 17th century, well temperament late 17th century (says https://www.albany.edu/piporg-l/tmprment.html)
So I now have two questions:

Are A♯ and B♭ similar in meantone temperaments?
Are A♯ and B♭ similar in well temperaments?
Comment: But that doesn't answer the question. The question is whether when using such a tuning, the tuner needs to choose which note to tune such a key to. Does a meantone temperament or e.g. Werckmeister III prescribe a single pitch for the A#/Bb key, to be used for both, or does it give two different pitches out of which the tuner must choose? That is the question. I think the answer is: the former for well temperaments, the latter for meantone temperaments (which simply assumes notes such as A# do not occur).
Comment: I don't have time to put in my answer but, yes, in something like 1/4 meantone, in theory, they'll be different, audibly so; one is about 20 cents below 800, one 20 cents higher.  Using one in place of the other is what gives you wold intervals.  Well temperament involves shifting the notes to avoid wolf intervals.
Comment: Dave's answer and MattPutnam's answer are correct.  A temperament is a system for tuning a keyboard instrument, so its specification must take into account the keys available on the instrument.  Any keyboard instrument that has the same key for A♯ and B♭ will necessarily be tuned in a temperament that specifies the same pitch for A♯ and B♭.
Comment: @reinierpost Werckmeister's are 12-tone temperaments.  Meantone temperaments do as  you note typically tune B flat as such, since A sharp is an unusual pitch for the period in which meantone temperaments were used, but I do believe there are examples of split-key keyboards with two keys at that position.  The question that would come up more realistically in practice is G sharp vs. A flat.
Answer: Most temperaments that you'll come across in practice do not differentiate between enharmonic notes, however there are many temperaments that do; they're rarely used, or "just theoretical" because there are not many fixed pitch instruments that provide more than 12 notes per octave so there aren't instruments that can be tuned to them.  An important thing to keep in mind is that a temperament is a highly practical construct -- how do I tune this thing so that it sounds good?
Take the Werkmeister temperaments: they're primarily used for organs, which almost always have 12 note octave keyboards, and thus you need to assign a single pitch to the pairs of enharmonic notes.
However, there were some instruments built with split key keyboards that provide the mechanism to differentiate between some enharmonic notes.  Indeed, people have gone pretty far with this idea, e.g. this instrument with 84 notes per octave tuned in 53-ET(?).
Another example is the English concertina -- it has 14 buttons/octave and differentiates between a♭/g♯, and e♭/d♯.  These can be tuned in 1/5 comma meantone to take advantage of this fact.
Finally, yes, continuous pitch instruments don't always (try to) create notes right at any particular tuning standard instead they can, especially in solo/lead situations, apply expressive intonation.
Comment: You are not addressing the possibility of retuning instruments between pieces. Conceivably a portative organ or other keyboard instrument can be retuned between pieces in different keys; such instruments must be tuned before performances anyway. So conceivably, temperaments may have been used that require such retuning.
Answer: In any 12-tone system, A♯ and B♭ are always the same. If they're different, then you have more than 12 tones.
When using a ratio-based tuning, there are always multiple ways to construct a particular interval. If it's a 12-tone temperament, you have to pick just one. The different ways to pick intervals constitute unique 12-tone temperaments.
Comment: @reinierpost in the days of meantone temperament, music tended to be written in a limited selection of keys, so there wasn't much call for retuning.  It was nonetheless possible, as you note.  The desire to use a wider range of keys led to development of temperaments that made it possible to avoid retuning.
Comment: Indeed, even most split-key keyboard with *more than 12* keys per octave will have the same pitch for A♯ and B♭ unless the A♯/B♭ key is one of the split ones (which it usually isn't).
Comment: So the question is: when using meantone or well temperaments, were only 12 tones used, or did players retune certain keys depending on the key a piece was in? Clearly, they didn't on church organs, but on home instruments, frequent retuning is necessary anyway, so it would not be too much of a problem.
Comment: Absolutely. As a player of very limited ability, lately I've been focusing on some pieces in the Fitzwilliam Virginal Book (music from around 1600). Some have two to three flats, some two to three sharps - one has a fourth sharp. D# and Eb, or G# and Ab, are completely different in meantone, so there is just no way to play all of these without retuning those keys. A piece by Bull uses both, and probably wasn't played in meantone. Italian theorists had advocated for equal temperament in the 1580s, so it wasn't unknown.
Comment: @reinierpost are you certain that these are not modern transpositions?  Key signatures with sharps didn't come into use until the middle of the 17th century, decades after Fitzwilliam was compiled.  Which pieces have three flats or three sharps?
Comment: @phoog: I'm using the Dover edition. It has two flats in the signature for [Rowland](https://www.youtube.com/watch?v=uF7CZh8-HwQ&t=8183s); I don't think it ever has sharps in signatures, but there is a piece with 3 to 4 sharps: [Alman CCXXVII](https://www.youtube.com/watch?v=MPQnFGq4FdQ&t=7156s). So Eb and D# both occur, in different pieces. I'm very interested to know which temperament Belder is using there.
Comment: @reinierpost thanks.  It's too bad liner notes aren't as easy to find online as are sound recordings.  I did find this review of volume 4 which does seem to imply that he used different temperaments for different pieces, or, if not, that he used a non-meantone temperament for all): http://www.musicweb-international.com/classrev/2016/Dec/Fitzwilliam_v4_95254.htm
Answer: No.  "Meantone" means the tuning has been adjusted so the pitch produced by either Bb or A# is the average (or the 'mean') of the two pitches. You end up with just 12 pitches per octave, just as you do in equal temperament.
EDIT: The OP has requested I elaborate on my answer, which I see has gotten a number of downvotes.  Perhaps that's deserved – as a music teacher I shade answers to the perceived level of what a student knows (e.g. in teaching a time signature "the top number is the number of beats per measure" is sufficient, and a discussion of simple vs compound meters waits until later).
With that out of the way…
Keyboard instruments prior to about 1500 had as many as 19 keys per octave, with split keys for all of the modern black keys, plus a B# and E# that were different from C and F. (See the first photograph in http://www.harpsichord.org.uk/wp-content/uploads/2015/04/archicembalo.pdf for a reproduction of an early 16th century archicembalo with 19 keys per octave in the lower manual.)
The large number of keys was required by Pythagorean tuning: as you go up the harmonic series you get different pitches for F#/Gb etc.
Manufacturing technology was improving quickly in the 16th century, with new techniques for pulling wire (the strings in most of these instruments were drawn brass).  As a result, we were now capable of making instruments with a larger range.   Even in Pythagorean tuning that means bumping up against the Pythagorean comma: three pure 5:4 thirds do not add up to a 2:1 octave.  The larger the range of the instrument, the more pronounced the discrepancy.
Concurrent with this was a desire to make instruments simpler, reducing the number of keys.  This would make them both easier to manufacture and easier to play.
Solving the Pythagorean comma at a practical level was needed.  The earliest solution that I know of was that of Pietro Aron in his book Toscanello in musica published in 1539: he proposed dividing the comma into four parts, and lowering the tuning of four consecutive fifths by that amount to create a perfect octave while retaining most of the pure thirds.  His system resulted in eight pure thirds and four that were terrible (wide by about 40 cents).  The fifths were narrow by about six cents, except for one – that was wide by a whopping  35 cents.  In case you're interested in looking into it in depth, the tuning portion of his book is online in translation at http://www.tonalsoft.com/monzo/aron/toscanello/aron_toscanello.htm
Using Aron's tuning made it possible to create an instrument with 12 keys per octave that sounded at least acceptable in a number of keys.  Keys that required the bad notes, known as "wolf tones" were avoided.
Aron's method came to be known as meantone tuning.  Tempering for two consecutive fifths meant that the major second interval was halfway (the mean) to the major third.  Give or take 1/10th of a cent, which is certainly close enough for the purpose.  Any tuning that results in equal whole steps can properly be called meantone, and meantone tunings can be created by using 1/3 of the comma, or 1/5th, or any other fraction less than the number of discrete pitches per octave (our 12TET system is one variety of meantone).
The development of meantone tuning was concurrent with the elimination of split accidentals, or at least as concurrent as the speed of information traveling in the 16th century would allow.  This meant it also had the effect of adjusting the black keys to fall between the Pythagorean sharp and flat pitches.
In the context of the question, my original answer – that meantone split the difference between sharps and flats – is accurate.  The fact that you can have meantone tunings with divisions of the octave other than twelve is true… but I judged it irrelevant to the question.
The next problem was how to handle the wolf tones.  Many tuners devised adjustments to meantone tuning to reduce or eliminate the wolves by raising or lowering specific pitches.  Werkmeister was one of them, and devised a number of possible tunings.  These tunings are called well temperament, because it allowed the instrument to play well in all keys.
Because well temperament results from the adjustment of individual pitches you end up with intervals that are not all the same size.  Your minor third in C will be different from your minor third in D or Ab.  Some found this a feature rather than a bug: each key now had its own unique character, distinct from any other key.  Various well temperaments stuck around through the 1800s, and are still used by "period" instrumentalists.
12TET began to replace well temperament in the mid 19th century, and is considered the standard today.
Comment: @dekkadeci - as a new user I don't yet have enough "reputation" to comment directly on your edit to the question, but it is incorrect.  Werkmeister tunings are well temperaments, not meantone tunings.  Meantone tunings take the average of the Pythagorean split accidentals; they are a "regular" or "linear" temperament, evenly dividing the Pythagorean comma.  Well temperaments make adjustments to meantone to reduce the wolf tones, and are "irregular" temperaments, which means not all steps are the same size.
Comment: Wrong. In just intonation, do re mi have frequencies 8:9:10, making intervals of a greater tone & a lesser tone. "X is a meantone temperament" means that X makes these tones the same size, i.e. makes 4 perfect 5ths = 2 octaves + major 3rd. Nothing to do with Bb/A#. One possible meaning of Bb=A# is that 12 perfect 5ths = 7 octaves. In this case 12ET is the only temperament with both properties; in quarter-comma meantone, 31ET and other meantones Bb and A# are different.
Comment: @RosieF - I agree that meantone makes the tones the same size, and that any ET is meantone, and that a meantone temperament may have different Bb/A# tones.  I disagree with the edit: "Meantone temperaments like Werkmeisters" (Werkmeister was added in the edit).  Werkmeister temperaments are not meantone, as they are irregular.
Comment: @Dave there's different versions of meantone temperament. here are 4 of them: https://en.wikipedia.org/wiki/Werckmeister_temperament
Comment: Only the first sentence of this question addresses the actual question being asked, but it is factually incorrect. The rest is all backstory, interesting, but no answer to the question.
Comment: @reinierpost - my answer was originally just the first sentence.  You'll see that's followed by my edit - the OP asked me to expound on it, which is why the backstory is there.
Comment: Do you have a reference that lays out the math behind the idea that the pitch is the mean of the two enharmonic notes?
Comment: @Dave math wasn't possible, as meantone tuning developed several hundred years before we were able to measure frequency.  The "mean" was the guess of the tuner.
Comment: @commonpike Werkmeister's tunings were well temperaments, the system that replaced meantone.  In meantone all whole steps are the same size; in well temperament they aren't.
Comment: @TomSerb oh boy, I edited the question now - I don't want to add more to the confusion. Could you please update your answer, so you can enlighten future readers, as well as ... me ? :-)
Comment: @TomSerb - To clarify, Werckmeister being mentioned as a meantone temperament was in the original version of this question. I corrected the spellings of the notes (I saw "Bd" in the original) but didn't verify what type of temperament/tuning Werckmeister was (and the spelling of that name looked plausible, so I didn't even check its spelling).
Comment: @Dekkadeci - my apology.  I thought that was your edit.
Comment: @commonpike - I've elaborated quite a bit below my original response
Comment: @TomSerb brilliant ! Accepted your answer, and many thanks. The downvotes were not deserved imho (and not mine!)
Comment: @TomSerb "In meantone all whole steps are the same size": This is not true.  Can you give an example of a historical meantone temperament in which it is?  If it *were* true, then why would meantone temperaments other than equal temperament exist? In a non-equal temperament where all whole steps are the same size, there will be two sizes of half steps.  What would those sizes be and why? (Also, lowering fifths by 1/4 comma does not create perfect octaves, only pure thirds.)
Comment: To put it another way, it is not possible for all whole steps to be the same size while at the same time having "eight pure thirds and four that were terrible (wide by about 40 cents)."
Comment: @phoog I said Aron's system divided the comma among four consecutive fifths.  That results  in eight pure thirds, and four that are quite wide,  In addressing Rosie's earlier statement I agreed that "the tones" (i.e. do-re-mi) are the same size.  I also said that any tuning that results in whole tones the same size can be considered meantone.  None of those statements are conflicting, because while they all address meantone temperaments they do not refer to the SAME tuning.
Comment: @TomSerb you said "in meantone, all whole steps are the same size."  That is not correct.  Do-re-mi are the same size, true, but not *all* whole steps.  If all whole steps were the same size, then c-d-e-f♯-g♯-a♯-c would all be the same size, and so would c♯-d♯-f-g-a-b-c♯.  Also, because 1/4-comma meantone results in pure thirds, but successive pure thirds are less than an octave, at least one of the thirds in c-e-g♯-c must be wide, and the two whole steps in that third cannot be equal to the two whole steps in the other thirds.


Show there is an eigevalue within a certain value of $\lambda$.

Question: Here is the problem: Let $V$ be a finite dimensional inner product space with $T:V\to V$ self adjoint transformation. Suppose there exists $v\in V$ a unit vector such that
$$\|Tv-\lambda v\|<\epsilon$$
Show that there must exist an eigenvalue $\lambda'$ of $T$ such that $$\lambda -\lambda'<\epsilon$$
Here's my attempt: Let $v$ be as supposed, then
$$\|Tv-\lambda v\|^2=\langle Tv-\lambda v, Tv-\lambda v\rangle=\|Tv\|^2-2\lambda \langle v,Tv\rangle +\lambda^2 \|v\|^2=\|Tv\|^2-2\lambda \langle v,Tv\rangle +\lambda^2$$
Here we use the fact that $T$ is self adjoint so its eigenvalues are real so theres no need to worry about conjugates, as well as the fact that $v$ is unit.
Now, let $v=\sum a_i v_i$ where $v_1,...,v_i,...,v_n$ are orthonormal eignevectors ($T$ is self adjoint so we use the spectral theorem):
Continuing from above:
$$\|Tv\|^2-2\lambda \langle v,Tv\rangle +\lambda^2=\|\sum a_i \lambda_i v_i\|^2-2\lambda \sum a_i\lambda_i +\lambda^2$$
where we use orthogonormality of the eigenvectors.
Now i get stuck however. Is this on the right track? Any help is appreciated.
Comment: Use **unit** vectors $v_1,\ldots,v_n$ so that you would know that $a_1^2+\ldots+a_n^2=1$.
Comment: I'm not quite sure how this helps, I already assume $v_1,..,v_n$ are orthonormal unit vectors.
Comment: Also use Pythagoras' theorem for the last norm, you should get $(\lambda_1-\lambda)^2a_1^2+\ldots+(\lambda_n-\lambda)^2a_n^2$, if I am right. Then, assume the opposite, i.e. that all $|\lambda_i-\lambda|\ge\epsilon$ and derive a contradiction.
Answer: Continue to use orthonormality of the orthornomal basis (i.e. Pythagoras theorem) from what you have so far to show that
$$
\Vert Tv - \lambda v \Vert^2 = \sum_i |a_i|^2 \lambda_i^2 - 2 \lambda \sum_i |a_i|^2 \lambda_i + \lambda^2 = \sum_i |a_i|^2 (\lambda_i - \lambda)^2,
$$
where we use the fact that $\sum_i |a_i|^2 = \Vert v \Vert^2 = 1$. (Also with a minor correction where the cross term should also have $|a_i|^2$ instead of $a_i$.)
Now, suppose that for all eigenvalues, we have $|\lambda_i - \lambda| \geq \epsilon$. (We have to assume that the relevant norm is being used.) Then the above formula shows that
$$
\Vert Tv - \lambda v \Vert^2 \geq \epsilon^2 \sum_i |a_i|^2 = \epsilon^2 ,
$$
a contradiction to our initial assumption. Hence we conclude that there must exist some eigenvalue $\lambda_i$ such that $|\lambda_i - \lambda| < \epsilon$.
Comment: I think the term should rather be $|a_i|^2$!
Comment: Thanks - fixed!
Answer: Since $T$ is self adjoint, we have a diagonalizing orthonormal basis $
\{v_1,\dots,v_n\}$ corresponding to eigenvalues $\lambda_1,\dots,\lambda_n$.  We write $v=\sum_{i=1}^n\alpha_i v_i$, with $\|v\|^2=\|\sum_{i=1}^n\alpha_i v_i\|^2=\sum_{i=1}^n \alpha_i^2=1$.
We know that $\|Tv-\lambda v\|^2<\varepsilon^2$. Expanding, we have: $$\|Tv-\lambda v\|^2=\|T(\sum_{i=1}^n\alpha_i v_i)-\lambda(\sum_{i=1}^n\alpha_i v_i)\|^2=\|\sum_{i=1}^n\alpha_i\lambda_i v_i-\lambda(\sum_{i=1}^n\alpha_i v_i)\|^2=\|\sum_{i=1}^n\alpha_i(\lambda_i-\lambda) v_i\|^2$$ Since $\{v_1,\dots,v_n\}$ is an orthonormal basis, we can rewrite:$$\|\sum_{i=1}^n\alpha_i(\lambda_i-\lambda) v_i\|^2=\sum_{i=1}^n\alpha_i^2|\lambda-\lambda_i|^2<\varepsilon ^2$$
Let $\lambda'$ be the eigenvalue for which $|\lambda-\lambda_i|^2$ is minimized. Than: $$|\lambda-\lambda'|=|\lambda-\lambda'|\sum_{i=1}^n\alpha_i^2\leq\sum_{i=1}^n\alpha_i^2|\lambda-\lambda_i|^2<\varepsilon ^2$$
And the conclusion follows.
Answer: You can assume that $T$ is diagonal, that is $T= \operatorname{diag} ( \lambda_1,...,\lambda_n)$.
Then $\sum_k |\lambda - \lambda_k|^2 v_k^2 < \epsilon^2$. If $|\lambda - \lambda_k| \ge \epsilon$ for all $k$ then we would have
$\sum_k |\lambda - \lambda_k|^2 v_k^2 \ge \epsilon^2$, a contradiction.
Addendum:
Since $T$ is self adjoint we can choose a basis of orthonormal vectors $u_1,...,u_n$ corresponding to eigenvalues $\lambda_1,...,\lambda_n$. If we let $U = \begin{bmatrix} u_1 & \cdots & u_n \end{bmatrix}$ we see that $T U = U \operatorname{diag} ( \lambda_1,...,\lambda_n)$ and so
$U^* TU = \operatorname{diag} ( \lambda_1,...,\lambda_n)$.
Since $U$ is unitary, $\|T v - \lambda v\| = \|   \operatorname{diag} ( \lambda_1,...,\lambda_n) U^* v - \lambda U^*v\|$, or letting $v' = U^* v$ (noting that $\|v'\| = \|v\|$) we have  $\| \operatorname{diag} ( \lambda_1,...,\lambda_n) v' - \lambda v'\| <\epsilon$.
Comment: Why can we assume $T$ is diagonal?
Comment: Because it is self adjoint.


Adding exponents differ with decimals

Question: Could someone explain to me why these two differ in value. Is it because of rounding and that it's a decimal number?
$(1.000218475^{23}- 1)*42731.41 + (1.000218475^{9}- 1)*42731.41 $
    = 299.33
$(1.000218475^{32}- 1)*42731.41 $
    = 299.75
Not sure what to tag, sorry.
Answer: You seem to expect that $a^b + a^c$ equals $a^{b+c}$. In general, it does not.
For example, $1^2 + 1^3 = 1+1=2$, but $1^{2+3}=1^5=1$.
Comment: Ahh yes you are correct, a^b*a^c = a^(b+c)
Comment: @user3276954: Indeed

Adding exponents differ with decimals


call 64-bit exe and 32-bit exe as a single file

Question: How can I call a 64-bit exe from a 32-bit exe in windows 7?
My requirement is I have created a batch file and have converted into exe using iexpress.
This exe works fine when I converted this exe from a 32-bit pc for a 32-bit pc.
And This exe works fine when I converted this exe from a 64-bit pc for a 64-bit pc.
When I tried to run 64bit from 31bit pc it show error Not valid
But I need to include this both for a single installation and call.
How can I do this ?
Answer: Excuse me, I think there is a misunderstanding here.
I understand that you have both .exe versions of a same program, one for 32-bit and one for 64-bit. However, you want NOT to execute both versions in every computer, but just the appropriate version for the underlaying OS, isn't it?
This way, you must include both .exe files in the installation files, but copy just one in the computer, so you just need to identify the version of the installing computer:
if exist "%SYSTEMDRIVE%\Program Files (x86)" (
   rem The OS is 64 bit
   copy D:\program_v64.exe C:\program.exe
) else (
   rem The OS is 32 bit
   copy D:\program_v32.exe C:\program.exe
)


Existence of tubular neighborhood

Question: Let $X$ be a topological space and $A$ a subset of $X$. My understanding of a tubular neighborhood $N$ of $A$ is that $N$ is an open set containing
$A$ such that $\bar N$ is a manifold with boundary which deformation retracts onto $A$. Is my understanding of tubular neighborhoods correct? and what are the more general conditions we put on $X$ such that a tubular neighborhood exists? i mean by googling i read that when $X$ is a manifold and $A$ is a compact submanifold than such a tubular neighborhood $N$ exists, but what about more general spaces like CW-complexes and so on? Thank you for your help!
Answer: Your understanding is pretty much right, but I would add a few things.
For $N$ to be a tubular neighborhood, it's not enough to require that $N$ is open and its closure is a manifold with boundary (you meant $\bar{N}$, not $\bar{A}$, right?).  You also want it to be nicely imbedded locally into $X$.  Wikipedia and Mathworld both describe this pretty well.
Any tubular neighborhood (not just one) should have the deformation retract property you mention.  It seems conventional to assume that $X$ is a manifold and $A$ is a submanifold, in which case existence is known.  I don't know about more general existence theorems, but there is a similar concept called a "regular neighborhood" of a subcomplex in a piecewise linear manifold.  See, for example, Hempel's book on three-manifolds.

Existence of tubular neighborhood


Problema com arrays no Python 3.6

Question: Eu comecei um pequeno curso sobre deep learning com Python, mas acabei tendo um problema com arrays...
  Eu geralmente pego o código da aula e o modifico bastante antes de criar um original, mas, dessa vez, quando rodei o código estudado, ele deu um erro:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Eu tentei resolver o problema de algumas maneiras, mas não consegui. Eis o código:
import tensorflow as tf
import numpy as np

class LinearRegression:
    def __init__(self):
        self.x_data = np.random.rand(100).astype(np.float32)
        self.y_data = self.x_data * 3 + 2
        self.y_data = np.vectorize(lambda y: y + np.random.normal(loc=0.0,scale=0.1))(self.y_data)
        self.A = tf.Variable(1.0)
        self.B = tf.Variable(0.2)
        self.Y = self.A * self.x_data + self.B
        self.loss = tf.reduce_mean(tf.square(self.Y, self.y_data))
        self.optmizer = tf.train.GradientDescentOptimizer(0.5)
        self.train = self.optmizer.minimize(self.loss)
        self.ini = tf.initialize_all_variables()
        self.sess = tf.Session()
        self.sess.run(self.ini)
        self.train_data = []
        for step in range(0, 100):
            self.ev = self.sess.run([self.train, self.A, self.B])[1:]
            if step % 5 == 0:
                print(step, self.ev)
                self.train_data.append(self.ev)

Line = LinearRegression()

Comment: E qual foi a linha que deu erro?
Comment: Linha 13 :self.loss = tf.reduce_mean(tf.square(self.Y, self.y_data))
Answer: Na linha: tf.square(self.Y, self.y_data) deveria ser: tf.square(self.Y - self.y_data).
Você quer calcular o erro quadrático médio e não passar self.y_data como nome da operação.

Problema com arrays no Python 3.6


Why was $1 \text{ OR } 1$ undefined in Boole's logic?

Question: I read that Boole's original OR function in which 1 or 1 was undefined then it has been modified so that while the formerly undefined case is now defined it is defined to 0(XOR) .
1- why Boole's original OR function in which 1 or 1 was undefined ?
2- why they redefine it ?
Comment: Please can you give a reference for the source that you have been reading (as it's wrong).
Comment: ones and zeros understanding boolean algebra
c.h 4
Answer: What you have read is misrepresenting Boole. See page 57 of Boole's Investigation of the Laws of Thought. Boole used $x + y(1-x)\,$ for inclusive disjunction and $x(1-y) + y(1-x)\,$ for exclusive disjunction. So Boole's definitions give $1 \lor 1 = 1 + 1 \cdot (1 - 1) = 1\,$ and $1 \oplus 1 = 1\cdot 0 + 1\cdot 0 = 0\,$ just as we would expect today.


Powershell running a command from variable

Question: I am trying to run a command that I have stored as a string in a variable, however when I try to run it with "Invoke-Command" I am told it needs to be "ScriptBlock" and not a string.
The command is:
ASIMPORT.EXE -rexactdb-01 -DTEST001 -u -~ I -URL X:\test.xml -Tglentries -OPT18 –Oauto

I am trying to run it as:
Invoke-Command -ScriptBlock $command

Tried with and without "ScriptBlock", always get the same error. Googling it, I honestly do not understand how should I approach the solution, so any advice is appreciated.
Answer: Instead of Invoke-Command, you need Invoke-Expression:
$command = 'svn help patch'
Invoke-expression $command

See cmdlet description:

The Invoke-Expression cmdlet evaluates or runs a specified string as a
  command and returns the results of the expression or command. Without
  Invoke-Expression, a string submitted at the command line would be
  returned (echoed) unchanged.
Comment: This is the most useful answer, since Invoke-Command does not allow any results to be returned from the command.
Answer: Define your variable as a scriptblock.
Like that:
$ScriptBlock = [ScriptBlock]::Create("get-process")

Invoke-Command -ScriptBlock $ScriptBlock

Answer: Try Below
Invoke-Command -ScriptBlock {&$command}


PHP - Get REAL ipaddress

Question: This is the function I use to get the client ip:
function get_client_ip_server() {
$ipaddress = '';
if ($_SERVER['HTTP_CLIENT_IP'])
    $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if($_SERVER['HTTP_X_FORWARDED_FOR'])
    $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if($_SERVER['HTTP_X_FORWARDED'])
    $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if($_SERVER['HTTP_FORWARDED_FOR'])
    $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if($_SERVER['HTTP_FORWARDED'])
    $ipaddress = $_SERVER['HTTP_FORWARDED'];
else if($_SERVER['REMOTE_ADDR'])
    $ipaddress = $_SERVER['REMOTE_ADDR'];
else
    $ipaddress = 'UNKNOWN';

return $ipaddress;
}

The only problem is that I get a error in PHP:
Notice: Undefined index: HTTP_CLIENT_IP
And in the other variables too. Question: How should I fix this and WHY does it work for others?
Comment: it depends on the server and how you have it setup. to be on the safe side put HTTP_ vars in variables and do checks with !empty.
Answer: Use isset on all the checks.
function get_client_ip_server() {
$ipaddress = '';
if (isset($_SERVER['HTTP_CLIENT_IP']))
    $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
    $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_X_FORWARDED']))
    $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
    $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_FORWARDED']))
    $ipaddress = $_SERVER['HTTP_FORWARDED'];
else if(isset($_SERVER['REMOTE_ADDR']))
    $ipaddress = $_SERVER['REMOTE_ADDR'];
else
    $ipaddress = 'UNKNOWN';

return $ipaddress;
}

Answer: try this
 $ipaddress = '';
      if (getenv('HTTP_CLIENT_IP'))
            $ipaddress =getenv('HTTP_CLIENT_IP');
        else if(getenv('HTTP_X_FORWARDED_FOR'))
            $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
        else if(getenv('HTTP_X_FORWARDED'))
            $ipaddress = getenv('HTTP_X_FORWARDED');
        else if(getenv('HTTP_FORWARDED_FOR'))
            $ipaddress = getenv('HTTP_FORWARDED_FOR');
        else if(getenv('HTTP_FORWARDED'))
            $ipaddress = getenv('HTTP_FORWARDED');
        else if(getenv('REMOTE_ADDR'))
            $ipaddress = getenv('REMOTE_ADDR');
        else
            $ipaddress = 'UNKNOWN';
        return $ipaddress;

Answer: try this
$http_client_ip = $_SERVER['HTTP_CLIENT_IP'];

if (!empty($http_client_ip)) {
$ip_address = $http_client_ip;

Answer: Or you can use '@' to stop the warning/error if it's unset or null, for example:
if (@$_SERVER['HTTP_CLIENT_IP'] != '')
    $ipaddress = $_SERVER['HTTP_CLIENT_IP'];

PHP - Get REAL ipaddress


Something is spamming from my hMail server - how can I deal with this?

Question: My Windows 2008 server is attempting to send out a lot of spam, I've just discovered, and I'm not sure how to see where the compromise is. For example: has someone hacked an account? Has someone hacked the server? Is there a virus on the server?
What can I do to investigate this?
Edit
Thanks for the replies so far. I am running hMail server, and have spent so long investigating the correct configuration but still I end up with these emails being sent.
Here is a screenshot of my Internet IP range settings on the server:
(let me know what else I can provide to help)
Comment: why you haven't checked "External to local e-mail addresses" in smtp authentication?
Comment: I would see also "incoming relays" and "logging" screenshots
Answer: Whatever logging you can enable, enable. Then use simple statistical analysis on the logs (eg if you have a linux/unix box available and know basic sed/perl/awk, pry out all the originating IPs submitting mail and |sort|uniq -c them then treat that list with geoip-lookup... as politically incorrect as it sounds, the ips causing massive traffic from locations that completely defy the geological structure of your company ecosystem usually ARE what you need to further investigate.
Answer: what happened to your server not necessarily depends by a virus in it. Probably you only need to setup your smtp server to not accept incoming request to send email. In this way you can use it only locally. If you use the default IIS smtp server, go to control panel and then admin tools. Find Internet Information Services Manager and select smtp server. Click on Properties and, in Access tab, click on Connection control. Here you have to add your ip address and choose "Only the list below" to grant your ips. Do the same clicking Relay restrictions in the same Access tab.
I use win 2003 server, but I suppose it'll be quite the same.
Hope it serves...
Answer: If the server is actually a mail server, running exchange or some other mail product, then you really need to look at what the best practices are to restricting mail relaying.  If it is a mail server then I'd recommend looking into how to restrict the # of recipients in a single message. I've set it as low as 5 while troubleshooting. This will usually let you troubleshoot your issue and not annoy your legit end users.  If its not a mail server then just hop into your router and block outbound port 25 from the infected server and then start figuring out if its a hack or a virus.
If you can give us some more detail on the server we can probably tailor the answers a bit.
Comment: Thanks a lot - I've updated my question with some more details
Comment: Well, not really familiar with your setup. Do you have any logs showing the smtp traffic?
Comment: Something to consider, do you have a authentication required setting? If so and its not on you should consider turning it on.


Find the fourth missing coordinate of a square in a Cartesian plane.

Question: Question: Plot the points $P(5, 1)$, $Q(0, 6)$, and $R(-1, 1)$ on a coordinate plane. Where must the point $S$ be located so that the quadrilateral $PQRS$ is a square? Find the area of this square.
My try at it: Finding the area is easy. We can determine the distance $PQ$ between $P$ & $Q$ and then multiply it by itself. However, how do we find the point $S$?
The solution given in the website:

I think that the person has just figured out the point from the diagram and not by using some Math (though, technically he did use Math to draw the figure and everything, but I am referring to something like a formula). I have the following questions:
1) Is there a way to figure out the unknown point $S$ using some formula?
2) If yes, can we do it by knowing only the distance formula and the mid-point formula?
3) Regardless of the answer to the above question; is there a more difficult/advanced way of doing it?
My try at the questions:
1) I thought of using the distance formula but that cancelled everything and didn't give me the coordinates.
2) I think that the diagonals of a square meet at the same point. Using this fact, we can calculate the mid-point of $RP$, say $(x1, y1)$ and then (taking $(x, y)$ to be the coordinates of the point $S$), use $(\frac{(x - 0)}{2}, \frac{(y - 6)}{2}) = (x1, y1)$. Does this make sense?
3) I feel like there's always a more advanced way, maybe you can shed some light on it?
P.S. I found something weird. By calculating $(x + 5, y -1) = (5 - 0, 1 - 6)$ (I subtracted the coordinates of $S$ and $R$ on the $LHS$ and of $P$ & $Q$ on the $RHS$), I am getting the correct answer! Am I going anywhere with this?
Comment: Consider the lines parallel to $PQ$ passing through $R$ and $QR$ passing through $P$. What do you think the point of intersection is ?
Comment: $S$? How does this help me again?
Comment: Yes.Are you asking for formula?
Comment: I think so because if I use the distance formula, I'll get $(x - 5)^2 + (y - 1)^2 = (x + 5)^2 + (y - 1)^2$ which gives $x = 0$...Wait, is this the correct way of doing it?
Comment: Because now that I see it, *I am* getting the *correct* value of $x$ using the distance formula. Maybe if I use point $Q$, I'll get the value of $y$.
Comment: Do you know how to write an equation of a line given two points?
Comment: Yeah. $(x2 - x1, y2 - y1)$ That is what I mentioned in the `P.S.` line. Am I allowed to use the line formula to figure out the coordinates?
Comment: Yes. Of course, Line formula will be easier too
Comment: @Mambo Though, why does this really work?
Answer: $$
RS\parallel QP \quad \wedge\quad  RS= QP\quad \text{(property of square)}\\
\begin{align*}
\implies \vec{RS} &= \vec{QP}\\
\vec{OS} &= \vec{OR}+\vec{RS}\\
&= \vec{OR} + \vec{QP}\\
&= (-5,1) + (5-0,1-6)\\
&= (0,-4)
\end{align*}$$
which is the reason behind the weird method you are mentioning.
Comment: Will it apply to all quadrilaterals?
Comment: At least in which opposite sides are equal?
Comment: @user331377 I am using the fact that opposite sides of the quadrilateral are parallel and of the same length, so this works for parallelograms and rhombi generally.
Comment: Okay, got it. Thanks! Though (and I am satisfied, still), any other proof? Maybe something that doesn't involve vectors?
Comment: So, is this solution given here (it's to a different problem): http://www.slader.com/textbook/9780840068132-algebra-and-trigonometry-3rd-edition/132/exercises/63/ incorrect?
Comment: Is $PQSR$ a parallelogram, or is $PQRS$ a parallelogram?
Comment: What's the difference?
Comment: @user331377 The difference is which of $QS$ or $QR$ is directly connected as a side of your parallelogram.
Comment: In that problem I just gave: $QS$. The diagram is given in the solution itself.
Comment: $\vec{OR}=(-1,1)$, not $(-5,1)$.
Comment: @mathlove Yes $(-1,1)$ is the coordinate given on the first line, and $(-5,1)$ is the one given in the image. And the first pair of coordinates does not form a square with $P$ and $Q$.
Comment: @peterwhy : Oh, I see. Thanks.
Answer: 1) Systematically use the distance formula with each of the co-ordinates $ P,Q $ and $R$.
2) If you are using mid-point formula, then it should be $\left(\frac{x+0}{2},\frac{y+6}{2}\right) = \left(\frac{-5+5}{2},\frac{1+1}{2}\right) = (0,1).$
Comment: I'm using the line formula as mentioned in the `P.S.` line and also in your comment. I was wondering, why does that really work? Because both the lines are parallel and of the same length? Does it apply to all parallel lines which are of the same length?
Comment: Can you please mention what line formula are you using?
Comment: Wait, I think I get it. Since both the lines are parallel, their slopes will be the same too and using that fact, we can use $\frac{y1}{x1} = \frac{y2}{x2}$, correct? I am using the formula using where if you're given two coordinates, say, $(x1, y1)$ & $(x2, y2)$. You can find out their slopes using $\frac{(y2 - y1)}{(x2 - x1)}$ and since the slopes of two parallel lines is the same, we get the correct solution, am I right?
Comment: That is not enough. Because there are infinitely  many points which will give you the same slope. You should write the line equations and find the point of intersection as mentioned above in the comments. Then it uniquely fixes $S$.
Comment: All right, thank you!
Answer: I don't mean to be critical, but a lot of the above is very over-complicated. Here is the easy and quick way to do this: take advantage of the fact that the relative spacings of the PAIRS of corners in any parallelogram are the same. I.e., whatever you do to get from the top left corner to get to the bottom left corner, do that same move to get from the top RIGHT corner to the bottom RIGHT corner, etc. You can literally do it in seconds, with no formulas. For instance, let's say I have these three corners: (0,3)   (6, 1), and (5, -2). When you draw this up on a graph, it is obvious that to get from (6, 1), to (5, -2),  you just do "down 3 and left 1". Do the same thing from (0, 3) and you get (-1,0). Done. No need for slopes, intersections, formulas, etc.


JPQL : multiple join. How to do my namedquery?

Question: Here's a quick diagram of my database.
http://img17.imageshack.us/img17/2474/mpd.png
In this scheme, I created JPA entities (for all tables with a red square).
I would like to create a JPQL query to get all aircraft that have references, references defined by a reference type given by parameter.
I tried :
    SELECT DISTINCT a FROM Aircraft a JOIN FETCH a.references r WHERE EXISTS (SELECT ref FROM Reference ref WHERE ref = r AND ref.referenceType.id = :id)
But i have an error cause Eclipse doesnt like the alias in JOIN FETCH a.references *r* and the request doesnt work in JUnit test.
Here my entities without getter/setter :
Aircraft
@Entity
@Table(name = "T_R_AIRCRAFT_AIR", uniqueConstraints = @UniqueConstraint(columnNames = "AIR_NAME"))
public class Aircraft implements java.io.Serializable {

    @Id
    @Column(name = "AIR_ID", unique = true, nullable = false)
    @TableGenerator(name="aircraftSeqStore",
        table="T_S_APP_SEQ_STORE_AST",
        pkColumnName="AST_SEQ_NAME",
        valueColumnName = "AST_SEQ_VALUE",
        pkColumnValue = "T_R_AIRCRAFT_AIR.AIR_ID",
        allocationSize=1)
    @GeneratedValue(strategy=GenerationType.TABLE,
        generator="aircraftSeqStore")
    private Integer id;

    @Column(name = "AIR_NAME", unique = true, nullable = false, length = 50)
    private String name;

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "T_J_REF_AIR_RFA",
               joinColumns = { @JoinColumn(name = "RFA_AIR_ID", nullable = false, updatable = false) },
               inverseJoinColumns = { @JoinColumn(name = "RFA_REF_ID", nullable = false, updatable = false) })
    private Set<Reference> references = new HashSet<Reference>(0);

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "T_J_MAN_AIR_MNA",
               joinColumns = { @JoinColumn(name = "MNA_AIR_ID", nullable = false, updatable = false) },
               inverseJoinColumns = { @JoinColumn(name = "MNA_MAN_ID", nullable = false, updatable = false) })
    private Set<Manual> manuals = new HashSet<Manual>(0);

    @OneToMany(fetch = FetchType.LAZY,
               mappedBy = "aircraft",
               cascade = { CascadeType.REMOVE })
    private Set<UserConfig> userConfigs = new HashSet<UserConfig>(0);
}

** Reference **
@Entity
@Table(name = "T_E_REFERENCE_REF",
       uniqueConstraints = @UniqueConstraint(columnNames = "REF_IDENTIFIER"))
public class Reference implements java.io.Serializable {

    @Id
    @Column(name = "REF_ID", unique = true, nullable = false)
    @TableGenerator(name="referenceSeqStore",
        table="T_S_APP_SEQ_STORE_AST",
        pkColumnName="AST_SEQ_NAME",
        valueColumnName = "AST_SEQ_VALUE",
        pkColumnValue = "T_E_REFERENCE_REF.REF_ID",
        allocationSize=1)
    @GeneratedValue(strategy=GenerationType.TABLE, generator="referenceSeqStore")
    private Integer id;

    @Column(name = "REF_IDENTIFIER", unique = true, nullable = false, length = 50)
    private String identifier;

    @Column(name = "REF_LINK")
    private String link;

    @Column(name = "REF_OBSERVATIONS", length = 4000)
    private String observations;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "REF_RFT_ID", nullable = false)
    private ReferenceType referenceType;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "REF_MAN_ID")
    private Manual manual;

    @OneToMany(fetch = FetchType.LAZY,
               mappedBy = "reference",
               cascade = { CascadeType.REMOVE })
    private Set<Translation> translations = new HashSet<Translation>(0);

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "T_J_REF_AIR_RFA",
               joinColumns = { @JoinColumn(name = "RFA_REF_ID", nullable = false, updatable = false) },
               inverseJoinColumns = { @JoinColumn(name = "RFA_AIR_ID", nullable = false, updatable = false) })
    private Set<Aircraft> aircrafts = new HashSet<Aircraft>(0);
}

** ReferenceType **
@Entity
@Table(name = "T_R_REFERENCE_TYPE_RFT",
       uniqueConstraints = @UniqueConstraint(columnNames = "RFT_TYPE"))
public class ReferenceType implements java.io.Serializable {

    @Id
    @Column(name = "RFT_ID", unique = true, nullable = false)
    @TableGenerator(name="referenceTypeSeqStore",
        table="T_S_APP_SEQ_STORE_AST",
        pkColumnName="AST_SEQ_NAME",
        valueColumnName = "AST_SEQ_VALUE",
        pkColumnValue = "T_R_REFERENCE_TYPE_RFT.RFT_ID",
        allocationSize=1)
    @GeneratedValue(strategy=GenerationType.TABLE, generator="referenceTypeSeqStore")
    private Integer id;

    @Column(name = "RFT_TYPE", unique = true, nullable = false, length = 50)
    private String type;

    @OneToMany(fetch = FetchType.LAZY,
               mappedBy = "referenceType",
               cascade = { CascadeType.REMOVE })
    private Set<Reference> references = new HashSet<Reference>(0);

    @OneToMany(fetch = FetchType.LAZY,
               mappedBy = "referenceType",
               cascade = { CascadeType.REMOVE })
    private Set<UserConfig> userConfigs = new HashSet<UserConfig>(0);
}

PS: I forgot to say that a table had been added between Aircraft and Reference. This is the Manual table. But i dont think there is an impact.
PS2: JPA implementation is made by Hibernate.
Any idea how to make the multiple join ?
Thank you !
Comment: How to join an entity which is already a join from one ? i.e how to join A with B with C ? it seems easy to join A with B, and A with C but for others big join i dont succeed.
Answer: You can execute your query much easier as follows:
SELECT DISTINCT a FROM Aircraft a JOIN FETCH a.references r
LEFT JOIN FETCH a.manuals
WHERE r.referenceType.id = :id

I've added join fetch a.manuals since otherwise I got LazyInitializationException. Added LEFT to prevent the absence of manuals to influence on the output.
Comment: Finally, i have a pb with my JUnit test. Too many lazy loading, so many collections are loaded and i have a outofmemory. I have difficulty with JPQL. So i dunno if my JPQL is working or not. Put an alias after a join fetch seems not be accepted by JPA Validator. For moment your answer does not allow me to understand how it works. Is this JPQL could be correct : `SELECT DISTINCT a FROM Aircraft a JOIN FETCH a.references JOIN FETCH a.references.referenceType WHERE a.references.referenceType.id = :id` ? Thank you for your patience.
Comment: No, this query won't work since this path `a.references.referenceType` isn't valid. Think yourself: you reference `referenceType` property of `references` collection which the latter obviously doesn't have.
Comment: I understand that using join fetch was done to "load" the collections configured for the lazy loading?
So is it possible to create a nested query? in SQL, we probably did it first by a query to select all references for a ReferenceType Id, then some joints to get the aircrafts (via the join table).
Comment: In JPQL you should forget about join tables since here you work with @Entities, @ElementCollections, @Embeddabbles and so on. In JPQL you will need joins only when you want to get access to entity through @ManyToMany or @OneToMany association as in the current case. Otherwise, if there was @OneToOne or @ManyToOne association of Aircraft with Reference then you could formulate your query as follows:
`SELECT DISTINCT a FROM Aircraft a LEFT JOIN FETCH a.manuals
WHERE a.reference.referenceType.id = :id`
Comment: Ok. Thank you for these explanations. So, if I sum up, joins are necessary for all `@ManyToMany` & `@OneToMany` associations, but not for `@ManyToOne` & `@OneToOne`....except if there is a lazy loading where we still need to do a join fetch to "load" our entity. That is exact ?
Comment: `@ManyToOne` and `@OneToOne` are eager-loaded by default so unless you specify them as `FetchType.EAGER` you won't need even JOIN FETCH for them. Also, FYI, `@ManyToMany` or `@OneToMany` are lazy-loaded by default.
Comment: Hhhmmm...so i have to change my entities perhaps. After an automatic generation with HibernateTools to create JPA entities, i have some associations like that : `@ManyToOne(fetch = FetchType.LAZY)`.
Comment: I don't understand. Your JPQL seems not to be good. When i run on server, there is an error : Errors in named queries Aircraft.refType.
Comment: 1. Alias seems not be tolarated in a join fetch query. 2. JPQL seems to precognize INNER JOIN FETCH. I didn't totaly resolved the pb. I'm still working on it...
Comment: On my end the query works as it should be, so the issue isn't with query. You can check my implementation of your case here:
https://github.com/bondarenko/so_11950279
Comment: My application crashed on init when there is a verification of named query in each entity. It seemes you used Spring.data. For my part, when i create a named query based on javax.persistence.namedquery in the entity i have some errors detected by Dali, and error in runtime.
Comment: Anyway, i won't multiplicate subjets on JPQL but i still have a question : how to manage `@ManyToMany` associations so ? If we have in the manual table some `@ManyToMany` with aircrafts, how to create a JPQL where we can filter with aircraft ID ? It's very strange to pass from SQL to JPQL :( For my case, i know i can create a JPQL like that `SELECT m FROM Manual INNER JOIN FETCH m.aircrafts` but it's impossible to use aircrafts in where clause with fetch condition. Should we force eager mode for this association, delete fetch, add an alias et add the criteria in where clause ?
Comment: OMG, sorry for the last question. I just realized even if i have some collections loaded in lazy mode, i can realize a request juste with inner join without fetching but using it into the where clause !!! But for alias in join fetch, it seems realy forbidden in JPQL, not HQL.


Changing controls order in row class div bootstrap 3

Question: Well, I'am building a web application that uses twitter bootstrap 3 , and supports both languages English and Arabic with two different  master pages for each,
am using div with class .row to put my controls inside
controls inside rows by default starts from left to right
when I change my website language to Arabic I want to reverse all items inside rows from right to left
am changing the master page with my stylesheet files, I've tried floating and directions but it never works for me for items inside div with .row class
<asp:Panel ID="pnl_TaskContent" runat="server" class="row">
                  <asp:Panel ID="pnl_TaskColumn" runat="server" class="col-md-12">

                                  <%--Task Name--%>

                                      <asp:Label ID="lbl_Task_Name" runat="server" Text="Task Name" Font-Bold="True" Font-Italic="False"></asp:Label>

                                              <asp:RequiredFieldValidator ID="RequiredFieldValidator27" runat="server" ErrorMessage="*"
                                                  ControlToValidate="txt_Task_Name" ForeColor="Red" ValidationGroup="saveTask" Font-Bold="True" Font-Size="Medium"></asp:RequiredFieldValidator>

                                          <asp:TextBox ID="txt_Task_Name" runat="server" ClientIDMode="Static" CssClass="form-control"></asp:TextBox>

                                              <asp:Button ID="button_tf" CssClass="btn btn-default dropdown-toggle" runat="server" Text="Functions" data-toggle="dropdown" ValidationGroup="none" />

                                                      <asp:Button ID="btn_AddTaskFunModal" CssClass="btn btn-default btn-block" runat="server" ValidationGroup="novali" Text="Add/Edit" data-toggle="modal" data-target="#addTaskFunctions-modal" />

                                                      <asp:Button ID="btn_BrowseTaskFunModal" CssClass="btn btn-default btn-block" runat="server" ValidationGroup="novali" Text="Edit" data-toggle="modal" data-target="#BrowseTaskFunctions-modal" />

                                  <%--Task Status--%>

                                      <asp:Label ID="lbl_Task_Status" runat="server" Text="Task Status" Font-Bold="True" Font-Italic="False"></asp:Label>

                                              <asp:RequiredFieldValidator ID="RequiredFieldValidator11" runat="server" ErrorMessage="*"
                                                  ControlToValidate="ddl_Task_Status" ForeColor="Red" ValidationGroup="saveTask" Font-Bold="True" Font-Size="Medium"></asp:RequiredFieldValidator>

                                          <asp:DropDownList ID="ddl_Task_Status" runat="server" ClientIDMode="Static" CssClass="form-control" Enabled="False">
                                              <asp:ListItem Value="N">New</asp:ListItem>
                                              <asp:ListItem Value="A">Active</asp:ListItem>
                                          </asp:DropDownList>

                                  <%--Task Priority--%>

                                      <asp:Label ID="lbl_Task_Proirity" runat="server" Text="Task Priority" Font-Bold="True" Font-Italic="False"></asp:Label>

                                              <asp:RequiredFieldValidator ID="RequiredFieldValidator12" runat="server" ErrorMessage="*"
                                                  ControlToValidate="ddl_Task_Proirity" ForeColor="Red" ValidationGroup="saveTask" Font-Bold="True" Font-Size="Medium"></asp:RequiredFieldValidator>

                                          <asp:DropDownList ID="ddl_Task_Proirity" runat="server" ClientIDMode="Static" CssClass="form-control">
                                              <asp:ListItem Value="H">High</asp:ListItem>
                                              <asp:ListItem Value="M">Medium</asp:ListItem>
                                              <asp:ListItem Value="L">Low</asp:ListItem>
                                          </asp:DropDownList>

                                  <%--Completion Rate--%>

                                      <asp:Label ID="lbl_Task_CompRate" runat="server" Text="Completion Rate" Font-Bold="True" Font-Italic="False"></asp:Label>
                                      <asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="txt_Task_CompRate" ErrorMessage="0-100" Font-Bold="True" ForeColor="Red" MaximumValue="100" MinimumValue="0" SetFocusOnError="True" Type="Integer" ValidationGroup="saveTask"></asp:RangeValidator>

                                              <asp:RequiredFieldValidator ID="RequiredFieldValidator31" runat="server" ErrorMessage="*"
                                                  ControlToValidate="txt_Task_CompRate" ForeColor="Red" Font-Bold="True" Font-Size="Medium" ValidationGroup="saveTask"></asp:RequiredFieldValidator>

                                          <asp:TextBox ID="txt_Task_CompRate" runat="server" ClientIDMode="Static" CssClass="form-control">0</asp:TextBox>
                                                                                %

what i want that when i change the display order to rtl, is to change the controls inside my row

When Direction From Left To Right but controls are not showing as expected
Comment: It would help if you could provide an example on any online code editor.
Comment: @Hashem Qolam i've edited my post
Comment: Amer, please consider posting the HTML output rather than the ASP code. Also please clarify how you make the page direction RTL. Posing the relevant CSS code, if any, would be great.
Answer: Well, you have unusable html in your post, so I can't test this, but last year I contributed to this old repository: https://github.com/carasmo/bootstrap-rtl/blob/master/dist/css/bootstrap-rtl.css
Has some useful code when you change direction. It's 3.1 but some of it still works well. You'll have to pick through it to see what you need to tweek.
Here's an example of the input-group fixes:
DEMO: http://jsbin.com/tipufu/1/edit
Assumes
body {direction:rtl}

CSS for RTL:
.input-group .form-control:first-child,
.input-group-addon:first-child,
.input-group-btn:first-child > .btn,
.input-group-btn:first-child > .dropdown-toggle,
.input-group-btn:last-child > .btn:not(:last-child):not(.dropdown-toggle) {
  border-top-right-radius: 4px;
  border-bottom-right-radius: 4px;
  border-bottom-left-radius: 0;
  border-top-left-radius: 0;
}

.input-group-addon:first-child {
  border-right: 1px solid #cccccc;
  border-left: 0;
}

.input-group .form-control:last-child,
.input-group-addon:last-child,
.input-group-btn:last-child > .btn,
.input-group-btn:last-child > .dropdown-toggle,
.input-group-btn:first-child > .btn:not(:first-child) {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
  border-bottom-left-radius: 4px;
  border-top-left-radius: 4px;
}

.input-group-addon:last-child {
  border-right: 0;
  border-left: 1px solid #cccccc;
}

.input-group-btn:first-child > .btn {
  margin-left: -1px;
}

.input-group-btn:last-child > .btn {
  margin-right: -1px;
}

.input-group-btn > .btn {
  position: relative;
}

.input-group-btn > .btn + .btn {
  margin-right: -4px;
}

.input-group-btn > .btn:hover,
.input-group-btn > .btn:active {
  z-index: 2;
}

SOME HTML

  @
  <input type="text" class="form-control" placeholder="Username">

  <input type="text" class="form-control">
  .00

  $
  <input type="text" class="form-control">
  .00


How can I find out why vim keeps changing my expandtab setting

Question: I use vim. Specifically I am using Janus. I have expandtab set. However, during the course of using vim, for some reason, my expandtab setting gets set to noexpandtab, and my files start to gain hard tabs. I have tried typing :verbose set expandtab? but this does not show me anything (specifically, it shows me that noexpandtab is set, but it doesn't show a file that is responsible for setting it).
So I would like to find out:

Why my expandtab setting might be changing
How I can track down the culprit and prevent it from happening

Thanks
Comment: What does your :verb set expandtab? show?
Comment: It just comes up with 'noexpandtab', i.e. no path to a file where it was set.
Comment: Reset your gvim and try again, first thing: :verb set expandtab? (don't forget the question mark).
Comment: Apart from that what does your :scriptnames show?
Answer: Try this
:verb set expandtab?
:verb set et?
:verb set invexpandtab?

expandtab can really be set in a number of ways :/
Comment: Ok so I have tracked it down to the [align plugin](https://github.com/tsaleh/vim-align/blob/master/autoload/Align.vim#L484). `:verb set expandtab?` showed me - I think perhaps I forgot the question mark when I tried it in the past.
Comment: I had this issue.  The cause was `set binary` in `~/.vimrc` which automatically sets `noexpandtab`.
Comment: Thanks, I will try that. I didn't realise that running those different commands might produce different answers. Also, what does `invexpandtab` do? I couldn't find much on google.
Comment: @jonleighton - Just like any other invcommand, it toggles the state on/off. set invnumber, set invexpandtab, set inv... help invnumber.
Comment: I think I'll try the tabular plugin as an alternative. (in the interim I've just deleted that line but that's quite hacky)
Comment: All these three commands do exactly the same thing. Vim attaches information about where `expandtab` is set to the `expandtab` option, not to a string used to set it.
Answer: I should add that in addition to the above if you tried the following:
:verb set expandtab?
:verb set et?
:verb set invexpandtab?

And you get back with no line number or file:
noexpandtab

It's more than likely that you have the following and need to change the order:
set expandtab

set binary
set noeol

Change to (note the order)
set binary
set noeol

set expandtab

The reason for this is due to set binary command has a few defaults it executes after it runs.  Including the following:
'textwidth'  will be set to 0
'wrapmargin' will be set to 0
'modeline'   will be off
'expandtab'  will be off

I noted DavidWinterbottom called this out in his comment, but that seemed to be the only comment that was hidden by default and this caused me to do a lot more reading that was necessary, so hopefully this post helps another poor soul from wasting countless hours tracking this down.
Answer: VIM settings can either be set in a configuration file, or in a modeline inside the file you're editing. Note that expandtab can be shortened in VIM to et, so be sure to look for that as well.
Possible configuration files I'd look for:

/etc/vim/vimrc and other files in that directory (sometime vimrc.local and such)
$HOME/.vimrc

As for modelines, they are simply configuration options for VIM, located as comments in the file itself. If this only happens with some files but not others, look for comments that look something like:
/* vim: set noet ai tw=75: */

And try to remove them and see if it helps.
Comment: Thanks. Grepping hasn't turned up much. I'm going to try ldigas when I next manage to repro the problem and see if that explains anything.


Article "promoted to front page" also displays all images of featured slideshow

Question: Currently using Shinbun theme and Drupal 7 (based on an existing site, as required for a project) and was struggling to create a slideshow of selected images, which I finally managed on the article pages with Views Slideshow module.

Works fine for all Article pages, using one image as static or more as a slideshow. Unfortunately, when using more as a slideshow and selecting the option "promoted to front page" and "sticky on top", to project the article in the front page, it also displays the images of the articles... And in the case of our slideshow, it shows them all, one under the other.

What I would like to do is, preferably, find a workaround to display only ONE of the slideshow images, OR show none of them.
Any suggestions? Thanks in advance.
Answer: It's not very clear from your question or the accompanying screenshot, but perhaps you are using a different view mode and/or Views display for the Article content type on the front page, and not actually using your slideshow Views display at all in that context. To be sure, I'd need more info:

In what context is the slideshow working? (Sounds to me like it works when you view an Article node)
In what context is the slideshow not working? (Sounds to me like this happens when an Article is displayed in a Views Block display on the homepage)

If this is the case, then you're not using Views Slideshow to display the article in this context, and you may also be using a different view mode (i.e., Teaser) to display the Article on the homepage.
Comment: Thank you for your answer! I am fairly new to drupal, I usually do things more manually, so my experience with this is very limited. The slideshow feature I used was based on [this tutorial](https://youtu.be/sXh8Ng9QNaA). What I can use is very limited as well (strictly on a drupal 7 theme). The slideshow worked as displayed in the article page, but not the other content types. The problem is that, as I have inserted a number of images to be in the slideshow, they all appear as pictured in the front page. So I would like to opt out of the images for this article, or select to show only one.


How to import tsfel module without raise error?

Question: I use the tsfel package to extract features from signals. I try to implement a personalized feature and I have read the documentation (https://tsfel.readthedocs.io/en/latest/descriptions/personal.html). I have followed the steps exactly but when i try to run the second step (i.e. Add the new feature to features.json) it raises an error ModuleNotFoundError: No module named 'tsfel.features_utils'.
Here is a simple example of code
import numpy as np
# from tsfel.add_personal_features import add_feature_json

@set_domain("domain", "statistical")
def range(signal):
    range = np.max(signal) - np.min(signal)
    return range

The error is: ModuleNotFoundError: No module named 'tsfel.features_utils'
How should I import the module?
Comment: Did you # your line2 import on purpose ?
Comment: is tsfel correctly installed? What version of tsfel are you using?
Comment: @LSeu yes i did it on purpose. Of course my code wouldn't get there because of error.
Comment: @apoorvakamath I think so. I just followed the instructions and used 'pip install tsfel'. The version is tsfel 1.0.4.
Answer: For the version 0.1.6, you may do as follows
from tsfel.feature_extraction.features_utils import set_domain

You can also confirm it from the github


How to deal with an $xy\le 1$ constraint?

Question: I have to solve the following optimization problem:
$$
\begin{align*}
\min_{x,y} &\{-x-y\} \\
\text{such that} \\
y &\ge 3 \\
y &\le 30 \\
x &\ge 0 \\
xy &\le 1 \\
\end{align*}
$$
I want to use a second order cone programming (SOCP) solver because the rest of my problem (not shown here) can be formulated as a second order cone program. However, my problem is the $xy\le 1$ hyperbolic constraint that has the inequality "the wrong way" to be written as a second order cone. It would be great if you could show me for this toy problem how one might deal with the $xy\le 1$ constraint. Thanks a lot!
Comment: $0\le x\le\frac{1}{y}$ and $y\ge 3$ imply $0\le x\le\frac{1}{3}$. So we clearly minimise by taking $y=30,x=\frac{1}{30}$.
Comment: Yeah, but my question is how to reformulate it for a computer convex solver to solve, not by hand. This is an example problem of a much more complicated problem that I'm dealing with.
Comment: I would say that it is not possible to formulate your problem as a convex optimization problem.
Comment: @gerw is correct. It's not convex.
Comment: @MichaelGrant I've not gone over the theory of convex optimization. Is it generally true that if a constraint is non-convex, then it is impossible to make it convex? Perhaps there are techniques to convexify this constraint?
Comment: No. With very few exceptions, you can't take a non-convex constraint and make it convex. You must apply nonconvex techniques here.
Answer: The constraint $xy\le1$ is non-convex, so the problem cannot be solved as stated using SOCP techniques.