Authorization bearer soap request

Question: I need to somehow include in my soap service envelope a header whose values are "Authorization" and "Bearer xXsomeCode123xX", this is the part of the code I need to edit with the new header, which then returns me an xml document with some data requested through the soap web service.
            //SERVICE
            Service service = new Service();
            Call call = (Call) service.createCall();
            call.setTargetEndpointAddress(new java.net.URL(endPointURL));
            call.setSOAPActionURI(soapActionURI);

            //INVOKE
            SOAPEnvelope response = (SOAPEnvelope) call.invoke(new Message(soap.asXML()));
            Document doc = new DOMReader().read(response.getAsDocument());
            return doc;

This is what i see in SoapUI (and works with the header set like that)

I know the question is confusing, and I am, I've researched on the internet but almost every header is made of username:password fields, while i only have this "Authorization" to work on
Answer: If you are using WebServiceTemplate you can do the method marshalSendAndReceive with a WebServiceMessageCallback , in these callback you can add RequestHeader in that you can put the Authorization and bearer + token, your method doWithMessage must looks like as bellow:
public void doWithMessage(WebServiceMessage webServiceMessage) throws IOException, TransformerException {
                    TransportContext context = TransportContextHolder.getTransportContext();
                    HeadersAwareSenderWebServiceConnection connection = (HeadersAwareSenderWebServiceConnection) context.getConnection();
                    connection.addRequestHeader("Authorization", String.format("Bearer %s", "********"));

                }

More info in this link
Answer: To add bearer authorization header in SoapUI you have to:
(keep in mind that Bearer token belongs to OAuth2)

click on "Auth" button in the left bottom corner of the request's window
using "Authorization" dropdown, select Add new Authorization.
then - Type -> OAuth2, press OK. you'll see a input field named
Access Token. Just insert you token in it.

Running your request, on http log you'll see something like that:
:DEBUG:>> "Authorization: Bearer .... [\r][\n]"
Comment: In SoapUI, I execute the authenticate request, which gives me a bearer token.  Great.  Now I copy & paste (carefully, to get the entire thing), into the Auth / OAUTH2 portion of my data request, and click the Play button.  But it doesn't hit my code breakpoint, nor does it show any results.  Instead, I get error 401, Bearer error="invalid_token".  I for sure used the right token.  Any ideas or screen shots to help out?
Comment: I should add that I also obtained a bearer token via CURL, and submitted my data request, and I get an empty response via CURL.  Again, no breakpoint hit in the code.  What are the possible issues?
Comment: If I take off the Authorize requirement on the endpoint, then it executes, hits the breakpoint, and returns data.

Authorization bearer soap request


MySQL table creating error

Question: I wanted to create a Date table (Data in portuguese), I had the "unique" attribute in front of dia (day), mes (month) and ano (year), but I decided to remove them, since it makes no sense, because there can be a lot of days "25" and a lot of "januarys" in the table, but as I removed the "unique" attribute I got the following errors

ERROR 1005 (HY000): Can't create table 'ist169515.Disponivel' (errno: 150)
  ERROR 1005 (HY000): Can't create table 'ist169515.Venda' (errno: 150)
  Query OK, 0 rows affected (0.07 sec)
  ERROR 1005 (HY000): Can't create table 'ist169515.Encomenda' (errno: 150)
  ERROR 1005 (HY000): Can't create table 'ist169515.RegistoEnc' (errno: 150)

The full code is the following:
<code>create table Alimento
    (nomeA varchar(80) not null unique,
    vegetariano boolean not null,
    PRIMARY KEY(nomeA));

create table Simples
        (nomeA varchar(80) not null,
    calgramas numeric(5,2) not null,
    tipo varchar(255) not null,
    PRIMARY KEY(nomeA),
    FOREIGN KEY(nomeA) REFERENCES Alimento(nomeA));

create table Agregado
        (nomeA varchar(80) not null,
    calorias numeric(5,2) not null,
    PRIMARY KEY(nomeA),
    FOREIGN KEY(nomeA) REFERENCES Alimento(nomeA));

create table Composto
    (nomeAgg varchar(80) not null unique,
    nomeS varchar (80) not null unique,
    quantidade numeric(4),
    PRIMARY KEY(nomeAgg, nomeS),
    FOREIGN KEY(nomeAgg) REFERENCES Agregado(nomeA),
    FOREIGN KEY(nomeS) REFERENCES Simples(nomeA));

create table Prato
    (nomeA varchar(80) not null,
     preco numeric(5,2) not null,
     PRIMARY KEY(nomeA),
     FOREIGN KEY(nomeA) REFERENCES Alimento(nomeA));

create table Restaurante
     (nomeR varchar(80) not null unique,
      PRIMARY KEY(nomeR));

create table Data
     (dia numeric(2) not null,
     mes varchar(45) not null,
     ano numeric(4) not null,
     PRIMARY KEY(dia, mes, ano));

create table Disponivel
     (nomeA varchar(80) not null,
     nomeR varchar(80) not null,
     dia numeric(2) not null,
     mes varchar(45) not null,
     ano numeric(4) not null,
     PRIMARY KEY(nomeA, nomeR, dia, mes, ano),
     FOREIGN KEY(nomeA) REFERENCES Prato(nomeA),
     FOREIGN KEY(nomeR) REFERENCES Restaurante(nomeR),
     FOREIGN KEY(dia) REFERENCES Data(dia),
     FOREIGN KEY(mes) REFERENCES Data(mes),
     FOREIGN KEY(ano) REFERENCES Data(ano));

create table Venda
     (nomeA varchar(80) not null,
     dia numeric(2) not null,
     mes varchar(45) not null,
     ano numeric(4) not null,
     nomeR varchar(80) not null,
     num numeric(5) not null,
     PRIMARY KEY(nomeA, dia, mes, ano, nomeR),
     FOREIGN KEY(nomeA) REFERENCES Prato(nomeA),
     FOREIGN KEY(dia) REFERENCES Data(dia),
     FOREIGN KEY(mes) REFERENCES Data(mes),
     FOREIGN KEY(ano) REFERENCES Data(ano),
     FOREIGN KEY(nomeR) REFERENCES Restaurante(nomeR));

 create table Cliente
     (email varchar(255) not null unique,
     PRIMARY KEY Cliente(email));

 create table Encomenda
     (email varchar(255) not null,
     nEnc numeric(5) not null unique,
     precoTotal numeric(5,2) not null,
     desconto double(20,2) not null,
     nomeR varchar(80) not null,
     dia numeric(2) not null,
     mes varchar(45) not null,
     ano numeric(4) not null,
     PRIMARY KEY(email, nEnc),
     FOREIGN KEY(email) REFERENCES Cliente(email),
     FOREIGN KEY(nomeR) REFERENCES Restaurante(nomeR),
     FOREIGN KEY(dia) REFERENCES Data(dia),
     FOREIGN KEY(mes) REFERENCES Data(mes),
     FOREIGN KEY(ano) REFERENCES Data(ano));

  create table RegistoEnc
     (email varchar(255) not null,
     nEnc numeric(5) not null,
     nomeA varchar(80) not null,
     PRIMARY KEY(email, nEnc, nomeA),
     FOREIGN KEY(email) REFERENCES Encomenda(email),
     FOREIGN KEY(nEnc) REFERENCES Encomenda(nEnc),
     FOREIGN KEY(nomeA) REFERENCES Prato(nomeA));
</code>
Comment: Do the tables `Prato` and `Restaurante` exist?
Comment: yes they do, I just refered the tables that are giving trouble, will put the complete code
Comment: http://stackoverflow.com/questions/1457305/mysql-creating-tables-with-foreign-keys-giving-errno-150
Answer: EDIT:
<code> FOREIGN KEY(dia, mes, ano) REFERENCES Data(dia, mes, ano)
</code>
instead of
<code> FOREIGN KEY(dia) REFERENCES Data(dia),
 FOREIGN KEY(mes) REFERENCES Data(mes),
 FOREIGN KEY(ano) REFERENCES Data(ano),
</code>
Comment: No, I dropped the old database created a new one just to be sure and it's giving me that error
Comment: It was the foreign key was not representing the same same thing as primary key. The combination of the 3 (dia, mes, ano) is the primary key, you were stating them separately. Cheers!

MySQL table creating error


Can you always decrease the variance by removing outliers?

Question: Consider a finite set of real numbers. Let its variance be $V$. Let the highest number be $h$ and the lowest number be $l$, and let's assume $l < h$.
Let  $x$ be an arbitrary number with $l < x < h$.
Now create a new set by removing one element equal to $h$ and replacing it with $x$. Call the variance of this new set $V_h$.
Also create a new set by removing one element equal to $l$ and replacing it with $x$. Call the variance of this new set $V_l$.
Is it true (and is there a proof!) of the statement: "either $V_l < V$ or $V_h < V$"?
To show that both are not always true, consider the set ${0,0,0,1}$ and replace one of the $0$'s with $0.9$. The variance goes up.
Answer: Call your data set $\{x_k\}_{k=1}^N$. Let's call the mean $\mu=\frac{1}{N}\sum x_k$, and write the variance $V=\sum (x_k-\mu)^2$.
Since we assume $l=\min x_k<h=\max x_k$, take $x_{\min}=l,x_\max=h$ and proceed by cases:
Pick $\epsilon>0$ small enough so that $x=x_\min+\epsilon\leq\mu$ (or, equivalently, $\epsilon\leq \frac{h-l}{2}$). Then obviously $$x_\min+\epsilon-\mu<x_\min-\mu\Longrightarrow(x_\min+\epsilon-\mu)^2<(x_\min-\mu)^2\Longrightarrow V_l<V.$$
Now by considering the case that $h>x=x_\min+\epsilon\geq\mu$, we may simply rewrite $x=x_\max-\tilde{\epsilon}$ where now $\tilde{\epsilon}=h-l-\epsilon\leq\frac{h-l}{2}$, and a similar line of reasoning as above will yield $V_h<V$.
Comment: This assumes you can pick `x`. I said "let `x` be an arbitrary number".
Answer: I think I may have found the proof.
Number the points $p_1,p_2,...,p_N$ from lowest to highest.
Replace one of the extreme points, $p_E$ where $E \in \{1,N\}$, by some $x$ with $p_1<x<p_N$. Call the new set ${q_1,...,q_N}$.
Now
$$
Var(q) = \frac{1}{N} \sum (q_i - \bar{q})^2
\le \frac{1}{N} \sum (q_i - \bar{p})^2
$$
since the variance is minimized around the mean.
So, we want to prove that
$$
\sum (q_i - \bar{p})^2 < Var(p)
$$
i.e. that
$$
\sum (q_i - \bar{p})^2 < \sum (p_i - \bar{p})^2.
$$
This reduces to
$$
(x-\bar{p})^2 < (p_E - \bar{p})^2
$$
since the sets only differ in one element.
Now choose $E$ so that $x-\bar{p}$ has the same sign as $p_E - \bar{p}$. As $p_E$ was an extreme point, we know that the above inequality holds.


Backing track chords Eb saxophone

Question: How to transpose the chords from this backing track from guitar to saxophone?

I tried the chords from the video, but they do not fit the alto sax. Do I just have to transpose them from guitar (C) to alto sax (Eb) by moving up by a minor third?
PS: I'm new to music theory
Answer: Other way. Alto sax being in E♭ means that a concert E♭ is written as C. So a concert C is written as A, and you need to move everything down a minor third.
My trick for remembering which way to go is to think about moving your instrument's key to the target key, and move the notes the same amount in the same direction. Think, "I'm in E♭, and need to go to C, so I go down a minor third." Another example, if you're reading off of a French horn part (in F): "I'm in E♭, and need to go to F, so I go up a whole step."
Comment: Or you could pretend the treble clef is actually bass clef and adjust accidentals like crazy :-)  . No, I don't actually recommend this!
Comment: So for CM7, which is C-Eb-G-Bb I go down a minor third resulting in A-C-E-G for the first chord. Is this correct?
Comment: Correct. But rather than move every note, I would suggest simply moving Cm7->Am7 and knowing that Am7 is ACEG.
Comment: @CarlWitthoft again, wrong way. If the music is already in bass clef then you can just read it directly as treble clef + 3 sharps. This works perfectly fine as long as there are no accidentals.
Comment: @MattPutnam  correct for reading bass clef.   I'm an old hand at transpositions -- it's really fun on clarinet, where Bb  to Eb or the reverse involves thinking of the upper and lower registers being reversed!
Answer: If it's a jam track, then that's the key it's in. Those are the chords the guitar plays, and the (alto) sax, in Eb, will have to do the transposing. It will be using notes basically from the Am scale if it was written for the sax to play. But it isn't written down, as it's for jamming to.
I suppose you could go the other way, so the sax was playing in Cm, in which case, the first chord on guitar would be Ebm. But then you couldn't use the backing track to play along to!
Comment: A reason for the downvote would be appreciated. That way, we all learn more.

Backing track chords Eb saxophone


Ruby backslash to continue string on a new line?

Question: I'm reviewing a line of Ruby code in a pull request. I'm not sure if this is a bug or a feature that I haven't seen before:
puts "A string of Ruby that"\
  "continues on the next line"

Is the backslash a valid character to concatenate these strings? Or is this a bug?
Comment: It would also be good to see a link to documentation of this feature.  Is the backslash a keyword? Operator?
Answer: That is valid code.
The backslash is a line continuation. Your code has two quoted runs of text; the runs appear like two strings, but are really just one string because Ruby concatenates whitespace-separated runs.
Example of three quoted runs of text that are really just one string:
"a" "b" "c"
=> "abc"

Example of three quoted runs of text that are really just one string, using \ line continuations:
"a" \
"b" \
"c"
=> "abc"

Example of three strings, using + line continuations and also concatenations:
"a" +
"b" +
"c"
=> "abc"

Other line continuation details: "Ruby interprets semicolons and newline characters as the ending of a statement. However, if Ruby encounters operators, such as +, -, or backslash at the end of a line, they indicate the continuation of a statement." - Ruby Quick Guide
Comment: Crazy. "If Ruby encounters operators, such as +, -, or backslash at the end of a line, they indicate the continuation of a statement." http://www.tutorialspoint.com/ruby/ruby_quick_guide.htm
Comment: **Caution:** `+` continues the **statement** but not the **string**.
`puts "foo"+"bar".upcase` gives you `fooBAR`, whereas `puts ("foo"+"bar").upcase` gives you `FOOBAR`.  (Whether or not there's a newline after the `+`.)

**But:**  if you use a backslash instead of the plus sign, it will _always_ give you `FOOBAR`, because combining lines into one statement, and then combining successive strings into one string, happen before the string method gets called.  This sort of thing might happen when you try to print strings in color, using e.g., `.red` at the end of the string :-)
Comment: I think you mean `\` line continuation
Comment: It's a little confusing to say that +, - and backslash indicate the continuation of a statement, because backslash *only* indicates the continuation of a statement, whereas + and - continue the statement *and* perform their normal operation. In other words, the backslash gets "removed", but the + and - don't. It makes more sense to say that + and - are operators that work across multiple lines (as do other things in ruby). Backslashes are different. For example, putting backlslashes between two strings on one line causes a syntax error.
Answer: The backslash character does not concatenate any strings. It prevents the line-break from meaning that those two lines are different statements. Think of the backslash as the opposite of the semicolon. The semicolon lets two statements occupy one line; the backslash lets one statement occupy two lines.
What you are not realizing is that a string literal can be written as multiple successive literals. This is legal Ruby:
s = "A string of Ruby that" "continues on the same line"
puts s

Since that is legal, it is legal to put a line break between the two string literals - but then you need the backslash, the line-continuation character, to tell Ruby that these are in fact the same statement, spread over two lines.
s = "A string of Ruby that" \
"continues on the same line"
puts s

If you omit the backslash, it is still legal, but doesn't give the result you might be hoping for; the string literal on the second line is simply thrown away.
Comment: "the backslash as the opposite of the semicolon": beautiful understanding.
Comment: So, you mean that Ruby parses the 2 literals as a single String? This would be more efficient than `<<` for many lines.
Answer: This is not a case of concatenated strings. It is one single string. "foo" "bar" is a syntactic construct that allows you to break up a string in your code, but it is identical to "foobar". In contrast, "foo" + "bar" is the true concatenation, invoking the concatenation method + on object "foo".
You can verify this by dumping the YARV instructions. Compare:
RubyVM::InstructionSequence.compile('"foo" + "bar"').to_a
// .... [:putstring, "foo"], [:putstring, "bar"] ....
RubyVM::InstructionSequence.compile('"foo" "bar"').to_a
// .... [:putstring, "foobar"] ....

The backslash in front of the newline will cancel the newline, so it does not terminate the statement; without it, it would not be one string, but two strings in separate lines.


Approximation rules?

Question: Let's say I need to approximate the expression $$\frac{1}{2}mv^2\left(\frac{M}{M+m}+1\right)$$ when $m<<M$.
Here is what I would do:
$$\frac{1}{2M}mv^2\left(\frac{M}{1+\frac{m}{M}}+M\right)
=\frac{1}{2M}mv^2\left[M\left(1-\frac{m}{M}+O(m^2)\right) +M\right]$$
Therefore approximating this, by dropping the higher-order terms in $m$ in the bracket I get:
$$\frac{1}{2M}mv^2(M+M) = mv^2$$
Ok, so when doing this are there any rules that we need to follow for example:
If the very small term is on the bottom of a fraction, use the binomial expansion to bring it up. (Is this always true?)
Are their any more, e.g. if we get something like $Mm$ what do we do? What about $Mm^2$ etc? When do we turn $M+m$ into just $M$?
Answer: If I may, I would suggest you first rewrite $$\frac{1}{2}mv^2\left(\frac{M}{M+m}+1\right)=\frac{1}{2}mv^2\left(\frac{1}{1+\frac{m}{M}}+1\right)$$ and that using that, for small values of $x$, $$\frac{1}{1+x} \simeq 1- x+ x^2-x^3 +\cdots$$ replace in the above $x$ by $\frac{m}{M}$ and get finally $$\frac{1}{2}mv^2\left(\frac{M}{M+m}+1\right) =m v^2-\frac{m^2 v^2}{2 M}+\frac{m^3 v^2}{2 M^2}+O\left(m^4\right)$$ that is to say  $$\frac{1}{2}mv^2\left(\frac{M}{M+m}+1\right) =m v^2\Big(1-\frac{1}{2}\frac{m}{M}+\frac{1}{2}(\frac{m}{M})^2+\cdots\Big)$$
In the same spirit, $Mm=M^2 \frac{m}{M}$ $Mm^2=M^3 \Big(\frac{m}{M}\Big)^2$
Comment: Basically, all rules are : Taylor, Taylor & Taylor ! There are other kinds of approximations such as Padé. Cheers :-)
Comment: Sorry I am more looking for a list of rules to use in general.

Approximation rules?


Finding $n$ such that $\frac{n+1}{n}$ < $\frac{\sqrt[n+1]{(n+1)!}}{\sqrt[n]{n!}}$

Question: I have been thinking about this limit:
$$\lim\limits_{n \rightarrow \infty}\frac{n}{\sqrt[n]{n!}} = e$$
Using a spreadsheet, I noticed that for $0 < n \le 150, \frac{n+1}{n} > \frac{\sqrt[n+1]{(n+1)!}}{\sqrt[n]{n!}}$.
The difference $\frac{n+1}{n} - \frac{\sqrt[n+1]{(n+1)!}}{\sqrt[n]{n!}}$ is strictly decreasing as $n$ increases.
I wondered if there exists an integer $k$ such that if  $n \ge k$, then $\frac{n+1}{n} < \frac{\sqrt[n+1]{(n+1)!}}{\sqrt[n]{n!}}$
What would be a standard way to determine if $k$ exists?  And if $k$ exists, what would be a standard way to determine $k$?
I suspect that there is a simple way to approach this question without using the gamma function. Am I right? Or does the determination of $k$ require using the gamma function?
Comment: FYI, using an [Approach0 search](https://approach0.xyz/search/?q=OR%20content%3A%24%5Cfrac%7Bn%2B1%7D%7Bn%7D%20%3E%20%5Cfrac%7B%5Csqrt%5Bn%2B1%5D%7B(n%2B1)!%7D%7D%7B%5Csqrt%5Bn%5D%7Bn!%7D%7D%24&p=1), I found the AoPS thread [a limit](https://artofproblemsolving.com/community/c7h504088p2831543). In message #2, it says "Proving this is less than one is equivalent to proving $\frac{n+1}{n}>\frac{\sqrt[n+1]{(n+1)!}}{\sqrt[n]{n!}}$", but then later "I don't know how to proceed from here". ...
Comment: (cont.) I also found several somewhat related questions here, but they dealt with somewhat other issues like $\lim_{n\to\infty}\frac{\sqrt[n+1]{(n+1)!}}{\sqrt[n]{n!}} = 1$, and the difference between the numerator & denominator, e.g., [Prove elementarily that $\sqrt[n+1] {(n+1)!} - \sqrt[n] {n!}$ is strictly decreasing](/q/238245) and [What is $\lim_{n\to \infty }\left(\sqrt[\leftroot{-2}\uproot{2}n+1]{(n+1)!}-\sqrt[\leftroot{-2}\uproot{2}n]{n!}\right)$?](/q/3598972).
Answer: The answer is no. By Stirling's formula
$$
\log n! = n\log n - n + \frac{1}{2}\log (2\pi n) + \mathcal{O}\!\left( {\frac{1}{n}} \right),
$$
i.e.,
$$
\log \sqrt[n]{{n!}} = \frac{1}{n}\log n! = \log n - 1 + \frac{1}{{2n}}\log (2\pi n) + \mathcal{O}\!\left( {\frac{1}{{n^2 }}} \right).
$$
Consequently,
\begin{align*}
\log \frac{{\sqrt[{n + 1}]{{(n + 1)!}}}}{{\sqrt[n]{{n!}}}} & = \log \left( {\frac{{n + 1}}{n}} \right) + \frac{1}{{2n + 2}}\log (2\pi (n + 1)) - \frac{1}{{2n}}\log (2\pi n) + \mathcal{O}\!\left( {\frac{1}{{n^2 }}} \right)
\\ &
 = \log \left( {\frac{{n + 1}}{n}} \right) - \frac{1}{{2n^2 }}\log (2\pi n) + \mathcal{O}\!\left( {\frac{1}{{n^2 }}} \right) < \log \left( {\frac{{n + 1}}{n}} \right),
\end{align*}
for all sufficiently large values of $n$. Using explicit error estimates, it may be shown that this inequality holds for all $n\geq 1$.
Comment: Thanks very much.  This is a great example of applying Stirling's formula!  :-)
Answer: We may use Mathematical Induction.
Problem: Prove that, for any positive integer $n$,
$$\frac{n+1}{n} > \frac{\sqrt[n+1]{(n+1)!}}{\sqrt[n]{n!}}.$$
Proof.
Taking logarithm on both sides, it suffices to prove that
$$\ln n! > n(n + 1) \ln n - n^2 \ln (n + 1).$$
We use Mathematical Induction.
It is easy to verify the case $n = 1$.
Assume that it is true for $n$.
For $n+1$, by the inductive hypothesis, we have
\begin{align*}
 \ln (n+1)! &= \ln n! + \ln(n + 1)\\
 &> n(n + 1) \ln n - n^2 \ln (n + 1) + \ln(n + 1).
\end{align*}
It suffices to prove that
$$n(n + 1) \ln n - n^2 \ln (n + 1) + \ln(n + 1) > (n + 1)(n + 2)\ln (n + 1) - (n + 1)^2\ln (n + 2)$$
or
$$n\ln n + (n + 1)\ln(n + 2)
> (2n + 1)\ln(n + 1)$$
or
$$(n + 1)\ln\left(1 + \frac{1}{n+1}\right) > n \ln\left(1 + \frac1n\right)$$
which is true (easy).
We are done.


How to redirect to another page when the time runs out

Question: I am trying to develop an online exam app with JSP. So I want to link to the results page with the same parameters of the current page (exam page) when a certain period of time runs out. I want to know how to add a timer and how to link to another page when the time is out.
Thanks.
Answer: You need to use Javascript to achieve this. There you'll need to create a JS segment looking something like this:
<code><script type="text/javascript">
  var myTimer = window.setTimeout(timer, 3000);

  function timer() {
    window.location.href = "new_page.htm"
  }
</script>
</code>
That script is meant for going into the body section to work. A script for your head section would require an onload event to take care of starting the timer. The example will redirect after 3 seconds.
Comment: you *really* need to store the timer so you can cancel it, and a simple function reference will suffice - avoid evals where possible (edited)
Answer: JavaScript is only client-side, it could be disabled or changed to cheat your application.
You have to keep track of the time at the server too, and you should also try to get input asap to your application, to know if the answer was "in time" or not.
Heavy AJAX is the way I would solve this problem.
Another way could be a Flash/Flex combo with a similar backend.


How many different hues, saturations and values are possible when converting RGB to HSV?

Question: If we specify a colour in the RGB space, there are $2^{24}$ different colours, as R, G and B are 8 bit numbers.
When a colour is converted to the HSV colour space (find the conversion formulas here for example), how many different values are possible for H, S and V?
Obviously, the total number of colours is equal in both spaces, as the conversion is a bijection. But how is the information distributed over the three dimensions of the HSV space?
Answer: The answer ist 118920. The 2^24 RGB values result in 118920 different hues, 19821 saturations, and 256 values. The last one is kind of obvious, but the first two were interesting. I wouldn't have expected the difference to be that big.
What is very interesting is the scatter plots of hue, saturation and values of the colours.
scatter plots of hue, saturation a value of RGB colours
It turns out that there are very few distinct hue values for low saturations and values, which makes sense, because hue is not "important" for greys and dark colours.
What I found most astonishing were the patterns in the hue-saturation plot.
Anyway, that was an interesting and fun exercise.


UIStackview `fillProportionally` distribution issue

Question: I have a container stack view and it has 2 other stackviews lets call them stackview 1 and stackview 2. Stackview 2 have a custom UIView with some label.
My issue is with stackview 1 and it has 2 arranged subviews. Axis of this UIStackView is vertical.  These subviews are custom UIView. These custom view may contain text or image and height of these custom views is not predefined and they are based on the content (i.e based on the height of the text).
Custom view 1 and custom view 2 are added in stackview 1. Stack view 1 and stack view 2 are added inside another container stack view.
My issue is I'm not able to display both these custom views (which are inside stackview 1) even if I return intrinsicContentSize (based on intrinsicContentSize of textviews) for these custom views in fillProportionally distribution.
If I return a constant width and height in intrinsicContentSize for customview then both views are displayed properly.
Inside my custom view
override var intrinsicContentSize: CGSize {
    let size = CGSize.init(width: 100, height: 100)
    return size
   }

Screenshot shows this behaviour.

But if I return size based on the intrinsicContentSize of UITextView (subview of customView, I have disabled scroll for textview) then only customview 2 is displayed and another view (customview 1) is not displayed.
Inside my Custom view
  override var intrinsicContentSize: CGSize {
       let size = textView.intrinsicContentSize
       return size
       }

Screenshot shows this behaviour.

I want fillProportionally behaviour but I cannot make it to work as I want which is to display both views (custom view 1 and custom view 2).
 According to documentation fillProportionally uses intrinsicContentSize to fill views proportionally. But why isn't that working in my case even after I overrided intrinsicContentSize var?
Why custom view 1 have zero hight even after overriding it's intrinsic content size?
I want both of these custom views to be displayed inside stack view 1.
I have been stuck here so I would greatly appreciate any help.
Comment: It often helps to give your views contrasting background colors to make it easier to see what's happening with the frames. Also, can you add an image of what you *want* the result to be? It's a little difficult to envision how you want the views to expand, since the text itself will remain a fixed size.
Comment: What if you say `textView.contentSize` instead of `textView.intrinsicContentSize`? Okay, I'm being lazy and not trying it myself, sorry, but could you just check?
Comment: Yes I tried that earlier and it didn't help @matt
Comment: Okay, well, I don't understand the example because there seem to be more views than you talk about. Please _thoroughly_ describe the view hierarchy and the goal. Thanks!
Comment: @JafferSheriff - let's start with the basics... Is `custom view 1` a `UIView` with a label? And `custom view 2` is a `UIView` with a (non-scrolling) text view? Based on that, how do you want your proportion calculated? It's still not clear (from your updated post) how the end result *should* look.
Comment: Updated the question. I have container stack view(yellow color view) which have 2 other stackviews (sv1 and sv2). Ignore stackview2 , which is bottom view with text.My issue is with stackview1 (violet in color). I want its subviews to be scaled proportionally but first view is getting hidden (in view hierarchy i found its height to be zero), even if i return `intrinsicContentSize`
Comment: @DonMag Both `custom view 1` and `custom view 2` are instances of same class. I want them to get scaled based on their content , which is text they contain.
Comment: @DonMag Both custom views have nonscrollable `UITextView` added as subviews.
Comment: @JafferSheriff - it's still tough to understand exactly what you want... in fact, I'm not so sure you really *do* want `.fillProportionally`. Can you show an image of exactly how you want the end result to look?
Comment: @DonMag I want the end result to look like image 1 but with proper height for custom view 1 based on its content height of "Pleasanton Panthers" text view. I also want to know why my configuration doesn't work and why it hides custom view 1
Comment: @JafferSheriff -- your "image 1" is not showing proportional fill based on the heights of the text. The "description" text is *at least* twice as tall as the "title" text, so "customView2" should be *at least* twice as tall as "customView1"
Comment: In image 1 i have set intrinsicContentSize as 100, 100. In image 1 as height of both custom view 1 and 2 are same they are not getting proportional height. In my image 2 Instead of hardcoding the size I returned their text views actual intrinsicContentSize and that made custom view 1 to get zero height. I don't get why is this happening
Comment: Is this what you are expecting? https://imgur.com/a/sTaTRLL
Comment: @DonMag  yes exactly. Height of these both views (custom view 1 and 2) should expand proportionally if the parent stack view have more height. That's all I want to achieve. I really really appreciate ur help mate
Answer: The .fillProportionally property of UIStackView is (from my experience) one of the most misunderstood elements of auto-layout.
So, I'm not entirely sure this is going to give you what you want, but give it a try.

Tapping the Text button will change the "description" text and tapping the Height button will change the height of the "container" view, so you can see how it looks with different amounts of text.
The Report button will print the resulting heights and proportional ratios of the views.
All via code - no @IBOutlet or @IBAction connections - so just start with a new view controller and assign its custom class to ProportionalStackViewController:
class ProportionalHeightView: UIView {

    let myNonScrollTextView: UITextView = {
        let v = UITextView()
        v.isScrollEnabled = false
        v.setContentHuggingPriority(.required, for: .vertical)
        return v
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }

    func commonInit() -> Void {

        let padding: CGFloat = 0.0
        addSubview(myNonScrollTextView)
        myNonScrollTextView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            myNonScrollTextView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: padding),
            myNonScrollTextView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -padding),

            // if we want the text top-aligned
            //myNonScrollTextView.topAnchor.constraint(equalTo: topAnchor),

            // if we want the text vertically=sentered
            myNonScrollTextView.centerYAnchor.constraint(equalTo: centerYAnchor),
        ])

    }

    override func layoutSubviews() {
        super.layoutSubviews()
        myNonScrollTextView.sizeToFit()
        invalidateIntrinsicContentSize()
    }

    override var intrinsicContentSize: CGSize {
        return myNonScrollTextView.bounds.size
    }
}

class TitleView: ProportionalHeightView {

    override func commonInit() {
        super.commonInit()
        myNonScrollTextView.font = UIFont.systemFont(ofSize: 22.0, weight: .bold)
        myNonScrollTextView.backgroundColor = .cyan
        backgroundColor = .blue
    }

}
class DescView: ProportionalHeightView {

    override func commonInit() {
        super.commonInit()
        myNonScrollTextView.font = UIFont.systemFont(ofSize: 17.0, weight: .regular)
        myNonScrollTextView.backgroundColor = .yellow
        backgroundColor = .orange
    }

}

class ProportionalStackViewController: UIViewController {

    var titleView: ProportionalHeightView = {
        let v = ProportionalHeightView()
        v.myNonScrollTextView.font = UIFont.systemFont(ofSize: 22.0, weight: .bold)
        v.myNonScrollTextView.backgroundColor = .cyan
        v.backgroundColor = .blue
        return v
    }()
    var descView: ProportionalHeightView = {
        let v = ProportionalHeightView()
        v.myNonScrollTextView.font = UIFont.systemFont(ofSize: 16.0, weight: .regular)
        v.myNonScrollTextView.backgroundColor = .yellow
        v.backgroundColor = .orange
        return v
    }()

    let containerView: UIView = {
        let v = UIView()
        v.backgroundColor = .white
        return v
    }()

    let proportionalStackView: UIStackView = {
        let v = UIStackView()
        v.axis = .vertical
        v.distribution = .fillProportionally
        return v
    }()

    let changeTextButton: UIButton = {
        let b = UIButton()
        b.backgroundColor = .gray
        b.setTitle("Text", for: .normal)
        return b
    }()
    let changeHeightButton: UIButton = {
        let b = UIButton()
        b.backgroundColor = .gray
        b.setTitle("Height", for: .normal)
        return b
    }()
    let reportButton: UIButton = {
        let b = UIButton()
        b.backgroundColor = .gray
        b.setTitle("Report", for: .normal)
        return b
    }()
    let btnStack: UIStackView = {
        let v = UIStackView()
        v.distribution = .fillEqually
        v.spacing = 20
        return v
    }()

    var nLines = 0

    var containerH = NSLayoutConstraint()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .systemTeal

        btnStack.translatesAutoresizingMaskIntoConstraints = false
        proportionalStackView.translatesAutoresizingMaskIntoConstraints = false
        containerView.translatesAutoresizingMaskIntoConstraints = false

        // add a horizontal stack view with buttons at the top
        btnStack.addArrangedSubview(changeTextButton)
        btnStack.addArrangedSubview(changeHeightButton)
        btnStack.addArrangedSubview(reportButton)

        view.addSubview(btnStack)

        // set text for titleView
        titleView.myNonScrollTextView.text = "Pleasanton Panthers"
        descView.myNonScrollTextView.text = "A one stop destination for all the Panthers fans! Experience our new futuristic techology-enabled fan experience an much more!" // "Single line"

        proportionalStackView.addArrangedSubview(titleView)
        proportionalStackView.addArrangedSubview(descView)

        containerView.addSubview(proportionalStackView)
        view.addSubview(containerView)

        // respect safe area
        let g = view.safeAreaLayoutGuide

        containerH = containerView.heightAnchor.constraint(equalToConstant: 240.0)

        NSLayoutConstraint.activate([

            // buttons stack 20-pts from top / leading / trailing
            btnStack.topAnchor.constraint(equalTo: g.topAnchor, constant: 20.0),
            btnStack.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
            btnStack.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),

            // container view 20-pts from bottom of buttons, 20-pts from leading / trailing
            containerView.topAnchor.constraint(equalTo: btnStack.bottomAnchor, constant: 20.0),
            containerView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
            containerView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),

            // container view height
            containerH,

            // constrain stack view 20-pts from top/bottom/leading/trailing to container
            proportionalStackView.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 20.0),
            proportionalStackView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -20.0),
            proportionalStackView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 20.0),
            proportionalStackView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -20.0),

        ])

        changeTextButton.addTarget(self, action: #selector(changeText), for: .touchUpInside)
        changeHeightButton.addTarget(self, action: #selector(changeHeight), for: .touchUpInside)
        reportButton.addTarget(self, action: #selector(report), for: .touchUpInside)

        [titleView, titleView.myNonScrollTextView, descView, descView.myNonScrollTextView].forEach {
            v in
            // un-comment next line to clear background colors
            //v.backgroundColor = .clear
        }
    }

    @objc func report() -> Void {

        let titleTextH = titleView.myNonScrollTextView.frame.size.height
        let descTextH = descView.myNonScrollTextView.frame.size.height

        let titleViewH = titleView.frame.size.height
        let descViewH = descView.frame.size.height

        let tRatio = titleTextH / descTextH
        let vRatio = titleViewH / descViewH

        print("text heights:\t", titleTextH, descTextH)
        print("view heights:\t", titleViewH, descViewH)
        print("Text view ratio: \(tRatio) view ratio: \(vRatio)")

    }

    @objc func changeHeight() -> Void {
        if containerView.frame.origin.y + containerView.frame.size.height > view.frame.size.height - 20 {
            containerH.constant = 220
        }
        containerH.constant += 20
    }

    @objc func changeText() -> Void {
        nLines += 1
        if nLines > 10 {
            descView.myNonScrollTextView.text = "A one stop destination for all the Panthers fans! Experience our new futuristic techology-enabled fan experience an much more!" // "Single line"
            nLines = 0
            return
        }
        var s = ""
        for i in 1..<nLines {
            s += "Line \(i)\n"
        }
        s += "Line \(nLines)"
        descView.myNonScrollTextView.text = s
    }

}


Directly open Spyder or open it through Pythonxy?

Question: Previously, I have been running Python in Spyder. I always started Spyder by directly double clicking its icon.
Today, I suddenly realize that I have another thing called Python(x,y). I notice that I can also start Spyder through it.
Do these two methods make any difference?
If not, what is the meaning of Python(x,y)? Does it have any other good features?
Answer:
Python(x,y)
Python(x,y) is a scientific Python distribution. This means that it not only installs Python in your system but also the most important scientific packages needed for a scientist to be productive with the language.
These packages are difficult to install by the user and also are too many to be installed one by one, so that's why Python(x,y) offers the possibility to install them all at once.
Spyder
Spyder is one of the packages distributed by Python(x,y), which offers a simple and convenient graphical environment to use the other scientific packages (like numpy or matplotlib). It resembles Matlab in its design.

Perhaps a comparison to Matlab is worth here:

Matlab is a huge program (about 5 gigs) that it's developed by one company and comes with a lot of packages and a graphical interface to use it.
Python(x,y) is also a big program (about 1 gig) but it's developed by two individuals who collect a lot of open source programs developed by a lot of different groups and institutions. It also comes with a graphical interface (Spyder) but there are others that fulfill a similar purpose (like the IPython notebook).
So in the Python scientific world, every package is developed independently of each other and there is the need of a "meta" program (like Python(x,y)) that distributes them together.
Answer: Actually i did not use spyder alone, but when you open it through Python(x,y) which is a scientific oriented distribution, some packages that are used in scientific/numeric computing automatically loaded.
Python(x,y) is based on python, Qt, spyder and includes many tools for scientific/numeric computation, visualizing (2D-3D), etc.
https://code.google.com/p/pythonxy/


An idea to chain/attach two tables rows to each other

Question: I am building an API which will handle to registers (in my case two tables) one Receiving Register and second Dispatching Register, as both are related with each other in some scenarios like a receiving register having a letter received from higher authorities and in this letter we need a response from other departments so we will dispatching the letter through dispatched register.
For this I have used pin_code in both the tables in receiving register I have kept it as an integer and updating it by one (n +=1) in each new record. while in dispatched register I have used the same field but made it optional with default value of "0" when I need to attach receiving table row to dispatched table row I just put the pin_code value from receiving register to this dispatched register pin_code field and it gives me the perfect solution.
Now my Actual question is that how  could I attach the same rows to each other with the same pin?
Or  would I need to use internal_pins in both the tables to fulfil the requirements?
Any idea / Algorithm which reduce the time complexity as well as space  please?
Note : - I have find some related results in joomla etc in the shape of Similar Posts or Similar Questions i.e. here in the right side of Stack Overflow website...
Comment: Can you add some code? Like how your database actually looks and what results you're expecting? Maybe some code that you've tried yourself? Your story alone is not enough to understand what exactly you want. (at least to me)
Comment: If pin code is present in both table why it would be hard to merge similar rows by pin code?
Comment: pin_code is working fine for both the tables rows to connect to each other but i am not understanding that how i will attach records in the same table?
Comment: Check my answer if this is what you want.
Answer: I am still unsure of the requirement but here are my thoughts from what we have right now. Basically this will join those request with receiving records. Those that dont will have null fields for the Receiving columns
<code>Select * from Dispatching d
left join
Receiving r
on d.pin_code=r.pin_code
</code>
If you want to see received register without dispatch record you can always use full join. But full join is not supported by mysql so youll probably need a union to replicate it.
Comment: Thanks for you quick response. I have no problem in printing the same. i need to know how to connect internal rows to each other.
Comment: Your question was "Now my Actual question is that how i could attach the same rows to each other with the same pin?". What do you mean by internal rows?
Comment: Specify the table designs and what output you wish to see.
Comment: sorry for ambiguity in the question. as you see that both the tables are connected via pin_code column and its working fine you know that, but what if i need to attach the rows in single (Same) table to each other? and for this purpose i think i will need to add one more column in both the tables like "enternal_pin" which will hold the pin_code for both the rows in the same table. example : table a row 2 is need to be connected to the table a row 4 for this i will need to save the same pin in enternal_pin and i hope it will help me to complete my aim.
Comment: Im sorry but i still do not get it. Can you please post your entire table design and can you explain the logic why you would need to join rows on the same table. I need the following information:

Table 1 Design and

Table 2 Design and

Expected Output


Evaluating an integral involving hyperbolic functions and exponentials

Question: I'm interested in evaluating the following integral, which I encountered while working on a special partition function $\int_{0}^{+\infty} a^{2}\sinh(x)^{2} e^{-ba\cosh(x)}dx$. Even an aproximate solution is accepted.
Comment: Hve you tried integration by parts with $u=\sinh(x)$ and $dv=\sinh(x) e^{-ba\cosh(x)}dx$?
Comment: Something Bessel like probably
Comment: @TitoEliatron not yet, I'll try later
Comment: @YuriyS I haven't studied them yet, I'm still an high-schooler. Could you please show me what you mean?
Comment: I'm on my phone, can't type formulas, just look up Modified Bessel functions, integral definitions. Also I suggest using Wolfram Alpha, it could give you the exact expression
Comment: @YuriyS ok, I'll look at that. I've already tried with Wolfram Alfa but I didn't get any answer
Answer: This is basically the same as
$$I(c)=\int_0^\infty \sinh^2(x) e^{-c \cosh(x)}dx$$
Use
$$\sinh^2(x) =\cosh^2(x)-1   $$
Modified Bessel function of the second kind:
$$K_0(c) =\int_0^\infty e^{-c \cosh(x)}dx $$
Using Feynman's trick of differentiation under the integral sign, we have:
$$I(c)=-K_0(c)+\frac{d^2}{d c^2} K_0(c)=K_1(c)/c$$
Here we used properties of Bessel functions from Wikipedia
Comment: Thank you so much for your answer. Is there a series expansion for $K_{0} (c)$ and $K_{1}(c)?$
Comment: @GabrielePrivitera, there is, but whether or not it works depends on the parameters. Bessel functions can be evaluated by most of the modern programs like Matlab or Mathematica and they can be considered a sufficient answer on their own, without the need to specify how they should be calculated
Comment: Copy that, thank for your help!


what the benefit of convenience initializer if do same job with initialize the class members with default values

Question: I am reading Designated Initializers with default values and convenience initializer and I am a little bit confused about them. If I can achieve every thing with Initializer with default values then why one should create convenience initializer.
I have created an example in both scenario and compare them.
Initializer with Default Values:
class Cat {

var color:String
var age:Int

init(color:String = "black",age:Int = 1) {
    self.color = color
    self.age = age
}

}

Convenience Initializer:
class Cat {
 var color: String
 var age: Int

 //If both parameters color and age are given:
 init (color: String, age: Int) {
      self.color = color
      self.age = age
 }

//If only age is given:
 convenience init (age: Int) {
      self.init(color: "black", age: age)
 }

 //if only color is given:
 convenience init (color: String) {
      self.init(color: color, age: 1)
 }

 //if nothing given
 convenience init () {
      self.init(color: "black", age: 1)
 }

}

Initializer varient calling:
//create Otto:
var Otto = Cat(color: "white", age: 10)
print("Otto is \(Otto.color) and \(Otto.age) year(s) old!")

//create Muffins:
var Muffins = Cat(age: 5)
print("Muffins is \(Muffins.color) and \(Muffins.age) year(s) old!")

//create Bruno:
var Bruno = Cat(color: "red")
print("Bruno is \(Bruno.color) and \(Bruno.age) year(s) old!")

//create Pico:
var Pico = Cat()
print("Pico is \(Pico.color) and \(Pico.age) year(s) old!")

Answer: Because sometimes initialising a class isn't that straightforward. Let's look at this Rectangle class. It has a width and height:
class Rectangle {
    let width: Double
    let height: Double

    init(width: Double, height: Double) {
        self.width = width
        self.height = height
    }
}

Here, you can add a convenience initialiser that takes a sideLength parameter:
convenience init(sideLength: Double) {
    self.init(width: sideLength, height: sideLength)
}

Or, a convenience initializer that takes a aFourthOf parameter:
convenience init(aFourthOf rect: Rectangle) {
    self.init(width: rect.width / 2, height: rect.height / 2)
}

There are lots of these situations.
Answer: That is a very interesting question.
You can always initialize using designated initializers but as the name suggests it ease the initialization when there are some complications or rare scenarios.
Here are a couple of examples
1. Look at the example below,
 class Cat {
       var color: String
       var age: Int

 //If both parameters color and age are given:
 init (color: String, age: Int) {
      self.color = color
      self.age = age
 }

 //If only age is provided:
 convenience init (age: Int) {
      self.init(color: "black", age: age)
 }

 //if only color is provided:
 convenience init (color: String) {
      self.init(color: color, age: 1)
 }

 //if nothing is provided
 convenience init () {
      self.init(color: "black", age: 1)
 }
}

2. While creating a storyboard instance we need to specify Name & Bundle. Since the bundle is Optional you can specify it as nil. Additionally, if you don't specify the bundle then XCode gives you a warning. But doing this every time for no reason becomes irritating.

You can't change the default init method for the UIStoryboard class. What should you do?? Simple create an extension to UIStoryboard and use a convenience initializer.
This way convenience initializer helps you code better.

As we observed above that there can be multiple cases during development where we need to add custom initialization. One important thing to keep in mind is Designated initializers must always delegate up (to base/super class).
Convenience initializers must always delegate across.


Ajax não envia o dado para outra página php

Question: Não estou conseguindo enviar o valor de um input para outra página php.
Em minha página produtos.php eu faço uma busca no banco de dados e carrego a página mostrar_itens dentro de uma div. Ao carregar os dados dentro desta div, eu monto um input. Esse "input: deflarg" que eu não estou conseguindo enviar para o carrinho.php
parte do código...mostrar_itens.php
echo '
';
echo ''."Definir a Largura da Porta: ".'<input type="text" name="deflarg" id="deflarg" size="5" maxlength="5"/>'. " cm".'	';
echo '
';

echo '
';
//echo '' . '<input type="submit" name="comprar" value="COMPRAR"/>'.'	';
//echo '' . 'Comprar'.'	';

echo'' . '
    '.'	';
echo '
';

Dentro da página mostra_item estou usando essa jquery + Ajax, porém sem sucesso.

Na página carrinho.php, estou fazendo assim:
<?php

$largura = $_POST["deflarg"];
echo "Largura: " . $largura;

?>

Onde estou errando ?
Comment: Veja se o Ajax está lendo os dados antes do envio. Faz um console.log() desse `$('enviar_para_carrinho').serialize()` para ver se os dados estão lá.
Comment: Esse `$('.enviar_para_carrinho')` é a classe da tag ``?
Answer: O problema é que, através do seletor:
$('enviar_para_carrinho')

Você está selecionando todos os elementos que possuem a tag <enviar_para_carrinho>. Desse modo, como provavelmente não existem esses elementos, você se enganou ao escolher esse seletor.
Se você quiser selecionar o elemento através de uma classe, você deverá prefixar o seletor através de um ponto (.), indicando que você quer selecionar o elemento através do atributo class. Assim:
$('.enviar_para_carrinho').serialize()

Se, no entanto, você quiser usar o ID do elemento para selecionar, você pode fazer assim:
$('#enviar_para_carrinho').serialize()

Para saber mais, queira consultar a página de seletores do jQuery.
Comment: Amigo explique o que você mudou no código, não precisava ter repostado tudo se você mudou apenas a seleção do form de `# `(id) pra classe `data: $('.enviar_para_carrinho').serialize(),`. Demorei pra perceber isso.
Comment: Realmente, obrigado pela observação, Bruno! :)  Quando escrevi a resposta original em 2017, ainda não estava muito acostumado com a forma como esse site funciona. Editei a resposta. ^-^
Comment: Caraca, que que essa pegunta tava fazendo na página inicial kkkk, nem vi que era de 2017 mano!!!


maildir in Windows for IMAP

Question: I'm interested in accessing my IMAP accounts offline.  I found that maildirs are a simple way to make it work.  I found that [offlineimap] takes care of almost everything in making the IMAP->maildir sync happen.  Then, I can open the account in Mutt or Wanderlust client.
One major problem, maildirs use colons in their filenames.  Windows doesn't allow colons.  I tried mount -f -s -b -o managed "d:/tmp/mail" "/home/of/mail" in Cygwin, but doing an echo test > /home/of/mail/test:file didn't work
I'm thinking about ext2fs, but I need an ext2 partition somewhere.  Can I make a file into a partition somehow?  I don't want to start modifying my hard drive's partition table.  Besides, does anyone know if ext2fs will support colons in filenames?
Answer:
One major problem, maildirs use colons in their filenames.

On Windows, a semicolon ; is often used in Maildirs. Since offlineimap is written in Python, it shouldn't be hard to make it do the same.

Can I make a file into a partition somehow?

There should be a program that can do that. (I know there's VFDwin for floppy disk emulation.) If not, there's a (hacky) alternative: create a passwordless TrueCrypt volume.

I don't want to start modifying my hard drive's partition table

gparted with ntfsprogs works really well.

Besides, does anyone know if ext2fs will support colons in filenames?

All Unix filesystems do. (In fact, even Windows' NTFS does.)
But Win32 itself probably doesn't. For NTFS, it uses colons to separate the file path from the stream name (kinda like xattrs on ext3).
(It's possible to install a POSIX subsystem in Windows NT, it is (was?) called "Microsoft Services for Unix", but I doubt it'll help you with this issue.)

maildir in Windows for IMAP


Why is this mapping not contractible?

Question: We define the relative homotopy for a pair $(X,A)$ to be the homotopy classes of continuous maps
$$(D^n, S^{n-1},s_0) \to (X,A,x_0)$$
This is technically a continuous map from $D^n \to X$ with the specifications that $S^{n-1} \to A$.
Any continuous mapping $D^n \to X$ is contractible so I am not sure why this specification on the subspace $S^{n-1}$ results in such maps not necessarily being contractible.
Why is a continuous map $(D^n, S^{n-1},s_0) \to (X,A,x_0)$ not necessarily contractible?
We are often told when they are contractible, i.e when $S^{n-1} \to A$ extends to a map on $D^n$.  However, I have never really understood why these maps aren't contractible to begin with.
Comment: Just look at the identity map $(D^2,S^1,s_0)\to(D^2,S^1,s_0)$. If there were a relative homotopy to the constant map at $s_0$, then it would restrict to a homotopy between the identity on $S^1$ and a constant map. However, the identity loop in $S^1$ is essential (another word for "not nullhomotopic").
Comment: I think the issue is that the OP did not factor in the "relative" part.
Answer: First, a point of terminology: a map is not said to be contractible (this is a property of spaces), it is said to be nullhomotopic.
Now, when looking at relative homotopy groups, two maps $f,g : (D^n, S^{n-1}, s_0) \to (X,A,x_0)$ are identified if they are homotopic relatively to $A$ (in short, "rel $A$"). This means that there must exist a homotopy $H : D^n \times I \to X$ such that all the following conditions hold:

$H(x,0) = f(x)$ and $H(x,1) = g(x)$;
For all $x \in S^{n-1}$ and for all $t$, $H(x,t) \in A$;
And for all $t$, $H(s_0, t) = x_0$.

It is true that, since $D^n$ is contractible, there will always exist a map satisfying the first condition. But it may or may not satisfy the other two; if it does, great the two maps are homotopic rel $A$, but otherwise they may not be. In particular, note that this implies that the two restrictions $f_{| S^{n-1}}, g_{| S^{n-1}} : S^{n-1} \to A$ have to be homotopic, which isn't always true.
To give an explicit example, consider the case where $A = \{x_0\}$. Then you're looking at maps $f : D^n \to A$ such that $f(\partial D^n) = \{x_0\}$, and two such maps are identified when there's a homotopy which is constant on $\partial D^n = S^{n-1}$. This is of course exactly the definition of the homotopy group $\pi_n(X,x_0)$, and you know that these aren't always trivial.
Even when $A$ is bigger than a singleton this may not be trivial. Stefan Hamcke gives an example in the comments: consider the identity of $(D^n, S^{n-1}, s_0)$. If the identity were nullhomotopic rel $S^{n-1}$, this would imply that the identity of $S^{n-1}$ would be nullhomotopic, which is not true for degree reasons.
Comment: Thank you for the nice answer! Is is then true that  for any two maps on the disk whose restrictions to the boundary are homotopic then these maps are homotopic as well?
Comment: @asdvn You didn't say, but I guess you are asking if the two maps are homotopy rel $S^{n-1}$? Then no, it is not the case. Consider a constant map $D^2 \to S^2$, and a map that collapses $S^1 = \partial D^2$ to a point to get $D^2 \to S^2 = D^2 / \partial D^2$. Then the restriction of both maps on the boundary are homotopic, but the two maps are not homotopic rel $S^1$ (they represent different elements in $\pi_2(S^2) = \mathbb{Z}$).

Why is this mapping not contractible?


Is it possible to get a page within an iframe to refresh the entire main page?

Question: At the moment I run a wordpress blog and I get users to authenticate within an iframe.  However there is information in side bars that does not refresh.  Is there some way I can do a whole of page redirect to
http://wordswithfriends.net/?page_id=386
after login?
Answer: You can set parent.location.
parent.location = 'http://wordswithfriends.net/?page_id=386';
Comment: Or even more foolproof, couldn't you just do this?: `parent.location = parent.location.href`
Comment: @sdleihssirhc Because he also said "redirect", I wasn't sure whether he wanted the page to "refresh" to itself or to a different URL.
Comment: I basically want to be able to send it anywhere
Comment: @delta If that's the case, setting `parent.location` to the desired URL should work for you.


On the solution to stochastic differential equations and Ito's lemma

Question: In this article, Sussmann shows there is a simple link between SDE of the form
$$\tag{1}
\mathrm{d}x=f(x)\mathrm{d}t+g(x)\mathrm{d}w
$$
and their correspondent ODE, provided $f$ and $g$ satisfies some regularity conditions.
But then...what is Ito lemma good for, if every SDE of this form can be solved with the same method as any other ODE?
Comment: Ito's lemma isn't used exclusively for solving SDEs...
Comment: Could you please give me some other areas of application?
Answer: The article doesn't discuss time-dependent coefficients
$$\mathrm{d}x=f(t,x)\mathrm{d}t+g(t,x)\mathrm{d}w,$$
where Itô-lemma applies.


Add permissions for a new content type

Question: Context: I created a new content type (press room nodetype) locally and made a feature with it so it is easier to deploy on my dev-stage-prod environments. This works perfectly well. The thing is, is I need to add permissions to some user roles right away in the same deployment process. I can't find the proper way to run some code after the feature-revert-all;
At the moment I put my code in a new module press_room.install.
function press_room_update_7001() {
    module_enable(['press_room_nodetype']); // installs the feature that will add the new content type

    $permission = [
        'edit any press_room content' => true,
    ];
    _add_permission_to_role('myrole',$permission); // too soon, content type not yet created
}

This module is enabled by another .install (homepage).
function homepage_update_7003() {
    module_enable(['press_room']);
}

With this code the new content type is created and the module to preprocess its output is enabled but the permissions are not given. It seems the content type is not (fully) created when the permissions needs to be added, so Drupal skips those lines and do nothing. If I run my code a second time, it works since the content type already exists.
Has anyone a solution to process code after a new content type has been created. What is the proper way to do this? Thank you.
Answer: This may not be what you're looking for but here is what we do to deploy on several production sites.

Store as much in Features as possible
Write update scripts when needed (as you've done). However, we enable modules via drush, never in code.
then run: drush en feature_module_name -y && drush updb

If multiple modules need to be enabled, we normal setup a chain of dependencies in the *.info files.

Add permissions for a new content type


Hyperlink row to fetch row data in another page, PHP?

Question: I want to fetch data of row buy clicking "apply" button in another page.
Which code should I use for hyberlink on the row?
also which code should I use for the another page which will show the row date?
This is the code I use:

<?php

/////// Update your database login details here /////
$dbhost_name = "localhost:1234"; // Your host name
$database = $CONFIG->dbname;       // Your database name
$username = $CONFIG->dbuser;            // Your login userid
$password = $CONFIG->dbpass;            // Your password
$conn = mysql_connect($dbhost_name, $username, $password);

  if(! $conn ) {
      die('Could not connect: ' . mysql_error());
   }

   $sql = 'SELECT * FROM jobs';
   mysql_select_db($database);
   $retval = mysql_query( $sql, $conn );

   if(! $retval ) {
      die('Could not get data: ' . mysql_error());
   }
   ?>

<?php
   while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
   ?>

                    <?php echo $row['jobid']; ?>
                    <?php echo $row['title']; ?>
                    <?php echo $row['company']; ?>

                        <form name="search" action="submit.php" method="POST">
                            <?php echo $row['jobid']; ?>
                        <input type="submit" value="apply" name="submit" />
                        </form>

<?php
   }

   mysql_close($conn);

?>
Comment: Stop using the **deprecated and as of PHP7 removed** mysql_* functions. Migrate to PDO and start using Prepared Statements.
Answer: If you want to send data from database to submit.php use hidden input type and and echo your data in the value section. Eg:
<form name="search" action="submit.php" method="POST">
<input type="hidden" name="jobid" value="<?php echo $row['jobid']; ?>" />
<input type="hidden" name="title" value="<?php echo $row['title']; ?>" />
<input type="hidden" name="company" value="<?php echo $row['company']; ?>" />
<input type="submit" value="apply" name="submit" />

And in processing page that is your submit.php use $_POST to fetch the data eg:
<?php
$jobid = $_POST['jobid'];
?>

How ever you are using mysql_* which is clearly outdated and removed from new php vevrsion. I recommend to use mqsqli or PDO. And start using prepare statements to remove the risk of sql injection.
Answer: You are describing something called AJAX. Don't be worried, it is actually quite easy.
See this example for an overview of what you want to do.
See this answer for some simple examples of AJAX to get you started.
Note that the PHP page with the AJAX javascript code, and the PHP page the AJAX sends data to, cannot be the same page. Although that is possible with <form> constructs, it is not possible with AJAX. (Instead of receiving the desired output, you will receive back the full HTML of the page)


Is there a (deep) relationship between these various applications of the exponential function?

Question: Here is a list of some applications of the exponential function.
1) The exponential mapping in Lie theory.
I put this first because my intuition tells me that this must be the most fundamental, or deep, way of thinking about the exponential function.  I have often been misled by my intuition however, and the main reason I feel strongly about this is because of how fundamental I consider Lie theory to be.
2) Fourier Series
3) Roots of Unity
4) Gaussian Distribution
5) Boltzmann Distribution
There are certainly other applications, but it always kind of bothered me that I couldn't use symmetry methods to see how (all of) these applications are related.  Is it possible that there is no way to do this, i.e. that it's just a happy accident that the exponential function has these applications and it is unrelated to any continuous symmetries?
Comment: (4) and (5) are related to combinatorial limits and the Central Limit Theorem, whereas (1) - (3) are mutually connected in obvious ways.  So the challenge comes down to finding a deep link between any of {1,2,3} and {4,5}.  One possible avenue of investigation is via the "characteristic function" (Fourier transform) of the Gaussian, which is a key tool in most proofs of the CLT.  Another promising route is via the Heat equation, diffusions, and random walks.
Comment: I don't think that the exponential map in the Lie-group context should be first, but this is clearly just a matter of taste. Probably the most fundamental fact about it is that it is the only measurable function for which $f(x+y)=f(x)f(y)$ for all $x,y$. From here you get that it is essentially the only function coinciding with it's derivative, and these two together encompass a whole world of algebra and analysis.
Comment: Since this got bumped: _Fourier Series and Integrals_ by Dym and McKean may be of interest.
Comment: @uniquesolution: Your suggestion has been used in my (updated) answer. Thanks.
Answer: Questions and Answers in MSE and two other references:
 Ad 1) :
How to derive these Lie Series formulas & chain references
 Ad 3) :
Ambiguous matrix representation of imaginary unit? idem
 Extra :
Where the exponent in the Laplace Transform comes from
 Ad 4) :
Gaussian Blur as a sample application of the Extra item

Updates.Ad 2). The Fourier transform
is a special case of the double-sided Laplace transform:
$$
F(p) = \int_{-\infty}^{+\infty} e^{-pt}\,f(t) dt \quad \Longrightarrow \quad
F(i\omega) = \int_{-\infty}^{+\infty} e^{-i\omega t} f(t)\,dt
$$
The Fourier transform, in turn, is a generalization of the complex
Fourier series:
start with equation (20) in the Wolfram reference and read until the end.
Ad 5). In this reference

Derivation of the Boltzmann Distribution

it is argued on page 23 (with obviously a typo in it) that the Boltzmann probability distribution $f(E)$ must have the following form:
$$
f(E_1) \times f(E_2) = h(E_1+E_2)
$$
Let's elaborate on this a little bit:
$$
f(E_1) \times f(E_2) = h(E_1+E_2) \quad \Longrightarrow \quad h(E) = h(E+0) = f(0)f(E)
$$
Derivative:
$$
h'(E) = f(0)f'(E) = \lim_{\delta\to 0} \frac{h(E+\delta)-h(E)}{\delta} =
\lim_{\delta\to 0} \frac{f(E)f(\delta)-f(0)f(E)}{\delta} =\\
f(E)\,\lim_{\delta\to 0} \frac{f(\delta)-f(0)}{\delta} =
f(E) f'(0) \quad \Longrightarrow \quad f'(E) = \frac{f'(0)}{f(0)} f(E)
$$
Continuing in terms of the article:
$$
\frac{df(E)}{f(E)} = \frac{-dE}{E_c} \quad \Longrightarrow \quad f(E) = A e^{-E/E_c}
$$
Which is the Ansatz for the Boltzmann distribution.
Ad 3). According to Wikipedia, De Moivre's formula is:
$$
\left[cos(x)+i\sin(x)\right]^n = \cos(nx) + i\sin(nx)
$$
And this can be proved for any integer $n$ , quite independent of Euler's formula.
It's rather the other way around: because of the pattern $\;f(x)^n = f(nx)\;$ , de Moivre's formula can be considered as a heuristics for Euler's formula.
But uniquesolution is quite right: <quote> Probably the most fundamental fact about it is that it is the only measurable function for which $f(x+y)=f(x)f(y)$ for all $x,y$ </quote> Can we mimic this behavior of $\,e^x$ with the function $f(x) = \cos(x)+i\sin(x)$ ? From trigonometry we know that:
$$
\cos(x+y) = \cos(x)\cos(y) - \sin(x)\sin(y)\\
\sin(x+y) = \sin(x)\cos(y) + \cos(x)\sin(y)
$$
Hence:
$$
f(x+y) = \cos(x+y) + i \sin(x+y) =\\ \left[\cos(x)\cos(y) - \sin(x)\sin(y)\right] + i \left[\sin(x)\cos(y) + \cos(x)\sin(y)\right]
=\\ \left[\cos(x) + i \sin(x)\right]\left[\cos(y) + i \sin(y)\right] = f(x)f(y)
$$
So our $f(x)$ behaves like an exponential function.
Comment: Thanks for the awesome answer to this old question!  It's going to take me some time to get through all of these links, but in the meantime I wanted to mention that my favorite derivation of the Boltzmann distribution in physics is directly related to symmetry, the basic idea being that entropy must be an additive integral of the motion, and hence must depend only on energy.  It can be found in [Landau vol 5](https://books.google.com/books?id=VzgJN-XPTRsC&lpg=PP1&pg=PA11#v=onepage&q&f=false)
Comment: @MattCalhoun: Alas, as a pensionado I have no easy access to a decent library these days. So I can't lay my hands on Landau & Lifschitz. Would it be possible to send me a copy of the relevant page(s)? An email address can be found in my (updated) profile.
Comment: the words "Landau vol 5" at the end of my previous comment are a link to the relevant pages, in google books.
Answer: The most important traits of the exponential function that make $e^x$ occur in that much applications are
a) Euler's identity $e^{i\pi} + 1 = 0$
and its implications for the definition of complex trigonimetric functions, i.e.
$$e^{i \cdot x} = \cos x + i \sin x$$
(like Fourier transformation, unit roots)
b) the fact that $\frac{d}{dx}e^x = e^x$
which lets $e^x$ naturally occur in many solutions of differential equations, which are often the most basic formulation of natural laws (growth/decay, gaussian distribution).
Comment: And using **b)** $\frac{d}{dx}e^x = e^x$ in taylor series expansion you can get the usual series expression for $e^x$


Dúvida em autenticação/autorização baseada em perfís de acesso com WebAPI Asp.Net Core MVC

Question: Tenho aqui uma aplicação Windows Forms + Sybase que possui um esquema de autenticação baseado em perfis de acesso. O diagrama do banco de dados é o seguinte:

Na tabela Permissão temos as descrições de todas as funcionalidades do sistema. Se pode acessar o cadastro de clientes, se pode ajustar o estoque, se pode excluir um produto, se pode realizar uma venda, etc.
Na tabela Perfil temos "Gerente", "Vendedor 1", "Vendedor 2", "Administrador", etc.
E a tabela Perfil_Permissao é a entidade associativa das duas tabelas, onde dizemos quais funções cada perfil tem acesso.
E cada usuário tem seu perfil, com as devidas permissões de acesso do perfil.
Estou criando uma WebAPI para esse sistema, mas não estou conseguindo conciliar essa forma de autenticação do sistema atual com as possibilidades de autenticação do Asp.Net MVC.
Gostaria que os authorizes dos controllers e actions se baseassem nesse esquema de permissão para conceder ou não acesso a eles.
Existe alguma forma de adequar esse esquema de permissão de acesso do sistema atual aos "authorize", "policy", "claims", etc, do Asp.Net Core MVC?
Answer: Nesse formato de permissão por perfil, utilizei as claims para resolver o problema.
É possivel mandar, por exemplo, multiplas claims do tipo "Role", colocando cada uma das permissões nessas claims.
Pode ser usado algo similar a isso:
<code>foreach(Permissao permissao in permissoes)
{
    Claim item = new Claim(ClaimTypes.Role, permissao.Codigo );
    lstClaims.Add(item);
}
</code>
E posteriormente a lista de claims é passada para o token utilizado.
<code>...
Subject = new ClaimsIdentity( lstClaims.ToArray() )
...
</code>
Foi assim que resolvi.


Understanding bVII harmony

Question: I was analyzing "Try to Remember" from the musical "The Fantasticks" and became stumped on what seems to be a flatted seventh major chord stuck in the middle of the song. I'd like to understand what's going on and how it fits in with the rest of the nearby chords.
In this arrangement, it's the F major chord at the end of the fourth line. Are we in a separate key at this point? Is this just a substitution for another chord?
Comment: Not necessarily relevant here, but ♭Ⅶ is an extremely common chord especially in Rock. Often without much theoretical justification, but it can typically be interpreted as Mixolydian mode.
Comment: Related with https://music.stackexchange.com/questions/29817/why-do-many-songs-in-major-keys-use-a-bvii-chord
Answer: The 'middle 8', as in so many songs, is a jump to a slightly remote chord then a 'cycle of 5ths' sequence back to the tonic.   But this time it hits the tonic and keeps on going!  Bm7, Em7, Am7, D7, Gmaj7 (we're home) Cmaj7, F - then a side-slip back to the dominant (D7) and home (G).  Nice, isn't it!
I could come up with some theory about bVII being a dominant substitute or 'borrowed' from somewhere.  But the simple truth is that bVII is so common in today's music as to almost count as diatonic.
Comment: I don't disagree that it is basically diatonic, but that still means it has to have a function, and I would say it has predominant function, same as ii or IV.
Comment: as it has already been discussed in the earlier question bVII is  a borrowed chord of the mixolydian mode. Functional it works to me like a suspension of V7 ...
Comment: Oh, anything can be justified as 'borrowed' from SOMEWHERE.   I'm not sure that sort of labelling helps very much.
Comment: It has a function in the backwards direction, as the culmination of the 'cycle of 5ths' string.   Going forwards - well it certainly precedes the dominant!  But it could just as well have gone other places. I don't see a strong function there.
Answer: I think it works there because it is the end of the circle of 5ths (not necessarily all dominant, but the root movement anyway starting with the Bm7) , but the F chord (FAC), especially with the melody notes A and E are substituting for ii there in a ii V I progression going back to G. The F note acts as sort of a suspension resolving to the E. One has to be a little flexible with the terms here to see how the notes can be played with.
Answer: bVII can be considered as a substitution of V7.
e.g. we expect V7 in a semi clause of a phrase and bVII substitutes V7 (d,f are shared tones of both chords).
see my answer - and many good other answers here:
Why do many songs in major keys use a bVII chord?
Comment: as I said in another comment *suspended V7* :BbDF-> GBDF (DF are common tones. (this impression of suspension and substitution may be quite subjective: beause  I'm expecting V7 and I feel fooled by the introduction of bVII - at least the very first time. Meanwhile we are so used of this progression that we are expecting bVII in similar situations  ;) - I say also substitution as it occurs in a semi clause (usually at the end of a phrase that is repeated - where we are used to have the dominant in classic music - and the second time the repeated phrase  leads to the final clause.

Understanding bVII harmony


What animals can distinguish or recognize musical chords of like 2 notes?

Question: I was just thinking if bird chirps fit into a musical scale in any case, so not sure about that. But what I'm wondering here is what animals "respond to" a pair of notes on the major or minor scale, like major third, minor third, perfect fifth, etc.. Just 2 notes for now, could go into 3 note chords if there's a lot of research.
But who has looked into this, is there anything of interest here? Like, for example, do dogs or rats or guinea pigs "like" major third chords, and "dislike" minor third chords, or dissonant vs. "pleasant" chords of 2 notes. By like/dislike, maybe there were some experiments where they learned to recognize or be stimulated by these sounds in some ways. Curious what the research is at a high level, and a key place to look further.
Comment: I'd suggest editing your question; currently, there could be a new answer posted for each animal species, and endless list-type question are not allowed.
Comment: I don't think this question is really [on-topic](https://music.stackexchange.com/help/on-topic) for this site.
Comment: I'm voting to close this question because although it is an interesting premise, this is both outside the scope of Music.SE and ultimately a list question.
Answer: Research has been done on this; this is a new topic for me, but I was able to find this paper: Paola Crespo-Bojorque and Juan M. Toro, "The use of interval ratios in consonance perception by rats (Rattus norvegicus) and humans (Homo sapiens)"  Two-note chords are used to investigate the perception of consonance in rats.  From the abstract:

...several comparative studies have tackled the question of how general the perception of consonance and dissonance of musical chords is across species.

Research has shown that Japanese monkeys (Macaca fuscata, Izumi, 2000), Java sparrows (Padda oryzivora, Watanabe, Uozumi, & Tanaka, 2005), European starlings (Sturnus vulgaris, Hulse, Bernard, & Braaten, 1995), black-capped chickadees (Poecile atricapillus, Hoeschele, Cook, Guillette, & Brooks, 2012), and pigeons (Columbia livia, Brooks & Cook, 2009), are able to discriminate across chords, and this capacity may be based on sensory consonance. In parallel, different neural responses have been observed for consonant and dissonant stimuli in macaque monkeys (Macaca fascicularis, Fishman et al., 2001).

So, Humans are not unique in their ability to differentiate chords, and may not be unique in the perception of "consonance" and "dissonance" either.  There are plenty of citations in that paper that link to other research on the same topic, if you wish to explore.  There is even research being done to see if various animals prefer certain chords.  Notably, Koda et al. 2013 and McDermott & Hauser, 2004 investigate using two-note chords as you suggested.  These studies did not find preference for consonance in their subjects (Tamarins and Campbell's monkeys).
Comment: "Discriminating" between two sounds simply means that they can tell the difference.  In this particular paper, rats were trained to press a lever, and the rats were rewarded with food for pressing the correct lever.  The idea is that if the rats can tell the difference between the consonant and dissonant tones, they will likely learn to press the correct lever for the reward.  Other experiments may use slightly different approaches.
Comment: Being really picky, *dyads* is a better label than *chords* - for me.
Comment: Amazing! Can you briefly add what they mean by "discriminate" the sounds, I'll take a look into the papers though, thanks.


Esse assembly não permite chamadores parcialmente confiáveis

Question: Eu tenho meu projeto, e nele eu tenho um dll para acessar alguns métodos, em desenvolvimento funciona normalmente, mas no ambiente de homologação esta dando esta msg:

"Esse assembly não permite chamadores parcialmente confiáveis. "

O que pode ser?
Obs: Já adicionei o "[assembly: AllowPartiallyTrustedCallers()]" no AssemblyInfo.cs
Comment: Descobri o problema, mudaram a política de hospedagem.
obrigado pela ajuda!
Answer: Uma opção é inserir no Web.config o seguinte:
<trust level="Full" originUrl=""/>

O erro acontece porque a aplicação pode estar configurada para Medium Trust.
Se ainda assim não funcionar, mude as referências, se houver:

System.Web.Mvc
System.Web.Routing
System.Web.Abstractions

Para Copy Local True nas propriedades da referência. Experimente aí publicar novamente.
Comment: Deu erro "Esta seção de configuração não pode ser usada neste caminho. Isso ocorre quando o administrador do site bloqueia o acesso a essa seção usando  de um arquivo de configuração herdado.
"
Comment: @RenanFBossa Coloquei mais umas dicas.
Comment: Mesmo erro mencionado acima... :/


Missing resource exception when trying to hit an application deployed on WebSphere Application Server

Question: I am getting an error as pasted below when I try to display a jsp(/jsp/login.jsp) page which is present in the application which I have deployed on WebSphere Application Server successfully.
[15/01/14 11:31:16:451 GMT] 0000002d servlet       E com.ibm.ws.webcontainer.servlet.ServletWrapper service SRVE0068E: Uncaught exception created in one of the service methods of the servlet /jsp/login.jsp in application CAA application. Exception created : java.util.MissingResourceException: Can't find resource for bundle com.fp.config.MessageResources, key en

  at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:365)
  at java.util.ResourceBundle.getBundle(ResourceBundle.java:125)
  at com.fp.websec.util.validation.UserMessages.getMessage(UserMessages.java:168)
  at com.fp.websec.util.validation.UserMessages.getMessage(UserMessages.java:94)
  at com.fp.websec.util.validation.Util.getTargetURL(Util.java:651)
  at com.ibm._jsp._login._jspService(_login.java:162)
  at com.ibm.ws.jsp.runtime.HttpJspBase.service(HttpJspBase.java:99)
  at javax.servlet.http.HttpServlet.service(HttpServlet.java:831)
  at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1663)
  at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:939)
  at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:502)
  at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:179)
  at com.ibm.wsspi.webcontainer.servlet.GenericServletWrapper.handleRequest(GenericServletWrapper.java:121)
  at com.ibm.ws.jsp.webcontainerext.AbstractJSPExtensionServletWrapper.handleRequest(AbstractJSPExtensionServletWrapper.java:241)
  at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3826)
  at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:276)
  at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:931)
  at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1583)
  at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:186)
  at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:445)
  at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:504)
  at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:301)
  at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:275)
  at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214)
  at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113)
  at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:165)
  at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
  at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
  at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
  at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
  at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
  at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
  at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1563)

 [15/01/14 11:31:16:467 GMT] 0000002d LocalTranCoor E   WLTC0017E: Resources rolled back due to setRollbackOnly() being called.
 [15/01/14 11:31:16:483 GMT] 0000002d webapp        E com.ibm.ws.webcontainer.webapp.WebApp logServletError SRVE0293E: [Servlet Error]-[/jsp/login.jsp]: java.util.MissingResourceException: Can't find resource for bundle com.fp.config.MessageResources, key en

  at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:365)
  at java.util.ResourceBundle.getBundle(ResourceBundle.java:125)
  at com.fp.websec.util.validation.UserMessages.getMessage(UserMessages.java:168)
  at com.fp.websec.util.validation.UserMessages.getMessage(UserMessages.java:94)
  at com.fp.websec.util.validation.Util.getTargetURL(Util.java:651)
  at com.ibm._jsp._login._jspService(_login.java:162)
  at com.ibm.ws.jsp.runtime.HttpJspBase.service(HttpJspBase.java:99)
  at javax.servlet.http.HttpServlet.service(HttpServlet.java:831)
  at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1663)
  at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:939)
  at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:502)
  at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:179)
  at com.ibm.wsspi.webcontainer.servlet.GenericServletWrapper.handleRequest(GenericServletWrapper.java:121)
  at com.ibm.ws.jsp.webcontainerext.AbstractJSPExtensionServletWrapper.handleRequest(AbstractJSPExtensionServletWrapper.java:241)
  at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3826)
  at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:276)
  at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:931)
  at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1583)
  at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:186)
  at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:445)
  at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:504)
  at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:301)
  at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:275)
  at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214)
  at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113)
  at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:165)
  at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
  at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
  at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
  at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
  at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
  at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
  at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1563)

[15/01/14 11:31:16:498 GMT] 0000002d servlet       E com.ibm.ws.webcontainer.servlet.ServletWrapper service SRVE0068E: Uncaught exception created in one of the service methods of the servlet /jsp/internalServerError.jsp in application CAA application. Exception created : java.util.MissingResourceException: Can't find resource for bundle com.fp.config.externalResources, key en_GB

  at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:365)
  at java.util.ResourceBundle.getBundle(ResourceBundle.java:104)
  at com.fp.websec.util.validation.Util.getExternalResource(Util.java:112)
  at com.ibm._jsp._internalServerError._jspService(_internalServerError.java:136)
  at com.ibm.ws.jsp.runtime.HttpJspBase.service(HttpJspBase.java:99)
  at javax.servlet.http.HttpServlet.service(HttpServlet.java:831)
  at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1663)
  at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:939)
  at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:502)
  at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:179)
  at com.ibm.wsspi.webcontainer.servlet.GenericServletWrapper.handleRequest(GenericServletWrapper.java:121)
  at com.ibm.ws.jsp.webcontainerext.AbstractJSPExtensionServletWrapper.handleRequest(AbstractJSPExtensionServletWrapper.java:241)
  at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.forward(WebAppRequestDispatcher.java:341)
  at com.ibm.ws.webcontainer.webapp.WebApp.sendError(WebApp.java:3262)
  at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3859)
  at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:276)
  at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:931)
  at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1583)
  at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:186)
  at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:445)
  at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:504)
  at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:301)
  at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:275)
  at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214)
  at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113)
  at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:165)
  at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
  at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
  at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
  at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
  at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
  at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
  at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1563)

[15/01/14 11:31:16:514 GMT] 0000002d LocalTranCoor E   WLTC0017E: Resources rolled back due to setRollbackOnly() being called.
[15/01/14 11:31:16:514 GMT] 0000002d webapp        E com.ibm.ws.webcontainer.webapp.WebApp reportRecursiveError Error Page Exception  The server cannot use the error page specified for your application because of the exception printed below.
[15/01/14 11:31:16:529 GMT] 0000002d webapp        E com.ibm.ws.webcontainer.webapp.WebApp reportRecursiveError Error Page Exception:

I am new to WAS and I don't know whats wrong with the deployment the file which it is searching is present in a jar file which is there in the files generated by the build.xml
I know this might be some silly mistake but your help would really be appreciated.
Answer: It looks like messages_en.properties is missing in your build path. check whether the properties file is in the proper location.
Comment: I dont have any file called messages_en.properties I do have a file called CAAConstants.java which is packed in a jar file and placed in \config folder. Still it cant find this file.
Answer: It's definitely failing to locate message resource files it requires. Both com.fp.config.MessageResources and com.fp.config.externalResources are are looking for properties files that contain internationalized message text.
Can you locate any such files that are in the source code but not included in jars/wars?
Comment: Hi dbreaux,

Thanks for your reply on this. I do have a MessageResources_en.properties and can locate this in the source code but this file is not included in any of the jar files. Might be the definite reason for getting this error.
Comment: Hi there is a properties file but I am not sure how to add that to my .ear file. When I build the application it generates a xyz.ear file which needs to be deployed on WAS 7. But this ear doesnt contain the requires properties file, please help.
Comment: Depends on where that `com.fp` code is expecting it. Often that's in the classpath, which could be within a Jar or in a WAR file's `WEB-INF/classes`.


Ring homomorphism

Question: The number of non-trivial ring homomorphisms from $\mathbb{Z}_{12}$ to $\mathbb{Z}_{28}$ is
(Options:                                                                                a.1  b.3  c.4  d.7)
Comment: Let $f$ be such a homomorphism, what could be the value of $f(1)$ ?
Comment: A ring homomorphism preserving identity would have to send $\phi(0)=\phi(12)=12\neq 0$, so I'm beginning to suspect that we're talking about groups after all, or the ring homomorphisms do not have to preserve identity.
Answer: To be a mere group homomorphism, then the order of the image of 1 will have to divide both 12 and 28. So that leaves four options for 1 to map to.
If it has to be a ring homomorphism, then 1 must map to an idempotent element of $\mathbb{Z}_{28}$. Only two of the four previous possibilities are idempotent.
Comment: @Tsotsi $\phi(1)\cdot\phi(1)=\phi(1\cdot 1)=\phi(1)$.
Comment: @TaxiDriver :o So it is! I have no idea why I overlooked that before! I will have to revise that omission, and I thank you for pointing it out.
Comment: why $1$ map to an idempotent element?
Comment: okay, and why "...that leaves four options for $1$ to map to"?
Comment: @Tsotsi ...because there are only four elements of $\Bbb Z_{28}$ which have orders dividing 12.
Comment: namely $O(7)=4,O(0)=1,O(14)=2,O(17)=6$, In which $0$ is the only idempotent element, do want to mean that?
Comment: @Tsotsi Don't combine the two different hints above. Being an idempotent has nothing to do with the group map in the first paragraph.
Comment: so then clearly state what is the answer and where I am going wrong
Comment: @Tsotsi I didn't see you "go wrong" besides combining the two hints :) The answer is that you can map $1\mapsto x$ where $x\in \{0,7, 14,21\}$, those all induce group homomorphisms, and nothing else is possible :) If you want a *ring* homomorphism then you're forced to map $1\mapsto 0$, (because the *ring* homomorphism needs to send 1 to an idempotent.)
Comment: @Tsotsi It isn't possible for $17$ to have order $6$ since $6$ doesn't divide $28$. Since it's coprime to $28$ it has order $28$.
Comment: 21 is also an idempotent element
Answer: I'm, going to proove more general fact: the order of the group $Hom(\mathbb Z_m, \mathbb Z_n)$ (i.e the group of homomorphisms from $\mathbb Z_m$ to $\mathbb Z_n$) is $gcd(m,n)$.
It's obvious that the order of the image of any homomorphism from $\mathbb Z_m$ to $\mathbb Z_n$ must devide both $m$ and $n$. Let us notice that for any $d$ that divides $n$ there exists a unique subgroup $H$ in $\mathbb Z_n$ which order is $d$ (if $n=dq$ then $H=\{0, d, 2d, ... , d(q-1)\}$).
There is also a simple fact that the number of generators of finite cyclic group $<a>_n$ of order $n$ is $\phi(n)$, where $\phi$ is Euler's totient function (by definition $\phi(n)$ is an arithmetic function that counts the number of positive integers less than or equal to $n$ that are relatively prime to $n$). Now I'm going to prove it.
At first let's show that if $a^q$ is a generator then $gcd(q,n)=1$. Assume that $q$ and $n$ aren't relatively prime. Therefore $q = kx$, and $n = ky$ for some integers $x$ and $y$. This means that $a^{qy} = a^{kxy} = a^{xn}=1$. So the order of $a^q$ is $y$. But $y<n$. It means that $a$ couldn't be a generator. Therefore if $a^q$ is a generator then $q$ and $n$ are relatively prime.
Now we want to show that if $gcd(q,n)=1$, then $a^q$ is a generator. More pricisely, we need to proove that if $(a^q)^s = 1$, then $s = xn$ for some integer $x$. It's obvious that $qs=xn$ for some integer $n$ (because $(a^q)^s = 1$ and our group has order $n$). But $gcd(q,n)=1$, so it's easy to see that $n$ devides $s$.
It remains to observe that given a homomorphism from $\mathbb Z_m$ to subgroup $H$ in $\mathbb Z_n$ means to set the map of $1$ to one of generators of $\mathbb Z_n$. Therefore the number of homomorpisms is $\sum_{k|gcd(m,n)} \phi(k)$ which equals $gcd(m,n).$
So the answer to your question: $gcd(12,28)=4$
Comment: This is almost completely irrelevant: the question is asking about _ring_ homomorphisms, not group homomorphisms.

Ring homomorphism


Meaning of notation: $x_{l,L}$

Question: The question is show that $$x_{l,L}X_{L,k}=\delta _{kl}$$ but what does that notation even mean?? The topic of this is continuum mechanics.
Answer: The notation uses the Einstein summation convention: sum over same indices.
The Kronecker delta $\delta_{kl}$ is the identity matrix.
This could be the component form of the matrix product of matrices $x=(x_{lm})$ and $X=(X_{jk})$:
$$
x X = I \Rightarrow \\
(x X)_{ik} = x_{lL} X_{Lk} = \delta_{kl} = \delta_{lk} = (I)_{lk}
$$
Comment: Also why does the LHS terms have commas on the subscripts and the kronecker delta one doesn't? (on the question i wrote)
Comment: So $x_{l,L}$ means a matrix with $l$ rows and $L$ columns right? and $X_{L,k}$ is matrix with $L$ rows and $k$ columns? But what values are actually in the matrix? or does that not matter...
Comment: how do I exactly prove the question though... I don't see how I can
Comment: @snowman I would need to have a look at the book or at least some context to answer why there are commas. This notation is used in tensor calculus and it might indicate that the quantity is indexed but not a tensor, e.g. a transformation matrix.
Comment: It is more likely that it is the component of the $l$-th row and the $L$-th column. $L$ seems to be the index of summation. I would normally expect lower case indices so there might be some other meaning attached. The only values which I can see are the 0 and 1 values of the Kronecker delta.
Comment: You could start to solve the problem by finding out the definition of small and big x.
Comment: In tensor calculus, comma's are often used to denote partial differentiation. I don't think this question can be answered absolutely without more context.

Meaning of notation: $x_{l,L}$


How to filter a PrimeNG table with a nested object?

Question: I want to filter my PrimeNG Table with fields that are not displayed. Here is my Datatable Object:
[
  {
    id: 1,
    actions: [
      'eat',
      'drink',
      'sleep'
    ],
    name: 'test',
    age: 18
  },
  {
    id: 2,
    actions: [
      'eat',
    ],
    name: 'test1',
    age: 22
  },
  {
    id: 3,
    actions: [
      'drink',
      'sleep'
    ],
    name: 'test2',
    age: 19
  }
]

Only this fields are shown in my table: "id, name, age". Now I'm creating my table like this:

 <-- HERE I WANT TO ADD THE ACTIONS
  <ng-template pTemplate="caption">
    Users

      <input pInputText type="text" (input)="dt.filterGlobal($event.target.value, 'contains')" placeholder="Search..." />

  </ng-template>
...

I don't know how to filter in this action array... If I add 'actions' to globalFilterField property, nothing happens. If I filter with "drink", it will display all entries. I tried to add actions.every() to the globalFilterField input properties, but this doesn't work.
Does someone know how to filter a PrimeNG table like this? Do I have to write my own filter?
Answer: You can create a custom filter using FilterUtils
import { FilterUtils } from "primeng/utils";

//...
  ngOnInit() {
     FilterUtils["includes"] = (value, filter) => value.includes(filter);
    //...
  }

and then you can use it:
dt.filter(value, 'actions', 'includes')