Do discriminative models model conditional expectation?

Question: In Machine Learning classic models like MLP, Logistic Regression or Linear Regression are called discriminative models.
I frequently read that those models estimate the conditional probability distribution P(y|x). However, if they would really represent this distribution they should be able to return multiple likely outcomes but in reality they usually return only a single y. Doesn't this mean what they actually model is not the conditional distribution, P(y|x) but the conditional expectation E[y|x]?
Answer: Discriminative methods are posed in contrast to generative methods, which model the joint distribution $p(x, y)$ of the input $X$ and output $Y$. But, the terminology isn't always consistent across authors. A discriminative model may refer to 1) A model of the conditional distribution $p(y \mid x)$ and/or 2) Any non-generative model that can predict $Y$ as a function of $X$. In the second case, the model need not be probabilistic (e.g. support vector machines).
Methods like ordinary least squares (OLS) and logistic regression do indeed model the conditional distribution. For example, in OLS it's Gaussian:
$$p(y \mid x) = \mathcal{N}(x \cdot \beta, \sigma^2)$$
where $\beta$ are the weights and $\sigma^2$ is the noise variance (which can be estimated as the variance of the residuals, given the usual assumptions). The conditional expectation $E[y \mid x] = x \cdot \beta$ is a point prediction. But, the conditional distribution can also be used to compute prediction intervals, sample multiple $y$ values, etc.
For logistic regression (with $Y \in \{0,1\}$), the conditional distribution is Bernoulli where:
$$p(Y=1 \mid x) = \frac{1}{1 + \exp(-x \cdot \beta)}$$


Conjugacy classes in non-abelian group of order $pq$

Question: Suppose I have a non-abelian group $G$ of order $pq$ ($\Rightarrow$ the center of $G$ is trivial) such that $p | (q-1)$.
The Class Equation gives $|G| = \sum[G:C(x)]$, where $C(x)$ denotes the centralizer of $x$, and the sum ranges over one element $x$ from each nontrivial conjugacy class. Since the centralizer of an element $x$ of $G$ is a subgroup of $G$, each of the summands is a divisor of $|G| = pq$. Thus, we may only have conjugacy classes of order $1$, $p$, $q$, or $pq$.
It's easy to see that, since the center of $G$ is trivial (i.e., the identity element $e$ is the only member of $Z(G)$ ), $[G:C(e)] = |G|/|C(e)| = (pq)/(pq) = 1$. Since $e$ is the only element of $G$ whose centralizer is all of $G$, it follows that we only have one conjugacy class of order $1$ in $G$. As such, we cannot have a conjugacy class of order $pq$, as then we would exceed the number of elements in the group. Thus, we only have conjugacy classes of order $p$ or $q$ remaining.
Upon viewing Number of conjugacy classes of nonabelian group of order $pq$., the user comment states that there are $p-1$ conjugacy classes of order $q$, and $(q-1)/p$ conjugacy classes of order $p$.
My question is, how did this user arrive at these values ? I definitely see that, taking the answer for granted for a moment, we then have $pq = 1 \cdot 1 + (p-1) \cdot q + (q-1)/p \cdot p$, so the given orders make sense. But, how to arrive at these exact orders $p-1$ and $(q-1)/p$ ? I see I haven't used the fact that $p|(q-1)$ here, so maybe that helps us out.
In general, how can I detect the number of conjugacy classes of a certain order, if we're not given the specific group $G$ that we're working with ?
Thanks!
Answer: Let $a$ and $b$ be elements of order $p$ and $q$ respectively.
Then
$$a^{-1}ba=b^s$$
where $s$ is a non-trivial solution of $s^p\equiv1\pmod p$.
As $\left<b\right>$ is normal in $G$, there are $q-1$ elements of
order $q$, and any element outside $\left<b\right>$ has order $p$.
So there are $pq-q$ elements of order $p$.
No element of order $p$ can commute with an element of order $q$
since otherwise their product would have order $pq$ and so the group
would be cyclic. Therefore the centraliser of an element of order
$p$ has order $p$, and each element of order $p$ has $q$ conjugates.
Likewise, the centraliser of an element of order
$q$ has order $q$, and each element of order $q$ has $p$ conjugates.
Therefore the $q-1$ elements of order $q$ fall into $(q-1)/p$
conjugacy classes (each of order $p$).
Likewise, the $pq-q$ elements of order $p$ fall into $(pq-q)/q=p-1$
conjugacy classes (each of order $q$).
Answer: Your nonabelian $G$ has class equation:
$$pq=1+k_pp+k_qq \tag 1$$
where $k_i$ is the number of the conjugacy classes of size $i=p,q$.  Now,  there are exactly $k_qq$ elements of order $p$ (they are the ones in the conjugacy classes of size $q$). Since each subgroup of order $p$ contributes $p-1$ elements of order $p$, and two subgroups of order $p$ intersect trivially, then $k_qq=m(p-1)$ for some positive integer $m$ such that $q\mid m$ (because $q\nmid p-1$).
Therefore, $(1)$ yields:
$$pq=1+k_pp+m'q(p-1) \tag 2$$
for some positive integer $m'(=m/q)$; but then $q\mid 1+k_pp$, namely $1+k_pp=nq$ for some positive integer $n$, which replaced in $(2)$ yields:
$$p=n+m'(p-1) \tag 3$$
In order for $m'$ to be a positive integer, it must be $n=1$ (which in turn implies $m'=1$ and hence $m=q$, whence $\bf k_q=p-1$). So, $1+k_pp=q$, whence $\bf k_p=\frac{q-1}{p}$. Therefore:
\begin{alignat}{1}
\#(G/\sim_{conj}) &= 1+k_p+k_q \\
&= 1+\frac{q-1}{p}+p-1 \\
&= p+\frac{q-1}{p} \\
\end{alignat}


Does Entity Translation hijack i18n's operations?

Question: I'd ideally like to use i18n to handle backend translation but use entity translation to maintain multiple language versions for each content node.
Does this require a lot of extra work or lead to caveats? I'm hoping they just handle different sides of the translation puzzle.
Answer: It's not that difficult or complicated, you just need to know what to do, where and using what. Have a look at Drupal 7 Multilingual Sites book, it has pretty good explanation of the whole process. Essentially, yes, Entity Translation plus i18n modules would take care of most of the things for you.


Xpath Wildcard (for example: "/Data/Customers/D*")

Question: I am selecting some nodes using XPath, and would like to use wildcards. Is this possible?
Something like the following would be useful:
<code>foreach (XmlNode xml_node in xml_document.SelectNodes("/Data/Customers/D*"))
{
   //
}
</code>
Answer: Try this:
<code>/Data/Customers/*[starts-with(name(.), "D")]
</code>


How can I get and stay in shape to play 2-hour gigs on the trumpet?

Question: Do I have to play 2-3 hours every day to make sure I can do this, or is there a way to do something like "weight lifting" for the trumpet?
I'm self taught, and stamina is an issue. I know technique has a huge role in stamina, and I'm working on this as well, but so does muscle development.
I guess my question is, just like running sprints for 20 minutes regularly can help you play a 90 minute soccer game, is there some equivalent for brass, that doesn't actually require me to play the same length of the gig I need to play every day?
Sorry for the strange question or if this is obvious and I just don't see it. My first thought is lip slurs, I guess, but just wanting feedback from experienced musicians about what they've found actually works for them.
I just played a 2-hr gig and at 1.5 hrs I was pretty blubbery. Boo. At least I had a snare drum to play on and a clarinetist who was willing to take more on...,
Comment: I haven't played the trumpet in decades so I'm probably not qualified to give a full answer, but when I did, I remember one thing that helped was keeping just the mouthpiece with me at all times, just to practice armature and strengthen facial muscles if I wasn't going to be able to do a full practice.  (Obviously, even with just the mouthpiece, the noise can be annoying to people around you, so best to do this only when you're alone.)
Comment: I can't answer better than others have, and I struggle with this myself most of the time, but when I was playing a lot and did have that kind of endurance, I found the most helpful book to be Max Schlossberg's *Daily Drills and Technical Studies*. There are some real killers in there, helpful also for building range. That, and H. L Clarke's *Technical Studies for the Cornet* - great stuff to practice for endurance and has a side effect of promoting fluency across keys.
Comment: I never played trumpet; only trombone, and I hope you agree there's no real difference here.

Either way, are you suggesting two hours of playing a trumpet without rest?
Comment: As you're transitioning, can you find a buddy to do a sort of a job share with you?
Answer: I struggled with endurance for many years, thinking I could not gig because of it. However, my clear experience was that my endurance (and range) improved once I was rehearsing and gigging regularly, and practice outside of the gigs was just for maintenance, not requiring extraordinary amounts of time.
The essential element of improving my endurance were at-least-weekly rehearsals of about two hours. This kept me playing for long periods on a regular enough basis that I could play two or three three-hour gigs with reasonable confidence.
If rehearsals and/or gigs aren't happening at least weekly, then I suggest one weekly practice session of two 45-minute segments with 15 minutes in between. This is roughly equivalent to a two-set gig or rehearsal and should be enough to keep your endurance up. Make the next day a rest/recovery day, then for the rest of the week just do normal practice, whatever that is for you.
Comment: +1 I think this can apply to many instrument types - personally, I struggle equally on bass [because of an old carpal tunnel injury] & vocals [because it's vocals;). By the time you're gigging regularly, you've done the heavy lifting. It's the one gig every 6 months that's tough.
Answer: My suggestion has two parts:

Practice every day. Even if it is only a short time, every day is the recipe. 15 minutes seems to be a good starting point (set the egg timer).

Do the most effective practice. Generally playing long sustained tones. In my experience shift between very high tones and very low tones. High tones for muscle training, low (= below the staff) for learning how to relax. Aim for very little or almost no pressure on the mouthpiece, it is the muscles that should work. Best is to play with a tuner and start pppp slowly increasing the same tone to ffff and then slowly going down to pppp again, all on the same breath.
Comment: I agree with this advice and was also going to suggest long tones. They do wonders for your tone quality on the trumpet. And Contrary to @BrianTHOMAS I actually have found great results by playing long tones into a tuner. The goal is to train the ability to modulate the pitch where you want it. Training your ear is important too, but that is a separate skill, and you will train your ear watching the tuner as well. Also a lot of tuners have tone generators which would be useful for training your ear (e.g. play a long tone at a constant interval above the generated tone)
Comment: I don't think it's good advice to "play with a tuner", because tuning should rely on your **ears** not your **eyes**.
Answer: I'd suggest dividing your practice session into 10-minute sessions, so you have recovery time in-between, but in each 10-minute slot you spend as much time with the instrument on your face as you can. I'd avoid just long notes because they don't reflect musically what you'll meet during an actual rehearsal. It's more productive (and tiring) to play lots of repeated notes at the same pitch instead.
Exercises like this are useful - each repeat is a semitone higher than its predecessor. Continue until you can comfortably progress until you've climbed an octave.

I play in a UK brass band - we have two 2 hour practices a week, and on every other day of the week I play at least 30 minutes. One of the stamina exercises we do as a band is turn to our red hymn books (every band has them) and play hymns one after another for 20 minutes solid. Exhausting, but rewarding. Also playing hours of carols at Christmas is good for building stamina.
Finally, on gig day, warm up for 20 minutes in the morning, playing gentle stuff - nothing too high. You'll find your stamina later in the day is better than you'd expect.
Comment: How much time are you suggesting between the 10 minute practice sessions?
Comment: @pixelearth - whatever you're comfortable with. There's no definitive rule. But splitting up your daily practice sessions mean you can play in intensive bursts.
Answer: I believe both existing answers are very good, but seeing this question I was immediately reminded of the book "Fitness for Brass" by Frits Damrow (Amazon | Scribd).
I don't have experience using it myself (it's not really aimed at horn players), but I've seen it being used by good amateur trumpetists I know.
Perhaps it can serve as a supplement to the other, more practical advices.
For horn players happening across this, try "Thoughts on Playing the Horn Well" by Frøydis Ree Wekre (Amazon | Scribd)! I see now this also happens to be recommended for trumpetists. It's not as focused on endurance though.
Comment: Sounds like a great book, but it's only with a free trial, meaning you have to give them your credit card and remember to cancel.
Comment: Ah sorry. I'll edit.


How to use YAML.load with handlers

Question: irb(main):001:0> a="run: yes"
 => "run: yes"
 irb(main):002:0> require 'yaml'
 => true
 irb(main):003:0> YAML.load a
 => {"run"=>true}
 irb(main):004:0> YAML.load(a, handlers => {'bool#yes' = identity})
 SyntaxError: (irb):4: syntax error, unexpected '=', expecting =>
 YAML.load(a, handlers => {'bool#yes' = identity})
                                      ^
    from /usr/bin/irb:11:in `

I want the yaml val is yes and i google find the handler will help.
But seems i do not use correct syntax.
I try to search related docs but fail.
Answer: The problems with the listed code are

that handlers isn't defined anywhere, you likely wanted :handlers
that identity isn't defined anywhere, maybe wanted :identity that
you are missing a > on your hash rocket (=>).

So to get this code to run it should (likely) look like
YAML.load("run: yes", :handlers => {'bool#yes' => :identity})

However, so far as I know the second parameter to YAML.load is a filename.
If you are able to change the input YAML, simply quoting the value "yes" will cause it come through as a string
YAML.load("a: 'yes'")
# => {"a"=>"yes"}

If you require the un-quoted string 'yes' in the YAML to be treated as 'yes', not true in ruby after parsing. I cobbled this together (with help from this question), using Psych::Handler and Pysch::Parser. Though I'm not sure if there's another easier/better way to do this without having to hack this all together like this.
require 'yaml'

class MyHandler < Psych::Handlers::DocumentStream
  def scalar(value, anchor, tag, plain, quoted, style)
    if value == 'yes'
      super(value, anchor, tag, plain, true, style)
    else
      super(value, anchor, tag, plain, quoted, style)
    end
  end
end

def my_parse(yaml)
  parser = Psych::Parser.new(MyHandler.new{|node| return node})
  parser.parse yaml

  false
end

my_parse("a: yes").to_ruby
# => {"a"=>"yes"}
my_parse("a: 'yes'").to_ruby
# => {"a"=>"yes"}
my_parse("a: no").to_ruby
# => {"a"=>false}

Sidenote in the console (and the source):
YAML
# => Psych

How to use YAML.load with handlers


Google Apps Script Html Service and Internet Explorer error "This content cannot be displayed in a frame"

Question: I am finally getting my Google script to work. It works fine in Chrome. I am using htmlservice.createHtmlOutputFromFile and the site is obviously hosted on google sites.
But when I try the page in IE, I get
This content cannot be displayed in a frame
To help protect the security of information you enter into this website, the publisher     of      this content does not allow it to be displayed in a frame.

I tried adding in head tag
meta http-equiv="X-Frame-Options" content="allow"

but it made no difference.
Is there a javascript trick or a GAS library function I can use to try to get  this to work cross browser?
Answer: Maybe your problem is related to cross domain cookies.
Check this answer maybe will work to you.


I can compile GeoIP support into uWSGI or Nginx. What's the difference?

Question: I'm running uWSGI with PHP and Python support through Nginx. All of this is compiled from source. I want GeoIP support.
Both Nginx and uWSGI can be compiled with their own GeoIP plugins/modules. Are there any practical differences between the two I should be aware of in terms of performance or resource usage? The uWSGI docs say using the GeoIP plugin can increase memory usage by upwards of 40mb.
If I compile GeoIP support into uWSGI I'm assuming I wouldn't need to use the uwsgi_param lines in my nginx config? This sounds more efficient to me, but I'm not sure.
Comment: First, you need to know _why_ you want GeoIP support. Then it should be obvious whether to use it in nginx, or your application, or both.
Comment: Mainly analytics. Now that I think about it though, it could be valuable in the future to block countries which would make it valuable at the Nginx level.
Comment: I don't think you want to do any significant _programming_, such as developing an analytics feature, in nginx's configuration file. And blocking countries is much more efficient when done by nginx instead of your application. See?
Answer: there is no need to compile something. Always use packages, please.
GeoIP module appeared in nginx version 0.7.63 and 0.8.6.
and of course give to Nginx this job.
Comment: What? There are absolutely reasons to compile things. Telling people to "always use packages" is ignorant of use cases that are not your own. Compiling is extremely simple to do for even novice admins and for Nginx very fast.


CORS Error happens in api-key request in react js

Question: I want to get api_kye and I use moqui framework in backend , use axios in react js project :
<code>     axios.get(SERVER_URL + '/rest/api_key', {
        headers: {
            Authorization: "Basic " + btoa(username + ":" + password) ,
            'Content-Type' : 'application/x-www-form-urlencoded' ,
        },
    }).then(response => {})
</code>
then , when requested the below error happened :
Access to XMLHttpRequest at '...' from origin '...' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value '...' that is not equal to the supplied origin.
Comment: well, what is the origin of your request? and which origin is allowed? Those two values have to be exactly the same. Or you allow all origins
Comment: Well your server doesn't specify your current domain as "allowed". Are you doing this from localhost? do you have control over the server?
Comment: This error happens when requested url and the window url has different origin. Plese check if both are same. For details https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy
Comment: Do you understand CORS? Based on the error message, it is enabled on your backend but misconfigured. Add your backend's CORS config to your question.
Comment: yes , there is no problem , I can send request in my localhost without any problem , and see my error and understand that the address that exist in from origin part of error not same to header has a value address of error they are different just in one "/"
Comment: So your allowed origin header contains a trailing `/`? Something like `https://example.com/`? If yes, remove that slash ... The value in the `Origin` header and the value in the `Allowed-Origin` header have to be ***exactly the same***  (or `Allowed-Origin` can also be `*` which will allow *all*  origins)
Comment: thanks ,  I corrected  the origin but now 401 (Origin not allowed) happens
Answer: This is not a reactJS error, this is a problem with your backend code, you need to look at the Moqui docs to see how you can allow the origin you are calling from to access your API
Answer: Enable CORS in the server side
Let's head back to our server's app.js file.
<code>app.get('/cors', (req, res) => {
    res.set('Access-Control-Allow-Origin', '*');
    res.send({ "msg": "This has CORS enabled " })
});
</code>
Also check the redirect URL in server side
Refer this link
Comment: IF you control the server.
Comment: If you look at the error message, you will see, that CORS obviously is already enabed on the server (though seemlingly allowing a wrong origin). Furthermore, this piece of code enables CORS exactly for that one call.
Answer: when ever you send an HTTP request to an API the server response should include your domain in response header otherwise chrome will raise this error: "Access to XMLhttprequest has blocked for origin ...."
so first of all make sure that your domain is included in server code.
if it's included already then the reason could be that server can't process your response correctly. maybe it crashed so the response is corrupted and chrome can't find your domain in response header and it raises that error
Answer: So i have a solution for this but you may or may not be able to build it.
CORS is a security feature, you should be receiving requests thru your backend and not the browser directly in general...
IF the data is not sensitive and you want to open an endpoint to the world without getting CORS errors you can do one of two things

Set the CORS headers from the server side. You'll need to understand HTTP requests and headers. you set these from the server. enabling cross origin with * will work.

Build a proxy. I've done this in AWS API gateway, I'll link another post. works good. basically AWS will act as your back end and take the response with CORS blocked. you will then proxy the request and strip the CORS header. When you call the api you will actually call AWS which calls the API, then AWS will pass the response back to you with CORS enabled.

Angular No 'Access-Control-Allow-Origin'
just follow these steps and it will work.
Comment: If you look at the error message, you will see, that CORS obviously is already enabed on the server (though seemlingly allowing a wrong origin).


Is it true that the polynomial $x^5 + x + 1$ has all its simple roots?

Question: I know that $a$ is root of $p$ iff $p(a)=p'(a)=0$
$p(x)= x^5 + x + 1$
$p'(x)= 5x^4 + 1$ then $p'(a)=0$ iff $5a^4 + 1 = 0$ iff $a^4=-1/5$
Now, $p(a)= a^5 + a + 1 = a. a^4 + a + 1 = (-1/5) a + a + 1 = (4/5) a + 1 = 0$
then, $a = 1 - 5/4$ so $a = -1/4$. But $(-1/4)^4  ≠ -1/5$ so there is no solution. So $p$ does not have multiple roots.
So $p$ has all its simple roots.
Is my exercise resolution correct? Are the steps well explained and justified?
Comment: Where'd the $a^4$ go?
Comment: I suppose you mean $a$ is a *multiple* root if and only if …
Comment: From $(4/5)a+1=0$ you should get $a=-5/4$, not $a=-1/4$. But your reasoning is otherwise correct, since $(-5/4)^4\not=-1/5$ either.
Comment: "... then $a=1-5/4$" is not correct.
Comment: @BadrB I  wrote badly that step. The correct is $a^4=-1/5$. I corrected it.
Comment: @BarryCipra You're right. I already correct it. Thank you very much!
Comment: @Ayesca, you corrected "$a=-1/5$" to "$a^4=-1/5$" early in your proof. This is a second mistake, toward the end. Both mistakes are minor, but both warrant correction.
Answer: Consider $f(x)=x^5+x+1$ and $f'(x)=5x^4+1$ like you said. Since $f'(x)$ is always positive, we can conclude that $f(x)$ is always increasing. This means that the function only crosses the x-axis once (since $f(x)$ is of odd degree). Therefore we can conclude that $f(x)$ has only one real root, and since the function is always increasing, it must be a simple root.
Comment: The OP wants to show that *all* the roots are simple, not just the real roots.
Comment: @BarryCipra Ohh I see. Thanks for the pointing that out.
Answer: You made a minor mistake when you wrote that $5a^4+1=0\iff a=-1/5$. You should have written $a^4=-1/5$ instead.
The rest is correct, assuming that you are working over a field with characteristic $0$.
Comment: @Ayesca I'm glad I could help.
Comment: You're right, I wrote badly that step. Thank you very much, I corrected it.
Comment: @JoséCarlosSantos, you overlooked a second minor error. See my comment below the OP.
Comment: @BarryCipra You're right: I missed that.


Tell whether $\dfrac{10^{91}-1}{9}$ is prime or not?

Question: I really have no idea how to start. The only theorem considering prime numbers I know of is Fermat's little theorem and maybe its related with binomial theorem.
Any help will be appreciated.
Comment: http://math.stackexchange.com/questions/300805/when-is-the-number-11111-1-a-prime-number
Answer: Just think through the actual number.
$10^{91}$ is a $1$ with $91$ $0$'s after it.
$10^{91}-1$ is therefore $91$ $9$'s in a row.
$\frac{10^{91}-1}{9}$ is therefore $91$ $1$'s in a row.
Due to the form of this number, $x$ $1$'s in a row will divide it, where $x$ is a divisor of $91$.
For example $1111111$ is a divisor, so is $1111111111111$.
Hence the number is not prime.
Comment: Cute.  Very pretty indeed. +1!
Comment: Really, you're not thinking of it in terms of "the actual number" here; you're thinking of it in terms of the decimal representation. The decimal representation isn't any more "the actual number" than the expression $\frac{10^{91}-1}{9}$, and this argument wouldn't work in hexadecimal. Still, upvoted.
Comment: no, 91 9's. Try taking some simpler examples, e.g. $10^3-1=1000-1=999$
Comment: Perhaps knowing too much theorems reduces your strike rate of easier problems. :D
Comment: Yep, poor wording but that's what I meant by thinking of the actual number. A lot of the time the initial reaction (mine too) is big, scary, clearly I'm just supposed to just throw a theorem at it. Sometimes things aren't as bad as they seem though :)
Comment: Great solution but i guess it should be 90 9's instead of 91 , elegant solution though
Comment: No 91 1s is not prime it has many divisors But it is not divisible by 7 1s or 13 1s,
Answer: Hint: Note that $91=7\cdot 13$, so the numerator is divisible by $10^7-1$.
If this is not obvious, it may be clearer if we let $x=10^7$. Then $10^{91}=x^{13}$, and it is a familiar fact that $x-1$ divides $x^n-1$ for any positive integer $n$.
Comment: Critical hit. Thanks.
Comment: You are welcome. There is a little more to write to finish the argument, but it should not be difficult.
Comment: So the number is divisible by $1111111$. ($7$ times) Right?
Comment: That;s right, $\frac{10^7-1}{9}$ is an integer, it is a divisor of our number, and it is obviously not equal to $1$ or $\frac{10^{91}-1}{9}$.
Answer: Using Why $a^n - b^n$ is divisible by $a-b$?,
$$a^{91}-1=(a^{13})^7-1^7$$ is divisible by $a^{13}-1$ and by similarly by $a^7-1$
Again, using Prove that $\gcd(a^n - 1, a^m - 1) = a^{\gcd(n, m)} - 1$,
$$(a^7-1,a^{13}-1)=a^{(7,13)}-1=a-1$$
Hence, $\displaystyle\frac{a^{13}-1}{a-1}, \frac{a^7-1}{a-1}$ are co-prime primes and divisors of $\displaystyle\frac{a^{91}-1}{a-1}$
Answer: You have
$$111111....1=1+10+10^2.....+10^{90}=(10^{84}+10^{77}+10^70.....+10^7+1) (10^6+10^5+10^4+ \dots + 10^0);$$
this is product of two integers 2 or greater,  so it is not prime.
Comment: If you could explain how you found those two factors, that would be great.


What is this chord called that looks similar to power chords?

Question: While watching to some guitar covers I found this chord that looks similar to a power chord. In the cover the guitarist played it on the second and fourth fret. It looks like this:

Images generated with chordgenerator.
I want to know how this chord is called. I also want to know how the system behind is working so I am able to write tabs myself with it. It looks like it has a similar system like the power chords with the root note. Where could I place this chord so it sounds good?
Furthermore, is it possible to play this with three notes like a "big powerchord". With big power chord I mean like in this sequence:
<code>|-------------------|
|-------------------|
|-------3-------6---|
|---3---3---6---6---|
|---3---1---6---4---|
|---1-------4-------|
</code>
Comment: This is still a powerchord. There are many kinds. The common ones are a fifth, but many bands use all manner of powerchords - just listen to Faith No More for a wide variety.
Comment: As to your three note question, that should work fine because the highest note is just an octave of the lowest so the interval relationships are essentially the same. But the power chords you tabbed are just standard 5 chords. To get them closer to the original chords you mentioned it would be 1-4-3 and 4-7-6 (on E-A-D or A-D-G strings respectively).
Answer: This is an interval of a minor sixth. Nameable chords usually need three notes in order to define them. A single interval can be a component of a number of chords. So, for this reason the naming of this chord would depend upon harmonic context; in other words, which other notes, if any, sound with it.
However, the interval of a minor sixth is commonly perceived as the first inversion of a major chord, without a fifth. So, in this case, this would be a first inversion E Major chord without the fifth, having a G# at the bottom, an E above, and no B.
Comment: minor 6th = inverted major 3rd.
Comment: Yes @Tim, that is a *much* more succinct way of putting it!!
Comment: +1 to Bob and Tim. The one place I'm sure it's used, and used as a chord's third below the root, is the intro to "Highway to Hell" by AC/DC.
Comment: I always associate it with *One Vision* by Queen...
Comment: @BobBroadley Thank you for your help! Could you please take a look at my question? I have edited it a little bit to refer to more questions that are connected with this.
Comment: I would also like to add that if this were to be called an E major, that referring to it as first inversion (or E/G#) would somewhat depend on the other instruments.  If the bass is playing an E, then one would not analyze the chord as E/G#, it would just be E major.  However, you could still refer to this shape as it applies to guitar as E/G# but you need to be aware of what the bass player is supposed to do if you are writing up a chart or a formal analysis.
Comment: @Basstickler - an inversion is relevant to the instrument it's played on. That is an E/G#, or 1st inv. Other instruments could be playing all sorts, and the bass could play whatever note - that chord on that guitar is still 1st inv. To get the bass to play it would need to be written specifically for bass, although if I saw that written, I might well play a G# on bass at that point.
Comment: @Tim - That's my point actually.  If you were writing a chart for the whole band, that chord symbol would dictate that the bass play a G#.  Also, if you were analyzing the piece, not specific to guitar, then the bass part would dictate the inversion.  If any of this is exclusively specific to the guitar part, then the symbol E/G# would be perfectly appropriate.  It just depends who the chart is for really.


How To Remove Menu Tabs From Custom User Dashboard

Question: I'm working on creating some custom user dashboards but cannot seem to find how to remove certain menu items. I intend to use a combination primarily of Panels with Context and Views (but I haven't ruled out simply using Homebox) but at this early stage learning D7 I've created a custom Variant in the system Panels template, created a rule set in the Variant which will set each user dashboard to load based on their subscription (Ubercart Role). Because of the nature of the Roles, different DBs are required.
As you can see in the attached screenshot, the menu tabs are showing left to right (View, Affiliate Center, Bookmarks etc), I've tried going through all the backend and cannot for the life of me find what controls them to show, could somebody please tell me what causes them to show, so I can either 'hack it' or delete it.
I know it maybe a theme influence and for my current testing I'm using Bartik, but I intend to use an HTML5 theme based on either AT Theme or Boilerplate, but haven't got to that stage as yet (or that maybe my next 'hack' learning lesson today!). Ultimately, I intend to use a Less framework, but for now I merely want to get the functionality working BEFORE I do CSS.
So, what's influencing the menus in my basic User DB as shown here?
https://dl.dropbox.com/u/55172207/screen_shot_cp.png
Thanks in advance to anyone for the help.
Answer: You can do that from your theme's template.php file by implementing the theme_menu_local_task().
Using this function you can also rename specific tabs.
Code for both actions is below.
It is taken from this file of our Ultima theme.
<?php

/**
 * @file
 * Theme local task function.
 *
 * Created by: Topsitemakers
 * http://www.topsitemakers.com/
 */

/**
 * Implements theme_menu_local_task().
 */
function YOURTHEME_menu_local_task(&$vars) {

  $link = $vars['element']['#link'];

  // List of tab names to be excluded; t() function will ensure that the
  // tab name will be matched and excluded on multilingual sites as well.
  // This is useful in case you have many modules installed on the site and
  // large number of tabs break the layout of the theme.
  $excluded_links = array(
    t('View'),
  );
  if (in_array($link['title'], $excluded_links)) {
    // Skip all further processing.
    return;
  }

  // Uncomment code below to rename the "View" tab for certain node types
  /*
  // Check if the link title is "View"
  if ($link['title'] == t('View')) {
    // Make sure we are on single node page
    if (arg(0) == 'node' && arg(1)) {
      $node = node_load(arg(1));
      // Do this for specific content types
      if ($node->type == 'page') {
        $link['title'] = t('View full page');
      }
    }
  }
  */

  // Continue building the local task link
  $link_text = $link['title'];

  if (!empty($vars['element']['#active'])) {
    // Add text to indicate active tab for non-visual users.
    $active = '' . t('(active tab)') . '';

    // If the link does not contain HTML already, check_plain() it now.
    // After we set 'html'=TRUE the link will not be sanitized by l().
    if (empty($link['localized_options']['html'])) {
      $link['title'] = check_plain($link['title']);
    }
    $link['localized_options']['html'] = TRUE;
    $link_text = t('!local-task-title!active', array('!local-task-title' => $link['title'], '!active' => $active));
  }

  return '
' . l($link_text, $link['href'], $link['localized_options']) . "
\n";

}

Comment: Thanks Topsitemakers! I'll check that out and feedback later today.
Answer: I solved this by removing the $vars ['tabs'] by commented out // in my template.php file (as seen below). This appears to solve my problem of Tabs appearing. I'm not sure it's correct, but it seems to have solved my issue. FYI, I was using a Bootstrap theme.
// Provide additional variables to theme.
  $vars['brand'] = theme('brand', array(
    'name' => $vars['site_name'],
    'href' => $vars['front_page'],
    'logo' => $vars['logo'],
  ));
  $vars['preface'] = theme('preface', array(
        'breadcrumb' => $vars['breadcrumb'],
        'title_prefix' => $vars['title_prefix'],
        'title' => $vars['title'],
        'title_suffix' => $vars['title_suffix'],
        'messages' => $vars['messages'],
        'help' => $page['help'],
    'actions' => $vars['action_links'],
  ));
// remove Tabs from var above
//   'tabs' => $vars['tabs'],


Adding a new pot to my guitar

Question: I am willing to add another tone potentiometer to my guitar and I wanted to know what is the best way to add a hole in the pickguard for the new pot.
Is there a dedicated tool for this task? What is the best and safest way to achieve this?
Answer: Your simplest bet is just to use a drill bit suitable for plastics (assuming it is a plastic pick guard)
I would probably use a small bit first, then one with the correct diameter for your pot, or better yet, something like this, which gives you the best of both worlds.

This is the Armeg WWB10.0T Wood Beaver Drill 10mm

Adding a new pot to my guitar


Partial expectation with indicator function

Question: I'm having trouble with proving the following problem, I think partial expectation should be used to solve this but can't figure it out.
Show that:
$E[X \cdot I(X\leq x)] = e^{\mu + \frac{1}{2}\sigma^{2}} \Phi(\frac{ln(x)-\mu-\sigma^{2}}{\sigma})$
where $I$ is the indicator function and $X$ is log-normal distributed with parameter $\mu$ and $\sigma$, i.e. $X \sim LN(\mu, \sigma^{2})$.
Appreciate if I can get some help with this and hopefully this is sufficient information but comment if you guys need more.
Answer: For $Y=log X\sim N(\mu,\sigma^2)$ and $x>0$,
$$E[X\cdot I(X\leq x)]=E[e^Y\cdot I(e^Y\leq x)]=E[e^Y\cdot I(Y\leq \log x)]=
\int_{-\infty}^{\log x} e^y \dfrac{1}{\sigma\sqrt{2\pi}}e^{-\frac{(y-\mu)^2}{2\sigma^2}}\ dy=\int_{-\infty}^{\log x} \dfrac{1}{\sigma\sqrt{2\pi}}e^{-\frac{(y-\mu)^2-2y\sigma^2}{2\sigma^2}}\ dy$$
Next completing the square in $(y-\mu)^2-2y\sigma^2=(y-(\mu+\sigma^2))^2-2\mu\sigma^2-\sigma^4$ and put it back into the exponent in the above integral. The answer will follow.
Comment: So the indicator inside the expectation tell us the bounds in which we integrate along? Is it wrong to think of the indicator inside the expectation as a random variable multiplying the $e^{Y}$
Comment: It is a random variable multiplying by $e^Y$, but this r.v. is a function of $Y$, and it is equal to either $0$ or $1$:
$$E[e^Y\cdot I(Y\leq \log x)]=E[g(Y)] = \int_{-\infty}^{\infty} g(y)f_Y(y)\,dy = \int_{-\infty}^{\infty} e^y\cdot I(y\leq \log x) f_Y(y)\,dy = \int_{-\infty}^{\log x} e^y f_Y(y)\,dy$$
Comment: @WillHunting After you ask a question here, if you get an acceptable answer, you can "accept" the answer by clicking the check mark ✓ next to it. This scores points for you and for the person who answered your question. You can find out more about accepting answers here: [How do I accept an answer?](http://meta.math.stackexchange.com/questions/3286/), [Why should we accept answers?](http://meta.math.stackexchange.com/questions/3399/).


Mercury not sending emails

Question: I have a Mercury SMTP server running on localhost (announcing as 127.0.0.1) right now.
Unfortunately, I am unable to send emails from it to GMail.
I tested sending an email to myself using localhost and PHP, and viewed the result in Outlook.
I received both an email and an error message that the email could not be sent.
In Mercury, the only settings I have changed are add the working user to the user-list and set up the SMTP server to announce as 127.0.0.1 (My from is set to @127.0.0.1). Port is 25.
I'm using SwiftMailer to connect (and I know the code works because I could connect to my GMail account).
When I paste the errors with
<code>if (!$mailer->send($message, $failures))
        {
          echo "Failures:";
          print_r($failures);
        }
</code>
I get something like Failures:Array( [0]=>'@gmail.com')
What could be the issue? Thanks!
Answer: Got the answer, I had to change SMTP settings to allow outgoing mails.
Here is where I got the answer for anyone else having the same problem

Mercury not sending emails


Drupal installed as composer package, Custom themes/modules folder

Question: I want a folder structure similar to:
<code>-web
--app
---themes
---modules
--core
</code>
In composer I can specify installer paths to put required modules in the /web/app/modules directory and install drupal core in the /web/core.
Can I get Drupal to look for themes and modules in the /web/app/themes and /web/apps/modules directories so I don't have to put anything custom inside the core directory (so Drupal core can be installed as a package and not stored in my git repo).
I've seen similar set ups with Wordpress allowing you to specify a 'CONTENT_DIR' constant that means Wordpress will look for wp-content in a different directory. Is there a similar way for Drupal?
I found this on git which achieves something but it requires a custom script https://github.com/davidbarratt/drupal-structure
Answer: Drupals extensions discovery looks only in some specific folders (see http://cgit.drupalcode.org/drupal/tree/modules/README.txt for more information).
But, you don't have to put your own modules inside of the core folder. You should use /modules instead.
The Drupals default directory is not ideal for a development workflow with composer in mind. Take a look at https://github.com/drupal-composer/drupal-project if you have not already.


Can I inject javascript code from the address bar into a flash video

Question: With regular HTML it's possible to change the look of the page and  make new cookies using javascript simply by typing it into the address bar and hitting Enter on keyboard.But what about flash videos.Is there a way to preform some action on the video on the page using javascript in the address bar?
Comment: Thank you both.But my question was can users access flash content through the javascript in broswer and if they can how to stop them?
Comment: What do you mean by flash content? JavaScript can manipulate the DOM so if you mean the `` HTML tag that holds the Flash plugin, than yes JS injection can be used to fiddle with that. And no, you probably cannot prevent that.
Comment: I mean this,there is an api to control the page and javascript from flash,but is there a way that an user can just type som js code in the address bar and mess the .swf file?
Comment: That's up to browser security, it shouldn't concern you directly unless it's server side related. Even if that is not possible, a user can inject JavaScript directly in your files, he doesn't have to bother to write in the URL bar. FireBug for Firefox allows you to run JavaScript code on a loaded site. Opera Dragonfly the same. There are others as well.
Comment: They cannot mess with the code inside the SWF file directly unless you are listening for JS callbacks inside your AS code and not sanitizing input properly (if the case).
Comment: Ok thank you that was the answer I was looking for.
Comment: I've updated the answer as well.
Answer: Unless I have misunderstood your question, I would advise that the last thing you would want to do is allow Javascript entered into your address bar to have any control over your page content.
Doing so allows users to abuse your pages and is also a security threat.
If you can avoid passing Javascript via the address bar, it is entirely possible for Javascript to 'control' flash objects on the page. Check this out:
http://livedocs.adobe.com/flex/3/langref/flash/external/ExternalInterface.html
And also this thread too:
Controlling a Flash Player using JavaScript
Comment: +1 voluntarily giving users access to running js from a url is just asking, nay, *pleading* for bad things to happen.
Comment: ...Users can already execute arbitrary javascript. If your flash application communicates with javascript, the client can make arbitrary commands against it. There's no preventing that.
Comment: This and the first comment are miss leading, it's always possible for the client to execute arbitrary JavaScript. It's client side code, the client has free rain on it and can manipulate it however they like. The only point were it becomes a security issue is if you store client JavaScript code on the server and then output it somewhere, this can lead to cookie theft, it's for this reason things like hotmail filter out script code. And as a note, you should never except any data from the client without sanitizing it. Don't assume the client JavaScript code you wrote will be used as intended.
Answer: You don't need that.
AS3 has the ExternalInterface class that deals with calling JavaScript functions from Flash.
You can both call JavaScript functions and get results returned by JavaScript functions directly from Flash.
All you need is read this:
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/external/ExternalInterface.html
Added after comments:
User is asking if JavaScript placed in address bar can "mess with swf" file.
JavaScript can only mess with SWF execution of its AS code if it contains callbacks that get data from JavaScript which are not properly sanitized.
JavaScript directly in address bar is less of a wary because using various addons, software etc (Firebug, Dragonfly) you can write as much JavaScript as you want and execute it as if it was part of that site (client side execution).


Isomorphic groups algebras with non-isomorphic groups

Question: There is an interesting result of Dade about isomorphism of group algebras:

There exists finite non-isomorphic metabelian groups $G$ and $H$ whose group algebras over any field are isomorphic.

I was looking for the examples of these groups, but I didn't find them; only the result is stated in most of the books or slides online. So, I have one obvious question and one modification of it.
Question 1. What are the (counterexamples) groups constructed by Dade?
Question 2. Is the example by Dade, the smallest order example?
Answer: You can find Dade's original paper at http://link.springer.com/article/10.1007/BF01109886.
He gives a construction of pairs of groups of order $p^3q^3$ for arbitrary primes $p,q$ with $q\equiv 1\pmod{p^2}$, so his smallest examples would be of order $1000$ ($p=2$ and $q=5$).
I've no idea whether smaller examples are possible using a different construction.


Elementary Question Regarding 2-adic Valuation

Question: What exactly is the 2-adic evaluation of an integer?  Is it related to modular arithmetic?
For example, how exactly does the definition of the ruler function work?
Comment: Have you read the Wikipedia article? http://en.wikipedia.org/wiki/P-adic_number
Comment: Is this what you are referring to or something else? http://ac.els-cdn.com/S0097316508000459/1-s2.0-S0097316508000459-main.pdf?_tid=0abd7352-e378-11e2-a2af-00000aacb360&acdnat=1372811729_126e90d6b8f17aa1201808ba4d3d422f
Comment: Precisely, although perhaps at a simplified level.
Comment: Yes, I was just hoping someone might be able to help explain it more clearly with respect to the ruler function.
Answer: The 2-adic valuation of a number is the largest number of times you can divide it by 2 and still get an integer. In other words, it is the exponent of the 2 in the prime factorization of the number.


If $z=i^{2i}$ then $|z| =?$

Question: I am given a complex number $z=i^{2i}$ so what would be $|z|$?
Firstly I took $\log$
$$
\log(z)=2i\log i\\
$$
thus
$$
\log(z)=2i\log(e^{-π/2}) = -i\pi;
$$
then inverting the log
$$
z=e^{ -i\pi}
$$
implying
$$ |z| =1.$$
Is this correct?
Comment: $|z|=1$ and follows directly... if you insert absolute value on both sides
Comment: how do you prove if $z=e^{-i\pi}$ then $|z|=1$?
Comment: Oops it looks like my Euler conversion is wrong
Comment: @JonMarkPerry $z=\cos (-\pi) -\sin(-\pi) $ and the result follows that $|z|=1$.
Comment: $i=e^{-i\pi/2}$? (square it you get $-1$).
Comment: Yes but is result $z=e^-π$ correct ? Is this method valid?
Comment: @Tesla: the most reliable way to figure out these kinds of problems is to go back to the definition $z^w = \exp(w\log(z))$ and work from there, as in several answers below.
Answer: All of the values of $i^{2i}$ are real. The possible values are
 $$i^{2i} = e^{2i\cdot\log i}=e^{2i\cdot(\frac{\pi}{2}i+2k\pi i)}
=e^{-\pi -4k\pi}=e^{-(4k+1)\pi}
$$
which are all positive, so they are all possible values of $|z|$.
Note that none of these is $1$.
Answer: Remember:

By definition, $i^{2i} = \exp(2i \cdot \log(i))$.
There are infinitely many different possible values of $\log(i)$. Because of the way $\exp(z)$ works, we have $e^{\pi i/2} = i$ and $e^{2\pi i n} = 1$ for all $n \in \mathbb{Z}$. So the values of $\log(i)$ are of the form $\pi i/2 + 2\pi i n = i\pi(1/2 +2n)$ for $n \in \mathbb{Z}$.

The combination of these facts (that complex powers are defined relative to a complex logarithm, and that the complex logarithm in general has more than one possible value) cause complex exponents to behave very differently from real ones (see here for another example: $1^i$ is not always $1$).
In the case at hand, $i^{2i}$, we can choose any integer $n$ in the logarithm of $i$, obtaining
$$
i^{2i} = \exp(2i \cdot \pi i (1/2 + 2n)) = \exp(-2\pi(1/+2n)) = \exp((-1-4n)\pi)
$$
The exponent there is completely real, so the value of the exponential function will match the value of the real exponential function. You can see that there are infinitely many different possible values for $|i^{2i}|$, one for each value of $\log(i)$ (that is, one for each value of $n$).
Comment: I think you have a typo , it should be $e^{\pi i}=-1$.
Comment: @Tolaso: thanks for pointing that out; I have fixed it
Answer: $i=e^{\frac12\pi i}$ so that $$i^{2i}=(e^{\frac12\pi i})^{2i}=e^{\frac12\pi i.2i}=e^{-\pi}$$

edit
This answer is not complete. See the comments of Carl. It only computes the so-called principle value. This by picking the usual logarithm. Be aware of the confusion that can arise here. I was a victim of that myself.
Comment: @CarlMummert I solved it by means of this edit.
Comment: This is only part of the story; see the answer by MPW
Comment: @CarlMummert Yes, I have seen that, and realize that it is indeed not the whole story. I am still wondering though where things go wrong in my answer.
Comment: The issue is that $i$ is also $e^{5\pi i/2}$, $e^{9\pi i /2}$, etc.   This answer finds the principal value by picking the "usual" logarithm.
Comment: @CarlMummert Thank you. Of course you mean $i$ here (not $1$). I will delete this answer within some minutes.
Comment: Yes, thanks. But it would not be bad to just leave a note that this computes the principal value - this is a common point of confusion (e.g. this very question)
Answer: Your first line is not correct, the property $\ln x^a=a\ln x$ is only valid for real numbers.  However it is true that $e^{\ln x^a}=e^{a\ln x}$. So, in the end, your answer is correct.
Comment: @barakmanos No it does not. You have to take into account the branch of the log , since it is a multivalued function. But what does hold is:

$$\log z_1^{z_2} =z_2 \log z_1 + 2\pi i k , \;\; k \in \mathbb{Z}$$
Comment: I'm pretty sure that $\ln x^a=a\ln x$ is also valid for complex numbers.
Comment: Actually it's not. Consider  the branch of $\ln$ for which $-\pi\le\text{arg }z<\pi$. $\ln (e^{3\pi i/4})^2=\ln(-i)=-\frac\pi 2$, but $2\ln e^{3\pi i/4}=\frac{3\pi i}2.$

If $z=i^{2i}$ then $|z| =?$


Convert ARM template in Azure to Gallery Template in Azure

Question: I would like to know how to convert ARM template in Azure to Gallery Template in Azure .I am not able to save the ARM template but able to save the Gallery Template .
Answer:
Azure Resource Manager Templates to be converted as Template specs to store in Gallery.
As per this Microsoft Document here are the steps to convert template manually through Azure portal.

Open the  Templates (preview)  in the portal.
Select the template to migrate.
Select  View Template.
Copy the template content.
In the portal search bar, search for  Template specs. Select that option.
Select  Create template spec.
Provide values for the name, subscription, resource group, location, and version.
Select  Next: Edit template.
For the contents of the template, paste the template you copied from the template gallery.
Select  Review + Create.
After validation successfully completes, select  Create.

And here is the Document for creating Template Spec from ARM.


Counterexample to a weak "definition" of group

Question: Usually, we see a group as the structure $\langle G, \cdot\rangle$, where $G\neq\emptyset$ and the binary operation $\cdot$ is associative and

$\exists e\in G,\,\forall a\in G,\,(a\cdot e=a=e\cdot a)$
$\forall a\in G,\,\exists b\in G,\, (a\cdot b=e=b\cdot a)$

We can use a equivalent version of the definition,  where the operation is associative and

$\exists e\in G,\,\forall a\in G,\, (a\cdot e=a)$
$\forall a\in G,\,\exists b\in G,\, (a\cdot b=e)$

But, I read in Herstein's book that if we consider the operation associative and with the properties

$\exists e\in G,\,\forall a\in G,\,(a\cdot e=a)$
$\forall a\in G,\,\exists b\in G,\,(b\cdot a=e)$,

this is not equivalent to group definition.
My question is: which are examples of structures that satisfies those conditions and are not groups?
Comment: I'm guessing the 5th itemized formula should read $a \cdot e = a$.
Comment: The 5th formula should be corrected.
Comment: Doesn't the first condition imply that $G$ has exactly one element? $e\cdot e=e=a$
Answer: Take any set with at least two elements and define $a * b := a$.
Comment: Or in other words, consider for any set $X$ with two element or more the set of constant functions $X\rightarrow X$ with the composition operation.
Comment: But for any $a$ and $b$ in $G$, there exists an $e$ such that $e\cdot e=a$ and $e\cdot e=b$ so $a=b$ and hence $G$ has exactly one element.
Answer: Assume that a multiplation on $G$ is associative.
If there is a right-identity $e$ with $ae=a$ for each $a$ and each
$a$ has a right-inverse $b$ with $ab=e$ for each $a$
then $G$ equipped with this multiplication is a group.
For a proof look here.
If there is a right-identity $e$ with $ae=a$ for each $a$ and each
$a$ has a left-inverse $b$ with $ba=e$ for each $a$
then $G$ equipped with this multiplication is not necessarily a group.
Let $G$ have exactly $2$ elements $e$ and $a$ and define $ee=e$,
$ea=e$, $ae=a$ and $aa=a$. It is routine to check that this multiplication
is associative. But with this multiplication $G$ is not a group.
Comment: This doesn't satisfy $ae=a$. Switch it.
Comment: @MartinBrandenburg. Done. Thanks.


How do I apply this maximum principle?

Question: I have the maximum principle: $$\text{If } \psi\geq 0 \text{ on }\Gamma. \text{Then }L\psi\geq0\text{ implies }  \psi\geq 0 \text{ in } \bar{D},$$ where $D=(0,1)\times (0,T], \Gamma$ is parabolic boundary. The operator is defined as $$Lu:=-u_{xx}+bu+du_t=f,$$ where $b,d,f$ are functions and $b\geq\beta>0,d\geq\delta>0$. I would like to show that $$||u||\leq(1+\alpha T)\max\{||Lu||,||u||_\Gamma\},$$ where $\alpha=\max\{0,(1-b)/d\}\leq1/\delta$. It is supposed to be an immediate consequence of the Maximum principle but I am stuck.
I have tried to apply the Maximum principle on $$\phi^{\pm}=\max\{||Lu||,||u||_\Gamma\}\pm u$$ but I don't seem to go anywhere.
Comment: What is $\Gamma$?
Comment: You also haven't told us what $u$ satisfies.
Comment: $\Gamma$ is the boundary of box $D$ without the top @par, $Lu=f$ is the differential equation satisfied by $u$.
Answer: The boundary $\Gamma$ is
$$
\Gamma=\{(t,x)\in \{0\}\times (0,1)\}\cup \{(t,x)\in (0,T)\times \{0\}\}\cup
\{(t,x)\in (0,T)\times \{1\}\}.
$$
You consider the problem
$$
-u_{xx}+bu+du_t=f \mbox{ in }(0,1)\times(0,T), \quad u=\phi \mbox{ on } \Gamma.
$$
Consider $v=u+M$. It satisfies
$$
-v_{xx}+bv+dv_t=f+bM \mbox{ in }(0,1)\times(0,T), \quad u=\phi+M \mbox{ on } \Gamma.
$$
Choose $M$ so that $f+bM\geq0$ and $\phi+M\geq0$ and you obtain from the maximum principle you stated that $v\geq0$, in other words
$$
u\geq-M=-\max(\inf(-\phi),\inf(-f/b))\geq -\max(\|\phi\|_\infty,\|\frac{f}{b}\|_\infty).
$$
Symmetrically, consider now the problem satisfied by $-u$, (which means just replacing $f$ and $\phi$ by $-f$ and $-\phi$). By exactly the same argument,
$$
-u\geq -N = - \max(\inf(\phi),\inf(f/b)) \geq -\max(\|\phi\|_\infty,\|\frac{f}{b}\|_\infty)..
$$
so altogether
$$
\|u\|_\infty\leq \max(\|\phi\|_\infty,\|\frac{f}{b}\|_\infty)\leq \max\left(1,\frac{1}{\beta}\right)\max(\|\phi\|_\infty,\|f\|_\infty).
$$
This is not the constant you wanted but your constant is puzzling me. You seem to say
$$
b\leq\beta,d\geq\delta\implies\max(0,\frac{b-1}{d})\leq\delta^{-1},
$$
this is not true in general, take for example $\delta<1$, and $b=\beta=1+\frac{1}{\delta^N}$, you obtain $$\max(0,\frac{b-1}{d})=\delta^{-N-1}>\delta^{-1}.$$
If you want to put some $\delta$ in the formula, you can, before you start, consider the problem satisfied by $\tilde{u}=u\exp(-\lambda t)$. Then, $f$ is changed to $\exp(-\lambda t)f$, $\phi$ is changed to $\exp(-\lambda t)\phi$, and $b$ is changed to $b+\lambda d$. The same argument then applies to $\tilde u$
Then you have instead, as long as $\beta+\lambda \delta >0$,
$$
\|u\|_\infty\leq\exp(\lambda T)\|\tilde{u}\|_\infty\\ \leq \max\left(1,\frac{1}{\beta+\lambda \delta}\right)\exp(\lambda T)\max(\|\exp(-\lambda t)\phi\|_\infty,\|\exp(-\lambda t)f\|_\infty),
$$
so if $f$ and $\phi$ do not depend on time, you obtain, for $\lambda>0$,
$$
\|u\|_\infty\leq\max\left(1,\frac{1}{\beta+\lambda \delta}\right)\exp(\lambda T)\max(\|\phi\|_\infty,\|f\|_\infty),
$$.
(and a worse bound than the direct one if $-\beta/\delta<\lambda<0$).
Comment: why is $-\max(\inf(-\phi),\inf(-f/b))\geq -\max(||\phi||_\infty,||f/b||_\infty)$?
Comment: @Vaolter  $|\phi|\leq \|\phi\|_{\infty}$ (a.e.), so $-\phi \geq -\|\phi\|_{\infty}$ (a.e.) idem for $f$. The max princ only asks for inequalities almost everywhere.

How do I apply this maximum principle?


Finding the tangent line and normal line to a curve

Question: $y = xy^2 + 4y^3 + 3x = 0$ at the point (1,-1)
To start I did the sum rule, separated all the terms, and got their derivatives
Then I expanded and substituted the point in and then used that slope to find the equation of the tangent line in point slope form
First, I was wondering if I did this correctly? Second, what is the slope of the tangent line?
Comment: You have to use implicit differentiation.
Comment: Why isn't the answer accepted?
Answer: Since there are y's on both sides of the equation, you need to use implicit differentiation, which essentially just boils down to treating y as a second variable and realizing that the derivative of y is $\frac{dy}{dx}$ not $\frac{dx}{dx} = 1$ like the derivative of x
$$\frac {dy}{dx} = (y^2+2xy\frac {dy}{dx}) + 12y^2\frac {dy}{dx}+3$$
$$\frac {dy}{dx} - 2xy\frac {dy}{dx} - 12y^2\frac {dy}{dx} = y^2+3$$
$$\frac {dy}{dx}(1-2xy-12y^2)=y^2+3$$
$$\frac {dy}{dx} = -\frac {y^2+3}{2xy+12y^2-1}$$
The derivative at (1,-1) is then
$$-\frac{(-1)^2+3}{2(1)(-1)+12(-1)^2-1}=-\frac 4 {9}$$
The slope normal line is the negative reciprocal of the derivative so it is therefore $\frac {9}{4}$
Comment: You lmissed a minus sign. The derivative is negative.
Comment: Thanks, it is corrected now


Alter html output of a term reference form field

Question: On my node edit form a term reference field is rendered with the following html output:

  <input type="radio" id="edit-field-trainingstype-und-12" name="field_trainingstype[und]" value="12" class="form-radio">
  External

As you can see the value attribute is set to 12 which is the term id of that particular item. Now I would like to replace 12 with the term name, External.
So it would look like:

  <input type="radio" id="edit-field-trainingstype-und-12" name="field_trainingstype[und]" value="External" class="form-radio">
  External

I am unsure which function to use to target this particular field.
I was looking at theme_checkbox() and theme_form_element() but I am uncertain how to proceed and if these are the right functions for the job.
UPDATE:
So I would like to show another field based on the option chosen for the field_trainingstype. In a hook_form_alter I am now doing this:
$form['field_organisaton']['#states'] = array(
  'visible' => array(
    ':input[name="field_trainingstype[und]"]' => array('value' => '12'),
  ),
);

But I would like to trigger this by term name External because the term id might differ per environment.
Answer: Doing it that way round will cause problems with the form submission; the value for a term reference field needs to be an integer and throwing a string at it will undoubtedly upset things. You could massage values back into place in a validate function but it seems a bit...messy.
The alternative would be to load the taxonomy term up in the form, so you can use the ID from there:
$terms = taxonomy_get_term_by_name('External', 'vocab_machine_name');
$term = array_shift($terms);
$form['field_organisaton']['#states'] = array(
  'visible' => array(
    ':input[name="field_trainingstype[und]"]' => array('value' => $term->tid),
  ),
);

That should make it reusable across different environments (provided the vocab only has one term with the name "External").
Comment: Arghh, ofcourse. Was thinking the other way around. Thanks.
Comment: taxonomy_get_term_by_name() returns an array of term objects, indexed by tid. So in my case, where I am sure  I have only one term with the name External I could and have to do this $term = reset(taxonomy_get_term_by_name('Extern', 'trainingstypen'));
Comment: So it does @undersound, sorry about that


How to use ternary operator in Vue template with filter?

Question: I have an app to set a filter depending on desktop or mobile design, but the ternary operator doesn't work.
Here is the component call:
<Metric
    prefix="R$"
    :is-numeric-subvalue="false"
    :is-total="true"
    subvalue="Abril à Maio"
    title="Disponível"
    :value="highlightData.available | defineFilter()"
/>

Here is my method to define the filter:
methods: {
  defineFilter () {
    const test = true
    const filter = test ? this.$options.filters.decimal(0) : this.$options.filters.shortedNumber()
    return filter
  }
}

My filters:
filters: {
  decimal: decimalFilter,
  shortedNumber: shortedNumberFilter
}

I received the warning:

[Vue warn]: Failed to resolve filter: defineFilter
Comment: it looks good to me . why do you think its not working?
Comment: @NileshPatel i don't know, isn't working Vue returns the warn "Failed to resolve filter: defineFilter"
Comment: That's because it's in your `methods`.  Move it to `filters`.
Comment: @Dan but how? move my method defineFilter to filters?
Comment: Yes, filters are just functions too
Comment: @Dan I tried to, but i received Cannot read property "$options" of undefined
Comment: As a general rule, you shouldn't use `$options` in your component.  What sort of data are you filtering?  It looks more like you want a method there anyway
Comment: @Dan I'm filtering any number, the question is that the filter causes it to be formatted with a different display and this formatted data must be passed as a prop for the child component
Comment: Which variable contains the number?
Comment: @Dan is a vuex mapState, called "highlightData.available" in this case is equal to 1805.85
Answer: Move your filter to filters and remove both methods.  The filter will receive the number value as an argument.  Since there is no this access to the component in a filter, you can use your predefined functions directly:
filters: {
  defineFilter(num) {
    const test = true;
    return test ? decimalFilter(num) : shortedNumberFilter(num);
  }
}

Make sure that both of your external functions are prepared to receive the number and return a value.  Here's a demo


How to get jquery switchClass working in Drupal 7

Question: I want to use the jquery "switchClass" in a Drupal 7 Website. I already got the jquery accordion and tabs working, by adding the library in this way:
drupal_add_library('system', 'ui.tabs');
drupal_add_library('system', 'ui.accordion');
Now i'm trying to get switchClass working this way:
drupal_add_library('system', 'ui.switchClass');
... which is not working.
What am i doing wrong?
Thank you for helping!
Lars
Answer: switchclass() isn't a library, it's a function that's part of UI Effects. So...
drupal_add_library('system', 'effects');

Should then let you use:
$('.foo').switchClass('foo', 'bar', 1000);


java.io.IOException: Cannot run program "sqlldr": CreateProcess error=2, The system cannot find the file specified

Question: Have written a method in JSF action bean which 'll execute sqlldr command, but the thing is am getting error at "Process".
But the same code work fine and load the data into a table when i tried it as a stand alone Java program.
note: Oracle and java path is also been set....
need help... :(
Below are my code:
method in Action Bean which will be called on Button click
public String executeControlFile() {

        try {
            Runtime rt = Runtime.getRuntime();

            Process pr = rt.exec("sqlldr userid=system/root control=d:\\emp\\emp.ctl log=d:\\emp\\empNew2.log");
        BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
        String line=null;

        while((line=input.readLine()) != null) {
         System.out.println(line);
        }
        int exitVal = pr.waitFor();
        System.out.println("Exited with error code "+exitVal);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

Error :
16:55:17,436 ERROR [STDERR] java.io.IOException: Cannot run program "sqlldr": CreateProcess error=2, The system cannot find the file specified
16:55:17,444 ERROR [STDERR]     at java.lang.ProcessBuilder.start(ProcessBuilder.java:459)
16:55:17,445 ERROR [STDERR]     at java.lang.Runtime.exec(Runtime.java:593)
16:55:17,447 ERROR [STDERR]     at java.lang.Runtime.exec(Runtime.java:431)
16:55:17,448 ERROR [STDERR]     at java.lang.Runtime.exec(Runtime.java:328)
16:55:17,449 ERROR [STDERR]     at com.cimm.actionBean.SqlLoaderBean.executeControlFile(SqlLoaderBean.java:134)
16:55:17,450 ERROR [STDERR]     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
16:55:17,451 ERROR [STDERR]     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
16:55:17,452 ERROR [STDERR]     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
16:55:17,453 ERROR [STDERR]     at java.lang.reflect.Method.invoke(Method.java:597)
16:55:17,454 ERROR [STDERR]     at org.apache.el.parser.AstValue.invoke(AstValue.java:170)
16:55:17,456 ERROR [STDERR]     at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:276)
16:55:17,457 ERROR [STDERR]     at org.richfaces.ui.application.StateMethodExpressionWrapper.invoke(StateMethodExpressionWrapper.java:76)
16:55:17,459 ERROR [STDERR]     at com.sun.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:68)
16:55:17,460 ERROR [STDERR]     at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:84)
16:55:17,461 ERROR [STDERR]     at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:98)
16:55:17,462 ERROR [STDERR]     at javax.faces.component.UICommand.broadcast(UICommand.java:311)
16:55:17,463 ERROR [STDERR]     at org.ajax4jsf.component.AjaxViewRoot.processEvents(AjaxViewRoot.java:329)
16:55:17,464 ERROR [STDERR]     at org.ajax4jsf.component.AjaxViewRoot.broadcastEventsForPhase(AjaxViewRoot.java:304)
16:55:17,464 ERROR [STDERR]     at org.ajax4jsf.component.AjaxViewRoot.processPhase(AjaxViewRoot.java:261)
16:55:17,465 ERROR [STDERR]     at org.ajax4jsf.component.AjaxViewRoot.processApplication(AjaxViewRoot.java:474)
16:55:17,465 ERROR [STDERR]     at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:77)
16:55:17,466 ERROR [STDERR]     at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:97)
16:55:17,466 ERROR [STDERR]     at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:114)
16:55:17,467 ERROR [STDERR]     at javax.faces.webapp.FacesServlet.service(FacesServlet.java:308)
16:55:17,467 ERROR [STDERR]     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
16:55:17,468 ERROR [STDERR]     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
16:55:17,468 ERROR [STDERR]     at org.ajax4jsf.webapp.BaseXMLFilter.doXmlFilter(BaseXMLFilter.java:206)
16:55:17,469 ERROR [STDERR]     at org.ajax4jsf.webapp.BaseFilter.handleRequest(BaseFilter.java:290)
16:55:17,469 ERROR [STDERR]     at org.ajax4jsf.webapp.BaseFilter.processUploadsAndHandleRequest(BaseFilter.java:388)
16:55:17,470 ERROR [STDERR]     at org.ajax4jsf.webapp.BaseFilter.doFilter(BaseFilter.java:515)
16:55:17,470 ERROR [STDERR]     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
16:55:17,471 ERROR [STDERR]     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
16:55:17,471 ERROR [STDERR]     at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
16:55:17,472 ERROR [STDERR]     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
16:55:17,472 ERROR [STDERR]     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
16:55:17,473 ERROR [STDERR]     at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:235)
16:55:17,473 ERROR [STDERR]     at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
16:55:17,474 ERROR [STDERR]     at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:190)
16:55:17,474 ERROR [STDERR]     at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:433)
16:55:17,475 ERROR [STDERR]     at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:92)
16:55:17,475 ERROR [STDERR]     at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEstablishmentValve.java:126)
16:55:17,476 ERROR [STDERR]     at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70)
16:55:17,477 ERROR [STDERR]     at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
16:55:17,477 ERROR [STDERR]     at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
16:55:17,478 ERROR [STDERR]     at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158)
16:55:17,478 ERROR [STDERR]     at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
16:55:17,479 ERROR [STDERR]     at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330)
16:55:17,479 ERROR [STDERR]     at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829)
16:55:17,480 ERROR [STDERR]     at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598)
16:55:17,480 ERROR [STDERR]     at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
16:55:17,480 ERROR [STDERR]     at java.lang.Thread.run(Thread.java:619)
16:55:17,481 ERROR [STDERR] Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
16:55:17,482 ERROR [STDERR]     at java.lang.ProcessImpl.create(Native Method)
16:55:17,482 ERROR [STDERR]     at java.lang.ProcessImpl.<init>(ProcessImpl.java:81)
16:55:17,483 ERROR [STDERR]     at java.lang.ProcessImpl.start(ProcessImpl.java:30)
16:55:17,483 ERROR [STDERR]     at java.lang.ProcessBuilder.start(ProcessBuilder.java:452)
16:55:17,483 ERROR [STDERR]     ... 50 more

And the Stand alone Java Program which is working Fine without any hurdle
public class Main {

    public static void main(String args[]) {

         try {
             Runtime rt = Runtime.getRuntime();
             Process pr = rt.exec("sqlldr userid=system/root control=d:\\emp\\configuration.ctl log=d:\\emp\\configuration.log");
         BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
             String line=null;

             while((line=input.readLine()) != null) {
                 System.out.println(line);
             }
             int exitVal = pr.waitFor();
             System.out.println("Exited with error code "+exitVal);

         } catch(Exception e) {
             System.out.println(e.toString());
             e.printStackTrace();
         }
     }
}

Thank you...
Answer: The problem comes from your code.
It's much better to use "cmd.exe /C " and and specify environment variables.
The best method is exec(String[] cmdarray, String[] envp, File dir). You can check java documentation.


Prove $\langle X \rangle \triangleleft G$ iff $gXg^{-1}\subseteq \langle X \rangle$ for all $g \in G$.

Question: $X$ is a nonempty subset of a group $G$.
Prove $\langle X \rangle \triangleleft G$ iff $gXg^{-1}\subseteq \langle X \rangle\,\forall\, g \in G$.
Where $\langle X \rangle \triangleleft G$ means $\langle X \rangle$ is normal in $G$
I believe that $\langle X \rangle \triangleleft G \implies gXg^{-1}\subseteq \langle X \rangle\,\forall\, g \in G$ is simple. i.e.
$\langle X \rangle \triangleleft G \implies g  \langle X \rangle g^{-1}\subseteq \langle X \rangle \,\forall\,  g\in G \implies g X g^{-1}\subseteq g  \langle X \rangle g^{-1}\subseteq \langle X \rangle \,\forall\,  g\in G$
But now I am trying to show that $gXg^{-1}\subseteq \langle X \rangle\,\forall\, g \in G \implies \langle X \rangle \triangleleft G$ and I am not sure how. If $X=\langle X \rangle$ then I'd be done, but I don't think I have anyway to show that. But I know I need to show $gXg^{-1}\subseteq \langle X \rangle \implies g\langle X \rangle g^{-1}\subseteq \langle X \rangle$ Can anyone point me in the right direction? Thank you
Answer: Since you have $gXg^{-1}\subseteq \langle X \rangle\,\forall g \in G$, for each $x \in \langle X \rangle$, we can express it as a finite product $\prod_{i = 1}^n x_i$ for some $x_i \in X\,\forall i = 1,\dots,n$.  Then it suffices to show that $gxg^{-1} \in \langle X \rangle$.  Note that $gxg^{-1}=g\left(\prod_{i = 1}^n x_i\right)g^{-1}=\prod_{i = 1}^n (gx_ig^{-1})$.  For each $i = 1,\dots,n$, $gx_ig^{-1} \in \langle X \rangle$, so it's a finite product of elements of $X$, so as $\prod_{i = 1}^n (gx_ig^{-1})=gxg^{-1}$.  Hence $gxg^{-1} \in \langle X \rangle$ for all $x \in \langle X \rangle$.
Comment: I'm new to Abstract Algebra and I learnt that to show that if H is normal in G, we have to show that $gHg^{-1}=H$ for all $g \in G$. Why do you say that it suffices to show that $gxg^{-1} \in $?
Comment: @lcycarus Your last prompt is the whole statement proved in my solution.  The key is to observe that g and its inverse cancels each other in between x_i's.  T address your problem, it's important to know the variables' quantifier.  As you've written, for all g in G, so take g=e, what do you get?


Why am I getting Uncaught TypeError: Cannot read properties of undefined (reading 'name')

Question: I am trying to display a specific beer based on the beer id I am appending to the url
import React from "react";
import { useState, useEffect } from "react";
import axios from "axios";
import {
  Routes,
  Route,
  Link,
  useNavigate,
  useLocation,
} from "react-router-dom";

export default function SingleBeer() {
  const [beers, setBeers] = useState([]);
  useEffect(() => {
    axios
      .get(`https://ih-beers-api2.herokuapp.com/beers`)
      .then((response) => setBeers(response.data));
  }, []);
  const location = useLocation();
  let beerId = location.pathname.split("/").pop();
  const navigate = useNavigate();

  let singleBeer = beers.filter((beer) => beer._id === beerId);
console.log(singleBeer)

  return (

Single Beer

 navigate("/beers")}> Go Back

{singleBeer[0].name}

  );
}

When I click show Details button for the corresponding beer on my Beers.js component the
SingleBeer component doesn't render, instead I get the error "Why am I getting  Uncaught TypeError: Cannot read properties of undefined (reading 'name')"
If I remove the 'h1' with the singleBeer[0].name, I can see the console.log for the single beer im not sure why the 'name' property of the single beer object is coming back as undefined if the object shows up in the console, all I am trying to do is access the specific beer route when I click show details in the previous component
Answer: Issues
I think there are a few possible issues happening here.

The beers state array is initially empty from the time the component mounts and through any subsequent render cycles until the axios GET request resolves and enqueues a beers state update that can be filtered.

Array.protptype.filter can possibly return an empty array if no elements match the predicate function. In this case singleBeer[0] is undefined and an error will be thrown if attempting to access singleBeer[0].name.

There might be a type comparison mismatch between beerId which will be a string type, and beer._id which might not be a string.
let beerId = location.pathname.split("/").pop(); // <-- string type

You want to type-safe comparisons when using strict equality (===).

Solution

If necessary, use a type-safe comparison by converting/ensuring both sides are strings.
 const singleBeer = beers.filter((beer) => String(beer._id) === beerId);

Gracefully handle if no match is found.
 if (!singleBeer) return "Sorry, tapped out. No beer here.";

 return (

Single Beer

 navigate("/beers")}> Go Back

{singleBeer[0].name}

 );

If you don't want to render the alternative view then at a minimum use a null-check/guard-clause on the potentially undefined object.

{singleBeer[0]?.name}

Comment: Thank you for taking the time to write such an in depth solution, the thing is that there is an element that matches the filter because I see it in the console, its an array with a single object that has the same id as the parameter I am appending to the URL. If I remove  {singleBeer[0].name} from my component, I see the single object from my filter method log to the console, when I dont remove it , the component doesnt render at all.
Comment: @mattangel Well, your console log is an unintentional side-effect so it might not accurately agree with the React component lifecycle when rendering to the DOM. I just pulled up the JSON data in the browser so I can see that `_id` is in fact a string value. Keep in mind that the `beers` state array will be initially an empty array until the fetch resolves and updates the local state. I'll update my answer.


Can I get the Node's content type in hook_flag_alter

Question: In the following code, I'm changing a flag with a short title of "Follow" to include the name of Content Type. Is it possible to add the content type so that I can not say Follow node but perhaps Follow Question, Follow Person, FOllow Group?
function hook_flag_alter(&$flag) {

    //node, taxonomy_term, user,  comment
    $extra_text_of_type = "";
    switch ($flag->content_type) {
      case 'node':
        $extra_text_of_type = "node";
        break;
      default:
    }

    $flag->flag_short = $flag->flag_short . ' ' . $extra_text_of_type;
  }

Answer: If you're using flag 2.x with Drupal 7, then this should give you what you want.
function hook_flag_alter(&$flag) {
    $type_text = "";
    switch($flag->entity_type) {
      case 'node':
        switch(reset($flag->types)) {
          case 'page':
            $type_text = t('Page');
            break;
          case 'blog':
            $type_text = t('Blog Post');
            break;
          default:
            $type_text = t('Node');
        }
        break;
      case 'user':
        $type_text = ('User');
        break;
      default:
    }

    $flag->flag_short = t('Follow @type', array('@type' => $type_text));
    $flag->unflag_short = t('Unfollow @type', array('@type' => $type_text));
}

Note: This code assumes that each flag only applies for a single content type.
Comment: You can use the keyed array returned from `node_type_get_names`.


XAMPP MySQL Cannot connect: invalid settings

Question: I'm trying to use mysql with xampp on windows 7 and I'm getting lot of errors.
I am able to run mysql through the command prompt just fine, so long as it is not running in xampp. here are the things I've done so far:

changed skype port settings
changed the password that xampp uses to match my mysql password
changed environment variables and PATH variable in windows 7
removed all oracle database related things in environment variables and PATH

Of note is that I can't use xampp and mysql while mysql server is listening on port 3036. I installed MySQL server 5.7.
Here is an image of my xampp dashboard:
https://i.stack.imgur.com/7omRY.png
Below is my mysql_error file contents:

2016-12-05 21:40:28 f1c InnoDB: Warning: Using
  innodb_additional_mem_pool_size is DEPRECATED. This option may be
  removed in future releases, together with the option
  innodb_use_sys_malloc and with the InnoDB's internal memory allocator.
2016-12-05 21:40:28 3868 [Note] InnoDB:
  innodb_empty_free_list_algorithm has been changed to legacy because of
  small buffer pool size. In order to use backoff, increase buffer pool
  at least up to 20MB.
2016-12-05 21:40:28 3868 [Note] InnoDB: Using mutexes to ref count
  buffer pool pages
2016-12-05 21:40:28 3868 [Note] InnoDB: The InnoDB memory heap is
  disabled
2016-12-05 21:40:28 3868 [Note] InnoDB: Mutexes and rw_locks use
  Windows interlocked functions
2016-12-05 21:40:28 3868 [Note] InnoDB: _mm_lfence() and _mm_sfence()
  are used for memory barrier
2016-12-05 21:40:28 3868 [Note] InnoDB: Compressed tables use zlib
  1.2.3
2016-12-05 21:40:28 3868 [Note] InnoDB: Using generic crc32
  instructions
2016-12-05 21:40:28 3868 [Note] InnoDB: Initializing buffer pool, size
  = 16.0M
2016-12-05 21:40:28 3868 [Note] InnoDB: Completed initialization of
  buffer pool
2016-12-05 21:40:28 3868 [Note] InnoDB: Highest supported file format
  is Barracuda.
2016-12-05 21:40:29 3868 [Note] InnoDB: 128 rollback segment(s) are
  active.
2016-12-05 21:40:29 3868 [Note] InnoDB: Waiting for purge to start
2016-12-05 21:40:29 3868 [Note] InnoDB:  Percona XtraDB
  (http://www.percona.com)
  5.6.32-79.0 started; log sequence number 1840435
2016-12-05 21:40:29 6480 [Note] InnoDB: Dumping buffer pool(s) not yet
  started
2016-12-05 21:40:29 3868 [Note] Plugin 'FEEDBACK' is disabled.
2016-12-05 21:40:29 3868 [Note] Server socket created on IP: '::'.
2016-12-05 21:40:29 3868 [Note] c:\xampp\mysql\bin\mysqld.exe: ready
  for connections.
Version: '10.1.19-MariaDB'  socket: ''  port: 3306  mariadb.org binary
  distribution
Comment: in summary, your setup are consist of MySQL Server 5.7, xampp, Oracle, and Skype..? Just to be sure, without being invoked from xampp it runs with port 3306 right? however it did not work while you start it from xampp as stated in __so long as it is not being ran from xampp__?
Comment: I mentioned Oracle and Skype because they might have been interfering, so I fixed them.
Comment: well, i do believe the only one that interferes each other are [MySQL Server 5.7](http://dev.mysql.com/doc/refman/5.7/en/connecting.html#option_general_port) and [MariaDB that being shipped with xampp](https://mariadb.com/kb/en/mariadb/configuring-mariadb-for-remote-client-access/#port-3306-is-configured-in-firewall). Have you tried to run MariaDB while turning off your MySQL Server services? also, just a reminder, Xampp control panel require us to run it as admin.
Comment: I'm not sure what has happened, but I can no longer launch mysql through the command prompt.
Here is a picture of my netstat -a -b results while I work this out http://i.imgur.com/GHeu7x0.png
Comment: "I'm not sure what has happened, but I can no longer launch mysql through the command prompt" - so, you can't access mysql once you turn off the mysql server service..? also to confirm things, you ran mysql as a user named "apps"...? anyway, it is better to ask this server related stuff to [ServerFault](http://serverfault.com/).
Comment: http://i.imgur.com/gsWj5b4.png
I'm at a loss for what to do. Mysqld.exe is running in my processes...
Answer: I'm nonplussed.
I configured mysql to login as user root with a password. However it worked when I tried to login with no password.


Kill all R processes that hang for longer than a minute

Question: I use crontask to regularly run Rscript. Unfortunately, I need to do this on a small instance of aws and the process may hang, building more and more processes on top of each other until the whole system is lagging.
I would like to write a crontask to kill all R processes lasting longer than one minute.  I found another answer on Stack Overflow that I've adapted that I think would solve the problem. I came up with;
if [[ "$(uname)" = "Linux" ]];then killall --older-than 1m "/usr/lib/R/bin/exec/R --slave --no-restore --file=/home/ubuntu/script.R";fi

I copied the task directly from htop, but it does not work as I expect. I get the No such file or directory error but I've checked it a few times.
I need to kill all R processes that have lasted longer than a minute. How can I do this?
Comment: I suspect you need "pkill" rather than "killall". http://superuser.com/questions/220517/how-to-kill-a-process-with-name-having-spaces
Answer: You may want to avoid killing processes from another user and try SIGKILL (kill -9) after SIGTERM (kill -15). Here is a script you could execute every minute with a CRON job:
#!/bin/bash

PROCESS="R"
MAXTIME=`date -d '00:01:00' +'%s'`

function killpids()
{
    PIDS=`pgrep -u "${USER}" -x "${PROCESS}"`

    # Loop over all matching PIDs
    for pid in ${PIDS}; do
        # Retrieve duration of the process
        TIME=`ps -o time:1= -p "${pid}" |
              egrep -o "[0-9]{0,2}:?[0-9]{0,2}:[0-9]{2}$"`

        # Convert TIME to timestamp
        TTIME=`date -d "${TIME}" +'%s'`

        # Check if the process should be killed
        if [ "${TTIME}" -gt "${MAXTIME}" ]; then
            kill ${1} "${pid}"
        fi
    done
}

# Leave a chance to kill processes properly (SIGTERM)
killpids "-15"
sleep 5

# Now kill remaining processes (SIGKILL)
killpids "-9"

Comment: @MiserableVariable the `-x` option of `pgrep` should be used, I guess.
Comment: A few comments: `$USER` should already by a usable shell variable. piping `pgrep`  to a plain `xargs` is redundant. You can save a bit on processing `ps` output if you use the correct options: `ps -o time:1= -p ${pid}` will give you just the time for that PID.
Comment: Will this not select all processes that have `R` in their name?
Comment: Yes it would be safer. Edited.
Answer: Why imply an additional process every minute with cron?
Would it not be easier to start R with timeout from coreutils, the processes will then be killed automatically after the time you chose.
timeout [option] duration command [arg]…

Comment: Almost, here it worked with:

     timeout 60 Rscript /home/ubuntu/script.R
Alternatively, you can test with
     time timeout 60 Rscript /home/ubuntu/script.R
Comment: so it would look like: ```timeout --kill-after=1m Rscript /home/ubuntu/script.R```
Answer: I think the best option is to do this with R itself. I am no expert, but it seems the future package will allow executing a function in a separate thread. You could run the actual task in a separate thread, and in the main thread sleep for 60 seconds and then stop().

Previous Update
user1747036's answer which recommends timeout is a better alternative.

My original answer
This question is more appropriate for superuser, but here are a few things wrong with
if [[ "$(uname)" = "Linux" ]];then
  killall --older-than 1m \
    "/usr/lib/R/bin/exec/R --slave --no-restore --file=/home/ubuntu/script.R";
fi

The name argument is either the name of image or path to it. You have included parameters to it as well
If -s signal is not specified killall sends SIGTERM which your process may ignore. Are you able to kill a long running script with this on the command line? You may need SIGKILL / -9

More at http://linux.die.net/man/1/killall


How to teach PhpStorm to recognise drupal {table} SQL syntax?

Question: I'm dealing with some really old drupal project full of SQL queries. PhpStorm's understanding of SQL is very handy however I have problems with drupalism like {table_name}. IDE complains that <reference> expected, got '{'.
How can i set up PhpStorm so that it will understand that the string inside curly braces is just a table name? Or at least make it ignore the curly braces?
Comment: Are you using the Drupal integration? I've never seen this issue with PHPStorm. Do you have a special plugin for the SQL that might be causing issues?
Comment: @SiliconMind That's not supported, I think. You can set sql dialect, but you can't set this specific thing, maybe because other plugins can run your code and give you results in live (like Database Tools and SQL)... maybe. I never used that, but I'm not sure that's a good practice.
Comment: @googletorp yes I'm using drupal support plugin bundled with PhpStorm
Answer: In PhpStorm Preferences > Tools > Database > User Parameters:

Check "Enable in string literals with SQL injection"
Add \{\w+\} to Parameter Patterns.

You may also want to modify the line with %\w+ to be allowed for language php for placeholders like %d. See screenshot and also JetBrain's PhpStorm blog post: Database Language Injection Configuration.
Comment: This doesn't solve the issue where the table columns are marked as unresolved. Need a solution that recognizes the table and its columns, as in the regular sql syntax.
Comment: I would change `\{\w+\}` to `\{(\w+)\}` to work better with PhpStorm's query execution (the Ctrl+Enter shortcut). Without the extra parentheses, if you try to execute the query, it will prompt you to input a parameter called **#1** for your `{table_name}`, but with the parentheses it will more helpfully prompt your for a **table_name** parameter.
Comment: Further to my previous comment, here are examples of the difference the parentheses would make. For a query string of `SELECT * FROM {node} WHERE nid = :nid`, pressing the Ctrl+Enter shortcut displays the following prompts: [with parentheses](https://i.imgur.com/q6sXMa4.png) and [without parentheses](https://i.imgur.com/es6ce4Q.png).
Comment: https://youtrack.jetbrains.com/issue/WI-4123
Answer: I don't know of any way to make PHPStorm recognize the Drupal SQL syntax.
But if you just want to debug a query that was created by Drupal, then you can remove the curly braces from the query after copying it to the PHPStorm query console.
Comment: The reason for the downvotes of this advice is because removing or neglecting to include brackets around table names will interfere with Drupal's table prefixing behavior.  See this link for details about the feature: https://www.drupal.org/node/2622
Comment: @WestonWedding I did not suggest removing the curly brackets while executing a query in Drupal. My suggestion was to remove the brackets after copying the query from Drupal to the PHPStorm query console. It is a bit of manual work, but helps when debugging queries created by Drupal.
Comment: I see!  Well, that isn't in your answer anywhere, so some people might be getting confused.
Comment: I updated the answer with a little more context.


Executar um script através do atributo 'name' não funciona

Question: Segue o código:
<select class="form-control" name="dd_medidaAplicada" id="dd_medidaAplicada">
<option value="0"></option>
<option value="cancelada">Advertência Cancelada</option>
<option value="escrita">Advertência Escrita</option>
<option value="verbal">Advertência Verbal</option>
<option value="dispensa">Dispensa por Justa Causa</option>
<option value="suspensao">Suspensão</option>

Eu quero executar um script toda vez que for mudado de item selecionado:
$("input[name=dd_medidaAplicada]").on('change', function() { alert( this.value );})

Porém, através do atributo name eu não consigo executar. Caso eu utilize o atributo ID, funciona! Segue exemplo:
$("#dd_medidaAplicada").on('change', function() { alert( this.value );})

Desta forma, o Alert executa sem problemas.
E sim, eu poderia usar o atributo ID, porem muitas vezes este mesmo problema acontece nos meus códigos e cansei de criar uma ID só para executar um código. Quero entender o porque de não executar.
Answer: O teu seletor está à procura de um input, devia estar à procura de um select. Para além disso duas observações:

se tens vários select, dá-lhes a mesma classe e usa $(".form-control").on(, assim serão todos selecionados
usa aspas nos seletores, select[name='dd_medidaAplicada']

$("select[name='dd_medidaAplicada']").on('change', function() {
  console.log(this.value);
})

<select class="form-control" name="dd_medidaAplicada" id="dd_medidaAplicada">
    <option value="0"></option>
    <option value="cancelada">Advertência Cancelada</option>
    <option value="escrita">Advertência Escrita</option>
    <option value="verbal">Advertência Verbal</option>
    <option value="dispensa">Dispensa por Justa Causa</option>
    <option value="suspensao">Suspensão</option>
</select>
Comment: Funcionou perfeitamente. Obrigado!
Answer: O elemento não é um input e sim um select, no jquery existem diversos tipos de seletores, no exemplo abaixo utilizei name*='dd_medidaAplicada', ou seja, qualquer item do select que conter dd_medidaAplicada no name.

$("select[name*='dd_medidaAplicada']").on('change', function() {
  alert(this.value);
})
//$("#dd_medidaAplicada").on('change', function() { alert( this.value );})

<select class="form-control" name="dd_medidaAplicada" id="dd_medidaAplicada">
<option value="0"></option>
<option value="cancelada">Advertência Cancelada</option>
<option value="escrita">Advertência Escrita</option>
<option value="verbal">Advertência Verbal</option>
<option value="dispensa">Dispensa por Justa Causa</option>
<option value="suspensao">Suspensão</option>
Comment: Faltaram só as aspas no seletor.
Comment: @Renan corrigido, valeu!
Comment: Obrigado pela explicação!


how to get ping value android

Question: I am doing an exercise in Android and I want to display value of a ping. I followed an existing answer (this topic). The fact is that the code that the person gave doesn't display any information (I toasted it to test the return value of the function "ping"). I called the function like this :
Toast.makeText(getApplicationContext(), ping("http://www.stackoverflow.com"), Toast.LENGTH_SHORT).show();

Any other kind of code to simply display ping value ?
I precise that my code is free of any other process, I just want to finally display this result in a small textView.
Here is my code.
MainActivity.java
private String ping(String url) {

    String str = "";

    try {
        Process process = Runtime.getRuntime().exec(
                "/system/bin/ping -c 8 " + url);
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                process.getInputStream()));
        int i;
        char[] buffer = new char[4096];
        StringBuffer output = new StringBuffer();
        while ((i = reader.read(buffer)) > 0)
            output.append(buffer, 0, i);
        reader.close();

        // body.append(output.toString()+"\n");
        str = "ping : " + output.toString();
        // Log.d(TAG, str);
    } catch (IOException e) {
        // body.append("Error\n");
        e.printStackTrace();
    }

    return str;
}

private Button button;
private TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textView = (TextView) findViewById(R.id.textView);
    button = (Button) findViewById(R.id.button);

    toggleButton.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            Toast.makeText(getApplicationContext(), ping("http://www.stackoverflow.com"), Toast.LENGTH_SHORT).show();
            });
    }); }

Comment: have you added Internet permissions in manifest?
Comment: Nope, what is the specific permission I should add please ?
Comment: check this http://stackoverflow.com/questions/2378607/what-permission-do-i-need-to-access-internet-from-an-android-application
Comment: Thanks for sharing this link asloob but my problem is still present.
Comment: Does it print anything in ADB Log ?
Comment: Yep, it print like the "ping" command in Shell Unix. Thanks
Answer: Try something like here: Android- Unstable, slow, unreliable PING
After public class NameOfYourActivity
// you need to define this value here, you will need it between "voids", "booleans", ...
long timeofping;

OnCreate:
// button on click listener
Button clickMyButton = (Button)findViewById(R.id.button);
clickFirstButton.setOnClickListener(new View.OnClickListener() {
    @Override
        public void onClick(View v) {
            // launch the ping process in a separate thread
            // beacuse of the stability of the app
            new Thread(ping).start();
        }
});

After method "onCreate"
// this code runs after the code bellow ("public Runnable ping ...")
void setPingResult(long pingtime) {
    Toast.makeText(getApplicationContext(), timeofping + " milliseconds", Toast.LENGTH_LONG).show();
}

// thread of "ping" process
public Runnable ping = new Runnable() {
        @Override
        public void run() {
            Runtime runtime = Runtime.getRuntime();
            try {
                long a = System.currentTimeMillis() % 1000;
                Process ipProcess = runtime.exec("/system/bin/ping -c 1 184.108.40.206");
                ipProcess.waitFor();
                timeofping = System.currentTimeMillis() % 1000 - a;
            } catch (IOException e)          { e.printStackTrace(); }
            catch (InterruptedException e) { e.printStackTrace(); }

            // update the ping result - we need to call this on the UI thread
            // because it updates UI elements (TextView)
            runOnUiThread(new Runnable() {
            public void run() {
                setPingResult(timeofping);
            }
        });

    }
}

Please fix me, if there are any errors!
Dont forget "imports"! (etc import android.widget.Toast;)
Comment: Oh gosh ! Thank you for answering Antonin, I have specialized in HTML/CSS since a long time now but I think i'll go back to Android for a while and I just needed this ! :)
Comment: @Zeratops If this works for you, please check this answer as "answered". Thanks
Answer: yourTextView.setText(ping("http://www.stackoverflow.com"));

Comment: Thanks for answering Sparrow_ua, but if the ping result doesn't display in a Toast I have big doubt on the result of your code.
Answer: Found my error : need to use IP adresse like 22.214.171.124instead of domain adress like www.google.com. Maybe there is a DNS permission to need ?

how to get ping value android