Como usar chave estrangeira para criar um registro em outra tabela

Question: Eu tenho duas tabelas users e users_info, gostaria de usar chave estrangeira, para quando eu criasse um registro na tabela users, criasse um registro com os campos vazios na tabela users_info, apenas com o id_user preenchido, é possivel?
Comment: pra criar outro registro, você precisará de uma trigger
Comment: @RovannLinhalis Conseguiria me dar um exemplo de como faria?
Comment: acredito que já tenha a resposta abaixo. =]
Answer: Acredito que ficaria assim, lembre-se que os campos da tabela user_info devem permitir valores nulos.
CREATE TRIGGER tg_user
AFTER INSERT ON users
FOR EACH ROW
  INSERT INTO user_info (id_user, outro_campo, exemplo)
  SELECT NEW.id, NULL, NULL
  FROM users
  WHERE id = NEW.id

Comment: Vou testar e ja te dou um feedback ;)


Project Euler Q.2 Ruby a[i] if a[i] % 2 == 0 not working

Question: Here's a link to my Github
https://github.com/kuanhsuh/projecteuler/blob/master/2redo.rb
My Question is in line 26:
c << a[i] if a[i] % 2 == 0

This method ignores the last even number of the Fibonacci sequence, and I dont know why.
My array A has 3524578, and this should be pushed to array C but it doesn't get pushed.
If i use the select method in line 29. It works fine.
So how come the code in line 26 doesn't work. Thanks
Comment: By Stack Overflow rules, the question should be as self-sufficient as possible, with the minimal example needed to demonstrate the problem inside the question itself; links are just bonus. Please keep it in mind in the future.
Comment: Please respect the time of the people who help you. Your code should be as easy as possible for them to read and understand.  This means: descriptive identifier names (not `a`, `b`, `c`), and disabled debug code removed.  In addition, when referring to large integers, it's helpful to use underscores in your code and documentation, such as 4_000_000 and 3_524_578.
Comment: (Regarding my previous comment, it is legal in Ruby to use underscores in numeric constants.)
Comment: I'm sorry i'll keep in mind in the future
Comment: A small thing: you can write `n.even?` or `n.odd?`.
Answer: Here are the computed values for i, i = 27, 28, 29, 30. Recall limit #=> 4_000_000.
i #=> 27
a[27] + a[28] #=> 514_229 + 832_040 #=> 1_346_269 < 4_000_000 #=> true # so continue
c.last #=> 196_418 #=> unchanged
b #=> 1_346_269
a #=> [..., 514229, 832040, 1346269]

i #=> 28
a[28] + a[29] #=> 832040 + 1346269 #=> 2178309 < 4000000 #=> true, so continue
c.last #=> 832_040 # c.last changes
b #=> 2_178_309
a #=> [..., 832040, 1346269, 2178309]

i #=> 29
a[29] + a[30] #=> 1346269 + 2178309 #=> 3524578 < 4000000 #=> true, so continue
c.last #=> 832_040 # unchanged
b #=> 3_524_578
a #=> [..., 1346269, 2178309, 3524578]

i #=> 30
a30 + a31 #=> 2178309 + 3524578 #=> 5702887 < 4000000 #=> false, so stop.

This shows why c does not get updated when i equals 30..


More than one outcome (dependent) variables in ordinal logistic regression

Question: I want to run ordinal logistic regression (OLR) in SPSS. My data include 6 predictor variable (two continuous and 4 categorical ) but my outcome variables are also 6 (categorical-likert scale).
e.g my dependent variable is Business development and 6 likert scale questions were asked for this, increase in profit, sales, size, asset, marketing and labour.
1-If I composite these 6 variable into one by first sum all the 6 variables and then recode them into again five categories like before (In SPSS in Transform, Compute variable and then recode into different variables). I think in this way I lost my original data and may categorize them wrong.
2-If I think of using Categorical Principle component analysis for reducing the dependent variables, it will give results (object scores) in continuous form on which I have to run linear regression. I do not want to run linear regression as my original data is categorical.
3-So option left is to run OLR without combining the dependent variable on each DV. It means that there is no model for Business development and 6 models for profit, sales....
My question is that

Is it preferable to run OLR with each DV and then summarize the results
OR Is there any other method for reducing DV and running OLR.
OR Is there any better method than ordinal logistic regression for this data.
Answer: Among the many possible ways to analyze this dataset, a one that I would try first is multivariate linear regression. Multivariate means that you have multiple outcome variables (the six Likert scales). Linear, rather than logistic, means that you treat each Likert scale as a continuous output. (It's true that ordinal logistic methods are more appropriate theoretically for rating scales, but that seems like overkill for a first attempt.) Rencher, "Methods of Multivariate Analysis" seems like a decent introduction.
Comment: thanks Jack. Could I use Rasch model on my data?
Comment: OR ANY IRT Model
Comment: i believe you've already asked the IRT / Rasch question elsewhere http://stats.stackexchange.com/questions/21268/using-rasch-model-to-explain-relationships-between-a-set-of-dependent-and-indepe
Answer: One approach to analyzing data of this form is to utilize an item-response-theory framework. "Business Development" is poorly defined. You have 6 items which ostensibly relate to Business Development, but according to the description you have no idea how they should be combined, if at all, to form a usable scale.
Parceling is the simplest approach: add the 6 likert items together and compose a single sum score. This is surprisingly adequate in a number of situations. It is helpful to verify all 6 items are positively correlated as a rudimentary dimensionality analysis.
A more flexible approach is fitting an item response theory model which treats business development as a latent trait which is input to the six likert scale manifest variables according to a proportional odds model with a set of intercepts and slopes. The R package mirt is capable of fitting these models. This is a more general approach to combining these measures. The "ability" is a generalized concept of a sum-score which accounts for the fact that some questions may have very low or very high prevalence, and that differences may be of varying weights in that regard. This is a rough, high level explanation, but you should be able to conduct some self-directed research to see if this is a useful approach to combining multiple ordinal measures.


IPhone App to IPad App How to make transition from ViewController.xib to ViewController-iPad.xib ?

Question: I am using XCode 4.0.
I am Transiting from my iPhone App to IPad as a universal app?
I have some doubts for xib files?
Should I use the autoresize element for each UIElement?
Or
Trasit each xib file to the ipad xib file?
How? Could not get the option for that?

.
Answer: Use different .xib files for iPad and iPhone and initWithNibName:bundle:. Determine whether to use one or another using this block
NSString *nibName = nil;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
  nibName = @"CustomViewControllerIpad";
}
else {
  nibName = @"CustomViewControllerIphone";
}

CustomViewController *viewController = [[CustomViewController alloc] initWithNibName:nibName bundle[NSBundle mainBundle]];

[self.navigationController pushViewController:viewController animated:YES];
[viewController release];


Checking for plagiarism with a proportion test

Question: I'm reviewing research proposals. The proposal is, in human eyes, practically the same as a 2017 degree thesis. The thesis guide professor is the principal investigator of the current project. I used an online site (https://copyleaks.com/) to verify the amount of similar text and it indicates 18%. I would like to add as many evidence to my decision not only to reject but also raise an expression of concern for plagiarism.
My question is: would it be correct to apply a proportion test to indicate that the proportion found, of 18% of equal text in an 18000-word document, is scarcely attributable to chance?
I used an online calculator for the calculation, available in https://www.medcalc.org/calc/test_one_proportion.php with these data
Comment: @sergiouribe If 20% is still considered acceptable, then 18% is too. No statistics needed. But the main problem I have is the reliability of that index (after all, it's summarizing into a single number some phenomenon that is way more complex than that)
Comment: @sergiouribe: * the previous thesis is not cited. The project is essentially the thesis but with a major n.* (something was cut off there) This is the main argument then, and not the hypothesis test. For that you would need to gather data as I indicated.
Comment: Why did you choose $p=0.05$ as null hypothesis value? That seems artificial. I think this is a case where you need to compare with an "empirical null", you need to find what is the typical percentage of similar text between such documents in a class of documents relevant for comparison. Say, if this is a lab field, it might be natural to copy some sections such as "methods and materials" and maybe others.
Comment: Thank you David, it seems that between 10 to 20% would be acceptable, with most opinions towards a maximum of 10%. See https://www.researchgate.net/post/What_percentage_of_similarity_plagiarism_is_generally_treated_as_acceptable
Comment: Indeed @kjetilbhalvorsen  . It's arbitrary and that's part of my question. I could consider that it is natural for a lab to continue with a line of research and to base projects based on previous work, but in the project the previous thesis is not cited. The project is essentially the thesis but with a major n.
Answer: In order to determine whether 18% is too big or not, it would be needed to have a precise definition of how that index is calculated. Fortunatelly, we have a calculator that does it for us, but I don't know to what extent the source should be trusted (i.e: more detail on how the calculation was done is required).
Assuming the p-value shown there is accurate, there is very strong evidence that it did not happen by chance, but an analysis on the methods used is of course critical (both for the index calculation and its conversion to a p-value)


Behavior of a disabled TextBox on post-back in asp.net webforms

Question: I was reading about the difference between Disabled vs Read only and I learned that with a disabled field the data is not send back on postback.
However I have a webforms page with a textbox like below:
<asp:TextBox runat="server" ID="vPlantNameTB" Text="" Enabled="false"></asp:TextBox>

On page load I set the value of vPlantNameTB to some value. (instead of blank).
Since I have this TextBox disabled.  I expect the value of the TextBox to be blank on post-back.  But that is not the case...
I am able to get the value I set it to on page load during post-post back.
Is this behavior normal for web-forms?
Comment: That is normal, and you can't get changed value (ex. use JQuery change the value, post back did not work)
Answer: In short:

yes, because the value is coming from your viewstate, not the form.

For a slightly more involved answer...
The form data that gets submitted (accessible through Request.Form) will be missing for vPlantNameTB as it is disabled and therefore not sent by the browser to the server.
Also included in the form data sent to the server is a hidden input (generated by the .Net engine) called __VIEWSTATE and it's value is a base64-encoded string that represents the current state of the page.
The page state automatically serialized out to the rendered web page and automatically deserialized when the form is posted (the deserialization process also handles re-association with your page controls which is why vPlantNameTB has a value again in your postback handler).
Scott Mitchell has a decent article about ViewState on MSDN which describes the process quite well.


How do i add icon for taskbar in Visual Studio 2019?

Question: I'm not sure whats happened but when i use to change the icon in application it would automatically change the taskbar icon, however it doesn't seem to be the case, is there something i'm missing?, thanks
Comment: You have to change form's icon too.
Comment: Could be caching. Is the icon pinned? Is is it correct after a reboot?
Comment: i haven't pinned it but could be caching ill try a restart!
Comment: have tried a restart, nothing! is so weird
Comment: [Reset icon cache](https://www.windowscentral.com/how-reset-icon-cache-database-windows-10)?
Comment: just done this hasn't changed, im so boggled haha :)
Comment: Thanks i'v just realised, i now feel stupid haha, thanks for all your help!
Answer: You have to change form's icon too. – Hidayet R. Colkusu
need to edit the form property and change the icon there!
Answer: Right click the Forms window, change its icon properties.

Application settings will only change the icon for the base Form I believe. (Form1)


How to change default timezone c#

Question: How can I change default timezone on my MVC(c#) web application?
Server located in USA, clients connecting from Turkey...
I'm looking for a global solution for it, as global.asax or webcofig...
I find a method, wrote a static datetime; it adds differences to UTC time zone. But when day light saved it returning wrong time. I need to change it manually and system is too sensitivie. I can't take risk as manual configure...
All clients have same timezone (GMT+2), So no need international things.
Thanks a lot.
UPDATE & SOLUTION:
<code>    public static DateTime DateNow()
    {
        return TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("Middle East Standard Time"));
    }
</code>
Comment: dear anders, that solution not completed; i already saw before. solution says "set timezone information in the web.config and convert your time according to the web.config's timezone." but it doesnt provide method for web config...
Answer: <code>        DateTime utcTime = DateTime.UtcNow;

        string zoneID = CurrentUserSession.TimeZoneID // Here you get the current login user session and their TimeZone which you configured in database at the time of user creation. or if you want to get client pc time zone then you have to use javascript and get client pc Timezone

        TimeZoneInfo myZone = TimeZoneInfo.FindSystemTimeZoneById(zoneID);
        DateTime custDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, myZone);
</code>

How to change default timezone c#


A morphism which fixes one root of an irreducible polynomial must also fix the others.

Question: Let $E/K$ be a field extension, let $p(x)$ be an irreducible polynomial in $K[x]$ which splits in $E$ with roots $\alpha_1$, $\alpha_2$, etc., and let $\sigma$ be an automorphism of $E$ which fixes $K$. Then $\sigma$ fixes $p(x)$ and so permutes the roots. The proposition I am trying to prove is that if $\sigma$ fixes one root $\alpha_1$ of $p(x)$ then it must also fix the other roots $\alpha_i$.
At first I thought the statement is false for $x^3-2$ in $Q[x]$, but it's not. Are there perhaps additional conditions needed to make this statement true?
Comment: the statement IS false for $x^3-2$ in $Q[x]$.
Comment: In general, it will fail for any polynomial with a mixture of real and non-real roots, as complex conjugation will only fix the real roots.
Answer: This fails exactly when the the order of the Galois group $G$ exceeds the degree of $p(x)$, call it $n$. Remember that the action of $G$ is transitive, so the order of a point stabilizer is (for any root $\alpha$)
$$
\left\vert\operatorname{Stab}_G(\alpha)\right\vert=\frac{|G|}n>1,
$$
iff $|G|>n$. So under those circumstances there exist a non-trivial automorphism $\sigma$ fixing $\alpha$. Non-triviality implies that $\sigma(\alpha')\neq\alpha'$ for some other root $\alpha'$ of $p(x)$.
OTOH, if $|G|=n$, then any point stabilizer is trivial, and the claim is true.
Yet another way of saying the same things is that  the claim is true iff $\alpha$ is a primitive element of $E/K$ (keeping the assumption that $E$ is the splitting field of the minimal polynomial of $\alpha$). As then $E=K(\alpha)$ this is almost a tautology.


What can we conclude about $a$ if $a^2=a$ in a monoid or semigroup?

Question: I found the following question in a test paper:

Suppose $G$ is a monoid or a semigroup. $a\in G$ and $a^2=a$. What can we say
  about $a$?

Monoids are associative and have an identity element. Semigroups are just associative.
I'm not sure what we can say about $a$ in this case other than that $a$ could be other things apart from the identity. Any idea if there's a definitive answer to this question?
Comment: you can conclude that $a^n=a$ for all $n\geq 1$.
Comment: @Surb For semigroup or monoid? Also, I guess they're asking what we can "conclude about $a$" in the sense that what the restrictions on $a$ are
Comment: Okay that one looks trivial as $a^2=a$. So we can write $a.a^2=a.a=a$ and so on....Probably they're looking for something more specific.
Comment: We can conclude that our monoid is not a free monoid: https://en.wikipedia.org/wiki/Free_monoid
Answer: If the test is for an introductory abstract algebra course, I say $a$ is an idempotent element of $G$.
Comment: @user48929 I think we may need more contexts to say more.
Comment: Well, that is quite obvious (almost by definition). I'm perhaps looking for the restrictions on $a$ if $a$ is idempotent and an element of a semigroup or a monoid
Comment: Can we draw any conclusions from associativity and existence of identity?
Answer: Several things can be said on $a$:

$a$ is idempotent,
$a$ is regular,
the subsemigroup generated by $a$ is trivial,
the $\mathcal{H}$-class of $a$ is a group.

Make your choice!
Answer: $$\{1,a,a^2,a^3,...\} = \{1,a,a,aa^2,...\} = \{1,a,a,a^2,...\} = \{1,a,a,a,...\} = \{1,a\}$$


How exactly did the knockout punch work in Ali vs Liston (1965)?

Question: Ali vs Liston was a very famous match in the history of professional boxing, where Ali downed his opponent in a 1st round, 1st minute KO.
I was watching the video of the match, but wasn't really able to make out how the punch on the chin knocked out a professional boxer.
What exactly did the punch do?
How did it really knock out Sonny Liston?
Answer: This is one of the most controversial boxing matches in history.
Some argue that the Alì's punch has not knocked out his opponent, but currently there are no concrete information about it.
On wikipedia there is an dedicated page with many info and many hypothesis on this match (also on the possibility that was fixed).
So, I think it is not possible to provide a concrete answer to these questions
Comment: Yeah, even the reddit folks [suggested](https://www.reddit.com/r/Boxing/comments/4kzc5b/how_exactly_did_the_knockout_punch_work_in_ali_vs/d3j0ese) me to google "PhantomPunch".  But, google didn't give me convincing results.  Looks like it indeed is a controversy.  Anyways, I'll wait for about a week for any more helpful answers before accepting.  :)


Given two points on a plane, and an area find all possible lines connecting the points.

Question: Say I have a $10\times10$ plane and I am given two points on the plane, suppose $(0,0)$ and $(10,10)$. What formula or algorithm could be used to trace all the possible paths between these two points? I would like to apply it to a plane of variable area and to any two points within that plane.
Here is a photo that will hopefully clarify

If the algorithm were to draw the route's lines they should be something like this. You could see that there are many other possible routes with an increase in 'turns' but these 4 'main'routes are the ones that span the whole plane to your target
Comment: I'm guessing there must be some constraint on what is meant by a valid path, otherwise there are clearly unlimited possibilities. Is the path confined to the integer grid? Or to line segments joining integer lattice points? Is there some restriction on directions? On revisiting points already part of the path?
Comment: You seems to implicitly assume that the path is indeed confined to the integer grid lines (despite your mention of "diagonally"). In your example, there are far more than 3 possible paths from x to y, unless there are more constraints you haven't yet explained. For example, starting from x, go down 1, right 2, up 1, left 1, up 1, right 1 to end at y. Is this one of the 3 paths?
Comment: If you are allowed to visit a location more than once, than the number of paths is unlimited. On the other hand of you can visit a location only once, it is easy to get trapped between your own path and the walls of your area.  For example in your picture, go $RDDDLUU$ and you are stuck.
Comment: Say once you take a step down, you cant go up, or versa vise. Also you cannot cross your own path twice
Answer: Suppose $(x_1,y_1)$ and $(x_2,y_2)$ represent the two points on a plane of size $m\times n$. You didn't specify restrictions on the paths, but I'll assume they must fall on gridlines.
Any path connecting these two points must have a net offset of $(x_2-x_1,y_2-y_1)$, so to find all the shortest paths you would just have to arrange $h=x_2-x_1$ horizontal and $v=y_2-y_1$ vertical steps starting from the first point. For example, with R = right and U = up, the move RRRRRUUURRUUUUUUURRR will take you from (0,0) to (10,10).
Now to find all possible paths (including those that overlap and cross earlier parts of the path), you could also insert backwards movements to create offsets like this: $(h+1)-1$, $(h+2)-2$,...,$(h+(m-h))-(m-h)$. Doing the same procedure for vertical motion, you can generate all possible paths by creating random sequences of left, right, up, and down motions in which the number of each motion is on that list.
In your example, you could not only move 10 right and 10 up, but also 11 right, 1 left, 12 up, and 2 down. For instance, RRRUUUUDLURRRDUUUUURRRRRUU is a valid path that would be generated by this algorithm.


Explain scientific error

Question:
The third step scientific error, however, the book and the professor says it is 100% correct
Please, I want to interpret and explain clearly her and thank you.
Comment: What's wrong with it? Is the third step a transform $e^{\ln|1+x|} = |1+x|$? If so, it's correct, as $e^{\ln a} = a$, $\forall a > 0$.
Comment: You mean the third line should be $|y| = \dots$?  That is, $y$ could be negative, and thus not equal to $|1+x| e^{c_1}$.
Comment: I think that is it (and this bit of sloppiness is then silently corrected by introducing the $\pm$ at the end).
Comment: Thank you very much, I understand the issue very well.
Answer: I don't this has an error in it. In that third line the exponential is split by its multiplication rule, then e^ln(1+x) is simplified to 1+x.
What do you think it should be?
Comment: Thank you very much, I understand the issue very well.

Explain scientific error


Finiteness of the Riesz potential of the Hausdorff measure restricted to a compact set

Question: If $E$ is compact set in $\mathbb{R}^n$ with $0<
  H^s(E)<\infty$, where $H^s$ is $s$-dimensional Hausdorff measure
  and $0<s<n$, then fix $x$ and define $$ m(r):=
  f(B(x,r)) :=H^s(E\cap B(x,r))$$
If $m(r)\leq r^s$, then $$
  \int_{B(x,1)} \frac{df(y)}{|x-y|^t} <\infty$$ for $0<t<
  s$.
Proof of special case: If $m(r)=r^s$, then it is trivial.
How can we prove this in general?
Answer: Use the Layer cake representation:
$$|x-y|^{-t} = \int_0^\infty \chi_{\{y : |x-y|^{-t} > \lambda\}} \,d\lambda = \int_0^\infty \chi_{B(x, \lambda^{-1/t})} \,d\lambda $$
Integrate both sides with respect to restricted Hausdorff measure $\mu=H^s_{|E}$, changing the order of integration on the right (Tonelli's theorem)
$$\int |x-y|^{-t} \,d\mu(y) =  \int_0^\infty \mu(B(x, \lambda^{-1/t})) \,d\lambda  $$
By assumption,
$$\mu(B(x, \lambda^{-1/t})) \le \min(\lambda^{-s/t}, H^s(E))$$ and the integral
$$
\int_0^\infty \min(\lambda^{-s/t}, H^s(E)) \,d\lambda  $$
converges because $s/t > 1$.


I'm 17 and I still sound like a 12 year old; will my voice ever change?

Question: here's the deal: although I have no former professional training in music, I still enjoy singing and playing the guitar. I am by no means unbelievably talented when it comes to singing, but I'd say that through practice I have managed to improve my singing skills a little bit (I have more control over my voice: it doesn't shake anymore, i can reach higher and lower notes than before, less off key notes etc) yet all the progress I've made is in vain because of how my voice sound in general (my vocal timbre?? i don't know if that's how you call it, english is not my mother tongue). So, I'm a 17 year old girl, but I still sound like an annoying 12 year old boy, and it's just ruining me. If I struggle a little bit, I can sound like a 7 year old adorable child. Yet, it seems impossible for me to gain a more feminine and beautiful voice. It's horrible. I hate myself for it.
So, my question is: will my voice ever change?
Comment: Your voice will change throughout your life. The voice isn't even considered to have matured until you reach your mid-30's.
Comment: Very few people like the sound of their own voice, especially on recordings. If your audience likes your voice, that's all you need.
Comment: @pro: Nah. Don't value others' opinions too highly. [See more and be more than your appearance or voice](https://www.youtube.com/watch?v=uDowwh0EU4w).
Answer: I am 58 years old, and still have the speaking voice of a 13 year old kid.
I answer the phone at home, and the telemarketers politely ask, "Is your mom or dad home?"
It's okay.
Because I am wicked-smart, and a really good musician and singer.
(I just end up singing the high harmonies, sometimes higher than those of the girl singer in my band. )
It is what it is.
Some people are gifted with luxuriant blonde hair, and others get dun brown locks.
Some have blue eyes and others have hazel eyes.
Mine are brown, tinged with red from all the beer drinking.
Some guys have a deep, wonderful baritone speaking voice like Sam Elliot's and others are cursed with a voice like mine or Geddy Lee of the band Rush.
It is what it is.
Embrace it, work with it, and make the most of it.
Be the very BEST guy with YOUR voice that ever was.
Comment: Also, some people prefer dun brown hair and voices like Geddy Lee over blonde hair and voices like Sam Elliot.
Comment: @ToddWilcox Indeed.  Or who could imagine Neil Young with any other voice than the one nature gave him?
Answer: 17 is not really a terminal age for voice changes.  It depends on your overall constitution and hormonal balance when changes happen.
That being said, there is a wide range of adult voices even for females and a lot of vocal character comes about by its formants which are to a considerable degree a function of mouth shape and size and tongue use than of the fundamental pitch.
If you end up as a high soprano, formants in your higher range collide with the singing pitch, leading both to problems producing recognizable vowels as well as a timbre that's sort-of neutral in character.  This is dealt with in classical singing using vowel adjustments.  Transferring those skill sets to other singing ranges leads to a singing voice character that is fundamentally different from your usual speaking voice.
The usual songbook range tends to be a lowest common denominator: as such, it will tend to favor alto-but-not-too-much female voice types.  Assuming that your voice is not going to change a lot more, this will put you at a bit of a disadvantage so it might make sense to practice spontaneous transposition a fourth or fifth up (read A, play E) to get into a range where you are more effective.
At any rate: at your age, your voice type cannot be considered final, and even if it were final, there would be a lot of options to put it to good use in music.
Answer: Get some professional training, classical voice is worth the $ for a short while.  Regardless of what you think your voice sounds like or should sound like every human has multiple ranges, and break points from one range to the next.  I think (but I'm not sure) it has to do with how the sound resonates in the cavity that is your larynx + mouth + sinuses.  When a person passes through notes at these register changes they will typically sound either like Bobby Brady in the Brady Bunch episode when his voice cracks and almost ruins the bands demo tape, or Julia Child (the chef, more like Dan Aykroyd imitating Julia Child).
For example (using myself) I now have a 3 octave range from D2 to D5 with a break point at Bb3-C4.  Oddly, I can sing fine in the high register but when I pass through that note on the way there look out, it's a mess.
You mention "control" and the irony is that one does not master vocals by "control" but by relaxation.  Also, trying to control the throat (which I thought was normal) will lead to a worse sound and eventual problems.  One controls the timbre of the vocal sound by exercising certain mouth shapes and diaphragm support.  Trust me if you were to spend some time on these aspects of vocal training with a coach you will not be disappointed.
As for living with your voice as it sounds now.  If you really listen to some of the famous rock and pop stars out there many have very poor voices (timbre wise).  When I listen discerningly to some of my favorite rock bands I can't believe the singer is getting away with what they're doing.  So maybe your voice sounds good enough.
Answer: I want to give you this one tip. 12 year old boys have very high pitched voices but they are not feminine because they do not speak light or airy. To sound feminine, I would say to speak at the same pitch, but speak a bit quieter and at the end of the sentence go a bit higher in pitch. Do not speak too loud in your lower range. Speak quiet in your middle range.
Answer: Very few people like the sound of their own voice, especially on recordings. I sing professionally and I don't like my voice. If your audience likes your voice, that's all you need.
Having said that, the only real difference between a boy's voice and a woman's voice is the styling, the pitch is the same.  So study female vocalists you like and learn to sing in their style by recording yourself.
A good singing teacher can help you with this as well.


ASP.NET forgets dlls in bin directory

Question: We have a plugin system on a WCF service that checks libraries placed in the bin folder for certain assembly level attributes and loads them. This allows customization of certain service calls based on which client is making the call. This works great most of the time. However, sometimes it seems to lose the dll, which causes the service to revert back to the default implementation for every client. The solution so far has been to just move the dll file out of the bin folder, and back in. This causes asp.net to pick up the file and customizations start working again.
I'm at a loss for why the assembly is getting missed like that after a certain amount of time. Any ideas as to what might be causing this?
Edit: Problem stated more clearly
Our services use a service factory to hand out custom implementations based on what client is calling the code. If there is not a custom implementation, we hand out a default implementation. We use GetAssemblies to check for assemblies that are decorated with an attribute designating them as a custom implementation and associating them with a client. The problem is that GetAssemblies stops returning a client's custom assembly even though the library remains in the bin folder. Moving the dll out of bin, and back into it will fix the issue for about a week until it happens again
Comment: *what* no longer uses the custom implementation?  Your code?  Do you mean the GetAssemblies() call doesn't return the assemblies you think it should return?  The problem isn't very clearly described.
Comment: Our services use a service factory to hand out custom implementations based on what client is calling the code. If there is not a custom implementation, we hand out a default implementation. We use GetAssemblies to check for assemblies that are decorated with an attribute designating them as a custom implementation and associating them with a client. The problem is that GetAssemblies stops returning a client's custom assembly even though the library remains in the bin folder. Moving the dll out of bin, and back into it will fix the issue for about a week until it happens again.
Comment: do you get any error or warning message in the eventlogs? also, any antivirus software running on that box?
Answer: The problem that you are having must be related to the automatic recycling of the appdomain. Apparently appdomain recycle behaves differently from a real restart. On recycle, it will only load dll that is explicitly reference and loaded as needed. See this link
http://www.chrisvandesteeg.nl/2006/06/15/appdomain-recycle-different-from-real-restart/
The fact that GetAssemblies will only return you the assembly that is currently loaded into the appdomain, this can explain the anomaly that you are getting with your program. To be safe, if you are dealing with plugin type library, you should always scan the plugin files (dlls) and load them explicitly using Assembly.LoadFrom. Another alternative is to host your WCF services externally in your custom host such as window service so that the life time of the host is not subject to the IIS recycling policy.
Read this for more information on appdomain recycling
http://blogs.msdn.com/tess/archive/2006/08/02/asp-net-case-study-lost-session-variables-and-appdomain-recycles.aspx
Comment: There is no accept option anymore. This would be the answer I would accept.
Comment: Pity too that I didnt get the bounty :p
Answer: How are you loading the assemblies?  Next question... why?  Assemblies in the bin directory should automatically be loaded and available to ASP.NET applications that reference them.  Perhaps you are getting some conflict here... ie, access is denied because some other thread/process has an open handle to the assembly.  Sorry that's so vague, but that's the only thing that immediately springs to mind.  You could potentially use FileMon or a similar tool to check this.
Also... what exactly do you mean by "lose" the DLL?  You are calling some specific method to find it, and it fails?  What is the error?  Have you checked the Event Viewer for unhandled exceptions?
Comment: We're calling AppDomain.CurrentDomain.GetAssemblies() and checking them to see if any have the correct attribute. If they do, then we use it instead of the default implementation. By "lose" I mean it no longer uses the custom implementation, and just uses the default instead.
Comment: *what* no longer uses the custom implementation?  Your code?  Do you mean the GetAssemblies() call doesn't return the assemblies you think it should return?  The problem isn't very clearly described.
Comment: I thought assemblies were lazy loaded. We had an application here that required some hints as to what assemblies to look at, because the core application had no direct reference to it.
Comment: He is using REFLECTION to dynamically load the assemblies.
Answer: GetAssemblies only returns a list of the Assemblies already loaded. If you haven't used a type from that assembly, it won't have been loaded yet. You need to use Assembly.Load to load the assembly you want off disk; the assemblies in the /bin folder are not automatically loaded into the app domain.
Also, you might look into using the Managed Extensibility Framework (MEF), it was designed specifically to handle the functionality you're talking about.
Answer: Assembly hint paths are checked only once when your AppDomain loads, even if you explicitly tell it to load an assembly by name it will not find it.  In order to solve this you need to reload your primary AppDomain, or create a secondary AppDomain and use that to load your assembly, this is what I have done in the past and it works fine.  It does however carry the overhead of a second AppDomain, not sure if thats a big deal or not.
Answer: ...replacing an assembly in a \bin directory will cause a whole new batch compile of that directory.
http://msdn.microsoft.com/en-us/library/5dws599a(VS.71).aspx
Do you have your initialization code in Application_Start inside global.aspx?

ASP.NET forgets dlls in bin directory


Module or method for handling my scheduling needs?

Question: I'm using Drupal 8 to build a website that I will use to manage a D&D Campaign. I'm looking for a way to set up session planning.
I would like something where I can create time slots where I am available and then the users can do one of two things:

Create a proposed session (select a time span within a time slot, add information on what they would like to do - could just be a textbox)
Join a proposed session (potentially with a cap on # of users per session)

Ideally, I would then be able to approve/deny proposed sessions and have approved sessions block out their time slots.
Is there anything that could work for this? The closest thing I've found would be https://www.drupal.org/project/appointment_calendar but that doesn't look like it would support the ability for multiple proposed sessions or the approve/deny aspect of it.
Or is there a way to make this work with a custom content type or something?
Answer: You may want to try Bookable Entities Everywhere. It looks rather adapted to what you are looking for, is available to D8 and has a few tutorials to get you started.
Comment: I had come across that one, but saw that it didn't have a stable release yet, that it's still in beta.
Comment: I would recommend to try it out and see if it works for you, there are many modules in alpha or beta that are very high quality in drupal.org.


What are difference between a data, a Statistic and a Value?

Question: A data (datum?) is an information such as
"tree 1 has a height of 5 meter" it is a data. Up to best of my understanding, height is a variable and 5 meter is a value. A variable and an associated value making up a data (datum?).
A statistic is any quantity computed from values in a sample that is used for a statistical purpose.
Such as

"The manager of a large hotel located near Disney World indicated that 20 selected guests had a mean length of stay equal to 5.6 days."
In this example, "5.6 days" is a statistic, namely the mean length of stay for our sample of 20 hotel guests. The population is the set of all guests of this hotel, and the parameter is the mean length of stay for all guests - (Wikipedia)

It looks like same as a datum. Also the quotation mark around "5.6 days" makes me think whether the term statistic means value.
Now my question is what are the differences between data, statistic and value.
What I have already tried: I have consulted my textbok 'Introduction to Biostatistics (A textbook of biometry)' by Dr. P. K. Banerjee; Also I have visited various website on google. However the differences are not clearing up.
Answer: I don't think "values" has a precise definition, but here is my attempt.
A datum is a single piece of data.  The datum can be comprised of many values.  For example, if you seek to collect height, weight, and age measurements from people, then a datum would be a single observation of someone's height, weight, and age.  Data are thus several observations of these values.
A statistic is a function of data.  Take the sample mean for example.  We input the data into this function and are returned a single value (or multiple values were you to compute the sample mean of a vector, for example).
Comment: @AlwaysConfused no. Statistics are not data in themselves. The are functions of data.
Comment: So may I call a statistic is basically same as a "secondary data"?
Comment: Note that this answer does not differentiate sample statistic/population parameter.


Unable to import _winreg in Python 2.7.9 virtual environment

Question: I'm running an app engine application in a virtual environment on windows 7 64bit, python 2.7.9 x64.
Here's the stacktrace:
    p_system = platform.system()
  File "C:\Python27\lib\platform.py", line 1310, in system
    return uname()[0]
  File "C:\Python27\lib\platform.py", line 1206, in uname
    release,version,csd,ptype = win32_ver()
  File "C:\Python27\lib\platform.py", line 597, in win32_ver
    import _winreg
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\devappserver2\python\sandbox.py", line 945, in load_module
    raise ImportError('No module named %s' % fullname)
  ImportError: No module named _winreg

However, it works just fine from cli (outside venv):
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\Admin>python
Python 2.7.9 (default, Dec 10 2014, 12:28:03) [MSC v.1500 64 bit (AMD64)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import _winreg
>>> import platform
>>> platform.system()
'Windows'
>>>

Why does this happen? What can I do to fix this?
Comment: @JoranBeasley, `_winreg` is normally built into python27.dll (see `sys.builtin_module_names`). This environment obviously excludes it because it's sandboxed.
Comment: _winreg is a part of python, so it's not on pypi and I cannot find it anywhere
Comment: you mean the application `virtualenv`? you probably need to install winreg? or win32api
Answer: Module _winreg, as the docs say, exists to "expose the Windows registry API to Python".
App Engine does not supply a "Windows registry API" (nor any other Windows-specific API).  Therefore, its sandbox blocks attempts to import the module -- note, at the end of your stack trace, that the exception is deliberately raised in module sandbox.py of the App Engine SDK.
Python's "virtual env" plays no part here -- it's all about App Engine.
Please clarify what task you're trying to accomplish with _winreg once your GAE app is deployed -- assume it's deployed to Linux servers (although the GAE runtime doesn't supply Linux-specific APIs either:-), so there is no Windows Registry API anywhere in the neighborhood...
Comment: The OP is trying `platform.system()`, which really should handle this scenario more gracefully.
Comment: It calls `platform.uname()`, and on Windows that calls `platform.win32_ver()`. This leaks the `ImportError` instead of handling it as it does  `AttributeError` for `sys.getwindowsversion`. Without access to the registry, it should fall back on parsing environment variables and the output of the `ver` command. For the latter, in 2.x `platform._syscmd_ver` may still fail ungracefully if a `RuntimeError` is raised by `popen`, such as when `%COMSPEC%` is undefined. `_PyPopenCreateProcess` should raise `OSError` for this; a `RuntimeError` is overkill.
Comment: Please open an issue on https://code.google.com/p/googleappengine/issues/list -- ideally amply explaining the task that requires calling `platform.whatever` in the first place, in the face of App Engine's determined, architected attempts to hide what platform the servers are running on, to focus on 100% platform independence:-).  At least, sharper, earlier, more in-your-face exceptions might be raised to diagnose such attempts to breach the sandbox...
Comment: I've never used GAE. In production does it substitute its own platform module and modify the sys module such as `sys.platform`, etc? Specifically in this case I was thinking this is a Python 2.x issue. `platform.win32_ver` should gracefully handle the absence of `_winreg`. On most systems the only information that `platform.win32_ver` doesn't get from `sys.getwindowsversion` is the kernel type (uniprocessor/multiprocessor and free/checked).
Comment: @eryksun, no, GAE just doesn't supply platform info -- it'a a PaaS (Platform as a Service) and keeps enough degrees of freedom to theoretically "switch platforms from under you" in the middle of things.  If you have a use case that's hurt by this, opening a feature request on the issue tracker (with full explanation of what necessary task this stops you from performing) is the only way to perhaps get this changed one day.
Comment: Hi all, does [this seem relevant?](https://cloud.google.com/appengine/docs/standard/python/issue-requests), "To use `requests`, you'll need to install both `requests` and `requests-toolbelt` using the vendoring instructions.

Once installed, use the `requests_toolbelt.adapters.appengine` module to configure `requests` to use `URLFetch`:"
Answer: The workaround provided by Google, until a fix is implemented, is as follows:

Go to: <sdk_root>\google\appengine\tools\devappserver2\python\sandbox.py
Find the definition of _WHITE_LIST_C_MODULES = [xxx]
Add the following two lines to the list:

'_winreg',
'_ctypes',
If this does not succeed, run python -m pip install google-cloud
Comment: I now get "NameError: global name '_dlopen' is not defined" error. Do you have any idea about this?
Answer: I think that the problem is that GAE is not aware that you are in development mode, I suppose because the SERVER_SOFTWARE variable is set to something not starting with "Dev".
If you execute the following code (before calling any GAE library) it should fix the issue:
import os
os.environ['SERVER_SOFTWARE'] = 'Dev'

Note: Make sure this code is removed before going to production.
Answer: I had this problem a few days ago.
As said above, the GAE sandbox on Windows blocks some routines or libraries, even built-in one, because it is developed to Unix-like platform.
I opened an issue to Google Team and they passed a workaround:
https://issuetracker.google.com/issues/38290292
That workaround worked well.


JavascriptMVC: CanJS loading without jQuery

Question: I cannot find in the documentation any "official" way to steal (stealjs) canJS without loading jquery.
The problem is that I'm working with Yii Framework (PHP) and some components need jquery before even i include myapp.js modules, that is i must include jquery before everything.
Now when i include myapp.js it also steals canJS that in turn will load jquery again breaking my application (2 instance of jquery running).
How can i steal canJS without jquery?
Comment: http://canjs.us/release/1.1.5/can.yui.js
Comment: I dont want to load yui, i want to loading canJS without the "library" because it shoudl be already loaded.
Answer: This probably isn't an ideal solution, but you can create an empty dummy.js file and map jquery's path to that in stealconfig.js:
<code>steal.config({
  ...
  paths: {
    "jquery": "dummy.js"
  }
  ...
})
</code>
Comment: mhm....honestly I thought about it too, but yes isn't an ideal solution, but it works like a charm XD.


Routing Error during "Ruby on Rails-Tutorial"

Question: It seems like some people here had this problem but I couldn't find any solution in another topic.
I am doing Chapter 3 of the Ruby on Rails-Tutorial, working on the static pages. When I want to open them on the localhost it gives me a "Routing Error" in the Browser.
My Ruby is currently on version 1.9.3.
My Rails is currently on version 3.2.
I have tried:

restarting the server
saving all the files again
checking any issues in the static_pages_controller.rb
checking any issues in the routes.rb
checking any issues in the static_oages_spec.rb

Also there are no bugs in the HTML code of the single static page. And I can't find any more help in the tutorial, neither in other questions here on StackOverflow.

Edit:
This is the actual error message from the browser:

Routing Error
No route matches [GET] "/static_pages/home" Try running
rake routes for more information on available routes.

if I go to http://localhost:3000/static_pages/home, to one of three static pages I have.
This is routes.rb:
SampleApp::Application.routes.draw do

get "static_pages/home"

get "static_pages/help"

get "static_pages/about"

end

Also, I tried "rake routes" in the terminal, too. This is the result:
home_static_pages GET    /static_pages/home(.:format)  static_pages#home
 help_static_pages GET    /static_pages/help(.:format)  static_pages#help
about_static_pages GET    /static_pages/about(.:format) static_pages#about
      static_pages POST   /static_pages(.:format)       static_pages#create
  new_static_pages GET    /static_pages/new(.:format)   static_pages#new
 edit_static_pages GET    /static_pages/edit(.:format)  static_pages#edit
                   GET    /static_pages(.:format)       static_pages#show
                   PUT    /static_pages(.:format)       static_pages#update
                   DELETE /static_pages(.:format)       static_pages#destroy

And this is the error message the server is giving me:
Started GET "/static_pages/home.html" for 127.0.0.1 at 2012-04-03 13:23:54 +0200

ActionController::RoutingError (No route matches [GET] "/static_pages/home.html"):
  actionpack (3.2.3) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'
  actionpack (3.2.3) lib/action_dispatch/middleware/show_exceptions.rb:56:in `call'
  railties (3.2.3) lib/rails/rack/logger.rb:26:in `call_app'
  railties (3.2.3) lib/rails/rack/logger.rb:16:in `call'
  actionpack (3.2.3) lib/action_dispatch/middleware/request_id.rb:22:in `call'
  rack (1.4.1) lib/rack/methodoverride.rb:21:in `call'
  rack (1.4.1) lib/rack/runtime.rb:17:in `call'
  activesupport (3.2.3) lib/active_support/cache/strategy/local_cache.rb:72:in `call'
  rack (1.4.1) lib/rack/lock.rb:15:in `call'
  actionpack (3.2.3) lib/action_dispatch/middleware/static.rb:62:in `call'
  railties (3.2.3) lib/rails/engine.rb:479:in `call'
  railties (3.2.3) lib/rails/application.rb:220:in `call'
  rack (1.4.1) lib/rack/content_length.rb:14:in `call'
  railties (3.2.3) lib/rails/rack/log_tailer.rb:14:in `call'
  rack (1.4.1) lib/rack/handler/webrick.rb:59:in `service'
  /Network/Servers/pluto.kayoom.lan/Users/benediktkrebs/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/webrick/httpserver.rb:138:in `service'
  /Network/Servers/pluto.kayoom.lan/Users/benediktkrebs/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/webrick/httpserver.rb:94:in `run'
  /Network/Servers/pluto.kayoom.lan/Users/benediktkrebs/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/webrick/server.rb:191:in `block in start_thread'

Comment: Yeah, but I found the problem anyway... ;)

I am at the very beginning of that stuff... =D

My Rails Server was running in the .../rails_projects/demo_app.
Currently I am working in the sample_app.

Thanks for the nice answers anyway... =D Hope I made you laugh shortly... ;)
Comment: If you add the actual error message people may be able to help you.
Comment: Also add the exact URL you are trying to load, and your routes file please.
Comment: Can you push your full current (not working) code to github? That would make it easier for people to find out what/where the problem is.
Comment: just paste your controller and let us see your controller class and methods, the routes that have been specified below should work if you have matching controller methods
Answer: Try this :
match "/static_pages/home" => "static_pages#home", :via => :get
match "/static_pages/help" => "static_pages#help", :via => :get
match "/static_pages/about" => "static_pages#about", :via => :get

Add into routes , restart the server and refresh browser .
Comment: Did exactly the way you said... Doesn't help, too. Sorry! =( Updated the question above a bit more.
Comment: Try to run 'rake routes > route.txt' . And check your routes into the file . And try that.
Comment: The routes in the text file are exactly the ones I have in the route.rb. Without any spelling error.
Comment: weird ... may be some platform issue
Answer: If you are using Spork you must re-run Spork so your tests will consider the changes in config files like routes.rb, that are pre-loaded with Spork, so are not automatically updated.

Stop Spork (Ctrl + C)
Run Spork again (bundle exec spork)

Source: this is the source of this information
"after changing a file included in the prefork loading (such as routes.rb), you will have to restart the Spork server to load the new Rails environment.
If your tests are failing when you think they should be passing, quit the Spork server with Control-C and restart it
Answer: your routes.rb file has problems, use either RESTful style:
resource :static_pages do
  collection do
    get :home
    get :help
    get :about
  end
end

or the non RESTful style:
match "static_pages/home", :controller => "static_pages", :action => "home"
match "static_pages/help", :controller => "static_pages", :action => "help"
match "static_pages/about", :controller => "static_pages", :action => "about"

for more details please refer to official guide: http://guides.rubyonrails.org/routing.html
Comment: Tried both. sadly it doesn't help... I still exactly the same error message. Also after restarting the Server and also after saving the file.
Answer: I had a few problems working through the Rails Tutorial, and it helped to be able to consult the author's GitHub repo: https://github.com/railstutorial
Find the file you're working on and compare it line by line. Or just cut and paste the full file and see if it will run, then track down your error.
Comment: Same problem again. Searched for the routes.rb in his github, copied into my file and saved. Restarted server and refreshed browser. Still the same error message.
Answer: If you check the routes.rb in config you'll probably find that the there is a 'e' missing from /home. Add that and you are golden. Or green. Or whatever :)
Answer: check your http:// address, specifically if you are on localhost:3000/path or localhost:3000/path1/path2, etc
Answer: Once you change the format of your mapping from get to match you will not need static_pages anymore, just go straight to localhost:3000/pagename e.g localhost:3000/about
Answer: From Ruby 2 to Ruby 3 there are some differences, but still the documentation for 3 is not easy to be found. There should be a tutorial only for that: practical differences between rails 2 and 3.
The guide provided by downloading Ruby on rails is "The book of ruby" but it's not good anymore. It should at least contain an advice at the beginning of chapter 19.
Answer: In
config/routes.rb
uncomment
root :to => 'welcome#index'


Displaying JS Alert in a styled modal (jQuery UI) window

Question: See the code below... And there's a fiddle here.
I want to style this with a jQuery UI. However, will I still be able to call this script, or will I have to embed it directly in the HTML page?
Here's the form...

<form onsubmit="showpell_13_14(document.getElementById('pellscore').value); return false;">
    <input type="text" value="Enter 13-14 PELL Score" onfocus="if(this.value == 'Enter 13-14 PELL Score') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Enter 13-14 PELL Score'; }" class="search-input-bg-pell" id="pellscore"  />
    </form>

Currently, when you search a PELL Grant Score, an alert() is called from another script.
The script is built out like this...
// Begin EFC Calculator for 2013-2014

function showpell_13_14(efc) {

  var pell;
  var ssg;
  var estpay;
  var monthpay;

    if (efc == 0) {
        pell = 5645;
        ssg = 0;
        estpay = -573;
        monthpay = 0;
    }

    else if (efc <= 100) {
        pell = 5595;
        ssg = 0;
        estpay = -523;
        monthpay = 0;
    }

    else if (efc <= 200) {
        pell = 5495;
        ssg = 0;
        estpay = -423;
        monthpay = 0;
    }

...with the results displaying based on this...
alert('Based on the 2013-2014 EFC you entered ('+efc+'), you may receive...'
                +' \n_________________________________________________________'
                +' \n-Tuition of 36 credits: $14,472'
                +' \n_________________________________________________________'
                +' \n-Direct Loan maximum for a Freshman* student: $9,405**'
                +' \n_________________________________________________________'
                +' \n-Potential PELL Grant Award: $'+pell+'.'
                +' \n_________________________________________________________'
                +' \n-Your estimated total out of pocket payment: $'+estpay+'.'
                +' \n_________________________________________________________'
                +' \n-Potential Student Success Grant: $'+ssg+'.'
                +' \n_________________________________________________________'
                +' \n-Your estimated monthly out of pocket payment: $'+monthpay+'.'
                +' \n...'
//              +' \nIf your student has $0 out of pocket, disregard the next few lines...'
//                +' \n_________________________________________________________'
//              +' \n-Your estimated monthly payment is calculated by...'
//              +' \n'
//              +' \nTaking your total out of pocket for the year ($'+estpay+')'
//              +' \nand subtracting your Student Success Grant ($'+ssg+') to get'
//              +' \n your overall payment which is then broken up over 9 months'
//              +' \nand comes to $'+monthpay+' per month.'
                +' \n_________________________________________________________'
                +' \n *Note: This is only configured for 1st year undergraduate students.'
                +' \n **Loan fees of 1% are included in the loan rates listed on this sheet.');

Again - I want to style this with a jQuery UI. However, will I still be able to call this script, or will I have to embed it directly in the HTML page?
Comment: You could try to overwrite `window.alert` to redirect the parameters to `jQuery().dialog()`... Though there's something bugging me about rewriting native functions.
Comment: I agree. I don't want to do that. In addition to the modern browsers, this has to be able to work on IE8, too. I don't think I can go that route.
Comment: Good ol' IE as we know it and hate it. That's the disadvantage about `alert`ing a feedback... it's pretty much uncontrollable without altering that native function. If you can, I'd alter the script to return it's result instead. I honestly don't see any other way...
Answer: The window.alert function and the jQuery UI dialogue are not related; the popup is just html.
The easiest solution to switching to a dialogue is to do the following:
put a blank div in your html
initialize it with jQuery UI with autoOpen set to false
instead of calling alert, replace the html of the blank div with the contents you would put in the alert and then show the jQuery dialog.

Before getting to my example, I have some general advice: don't ever put more than a single function inside an html tag. In general, try to keep your JavaScript and your html separate, as it'll make your (and anyone working with your code's) life easier. And since you're using jQuery, it's better to avoid JavaScript inside tags altogether by using the .on() function and binding your functions programmatically.
So I worked on your fiddle a bit, and got the jQuery UI dialog working. I also removed all the javascript from your html.
Lines 1-23 bind function to the form's onsubmit, the textbox's onfocus and onblur, and initializes the jQuery UI dialog (docs here).
Starting from Line 504, I've modified the alert to use the jQuery UI dialog.
I did this by setting the old alert text as a variable and replacing the newlines with html linebreaks so they show up properly in the dialog. And then I inserted the content into the dialog and opened the dialog.
Here is the Fiddle.
Let me know if it all makes sense to you, or if you have any questions :)
P.S. When you use jQuery $('#pellscore').val() is way shorter than document.getElementById('pellscore').value ;)
Update
The Problem
So here's the problem with your current setup: you're using (and relying on) a ridiculously old version of reveal.js. My guess is that you googled "jquery reveal" and came across this link to zurb's version of reveal.js. If that's how you got it, (and most definitely if you got it from somewhere else) you probably didn't notice that a) it hasn't been updated in two years,  b) it uses jQuery 1.4.4, which is three years old, or c) the the bold notice that states that it won't be updated anymore.
Either way, the reason your page breaks is because jquery.reveal.js makes a call to .live, which is deprecated since jquery 1.7 and completely removed as of 1.9 .
The Solution
I hate the idea of patching something that's two years old, but unless you want to rewrite a bunch of code and try integrating the current version of reveal.js (source), I recommend the following quick fix:
Open up jquery.reveal.js, go to line 20, and replace .live with .on, e.g.
from
$('a[data-reveal-id]').live('click', function(e)

to
$('a[data-reveal-id]').on('click', function(e)

That should fix your problem. I tried it locally and it seemed to work. Let me know if it works for you :)
Comment: I am going to work on implementing the new version of reveal. I thought that's what I had... didn't dig through Github enough I suppose. Your answer works for me. Much thanks!
Comment: It makes sense to me. Tried it and it works great. However (and you might find this has something or nothing to do with the situation), when I place all this into the page (dependencies include jQuery 1.7.1), it doesn't work. When I run it with 1.9.1, then everything else I have doesn't work, and the script you did (in your fiddle) doesn't work either.
Comment: There's a link to my current set up [**here**](http://webfro.gs/south/kb2/) and I've created a link to the same page with your set up [**here**](http://webfro.gs/south/kb2/index2.html)...
Comment: Forgot to remove authentication from the server. You should be good now.
Comment: I'm glad you're not taking the lazy way out lol. Glad to help :)


String to tuple of words

Question: I define a word as a sequence of characters (from a to Z) which might also contain an apostrophe. I wish to split a sentence into words, with the apostrophes removed from the words.
I'm currently doing the following to get the words from a piece of text.
import re
text = "Don't ' thread \r\n on \nme ''\n "
words_iter = re.finditer(r'(\w|\')+', text)
words = (word.group(0).lower() for word in words_iter)
for i in words:
    print(i)

This gives me:
don't
'
thread
on
me
''

But what I wan't is:
dont
thread
on
me

How can I change my code to achieve this?
Please note that there is no ' in my output.
I also wish for words to be a generator.
Comment: Aren't you almost there, just add an `i = i.replace("'", "")` in your `for` loop and then yield the string if it's non-empty?
Comment: How much input are you trying to parse?
Comment: @Tritium21 I'm building a corpus, so I'm processing text files of different lengths.
Answer: This looks like a job for Regex.
import re

text = "Don't ' thread \r\n on \nme ''\n "

# Define a function so as to make a generator
def get_words(text):

    # Find each block, separated by spaces
    for section in re.finditer("[^\s]+", text):

        # Get the text from the selection, lowercase it
        # (`.lower()` for Python 2 or if you hate people who use Unicode)
        section = section.group().casefold()

        # Filter so only letters are kept and yield
        section = "".join(char for char in section if char.isalpha())
        if section:
            yield section

list(get_words(text))
#>>> ['dont', 'thread', 'on', 'me']

Explanation of Regex:
[^    # An "inverse set" of characters, matches anything that isn't in the set
\s    # Any whitespace character
]+    # One or more times

So this matches any block of non-whitespace characters.
Comment: Note that this is around 4 times slower than my version.
Comment: I'll accept that timing after you add `.casefold`/`.lower` to yours. ;) Mine's more technically correct 'cause I check whether `isalpha` rather than remove ASCII punctuation, too, but I'll let that slide.
Comment: I think you can lower it once, using `.lower()` in the `re.finditer` call.
Comment: That'll work on the whole string at once, though, which we want to avoid.
Comment: Updated my solution with new timings.
Answer: words = (x.replace("'", '') for x in text.split())
result = tuple(x for x in words if x)

...does just one iteration over the split data.
If the data set is large, use re.finditer instead of str.split() to avoid reading the entire data set into memory:
words = (x.replace("'", '') for x in re.finditer(r'[^\s]+', text))
result = tuple(x for x in words if x)

...although, tuple()-ing the data will read everything in memory anyway.
Comment: wont strip the ' in "don't"
Answer: Using str.translate and re.finditer:
>>> text = "Don't ' thread \r\n on \nme ''\n "
>>> import re
>>> from string import punctuation
>>> tab = dict.fromkeys(map(ord, punctuation))
def solve(text):
    for m in re.finditer(r'\b(\S+)\b', text):
        x = m.group(1).translate(tab).lower()
        if x : yield x
>>> list(solve(text))
['dont', 'thread', 'on', 'me']

Timing comparison:
>>> strs = text * 1000
>>> %timeit list(solve(strs))
10 loops, best of 3: 11.1 ms per loop
>>> %timeit list(get_words(strs))
10 loops, best of 3: 36.7 ms per loop
>>> strs = text * 10000
>>> %timeit list(solve(strs))
1 loops, best of 3: 146 ms per loop
>>> %timeit list(get_words(strs))
1 loops, best of 3: 411 ms per loop

Comment: `text.split()` processes the whole shebang at once, Baz wants to process cumulatively.
Comment: Nice, but what about dashes? "word1---word2 word3"
Comment: @hcwhsa text.lower() will create a copy of text which I wish to avoid since it can be very big
Comment: @hcwhsa As I stated in my question, I only define a word to include from a to Z plus apostrophes. Your code will pass through letters from non English alphabets and numbers etc.
Comment: @Baz You can use regex for that: `x = re.sub(r'[^a-z]+', '', m.group(1), flags=re.I).lower()`
Answer: import string
tuple(str(filter(lambda x: x if x in string.letters + string.whitespace else '', "strings don't have '")).split())

Comment: As with hcwhsa's, `text.split()` processes the whole shebang at once, Baz wants to process cumulatively.

String to tuple of words


Generate a Monte Carlo sample from a PDF defined by a Fourier Series

Question: I have a probability distribution (PDF) defined by a Fourier series.. actually it's a purely cosine series over a known range. The PDF quite smooth, so most of the power is in the low 5 or so frequencies. The function is (like a PDF must be) always positive. It's well defined everywhere.
I only need a single sample, so tabulation or function fitting is likely too expensive; that'd pay off if I needed thousands of samples, but I need just one, then I'll throw the PDF away and generate a new one.  (This is all part of a Markov chain walk, and the transitions are defined by Fourier coefficients).
So, I want to efficiently generate one sample from this PDF. What's the best strategy?
One method that works but is slow is to use a von Neuman rejection method.  The PDF is bounded from above by the sum of the absolute values of all the sine coefficients. I can generate a random point x in U(0,1), evaluate the series for that x, then accept the point with a probability based on the ratio of f(x) and the upper bound. This will work but it's super-slow!
The second strategy would be to generate a U(0,1) sample and feed it through the inverse CDF, but that involves solving a nonlinear equation for x, which is iterative and even slower.
Are there any other strategies I can experiment with?
Comment: You speak of "evaluating the series" -- it seems that what you have is actually a Fourier sum?
Answer: You could divide the interval into subintervals, for each subinterval precalculate the minimal and maximal values of each cosine there, and then when you have a distribution you can use that to calculate better bounds in each interval. Then you need to sum the areas under all the bounds, generate one random number to choose a subinterval according to the summed areas, and then apply the rejection method within the subinterval. However, if most of the power is in the lowest $5$ modes, I doubt that this will lead to a significant improvement, if any; in fact I doubt that in that case you'll be able to significantly improve on the simple rejection method with any method.
Answer: The solution has a nice elegance about it.
Since this is a Fourier series, there's both cosine and sine terms over the range -pi/2 to pi/2. Break the sum up into the two halves. Notice the cosine terms are symmetric around 0, the sine terms are antisymmetric.  So if we can first  properly sample a point x from the cosine series alone from 0 to pi/2, we can use the simple evaluation of F(x) versus F(-x), using the ratio to decide which point to accept. The sine terms basically let you choose between the two alternatives.
But this still leaves the problem of sampling from a (simpler) cosine series from 0 to pi/2. Well, we can transform that recursively into symmetric and antisymmetric  terms over the range 0 to pi/2!  You can do this by shifting and stretching the range, making it a Fourier series again (which can now be sampled recursively), or by just keeping track of odd and even cosine terms... the methods end up being equivalent.
So each recursive level breaks down the sampling to a self-similar problem but with half the coefficients. Since Fourier coefficients rapidly decrease (assuming the PDF is pretty smooth) you'll likely end up with the simple problem of sampling from a single cosine lobe with ignorably small noise added to the lobe. Sampling from a cosine is easy (asin(x)), thus terminating the recursion.
In practice, this all works stably and fast, especially if you have just 4 or 8 terms.


Contradiction proof that a sequence cannot converge in probability

Question: Let $Y$ be distributed as a $N(0,1)$ random variable. Let $(Y_{n})_{n\in\mathbb{N}}$ be the sequence of random variables such that $Y_n=(-1)^nY.$ Prove that $Y_n$ does not converge in probability to any random variable.
Attempt: Assume $Y_n\rightarrow^pW$ for some random variable $W$. Then we have that $\lim_{n\rightarrow\infty}P(|Y_n-W|\le\varepsilon)=1$. However, I don't know how to apply this here. Perhaps proof by contradiction?--
Comment: @angryavian corrected this typo - thanks. Any ideas how to solve this?
Comment: You also didn't write down the definition of convergence in probability correctly. Double check the subscript of the limit, and the limiting random variable.
Comment: @angryavian i've corrected this now. No clue how to do ths problem though:(
Comment: $Y_n - Y$ should be $Y_n - W$
Answer: Note that $|Y|=|Y_n|$ for all $n$.
If $|Y(\omega)| = |Y_n(\omega)| > 2\epsilon$ and  $|Y_n(\omega) - W(\omega)| \le \epsilon$, then $|Y_{n+1}(\omega) - W(\omega)| = |-Y_n(\omega) - W(\omega)| > \epsilon$. Thus,
$$P(|Y| > 2\epsilon, |Y_n - W| \le \epsilon) \le P(|Y_{n+1} - W| > \epsilon).$$
If $Y_n \overset{p}{\to} W$, then the right-hand side tends to zero as $n \to \infty$, and therefore so does the left-hand side.
Then,
$$P(|Y| \le 2\epsilon, |Y_n - W| \le \epsilon)
= P(|Y_n-W| \le \epsilon) - P(|Y| > 2\epsilon, |Y_n-W| \le \epsilon) \overset{n \to \infty}{\longrightarrow} 1-0 = 1.$$
This implies $P(|Y| \le 2\epsilon) = 1$, which is false for $Y \sim N(0,1)$. (More generally, the only way $Y_n = (-1)^n Y$ converges in probability is if $Y=0$ almost surely.)
Comment: @StevenStadnicki Thanks!


Send Mail to Specific Roles

Question: I need to send Emails to site users with specific role like "Administrator".
This is achievable using view on any action like "After saving new content".. etc..
But i want to send emails on one menu click event, I have menu item in Management Menu of Drupal and on click of that i want to send mails to all admin users.
How this is achievable?? Please suggest me guys..
Thanks in advance..!!
Answer: With custom module.
See hook_menu()
As page_callback define your "send mail" function for restricted user roles
Comment: I know this but how can i achieve this using rules as i have to pass message body, subject and other parameters from token..
Comment: Create rule on Event: System->init and then check for url as condition and add custom php as result
Comment: Thanks.. but is it possible to add default value of field as replacement pattern..??
Comment: if you can add a field value then this field should evaluate to default value if no other value was defined for that field

Send Mail to Specific Roles


Xcode 6.1 Autolayout issue for 3.5in display

Question: I have a very strange issue with Autolayout. Check attacked screenshot, I am primary interested in that red topbar. I set all constraints, and it works pretty well for all sizes, except 3.5in.

How is it possible something like this? Is this an Xcode bug?
Note: There are no constraints added programatically. Everything is right there, in storyboard.
Answer: In the end, it proved to be some problems in the way I set constraints. Deleted all, and redoing them, solved the problem.


mysqli_query() expects exactly 2 parameters 1 given

Question: Alguém me ajuda com esses 2 erros?

Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in
  C:\xampp\htdocs\Flexor\config.php on line 11

Fatal error: Uncaught Error: Call to undefined function mysql_error()
  in C:\xampp\htdocs\Flexor\config.php:11 Stack trace: #0
  C:\xampp\htdocs\Flexor\logar.php(2): include() #1 {main} thrown in
  C:\xampp\htdocs\Flexor\config.php on line 11

<?php
$host = "localhost"; //Servidor do mysql
$user = "root"; //Usuario do banco de dados
$senha = ""; //senha do banco de dados
$db = "jpec"; //banco de dados
$nome_site = "nome"; //Nome do site
$email = "firstname.lastname@example.com"; //E-mail do administrador
$site = "http://www.jpecinformatica.com"; //Seu site n se esuqece de bota o http://

mysqli_connect($host, $user, $senha) or die (mysql_error());
mysqli_select_db($db) or die (mysql_error());
?>

Answer: Como o próprio erro diz, mysqli_select_db espera dois parâmetros, mas só recebeu 1. De acordo com a documentação, o mysqli_select_db deveria receber um link, que é gerado pelas funções mysqli_connect ou mysqli_init, ou seja:
$link = mysqli_connect($host, $user, $senha);
mysqli_select_db($link, $db);

Quanto ao erro Call to undefined function mysql_error, novamente, segundo a documentação essa função foi descontinuada, use mysqli_error conforme indicado aqui. Para tratar erros durante o mysqli_connect, utilize mysqli_connect_error:
$link = mysqli_connect($host, $user, $senha) or die(mysqli_connect_error());
mysqli_select_db($link, $db) or die(mysqli_error($link));


Swap static public IPs without creating DNS conflicts?

Question: Our ISP is Comcast and we have 5 static public IPs from them that we use for various services, including customers connecting to our network, VPN, web, DNS, etc...
We need more IP addresses from Comcast. Unfortunately, Comcast is telling us that they can't just simply give us 5 more addresses. They only give static IP addresses in blocks of 1, 5 or 13.
In order for us to get more static IPs, they have to take away our current 5 static IPs and give us 13 new ones.
How do we make this transition without causing all sorts of DNS chaos?  We run public DNS servers, so we can make the DNS changes ourselves, but it will take some time obviously for those DNS changes to propagate throughout the internet.
Are there any easy ways to make this transition? Like create some type of fallback DNS entry or something? Surely there must be some sort of procedure for this kind of thing. The Comcast support guy was useless.
Answer: DNS records don't propagate, they are cached for the TTL (lifetime) of the record in question. I'm assuming your name servers are staying the same (based on what you've posted) so you'll want to look at the TTL of the records that are going to change and possibly lower the TTL to something that you're comfortable with. Any entity trying to access your "public" resources based on DNS that has your old information in their cache (for the lifetime of the TTL) will use the old information in their cache until the TTL expires and they perform a new lookup for those records. Any entity trying to access your "public" services that doesn't have any of your records cached will get the new information immediately. So if your current TTL is 3600 seconds (1 hour) then any entity that has that information in it's cache will attempt to use the old information for one hour, then the TTL expires and a new lookup is performed, at which time the new information is retrieved and cached (for the lifetime of the TTL).
Comment: Just to add some commentary: IMHO people worry too much about changing their DNS records (based on a lack of understanding of how DNS works, no offense intended). My suggestion is to change the TTL on your current records to 1 hour (if they aren't already) and make the change at a time when you think there will be the least traffic to the "public" resources that rely on those records for DNS resolution. Late on a Friday or Saturday night is usually a good time.
Comment: I blame AOL for that paranoia: +1 thought :)
Comment: @Zypher: I hear Steve Case laughing somewhere... I bet he's working on some new BBS he's about to launch.
Comment: yep, i've got him locked in my closet working on MY new BBS :)
Answer: Could you keep both IP range ? If it is the case, move your servers to the new IPs and put a redirection (with a router NAT) from the old to the new IPs. Change your DNS to the new range and wait for the propagation.
When it is done, you can remove your NAT, and free the old IP.
Check yours protocols : some are not able to cross NAT firewalls (like IPSec).
Answer: Being in a similar situation, I created a free account at editdns.net and configured a secondary zone for my domain.  Once the zone transfers were working I updated my domain registrar's name servers to point to the EditDNS.NET name servers (free01.editdns.net and free02.editdns.net) instead of my DNS servers.
Once I was sure the domain was resolving correctly from editdns.net I had the ISP switch over my IP addresses.  Next I updated all of my DNS server records with new addresses.  Finally I reconfigure the editdns secondary zone to pull from my new dns server IP addresse.
Now I could have switched my domain registrar name servers back to my DNS servers but I figured it was nice having editdns.net name servers handling the dns lookup requests.  So I left my domain registrar name servers pointing to the editdns.net name servers and I keep them updated through secondary zone transfers from my dns servers.
If done correctly there would be minimal impact to the internet world...


Cannot ssh to remote machine in VSCode

Question: I upgraded to VSCode 1.36.0 a couple days ago, and I am not able to ssh into the remote machine since then. When I try to do so, the following error comes up:
flock: 99: Input/output error
Anyone can help to find a workaround for this?
Comment: What's your OS?
Comment: Try `1.36.1` and see if it helps
Comment: just use `puTTY` meanwhile.
Answer: This issue was opened on VScode github repository:
https://github.com/microsoft/vscode/issues/76675
Someone suggested a solution which worked for few:

Add "no_proxy=127.0.0.1,localhost" to ~/.wgetrc, this issue will not exist.

You should follow this thread to know when the issue was resolved
Comment: I am already aware of this thread, however I'm in a more critical need to have it solved sooner. I used the mentioned solution but it didn't work for me
Comment: did you checked out this issue: https://github.com/microsoft/vscode-remote-release/issues/895
I pretty sure the right place to follow your issue is over github, for more patches or updates.
Otherwise if you're problem is that critical I would just **downgrade** my VSCode enviroment
Comment: Reinstall from older version?
By the way, they closed both issues, did you try to update?

Cannot ssh to remote machine in VSCode


Regarding existence of continuous function which is onto

Question: I am solving previous years problems in analysis/ topology of my institute and I am doubtful about this answer of this question.
Question is - Can there exists a continuous function from [-1,1] to R ( Set of Real numbers) which is onto.
I think there can exists as any interval  is equivalent ( cardinality wise)  to set of real numbers.
But the answer is no.
Please help.
Comment: Note:  equicardinality does not require a *continuous* function
Answer: One can show that the continuous image of a compact set is again compact, see for example https://math.stackexchange.com/a/226328/450140.
As $\mathbb{R}$ is not compact with the standard topology this proves that such map can not exist.
Answer: A theorem in analysis states that a continuous function on a compact set (e.g. closed interval) is bounded and attains its minimum and maximum.  Because $\mathbb{R}$ is unbounded, such a function cannot map to all of $\mathbb{R}$.


How to plot a line on a biplot made from PCA coeff and score data?

Question: I'm creating biplots of PCA data using the coeff and score outputs. I am looking to draw a  line between the furthest points on the biplot. I'm not sure how add a line to the plot without adding it myself (which would be tedious).
I know which 2 points are the furthest away from each other.
My coeff is a 7x7, but I am using the first 3 columns for the biplot as well as columns 1:3 in my score matrix.
How would I go about plotting a line with either line or plot3 between these 2 points. It seems like it can be done but I am unsure of what data to specify for the line.
Answer: plot3 accepts 3 inputs as the X,Y, and Z coordinates.
since you need a line between two points you need to input the two 3D observations
plot3(X1,Y1,Z1,...)
say that your 2 observations with the greatest distance between them are the 3rd and the 5th
then
plot3(scores([3 5],1),scores([3 5],2),scores([3 5],3))

would give you what you need
happy plotting!
Comment: Thank you for this! This works perfectly as intended. I was just unsure of what data I should be using for the line. You have only been a member since today, thank you for coming here.


Warning ao instalar nodemon. Como resolver?

Question: Instalei o nodemon com o seguinte comando
$ sudo npm install -g nodemon

Recebi o seguinte erro:
npm WARN notsup Not compatible with your operating
system or architecture: email@example.com

Qual a importancia desse erro? POsso despreza-lo? Como resolve-lo?
Estou rodando Ubunto 16.04 64.
Comment: Estás a usar o `nodemon` em desenvolvimento e não em produção certo? nesse caso, e se não tiveres problemas de recarregamento podes ignorar. É esse o caso?
Answer: A dependência fsevents é destinada ao uso no OSX, de acordo com o README do pacote no NPM.
Como seu sistema operacional é um Linux, você pode seguramente ignorar essa warning já que o nodemon não vai se utilizar dela mesmo. :)


How to replace the search submit button with a Font Awesome character?

Question: I would like to replace the search submit button with a Font Awesome character like the Magnifier (Search Icon) character, and put Search the site inside the search box.
How can I achieve something like this?
Comment: You need to add more than a one-line question, and add more than the question title.
Answer: In order to add the new form button, I used hook_form_FORM_ID_alter in my template.theme file in my theme folder (Notice:replace ThemeName with the name of your theme in below code):
ThemeName.theme:
**
 * Replace the Search Submit Button with a Font Awesome Character.
 */
function ThemeName_form_search_block_form_alter(&$form, &$form_state) {
  $form['keys']['#attributes']['placeholder'][] = t('Search');
  $form['actions']['submit']['#value'] = html_entity_decode('');
  $form['actions']['submit']['#attributes']['class'][] = 'search-button';
}

Remeber use html_entity_decode() to parse the Unicode code.
and CSS:
.search-button input[type="submit"]{
    font-family: FontAwesome;
    color: #fff !important;
    display: inline;
    font-size: 18px;
}

Answer:
To convert the label to a placeholder text, you need to use hook_form_alter in your custom theme in Drupal. The form id for the search box is seach_block_form, so you can use the following code to do this:
/**
 * Implements hook_form_alter().
 */
function hook_form_search_block_form_alter(&$form, &$form_state) {
  $form['keys']['#attributes']['placeholder'][] = t('Search');
}

To change the look and feel of the search button, you can simply use CSS. What I usually do is to set the background to an the icon and use text-indent to hide the text.
Comment: @MojtabaReyhani In the `.theme` file. Remember to change the `hook` to your theme name.
Comment: @MojtabaReyhani It should be fairly simple with CSS to get what you want. All you need is an image of the search icon, rest is just a matter of color, placement etc
Comment: @MojtabaReyhani Any more help would mean that I would do it all for you
Answer: I've done the following in a preprocess function to add font-awesome icons. It's a bit difficult with the search input because the only thing that identifies the search button is the label. Then hide the element with the selector .button--text in CSS.
function MYTHEME_preprocess_input(&$variables) {
  $element = &$variables['element'];
  // Ugh :(
  if ($element['#type'] === 'submit' && $element['#value']->__toString() === 'Search') {
    $variables['children'] = $element['#children'];
    $variables['children'][] = [
      '#theme' => 'html_tag',
      '#tag' => 'i',
      '#attributes' => ['class' => ['fa', 'fa-search']],
    ];
  }
}

Comment: Please update your question so that there are details about "cant get any result". This is too broad of a statement to answer. Are there any error messages? Did you rebuild cache? What's your template like? What's the markup?
Comment: I add above code to my theme file and change the "MYTHEME" to real theme name, I rebuild cache for several times, but yet search submit button not changed.
Answer: Instructions for Drupal 8 / FontAwesome 5
Create a YOUR_THEME_NAME_HERE.THEME file and place it in your themes directory (ie. your_site_name/themes/your_theme_name)
Paste this into the file, it is PHP code to find the Search Block and change the value to the UNICODE for the FontAwesome icon. You can find other characters at this link https://fontawesome.com/cheatsheet.
<?php
function YOUR_THEME_NAME_HERE_form_search_block_form_alter(&$form, &$form_state) {
  $form['keys']['#attributes']['placeholder'][] = t('Search');
  $form['actions']['submit']['#value'] = html_entity_decode('');
}
?>

Open the CSS file of your theme (ie. your_site_name/themes/your_theme_name/css/styles.css) and then paste this in which will change all input submit text to FontAwesome. Not sure if this will work if you also want to add text in the input button though for just an icon it is fine.
Make sure you import FontAwesome, add this at the top of the CSS file
@import url('https://use.fontawesome.com/releases/v5.0.9/css/all.css');

then add this in the CSS
input#edit-submit {
    font-family: 'Font Awesome\ 5 Free';
    background-color: transparent;
    border: 0;
}

FLUSH ALL CACHES AND IT SHOULD WORK FINE
Add Google Font Effects
If you are using Google Web Fonts as well you can add also add effects to the icon (see more here https://developers.google.com/fonts/docs/getting_started#enabling_font_effects_beta). You need to import a Google Web Font including the effect(s) you would like to use first in the CSS so it will be
@import url('https://fonts.googleapis.com/css?family=Open+Sans:400,800&effect=3d-float');
@import url('https://use.fontawesome.com/releases/v5.0.9/css/all.css');

Then go back to your .THEME file and add the class for the 3D Float Effect so the code will now add a class to the input. There are different effects available. So just choose the effect you like, change the CSS for the font import and the change the value FONT-EFFECT-3D-FLOAT int the code below to font-effect-WHATEVER_EFFECT_HERE. Not effects are still in Beta and don't work in all browsers so read here before you try it https://developers.google.com/fonts/docs/getting_started#enabling_font_effects_beta
<?php
function YOUR_THEME_NAME_HERE_form_search_block_form_alter(&$form, &$form_state) {
  $form['keys']['#attributes']['placeholder'][] = t('Search');
  $form['actions']['submit']['#value'] = html_entity_decode('');
  $form['actions']['submit']['#attributes']['class'][] = 'font-effect-3d-float';
}
?>

Answer: For Drupal 8 / FontAwesome 5  (other similar solutions above did not work)
If you have the fontawesome module already installed you can add to your THEMENAME.theme file
use Drupal\Component\Render\FormattableMarkup;

function THEMENAME_form_search_block_form_alter(&$form, &$form_state) {
    $form['keys']['#attributes']['placeholder'][] = t('Search');
    $value = new FormattableMarkup('@text', ['@text' => '',]);
    $form['actions']['submit']['#value'] = $value;
}

Answer: Changes must be made in the yourtheme.theme file in your yourtheme directory. The following changes the submit button text.
function yourtheme_form_search_block_form_alter(&$form, &$form_state) {
  $form['actions']['submit']['#value'] = t('Zoeken');
}

Answer: If you use boostrap subtheme and drupal you can remove glyphicon in settings theme for all buttons BUT you can remove glyphicon for specific button with this hook in your TEMPLATE.theme
https://drupal-bootstrap.org/api/bootstrap/bootstrap.api.php/function/hook_bootstrap_iconize_text_alter/7
function YOURTEMPLATENAME_bootstrap_iconize_text_alter(array &$texts) {
  // use ksm($form) OR other dump($form) functions
  if($texts['contains']['YOURTEXT']) {
    unset($texts['contains']['YOURTEXT']);
  }
}

if you want to show the title of the button, you must copy the file bootstrap/src/Plugin/Form/SearchForm.php into your SUBTHEME
YOURSUBTHEME/src/Plugin/Form/SearchForm.php
copy and paste the content of the file into your file and edit the content like that :
<?php
...
use Drupal\bootstrap\Plugin\Form\FormBase;
...

  public function alterFormElement(Element $form, FormStateInterface $form_state, $form_id = NULL) {
    $form->advanced->setProperty('collapsible', TRUE);
    $form->advanced->setProperty('collapsed', TRUE);
    $form->basic->removeClass('container-inline');
    $form->basic->submit->setProperty('icon_only', FALSE);
    $form->basic->keys->setProperty('input_group_button', TRUE);
  }
}

with this you will see the text "search" only and no glyphicon on your search button
don't forget to flush the cache !
Answer: You can do it inside a twig template YOURTHEME/templates/input/input--button.html.twig
Add this above the lines where <button> is rendered:
{# replace Glyphicon with FontAwesome for Search #}
{% if icon and icon['#attributes']['class']|join matches '/search/' %}
  {% set icon = {
    '#type': 'html_tag',
    '#tag': 'i',
    '#attributes': {
      'class': [
        'fa', 'fa-search'
      ],
      'aria-hidden': 'true'
    },
  } %}
{% endif %}

It will replace the default icon object, adding an  tag with FontAwesome CSS classes.
You can check the icon object defaults using dump:
{{ dump(icon) }}


What is the use of generators of a category?

Question: An object $X$ is a generator of a category $\mathcal{C}$ if the functor $Hom_{\mathcal{C}}(X,\_) : \mathcal{C} \rightarrow Set$ is faithful.
I encountered the notion in the context of Morita-equivalence of rings, but I don't understand what its use is.
Why is $X$ called a "generator"? What does it generate?
Comment: The terminology was "poorly chosen" (Maclane's words). A better name would be "separator" or "discriminator" (my word), because it helps discriminate one morphism from another
Comment: See these related questions: [[1](http://math.stackexchange.com/q/374889/5191)] [[2](http://math.stackexchange.com/q/257989/5191)].
Answer: Generators don't generate the category. This explains why "generator" is an unfortunate terminology. A better one would be "separator". I've seen this suggestion in many places. This makes sense, because every two non-equal morphisms $f,g : A \to B$ may be separated by a morphism $i : X \to A$, i.e. $fi \neq gi$.
However, assume that our category has coproducts. Then, if $A$ is any object, then there is a canonical morphism $\bigoplus_{f \in \hom(X,A)} X \to A$ and this is an epimorphism - exactly because $X$ is a generator. This looks more like a generating set (remember that for example an $R$-module $M$ is generated by a subset $S$ if and only if $\bigoplus_{s \in S} R \to M$ is an epimorphism).
Comment: It is true for categories with coproducts in which every epimorphism is regular.
Comment: I think it is in fact true that if a category is cocomplete then a generator is precisely an object generating it under colimits. Can you confirm?
Answer: While I don't know the actual etymology, I interpret the word "generate" as generating elements of the category.
There is a notion of a "generalized element" of an object: a generalized element of $A$ is simply an arrow with target $A$. This is the "right" notion of element: for example, a morphism $f : A \to B$ is monic if and only if $f(x) = f(y) \implies x=y$ for all generalized elements $x,y$ of $A$.
However, allowing arbitrary objects as domains of a generalized element is unwieldy. $X$ is a generator if the class of generalized elements with domain $X$ has "enough" elements.
In the element language, $X$ is a generator is the same thing as saying that, for $f,g : A \to B$, $\left(\forall x: f(x) = g(x)\right) \implies f = g$ when $x$ ranges over all generalized elements of $A$ that come from $X$.
You can even think of replacing an object with its class of generalized elements... or just the class of generalized elements with domain $X$. This is actually the functor $\hom(X, -)$.
$X$ is a generator if and only if the functor $\hom(X, -)$ is faithful. We can think of this as saying that $X$ generates enough elements of the category to faithfully represent its structure.
(note that you can consider a whole class of objects rather than just a single object)
As a counterexample, $\mathbf{F}_p[x]$ doesn't generate $\mathbf{CRng}$: the image of $\hom(\mathbf{F}_p[x], -)$ is faithful on the subcategory of $\mathbf{F}_p$-algebras, but it collapses all other rings into the empty set.
Comment: In the last paragraph, what is the subcategory generated by an object? Notice that $R$ is *not* a generator in the category of $R$-algebras. Initial objects are "never" generators.
Comment: @Martin: Oh right, I meant $\mathbf{F}_p[x]$.


How does Wolfram Alpha compute the indefinite integral $\int \frac{1}{\sqrt{2x-x^2}}dx$

Question:
I want to find the indefinite integral of $1/\sqrt{2x-x^2}$.

I rearranged the expression to $\displaystyle \int \frac{1}{\sqrt{1-(x-1)^2}}$, which is equal to $\displaystyle \int \arcsin'(x-1)$. As far as I can tell, this should evaluate to $\arcsin(x-1)$, because $[\arcsin(x-1)]'=\arcsin'(x-1)\times1=\arcsin'(x-1)$.
When I evaluate this expression on Wolfram Alpha, I get $\displaystyle-2\arcsin(\sqrt{1-\frac{x}{2}})$. Differentiating this also yields $\arcsin'(x-1)$. I assume that these two expressions ($\arcsin(x-1)$ and $\displaystyle-2\arcsin(\sqrt{1-\frac{x}{2}})$ ) simply differ by some constant.
How exactly is Wolfram Alpha's output reached?
Comment: **_This maybe irrelevant but I felt like it needed attention here_**
$$\,$$
Only now does one truly realise the importance of the integration constant; $+C$. Integrals that lead to trigonometric functions like this have multiple answers. With $\arcsin(1-x), -2\arcsin(\sqrt{1 - \dfrac{x}{2}})$ another possible answer could be $\arccos(1 - x)$.  Each differing with a constant of $\dfrac{\pi}{2}$.

While all these are correct options, in future, remember that each of these graphs have a different range (although your question did not require this info now). (and don't forget your $+C$!).
Answer: Note that
\begin{align}
\int \frac{1}{\sqrt{2x-x^2}}dx
&=\frac12\int\frac1{\sqrt{\frac x2}\sqrt{1-\frac x2}}dx
= 2\int\frac{d(\sqrt{\frac x2})} {\sqrt{1-\frac x2}}\\
&=-2\cos^{-1} \sqrt{\frac x2}=-2 \sin^{-1} \sqrt{1-\frac x2}
\end{align}
Comment: @FrightenedofSinusoids - Merely a shortcut for the substitution $t= \sqrt{\frac x2}$, i.e. $dt = d(\sqrt{\frac x2})=(\sqrt{\frac x2})'dx$.
Comment: Thank you for the response. Could you please clarify what you mean by $d(\sqrt{\frac{x}{2}})$? I have not seen that notation before.
Comment: Is this a "u-substitution" with "$u=\sqrt{\frac{x}{2}}$" and "$2du=\frac{1}{2\sqrt{\frac{x}{2}}}dx$"?
Comment: ahh. Thank you!
Answer: $$
\begin{aligned}
I & =\int \frac{1}{\sqrt{x}} \frac{1}{\sqrt{2-x}} d x \\
& =2 \int \frac{1}{\sqrt{2-(\sqrt{x})^2}} d \sqrt{x} \\
& =-2 \cos ^{-1}\left(\frac{\sqrt{x}}{\sqrt{2}}\right)+C\\&= -2 \sin ^{-1}\left(\frac{\sqrt{2-x}}{\sqrt{2}}\right)+C\\&= -2 \sin ^{-1}\left(\sqrt{1-\frac{x}{2}}\right)+C
\end{aligned}
$$


User login through token in URL in drupal 6

Question: I have a drupal 6 website and I would like to implement the functionality to allow user of a particular user role to login into site using the token value in the url.
I have user role "SAP" in the website and will send a link to user in mail "www.example.com/user/token". When user click on this link, I want allow user to login into site automatically.
I have searched through into google and drupal site but I did not find any solution.
Thanks in advance.
Answer: urllogin module provides a way to transparently log users into the web site when they follow a link.
Give the "login via URL" permission to users who are allowed to log in with this module.
Alternatively you can try this module also
Easy Login allows the admin to give a permission to users so they are able to log in via an url.
Hope it will match your requirement !!
Comment: Thanks for your quick reply. I will check this. Do you have any idea about token authentication module? I was checking this but could not configure this properly.
Comment: Sorry no idea !!
Comment: Ok. No problem.  I have checked urllogin project page in drupal and its suggest that we need to use "Token authentication" for the e-commerce site and I need login from url for the e-commerce functionality.
Comment: Where it mentioned i can't see it, it only mentioned 'For accessing RSS feeds' use Token authentication
Comment: Check this -----   If the site contains highly sensitive material or e-commerce, then probably neither module should be used, but a careful use of Token Authentication for a limited part of the site might be possible
Comment: Yes, I have checked that already. I know we should avoid to login through url for e-commerce site but I need to implement this.
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/8787/discussion-between-bala-and-jayendra-kainthola)
Comment: Worth checking this links http://drupal.stackexchange.com/questions/1583/how-to-embed-username-and-password-in-a-url  and http://stackoverflow.com/questions/1109373/drupal-login-using-parameters-for-login-and-password-in-url
Comment: Sorry, Chat url is blocked in my company. So, I am not able to join you in chat.
Comment: You understood wrongly, you can use both this module for E-commerce site and only the disadvantage using 'Token Authentication' is user can access the limited part of the website
Comment: Ok.. I will try.