Force the usage of path aliases

Question: The title is explaining what I'm trying, my question is: Am I doing it right?
function hook_entity_view($entity, $type) {
    if (arg(0)=='node') {
        drupal_goto($entity->type.'/'.$entity->nid);
    }
}

My aliases look like this: article/123

article is the entity type.
123 is the node ID.

When I go to ../node/123 than I get a 503.
Answer: Looks like you are creating loop redirection. But that you can test by examining logs. I believe there is an easier way: already implemented Global Redirect module:

This module uses hook_init to interrupt the page load and action the alias lookups. If any of the above rules apply then the appropriate action is taken. If no rules apply then the page load continues uninterrupted. An example of this in use is on the site it was developed for. http://www.sportbusiness.com/node/160559 will redirect to http://www.sportbusiness.com/news/160559/lagardere-sets-up-sports-division due to the alias setup on this site.
Comment: It does more but basically the same as what I already had. When visiting `node/123` again (with Global Redirect enabled), than it results in the same error "The page does not refer in a proper way".
Comment: @Fleuv If you have some kind of referer-based security turned on, you can expect funny results. Referer http header is optional and should never be used to actually decide anything - and your site seems to be doing exactly that.

Force the usage of path aliases


É possível ter mais de uma Primary key em uma tabela?

Question: Tenho uma academia e estou usando uma Pk para que todos os usuários da academia tenha o seu próprio (ID).

É possível usar outras PK na mesma tabela?
Por exemplo: para evitar que o Número da Matricula ou até mesmo o
CPF/RG se repitam, é possível adicionar uma PK para os mesmos?
Comment: inclusive nem seria recomendado caso fosse possível, pense bem?
Answer: Não não é possível ter mais de um PK em uma mesma tabela. Use Constraints (Restrições), no seu problema use a restrição UNIQUE, que irá garantir que todos os valores da sua coluna sejam diferentes.
UNIQUE

A restrição UNIQUE identifica de forma única cada registro em uma
tabela de um banco de dados.
As constraints UNIQUE e PRIMARY KEY garantem a unicidade em uma
coluna ou conjunto de colunas.
Uma constraint PRIMARY KEY automaticamente possui uma restrição
UNIQUE definida.
Você pode ter várias constraints UNIQUE em uma tabela, mas apenas uma
Chave Primária por tabela.
Comment: Obrigado, entendi agora!
Comment: @GuilhermeMoura bom que puder ajudar :) Ótima pergunta. Seja bem vindo ao Stack Overflow, recomendo a leitura no [tour](https://pt.stackoverflow.com/tour) para entender um pouco mais como funcionam as coisas por aqui.
Answer: É possível usar outras PK na mesma tabela?
- Não, o que você pode usar é a PK de uma outra tabela como FK (Chave Estrangeira) de outra tabela. Outra forma possível também seria a utilização de uma chave primaria composta por 2 campos.
 Exemplo:
TabItem
PK - idItem
TabTipo
PK - IdTipo
TabTipoItem
PK - IdItem
PK - IdTipo
Para evitar que o Número da Matricula ou até mesmo o CPF/RG se repitam, é possível adicionar uma PK para os mesmos?
Você pode utilizar o campo como Unique que desta maneira os valores não irão se repetir.
Answer: Não é possível ter mais de uma chave primária por tabela, ela é a coluna ou conjunto de colunas que identificam uma linha.
Para previnir que valores repetidos seja inseridos em determinadas colunas, torna ela um unique key.
Answer: Na verdade você pode ter duas ou mais chaves primarias em uma tabela no MySQL, inclusive uma chave estrangeira pode ser uma chave primaria na tabela definida.
Uma observação importante, geralmente campos autoincrement são chaves primarias por default. Então não crie um campo autoincrement antes de criar a chave primaria composta.
ex:
ALTER TABLE pedidoitem
ADD CONSTRAINT PK_unic_prod PRIMARY KEY (codigo,codigopedido,codigoproduto);

Após criar a chave primária você pode atribuir ao campo código a função AutoIncrement.
detalhe: codigopedido e codigoproduto são duas chaves estrangeiras
E campos de chaves primárias não podem ser nulos...

Segue a sintaxe exemplo:
PRIMARY KEY on CREATE TABLE - ID e Lastname são chaves primárias
CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)
);

PRIMARY KEY on ALTER TABLE

ALTER TABLE Persons
ADD CONSTRAINT PK_Person PRIMARY KEY (ID,LastName);


Having trouble starting/restarting httpd (apache)

Question: I rebooted my server and now the httpd will not restart.
I tried using the command "service httpd start" but get this in response
[root@mail ~]# sudo service httpd start
Starting httpd: (13)Permission denied: make_sock: could not bind to address [::]:8888
(13)Permission denied: make_sock: could not bind to address 0.0.0.0:8888
no listening sockets available, shutting down
Unable to open logs

I am logged in as root.  I have no directory in my ect directory called  conf to find  conf/httpd.conf nor do I have init.d/apache2 in my ect directory.  I looked at my ect/init.d file but see nothing about ports.
I have a lot to learn but in the meantime I need to get this back up and running.
Thanks for any help.
Comment: Something is already bound port 8888. Running "netstat -tulpn | grep :8888" should tell you the name of process using the port.
Comment: [root@mail ~]# netstat -tulpn | grep :8888
[root@mail ~]#
I get nothing :(
Comment: Sorry, I didn't read the error properly. It's not a bound port problem, it's an SELinux problem. Solution detailed in answer below.
Answer: You've most likely got SELinux enabled and in "enforcing" mode.
You can disable it with:
sudo setenforce 0

You can then start apache as normal with
sudo service httpd start

If you want to disable SELinux permanently, edit /etc/selinux/config and change SELINUX=enforcing to SELINUX=disabled
If you want to continue using SELinux, you'll need to fix your config by adding access to the port, with something along the lines of
sudo semanage port -a -t http_port_t -p tcp 8888

Comment: This is on the right track.  I did this right before you answered and can now get httpd to start. However, apachectl -k restart just returns a new line and nothing else.


Is there any example of Two logically equivalent sentences that together are an inconsistent set?

Question: In my textbook it say this is true. But I do not see how. How can something be inconsient if they both have the same truth value.
Answer: Inconsistent simply means if you assume both are true, you can get a contradiction.
If each are a contradiction to begin with, then they are equivalent but inconsistent.
Being inconsistent together doesn't mean they have to be each be consistent by themselves.
Answer: Saying that a set of statements is inconsistent means that there is no way they can all be true simultaneously.
Saying that two statements are logically equivalent means that they invariably have the same truth value as each other.
So, suppose you have two statements, each of which is always false (these are called contradictions).  For example, if you are talking about propositional calculus such a statement could be $p\wedge\neg p$.
Now under any circumstances whatever, your two statements have the same truth value, namely, "false" - because they are always false.
If you consider the set consisting of these two statements, there is no way they can both be true simultaneously - because there is no way that even one of them can be true.  So the set is inconsistent.
Answer: If you have two statements $A,B$ such that $A \Leftrightarrow B$, and have $A,B \Rightarrow (C \land \lnot C)$ you also have $A \Rightarrow (C \land \lnot C)$, so if $A$ is incosistent by itself, like $A=D \wedge \lnot D$ you are there.


high precision calculation in numpy

Question: How to perform high precision calculation in numpy?
By high precision I mean 100 precision in decimal.
Comment: Python has `Decimal` for this purpose, but NumPy has only standard datatypes like `np.float32` and `np.float64`.
Comment: Thanks Michael! Do you know if the Decimal is as fast as Numpy?
Comment: It's built on "normal" Python, so you have to run loops over the elements which will be much smaller as NumPy, I guess. See [here](https://docs.python.org/3.7/library/decimal.html) for reference.
Answer: Numpy doesn't have arbitrary floating-point precision. You'll want to use decimal from the standard library, or a third-party library like mpmath. Both of those libraries use C extensions for their internal calculations, so they should be fairly fast.
Comment: mpmath uses pure Python unless gmpy is installed.

high precision calculation in numpy


Which statistical software is suitable for teaching an undergraduate introductory course of statistics in social sciences?

Question: I am looking for a statistical software package which I can use in an introductory course of statistics for a social science study programme. The students have no prior knowledge of statistics and no experience with programming languages either. The goal is to introduce them to basic statistical concepts (as means, variance, sum of squares, p-values, ... and finally linear regression) and to enable them to conduct basic analyses on their own using example datasets. The course should be about learning concepts by doing statistics rather than memorizing formulas (although I think formulas are important).
Therefore, I am looking for an alternative to the usual syntax (as normal R) or point-and-click (as SPSS or Rcmdr) driven software. The software should be easily learnable and it should have a clear graphical user interface which visualizes datasets and offers the standard graphs and tables. The best would be if it visualized all different steps of an analysis (e.g. reading & manipulating data, computation of descriptive measures, making descriptive tables & graphs, computation of inferential measures, plotting of inferential graphs, export to a report).
Do you have suggestions of (open-source or free) statistical software which is suited for learning and first practising statistics?
EDIT
Thanks for your suggestions. I have looked into gretl, and two other programms I have found during my own online enquiry: RapidMiner and Statistical Lab.[1]
I have found that gretl's interface and output is more clear and focused than e.g. Rcmdr, SPSS or Stata. Therefore, it is a well qualified tool for starting teaching statistics from my point of view.
However, the flowchart GUI's of RapidMiner and Statistical Lab impressed me as they visualize the single steps of a statistical analysis (starting with loading data). I think this might be helpful to many students who struggle with the usual focus on mathematical explanations. Of course, RapidMiner seems to me too overloaded with functions, menus and buttons for beginners whereas the Statistical Lab is much more focused. The big plus of the Statistical Lab is the console-like "R-Calculator" with a "R-code Wizard" which assists in producing real R syntax as the Statistical Lab relies on R for its computations.
Finally, I decided to start with the Statistical Lab in the first semester while introducing the basic concepts and switch to RStudio (and Rcmdr) in the second semester.
[1]: Gnumeric, SciPy, Scilab, GNU Octave and alike seem to me less directed to social sciences.
Comment: @Matthias: I think if your students are coming/aiming  from/for a social sciences field, teaching them R as a first step in Statistics is an overkill. Most of them will have problems with the concept of console, commands, syntax etc. and you'll spend more time going through "programming concepts" (what is 'function', 'loop' etc.) than "statistics".
I base this on prior experience, when I did tutorials for a Stats 101 in a Soc.Science department; people missed the point of the lectures cause they focused more in getting R to work for them than actually exploring their data.
Comment: For what it's worth, I have used R successfully in my introductory stats course for political science. I used [RStudio](http://www.rstudio.com/). I also had weekly "labs" where I would allow students to work together on small assignments, while I went around and answered questions. With some well-commented example code, the students did well and hardly complained at all. They actually complained a lot less about R than they did the previous semester when I used Stata. Because Stata isn't free, students had to come in for lab hours to do their work -- they hated it.
Comment: I think that R in conjunction with RStudio can be an excellent approach.  It also sets the stage for reproducible research practice, unlike menu systems.  I would recommend giving out several code templates that the students can load into RStudio from the web (RStudio makes this easy) and let the students do the work of changing variable names and statistical models to what is needed for the problem at hand.
Comment: @user11852: The other less palatable option might be for Satistics departments to insist that "Stats 101 for Social Sciences" classes have a prerequisite of some programming experience or a remedial class on programming. These days when almost all subjects are so heavily computation biased there really is no reason why Programming-101 shouldn't be the very first class everyone takes.
Comment: @user11852: You may be right but it's sad that high schools send students out with no programming exposure at all. Or universities that allow this gap. There ought to be no student coming to a university class that doesn't know what a loop or function is. Delaying exposure just pushes the problem elsewhere.
Comment: @curious_cat: You are preaching to the converted; I did CS for my undergrad. Probably yes, a basic programming/CS class would be beneficial for the majority of students and I think most Physical Sciences curricula have one already actually. Is it necessary for Humanities students though? Maybe, but probably not as important as learning how to apply simple formal statistical techniques and interpret the results.
Comment: I'm curious: What was the reason you did not like, say R?
Comment: Actually, I do like R! But I think it is too much for an introductory course to focus on statistics and syntax learning. Also, I am not convinced by making use of point-and-click menus in an introductory stats course because in many cases students tend to stick to this undesirable practice (which reduces reproducibility) far too long. Furthermore, I would like to teach them syntax (e.g. R or Stata) as the next step in the next semester.
Comment: @curious_cat: This is a really big discussion; in broad terms I agree with what you say. Nevertheless, there is a time and place for everything and I believe a Stats 101 class for Social Sciences students is not the "time and place" to close the "programming gap".
Comment: @non-numeric_argument: How did it work out for you?  Do you have feedback or evaluation of the quality of your choice or what you are doing now with the material.
Comment: This is an old thread that has understandably generated much interest but neither the question nor the answers to date convince me that it's a good question by present standards. It's too broad and invites statements based on personal opinion (or personal circumstances). Most of the answers bring in quite different issues, such as whether we should be teaching programming too. The answers could vary enormously according to whether this is the first and last statistics course the students ever do or the students are likely to be doing something statistical for the rest of their careers.
Comment: ,,, and indeed different students in the same course could fall under either heading, and indeed the students may not know their own futures. The OP's decision to use a different program in each semester raises the issue of whether that worked well.
Comment: @usεr11852 to clarify, social science is not humanities.
Answer: Maybe Gretl?
http://gretl.sourceforge.net/
It is free and used at our University for undergraduate statistics.
Comment: +1. Excellent suggestion. I have always found Gretl's GUI intuitive and to the point and the feedback it provides accurate and without too much frills that would put off some less "techy" students. Plus it is free, well-documented and has an R console if someone if incline to see something a bit "deeper".
Answer: I would avoid most of the "famous" stuff, MatLab, Maple, Mathematica, JMP, SAS, or Minitab, because when your students graduate they have to pay thousands of dollars per year to use it professionally.  Each company tends to have its particular favorite tool, and if you teach them a tool that their company won't pay for then their skill-set is wasted.  I also don't like the proprietary libraries - they train users to push buttons and if the user wants to go somewhere else (JMP or whatever) there is no carry-over of learning.
Python inclding SciPy/NumPy is pretty good.  It is open source and well supported.  It has a learnable/easy grammar.  It is still interpreted so its not screaming fast, but if they don't know any scripting or spreadsheeting then it is much faster than they would ever need.  PythonXY is good version, has good libs and support.  I also like that GUI programming is possible through it.  Building standalone applications in windows is a little challenging but likely waaaay above the level of your students.  (edit) Sage and Cython substantially improve the value proposition of Python.  The interface, and usability are substantially improved.  A compiled code that is 1000x faster than a pretty good interpreted code sounds great (or amazing) to me. EDIT: I have had some fun using the Anaconda (aka conda) distributions, and they are also very straightforward to use.
I am not a huge fan of Perl.  It is a little outdated.  It is about parsing and processing text more than math/science.  Don't get me wrong, it can do math/science, but if you know VBA then MSWord can do math/science.  Being able to isn't the same has having a particular job as your primary focus.
I like R, even though you don't, because it is aggressively being developed by qualified PhD's in math/stats.  This means that even though the grammar might be klugy, it is going to have libraries that are up to date, and proven error free.  (In general)
Excel is not a bad start.  Once you know one spreadsheet it makes using any other easier.  In a business setting nearly every company has MicroSloth office so Excel isn't a bad idea.  I don't like their scripting, but that is just preference, I can still use it.  It costs about 150 dollars US compared to 5000 dollars US for some of the other softwares so its entry-cost for normal folks is more reasonable.
JMP script language is alien.  It does not translate to other (nonSAS) software.  Stay away from it.  The only redeemable feature of the language is that it can (in some limited sense) run "R" code.  If you are coding in "R" just use "R" and "RStudio".
I have not used MathCAD so I cannot speak to its relevance.  I think it is more symbolic, less about importing external data.  It is cheaper, so far.  It is not free and open.  Facility at it doesn't translate to facility in another language.  (EDIT) Also in this category is EES, which I am similarly not impressed with outside of a very narrow window of use.
EDIT: I have been impressed a little by LabVIEW.  It is simple enough to use that a few hours can get someone capable.  It runs really fast, like literally 1000x faster than MatLab for literally the exact same (MathScript) code.  If you have some heavy-lifting, it is worth a little consideration.  It does cost money, but something in the neighborhood of 1/5 of conventional big-iron.
Best of luck
EDIT: I would not use Statistical LAboratory because even when you select "english" for language it comes out in German, and it does not uninstall on windows 7.  Both administrative weaknesses make it a no-go for me.  I can't operate it, and when I tried to remove it that failed.
By trial and error I discovered the menu setting to make it display in English.  It appears to be a relatively simple (and therefore useful and a consistent) interface into some R libraries for data processing and display.  I will have to look more into it, so at this point 'the jury is still out.'
EDIT more:
->Here<- is a fun link to a whole other discussion about tools and workbenches.
Comment: There's also RPy http://rpy.sourceforge.net/, R as a library for Python, so you get the up-to-date, proven-error-free aspects of R with the syntactic simplicity of Python.
Comment: "they train users to push buttons and if the user wants to go somewhere else (JMP or whatever) there is no carry-over of learning." SAS, a proprietary program, doesn't particularly train well for "pushing buttons", and having trouble carrying over between different languages is hardly a feature of proprietary software alone. Heck, I was more at home going from SysStat to JMP than I was from Python to R.
Comment: @Epigrad - I watch it turn engineers brains off all the time.  Dozens and dozens of folks.  I am glad that you found utility for it, but I strongly expect that you are an outlier and the general trend of harm is not substantially changed by your experience.
Comment: @EngrStudent: Thank you for your effort to try Statistical Laboratory! The menu setting for English language is indeed non-intuitive, but after having it set once I have not encountered more issue with language. Unfortunately, I cannot get the "R-Graph Wizard" to work, though the normal R-Graph works fine if I put in some R code. Therefore, I will give my students some example code snippets to produce basic graphics. Maybe I switch earlier to RStudio...
Answer: You can use R without making it too complicated
Academic work using data analysis in the social sciences is sometimes programmed in R, and it is useful for students to have an exposure to this language during their undergraduate degree.  This language is free and it is widely used in the professions, so it is helpful for students to begin learning it early.  My view is that it it best to expose students to the language they will be using as early as possible, rather than peppering them with minor exposures to less-adaptive languages.  While this might take some effort in your own course, it will be of benefit to later instructors in the degree program, who can then presume some basic familiarity with the language in later courses.
Now, the main challenge in doing a course with R is that there is a lot to learn in the long-run, and you want to give a simple presentation that avoids having to teach too much of the initial structure and syntax.  For an introductory course you should set narrow and feasible goals in terms of coverage, and cover the minimum number of statistical programming topics required to implement the data analysis in your course.  To simplify your teaching you can give students a cut-down version of the analysis, by doing some of the preliminary steps yourself.  For example, in an introductory course you could use the following simplifications:

What to remove (and how to remove it)

Remove consideration of packages: For an introductory course it is best to work with the base program, which contains enough functionality to deal with data-frames and apply introductory statistical tests and models.  I recommend avoiding extension packages for an introductory course, but if you particularly want to use some additional packages, you should provide the code to install and load these yourself in the relevant exercises.  Students should be able to copy or run your existing code to install and use any packages they want to use.  To avoid difficulties with conflicting function names (in case a student loads other packages and creates a problem) you can refer to non-base functions directly using the package::function syntax.

Remove the data importation step: This can be done by making sure that all of the datasets you give the students are already in .rds form, and you can even start your students off by giving them the first lines of code needed to import the data file from the course website or a local directory.  I recommend giving your students some notes or resources on data importation for the benefit of those students who wish to learn this, but make the importation step non-assessable in the course, and provide students with the code for importation in each exercise.

Remove the data-wrangling (unless you particularly want to teach this bit): This can be done by giving students pre-wrangled data forms in different .rds files.  For example, you might have one dataset in wide form (CancerDataWide.rds) and the same data in long form (CancerDataLong.rds) as seperate files.  If you particularly want to teach data-wrangling in the course you can provide some notes for this and allocate some time to it, but you can also remove this part by providing pre-wrangled data if you prefer.  Data-wrangling is a long subject, so if you want to teach this you will need to allocate some serious time.

What to include

Teach students the basics of the mathematical and logical operators: Take a bit of time to teach the basic mathematical operations and the logical operations.  Students should be able to use mathematical operations to manipulate values and they should be able to conduct logical queries, etc.  This will help students when they want to compute a value from other values or when they want to perform a logical query (e.g., for subsetting purposes).

Teach students the basics of vectors, data-frames, lists and subsetting: The data you provide should be in .rds form as data.frame objects, so you should teach your students the basics of looking at data in this object form.  Teach them the functions View, str and head and teach them some basic subsetting syntax so that they can extract individual variables or rows matching some logical query, etc.  Once students can deal with this you can move on to teach them some basics of subsetting from lists, so that they can extract information from list objects.  All of this is fairly simple and can probably be covered in a single session, with some assistance and reminders in subsequent tutorial work.  In most introductory courses you can get away with avoiding matrices and arrays.

Restrict your statistical analysis to a few key models/tests: For an introductory course you will most likely cover some basic data analysis methods including looking at correlation, T-tests, leading into regression and ANOVA.  You will probably also teach some basic graphical methods including scatterplots, barplots, histograms (preferably KDEs), etc.  All of these can be implemented with functions in the base program with relevant queries on an initial data frame.  You will need to teach your students various functions for these things, but they are all fairly simple and most of the work is automated in the functions.
Answer: You could try using Gnumeric, a highly thought of spreadsheet, there is also an Open Office spreadsheet.  Provided you explain the pitfalls of using spreadsheets, particularly Excel, after college in their subsequent practical lives they may not have the luxury of something like SPSS, but could still get useful service from these free products that are not too demanding of maths and programming skills.  Many office environments contain Excel by default.
Have a look at:
http://groups.google.com/group/sci.stat.math/browse_thread/thread/26fe9a9a0d91139d# - Statistics and Excel 2007
and search for similar references such as
http://groups.google.com/group/comp.soft-sys.stat.spss/browse_frm/thread/3940bcd6c6266f1b/d85edd4978e53568?hl=en#d85edd4978e53568
 Keeling, Kellie B. & Pavur, Robert J. (2007). A comparative study of the reliability of nine statistical software packages. Computational Statistics & Data Analysis, 51, 3811–3831.
Answer: I have been CalEst. The license is cheap, like 10 buck and provides both calculations/graphics as well as great simulation/activities for the students to practice. Moreover, in their website, they have some tools, mainly on distributions you may find useful.
Comment: This answer is a bit short.  Could you some more about why you will propose this software, and which afdvantages it have compared with the competition?
Answer: I personally use DataMelt software for teaching of statistics. It's very well documented, it has tutorials, books and a lot of examples to look at. What is also important is that one can search for any example, and you can get a reasonable answer (in Javadoc and code snippets). Students can learn not only Python (which is the default programming language), but also how to code statistical methods in Java. In my view, this is a significant strength: students do not need to learn very specialized "statistical" language, like R-stat. They can learn Java at the same time too, which can open a lot of opportunities if they will decide to go to the industry.
Answer: I use StatCrunch.com (by Pearson). It is web-based with menus and boxes, no coding required, simple, has everything necessary for introductory statistics and lots of how-to videos on internet. The 6 month subscription is only $15.


Prove dependence of $X \sim N(0,1)$ and $Y = WX$, where $W$ takes value $1$ and $-1$ with P = 1/2

Question: $\newcommand{\P}{\mathbb{P}}$$\newcommand{\E}{\mathbb{E}}$$X \sim N(0,1)$
$W$ is Rademacher distribution
$Y = WX$
https://en.wikipedia.org/wiki/Rademacher_distribution
In order to prove dependece of random variables I need to show, that $\P(X,Y) = \P(X)\P(Y)$ is violated.
I tried to find counterexample that would show, that the variables are dependent.
First of all, I thought to show that $\E(XY) = \E(X)\E(Y)$ is not true.
But in this case it is true $(\E(XY) = \E(X)\E(Y) = 0)$.
How can I prove, that variables are not independent
Comment: Could you clarify that you mean $Y=WX$ and not $Y$ is the convolution of $W$ and $X$? Further to this, this seems like a self study question, so if it is could you add the self study tag?
Comment: @StatsPlease edited
Comment: If you need more help just comment on my answer and I'll attempt to guide you.
Answer: What values can $Y$ take if $X=0$? What values can $Y$ take if $X=1$?
Are the conditional pdfs for $Y$ the same at the two values of $X$?
Comment: @DanielYefimov But can you follow up your conclusion that the conditional distributions are different to arrive at the conclusion that $X$ and $Y$ are _dependent_ random variables?
Comment: @DanielYefimov Perfect!
Comment: If $X = 0$, than Y can take only $0$ value.
If $X = 1$, than Y can take values $1$ or $-1$ with $P = 1/2$ for both values.

And from the fact above, i think, we can conclude, that pdfs for $Y$ at different values of $X$ are different.
Comment: @DilipSarwate So we concluded, that our conditional distributions are different. It means, when variable $X$ has different values, the output of $Y$ changes. So, change in $X$ provoke change in $Y$. So, $X$ and $Y$ are dependent.

Am I right?
Answer: I'll try and guide you to an answer.
We know:
$$X\sim N(0,1)$$
and
$$W=\begin{cases}
\,\,\,\,\,1, & p=0.5\\
-1, & p=0.5\\
\end{cases}$$
We also know that $Y=WX$. So:
$$Y=\begin{cases}
\,\,\,\,\,X, & p=0.5\\
-X, & p=0.5\\
\end{cases}$$
This shows that $Y$ is dependent on $X$.
Comment: @StatsPlease "$X$" is a function. It is a special kind of function that we call random variable, because its _range_ is characterized by _another_ function, the "distribution function" that $X$ "obeys". We _never_ write $X=N(0,1)$ or for any other distribution, namely we _never_ use the $=$ symbol, and this is because $X$ _follows_ a (in this case) Normal distribution, it is not "equal" to a normal distribution. In most cases we do not have a clue about the functional form of $X$.
Comment: Yes, it is known.
Comment: This answer started out nicely but the _conclusion_ (everything after the dotted line) is sheer nonsense. It is _not true_ that $Y = X$; what is true is that they have the same distribution. -1 pending correction.
Comment: @DilipSarwate Apologies for my answer. I'm not sure where the mistake is (I'm guessing it's a technical one). As far as I can see, it's reasonable to say $Y=X\,\,\text{w.p. } 1$ and they are perfectly dependent. I'm obviously missing something, so your help would appreciated.


How to undo the scroll of a html slider button?

Question: My problem is that when I press my "slider__navlink" buttons. They scroll to the div of the desired slide. I would like to be able to cancel this scroll or make a scroll to the level of the title above while displaying the correct slide.

Mes compétences

Front-end

        2

        3

I try some js script but it interfere with the button and his first functionnality
Answer: If I understood you correctly.
You can use scroll-behavior: smooth
And this CSS code:
html {
  scroll-behavior: smooth;
}

:target:before {
    content: "";
    display: block;
    height: 100px;
    margin: -100px 0 0;
}


Javascript member variable undefined

Question: function Class() {
    var self=this;
    self.searchfield=$('#search');
    self.resultbox=$('#searchresults');

    self.onSearchFieldChanged=function() {
        console.log("F: "+self.searchfield);
        console.log("R: "+self.resultbox);
    }
    self.searchfield.live("keyup",self.onSearchFieldChanged);
}
var INSTANCE=null;
Class.init=function() {
   INSTANCE=new Class();
}
$(document).bind("globalsloaded", Class.init);

As soon as I type something in #search input, the output on console is as following:
F: undefined
R: undefined

So why are those two variables undefined? They ARE in scope and should contain the corresponding jQuery objects.
Comment: Works: http://jsfiddle.net/nSRP4/.
Comment: Did you forget `$(document).ready()`?
Comment: It actually works, are you sure to call the snippet when the concerned dom elements are ready?
Comment: Edited the post to show how initialization is actually done. `globalsloaded`is a custom event which is fired as soon as `device ready` is triggered (it's a phonegap app). So dom should be ready if the device is.
Comment: it sounds like your culprit is `self.searchfield=$('#search'); self.resultbox=$('#searchresults');` so double check your id's
Comment: Try to log them right after you instantiated the `CLASS` with `INSTANCE.onSearchFieldChanged()`. They can't really be `undefined`, otherwise you couldn't call the `live()` method on it
Comment: Provide a complete example rather than a snip; this is obviously an involved problem so all the components will be necessary to find the culprit.
Comment: The current behaviour implies the event is bound, and thus the code inside `Class` has been executed. In that case, `searchfield` *cannot* be `undefined` because `$` *never* returns that value. There must be something else happening - are you overwriting the variables at a later time? Could you provide a demo on http://jsfiddle.net?
Comment: genrally this problem appears when init is not done at `$(document).ready( function() { ... });` in this case html is still not loaded and the result of `$('#search')` is `null`
Comment: Works fine with this $(document).ready(Class.init);
Comment: Sorry guys. Didn't get a working example on JSFiddle. See my answer below for the solution.
Answer: After 5 days of work I found the Problem: JQueryMobile
What happens is:

deviceready event by phonegap
domready event
My init is called
JQM extracts the input#search element to reinsert it again, surrounded by some style divs
The div I saved in my init is no longer valid, as refers to the "old" dom element

Now I am doing my initialization in the pageinit event of JQM. No problems anymore.

Javascript member variable undefined


lilypond - forcibly write string number under the staff

Question: I am translating a guitar part into lilypond. The string numbers (the ones that show up inside a circle) are showing up on top of the staff.

Is it possible to force lilypond to write them under the staff.... or next to the note head?
Answer: In order to place the string numbers below the notes use
\set stringNumberOrientations = #'(down)
See String number indications in the Lilypond Notation Reference.
It's also possible to set the number to the right or left of a note. For more information, see Fingering instructions, specifically the fingeringOrientations property.
Answer: If you want to get the string numbers to the right of the note heads use \set stringNumberOrientations = #'(right). This only works for notes in a chord event though, so instead of doing a2\0 you'd need to do 2.
Side note: Your excerpt strongly looks like Tárrega's Recuerdos de la Alhambra, am I correct? I did type this thing into LilyPond some time ago (although it is missing some cleaning and formatting) because I prepared some notes for playing this on electric bass: https://petzel.at/TARREGA.pdf
Comment: I am considering (not seriously yet.... but the thought has crossed my mind, at least) to sit down to hack lilypond to have a `classical guitar mode` so not to have to write so many quirks to get what we want.... well, I am not there yet in terms of getting what I want _but still_.
Comment: @eftshift0 Will clean it up and provide the ly source the next days. I'm just very busy with work currently.


apache solr error: HTTP 500; /usr/local/solr/example/solr/data/index/segments_15qc (Permission denied)

Question: I just noticed that my website apache solr doesn't work any more, but I didn't touch my website for a while. When I tried to delete my solr index, I got this error message:

HTTP 500; /usr/local/solr/example/solr/data/index/segments_15qc (Permission denied) java.io.FileNotFoundException: /usr/local/solr/example/solr/data/index/segments_15qc (Permission denied) at java.io.RandomAccessFile.open(Native Method) at java.io.RandomAccessFile.(RandomAccessFile.java:241) at org.apache.lucene.store.FSDirectory$FSIndexOutput.(FSDirectory.java:441) at org.apache.lucene.store.FSDirectory.createOutput(FSDirectory.java:306) at org.apache.lucene.index.SegmentInfos.write(SegmentInfos.java:388) at org.apache.lucene.index.SegmentInfos.prepareCommit(SegmentInfos.java:827) at org.apache.lucene.index.IndexWriter.startCommit(IndexWriter.java:4570) at org.apache.lucene.index.IndexWriter.prepareCommit(IndexWriter.java:3414) at org.apache.lucene.index.IndexWriter.commitInternal(IndexWriter.java:3485) at org.apache.lucene.index.IndexWriter.closeInternal(IndexWriter.java:1873) at org.apache.lucene.index.IndexWriter.close(IndexWriter.java:1812) at org.apache.lucene.index.IndexWriter.close(IndexWriter.java:1776) at org.apache.solr.update.SolrIndexWriter.close(SolrIndexWriter.java:144) at org.apache.solr.update.DirectUpdateHandler2.closeWriter(DirectUpdateHandler2.java:179) at org.apache.solr.update.DirectUpdateHandler2.commit(DirectUpdateHandler2.java:411) at org.apache.solr.update.processor.RunUpdateProcessor.processCommit(RunUpdateProcessorFactory.java:85) at org.apache.solr.update.processor.LogUpdateProcessor.processCommit(LogUpdateProcessorFactory.java:154) at org.apache.solr.handler.XMLLoader.processUpdate(XMLLoader.java:190) at org.apache.solr.handler.XMLLoader.load(XMLLoader.java:79) at org.apache.solr.handler.ContentStreamHandlerBase.handleRequestBody(ContentStreamHandlerBase.java:58) at org.apache.solr.handler.RequestHandlerBase.handleRequest(RequestHandlerBase.java:129) at org.apache.solr.core.SolrCore.execute(SolrCore.java:1376) at org.apache.solr.servlet.SolrDispatchFilter.execute(SolrDispatchFilter.java:365) at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatc: /usr/local/solr/example/solr/data/index/segments_15qc (Permission denied) java.io.FileNotFoundException: /usr/local/solr/example/solr/data/index/segments_15qc (Permission denied) at java.io.RandomAccessFile.open(Native Method) at java.io.RandomAccessFile.<init>(RandomAccessFile.java:241) at org.apache.lucene.store.FSDirectory$FSIndexOutput.<init>(FSDirectory.java:441) at org.apache.lucene.store.FSDirectory.createOutput(FSDirectory.java:306) at org.apache.lucene.index.SegmentInfos.write(SegmentInfos.java:388) at org.apache.lucene.index.SegmentInfos.prepareCommit(SegmentInfos.java:827) at org.apache.lucene.index.IndexWriter.startCommit(IndexWriter.java:4570) at org.apache.lucene.index.IndexWriter.prepareCommit(IndexWriter.java:3414) at org.apache.lucene.index.IndexWriter.commitInternal(IndexWriter.java:3485) at org.apache.lucene.index.IndexWriter.closeInternal(IndexWriter.java:1873) at org.apache.lucene.index.IndexWriter.close(IndexWriter.java:1812) at org.apache.lucene.index.IndexWriter.close(IndexWriter.java:1776) at org.apache.solr.update.SolrIndexWriter.close(SolrIndexWriter.java:144) at org.apache.solr.update.DirectUpdateHandler2.closeWriter(DirectUpdateHandler2.java:179) at org.apache.solr.update.DirectUpdateHandler2.commit(DirectUpdateHandler2.java:411) at org.apache.solr.update.processor.RunUpdateProcessor.processCommit(RunUpdateProcessorFactory.java:85) at org.apache.solr.update.processor.LogUpdateProcessor.processCommit(LogUpdateProcessorFactory.java:154) at org.apache.solr.handler.XMLLoader.processUpdate(XMLLoader.java:190) at org.apache.solr.handler.XMLLoader.load(XMLLoader.java:79) at org.apache.solr.handler.ContentStreamHandlerBase.handleRequestBody(ContentStreamHandlerBase.java:58) at org.apache.solr.handler.RequestHandlerBase.handleRequest(RequestHandlerBase.java:129) at org.apache.solr.core.SolrCore.execute(SolrCore.java:1376) at org.apache.solr.servlet.SolrDispatchFilter.execute(SolrDispatchFilter.java:365) at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatc

But I didn't find "/usr/local/solr/example/solr/data/index/segments_15qc" file in the index folder.
Does anyone have any idea? If my setup was wrong, could anyone give some idea that how to set apache solr on drupal 7. I really appreciate it.
Answer: Thanks, guys. I found the answer out. I changed the permission for the folder which includes solr-config setting files from 755 to 777. Everything works fine now.
Reference: Solr Exception


Path for images inside a block

Question: Right now I'm at "http://localhost:8080/drupal/xxxx/user/password" and I added an image inside a block like this "sites/default/files/background.jpg"
But I think is wrong because I'm at 2 paths "user/password" and it is not taken my images, in which way can I write the path to access to my images???
Answer: You can display image using following URL:
/drupal/xxxx/sites/default/files/background.jpg
This is for your local setup. While migrating your drupal setup to production at root directory, your image url will break, because of directory change. To avoid this, you will need to change the path of image as below:
/sites/default/files/background.jpg
You can fix this broken your without changing the URL at production by using Pathologic. After Installing this module, you will need to enable Pathologic filter by checking Correct URLs with Pathologic in Text Formats e.g Full HTML. Then select Correct URLs with Pathologic tab from vertical tabs & Path relative to server root (/foo/bar) radio option. Add following values in the text area & save.
/drupal/xxxx/
/
Comment: Didn't know that module, thx so much !!
Answer: The main idea is just to use this "<?php echo base_path(); ?>" That will give you the main path and then you can go with "sites/default/....."
Answer: I believe all you need to fix on that is change the URL to /sites/default/files/background.jpg
Comment: Just 1 slash before "sites" ?
Comment: That will go straight to my localhost, but the system is inside 2 subfolders... I cant place that slash

Path for images inside a block


Determining probability generating function for event "$SS$"

Question:
Given a sequence of Bernouilli trials, we have $P(S) = \frac{2}{3}$ with $0<p<1$. The event "SS" occurs on the $i$-th trial if we observe an $S$ on the $i$-th trial following a $S$ on the $(i-1)$-th trial. We let $Q$ be the waiting time random variable to see the first event "SS". Show that the probability generating function of $Q$ is given by
  $$
\frac{4}{27}s^{2}\bigg(\dfrac{2}{1-\frac{2}{3}s} + \dfrac{1}{1+\frac{1}{3}s}\bigg)
$$

I cannot determine how to approach this question to get the probability generating function in that form. My first thought is to let $Q_{1}$ be the waiting time for the first "$S$", and let $Q_{2}$ be the waiting time for the second "$S$" after getting the first "$S$".
Then $Q_{1} \sim Geo(\frac{2}{3})$, and $Q_{2} \sim Geo(\frac{2}{3})$, and as they are independent I can multiply their respective probability generating functions to get the probability generating function for $Q$.
But this gives me
$$
\dfrac{\frac{4}{9}s^{2}}{(1-\frac{1}{3}s)^{2}}$$
which I cannot simplify to be the requested form. This leads me to think that I made an error in my approach, and I should be approaching this question completely differently.
Comment: Try to calculate the law of $Q$, i.e. $\mathbf{P}(Q=k)$ for every $k$ and then the generating function in the usual way. The support of the law of $Q$ is $\{2,3,4,...\}$, that's why there is an $s^2$ appearing as a factor.
Comment: @Nocturne I'm not quite sure what you mean, do you mean express it as a series and then do a summation?
Comment: Yes. But calculating $\mathbf{P}(Q=k)$ may not be trivial. There may be another way to do this.
Comment: @Nocturne Given that I know the distributions of everything, that seems a bit unnecessary.
Comment: $Q$ is not the sum of $Q_1$ and $Q_2$. The two successes should occur one after another.
Comment: @Nocturne I don't know what I was thinking, you are correct.
Comment: Are you familiar with Markov chain theory?
Comment: @Nocturne Yes, well, becoming familiar.
Comment: You can create a Markov chain with three states : 0, 1 and 2, corresponding to having observed zero S, one S and two S respectively. The state 2 is an absorbing state and you want to calculate the law of the time to absorption $Q$. If we note $P$ the transition kernel, then $\mathbf{P}(Q>k) = \mathbf{P}_0(X_k=0) + \mathbf{P}(X_k=1) = P^k(0,0) + P^k(0,1)$. The powers of $P$ can be calculated by diagonalization. The two eigenvalues are $2/3$ and $-1/3$, which correspond to the two series you wrote in your question.
Comment: Given the information that is presented in the chapter of the book which this question is a practice problem at the conclusion of, I don't think that that is the approach we are meant to take. I appreciate it though!
Comment: I cannot think of any easier way to calculate the law of $Q$ at the moment.
Comment: @Nocturne Could I condition on the outcomes somehow, and then calculate the pgf? I think it may be a conditioning problem.
Comment: Could you be more precise? There is an implicit conditioning in the Markov chain transition kernel construction.
Comment: @Nocturne DK's answer is what I was trying to come up with as far as conditioning
Answer: The atomic monomials are
$
\begin{array}{}
S=\color{#00A000}{2}\left(\frac x{\color{#00A000}{3}}\right)^{\color{#C00000}{1}}&\text{length $\color{#C00000}{1}$, probability $\color{#00A000}{\frac23}$}\\
NS=\color{#00A000}{2}\left(\frac x{\color{#00A000}{3}}\right)^\color{#C00000}{2}&\text{length $\color{#C00000}{2}$, probability $\color{#00A000}{\frac29}$}\\
NNS=\color{#00A000}{2}\left(\frac x{\color{#00A000}{3}}\right)^{\color{#C00000}{3}}&\text{length $\color{#C00000}{3}$, probability $\color{#00A000}{\frac2{27}}$}\\
NNNS=\color{#00A000}{2}\left(\frac x{\color{#00A000}{3}}\right)^{\color{#C00000}{4}}&\text{length $\color{#C00000}{4}$, probability $\color{#00A000}{\frac2{81}}$}\\
\qquad\vdots
\end{array}
$
The first element can be any of the atomic monomials.
The middle elements can be any non-negative number of the atomic monomials, except $S$.
The last element is an $S$.
$$
\overbrace{\frac{2\left(\frac x3\right)^1}{1-\frac x3}}^{\text{first element}}\ \overbrace{\frac{1\vphantom{\left(\frac x3\right)^1}}{1-\frac{2\left(\frac x3\right)^2}{1-\frac x3}}}^{\text{middle elements}}\ \overbrace{\frac{2x\vphantom{\left(\frac x3\right)^1}}3}^{\text{last element}}=\frac{2\left(\frac x3\right)^1}{1-\frac x3-2\left(\frac x3\right)^2}\frac{2x}3=\bbox[5px,border:2px solid #C0A000]{\frac{4x^2}{9-3x-2x^2}}
$$

Explanation of the Generating Functions Above
The "first element" can be $S,NS,NNS,\dots$. Its generating function is
$$
\overbrace{2\left(\frac x3\right)^1}^{S}+\overbrace{2\left(\frac x3\right)^2}^{NS}+\overbrace{2\left(\frac x3\right)^3}^{NNS}+\cdots=\frac{2\left(\frac x3\right)^1}{1-\frac x3}
$$
Each "middle element" can be $NS,NNS,NNNS,\dots$. Their generating function is
$$
\overbrace{2\left(\frac x3\right)^2}^{NS}+\overbrace{2\left(\frac x3\right)^3}^{NNS}+\overbrace{2\left(\frac x3\right)^4}^{NNNS}+\cdots=\frac{2\left(\frac x3\right)^2}{1-\frac x3}
$$
The "middle elements" can consist of $0$ or more of these. Their generating function is
$$
1+\left(\frac{2\left(\frac x3\right)^2}{1-\frac x3}\right)+\left(\frac{2\left(\frac x3\right)^2}{1-\frac x3}\right)^2+\left(\frac{2\left(\frac x3\right)^2}{1-\frac x3}\right)^3+\dots=\frac1{1-\frac{2\left(\frac x3\right)^2}{1-\frac x3}}
$$
The "last element" is $S$. Its generating function is
$$
\frac{2x}3
$$
Comment: Thank you for this, I honestly haven't formally learned this kind of method yet in my studies but it's very neat!
Comment: [Concrete Mathematics](http://www.amazon.com/Concrete-Mathematics-Foundation-Computer-Science/dp/0201558025) is a good reference for this method.
Answer: robjohn already has a solid answer for you, but here's another approach if you're more inclined to conditioning, which I see you considered in the comments.

Let $Q_{1}$ be the waiting time for the first "$S$". Then, as you noted, $Q_{1} \sim Geo(\frac{2}{3})$. Now we condition on the $(Q_{1}+1)$-th trial.
We have that
\begin{equation*}
    Q=
\begin{cases}
    1+Q_{1},& \text{if } (Q_{1}+1)\text{-th trial is "S"}\\
    1 + Q_{1} + R,              & \text{if } (Q_{1}+1)\text{-th trial is not "S"}
\end{cases}
\end{equation*}
where $R$ is the remaining time to get "$SS$" after getting a failure. Note that $R$ and our event $Q$ have the same distribution, i.e. $E(S^{R}) = E(S^{Q})$
Now conditioning,
\begin{align*}
G(s) = E(s^{Q}) &= E(s^{1+Q_{1}}) \cdot P[(Q_{1}+1) \text{-th trial is "S"}] + E(s^{1+Q_{1} + R}) \cdot P[(Q_{1}+1) \text{-th trial is "F"}] \\
&=s \cdot E(s^{Q_{1}}) \cdot \frac{2}{3} + s \cdot E(s^{Q_{1}}) \cdot E(s^{Q}) \cdot \frac{1}{3}
\end{align*}
Now you know the probability generating function of $Q_{1}$ as it is geometrically distributed, and you solve for $E(s^{Q})$ accordingly. You should end up with $\dfrac{4s^{2}}{9-3s-2s^{2}}$, and partial fractions will get you to your desired result.

What's wrong with your approach:
You cannot simply take the summation of $Q_{1}$ and $Q_{2}$ to find your probability generating function for $Q$, as you require the second "$S$" to occur immediately after the first one. Were you looking for the event of the first occurrence of the pattern "$SF$" say, then you could use a summation like you did. This would work because your pattern would not be "resetting" with each subsequent "$S$" before your required "$F$".


Mozilla Firefox is not displaying the css correctly, although -moz- was added

Question: display: inline-block; has been added to the code and to insure that IE and Firefox display it correctly as well -moz-inline-stack; and *display: inline; were added too.
Although these steps were taken firefox is not willing to display the element correctly.
This is the intended display:

This is how firefox is displaying it:

#currencies {
  display: -moz-inline-stack;
  display: inline-block;
  zoom: 1;
  *display: inline;
  color: black;
  font-size: 0; /* to eliminate space between buttons */
  line-height: 1.5;
  cursor: pointer;
}

#currencies span {
  display: -moz-inline-stack;
  display: inline-block;
  zoom: 1;
  *display: inline;
  padding: 1.5px 5px;
  border: 1px solid black;
  background: none #F6F6F6;
  font-size: 12px;
  background-color: transparent;
  font: Montserrat;
  letter-spacing: 2px;
  vertical-align: 2px;
}

#currencies .left {
  -webkit-border-top-left-radius: 4px;
  -webkit-border-bottom-left-radius: 4px;
  -moz-border-radius-topleft: 4px;
  -moz-border-radius-bottomleft: 4px;
  border-top-left-radius: 4px;
  border-bottom-left-radius: 4px;
  border-right: none;
}

#currencies .right {
  -moz-vertical-alignment: top;
  -webkit-border-top-right-radius: 4px;
  -webkit-border-bottom-right-radius: 4px;
  -moz-border-radius-topright: 4px;
  -moz-border-radius-bottomright: 4px;
  border-top-right-radius: 4px;
  border-bottom-right-radius: 4px;
  border-left: none;
}

#currencies .selected {
  font-weight: normal;
  color: white;
  background: black;
  zoom: 1;
}

  USD
  EUR
  CHF

Does anyone know a solution for this?
Comment: Your snippet works fine for me in Firefox, so it might be something else in the code that you haven't shown?
Comment: I am also seeing the correct display in Firefox.   It's worth noting that most of your -moz and -webkit rules are unnecessary; the standard `border-radius` rules have been fully supported in both for years, for example.   Firefox also supports `inline-block`, and due to the css order that rule is going to end up overriding the (afaik obsolete) `-moz-inline-stack` rule anyway.  You might consider going through and removing those no-longer-necessary vendor-specific rules (or better yet remove *all* of them, and use css autoprefixer to fill in any that are actually still necessary at build time)
Comment: Hi FluffyKitten, Hi Daniel, thank you both for your replies. The weird thing is that it indeed does display it incorrectly on my firefox and the one of my friend. And thanks daniel, I'll remove the border-radius specific tags, as they are really no longer needed (it's an old code).
Answer: put the -moz-inline-stack below not above the other:
display: inline-block;
display: -moz-inline-stack;

on general browsers display: inline-block; will work by default and display: -moz-inline-stack; will not as they do not recognize this. Though in firefox it will.
Remember: the style that comes last is always applied.
ALSO: I do not understand why use -moz-inline-stack as display: inline-block works for everybody.
hope that helps.
Answer: Thanks to masterpreenz I got on the right "way" I added the -moz- related code below the other code, but it was still not displaying correctly. I had to change the -moz-inline-stack to moz-inline-box and it worked.
I actually don't understand why in my case firefox did not display display: inline-block; correctly, but hey if -moz-inline-box; does the job, I'm fine with it.


$X=Spec(A)$. $X=\bigcup\limits_{i=1}^N D(f_i)\Rightarrow (f_1, ..., f_N)=A$

Question: Let $X=Spec(A)$ and note $D(f)\simeq Spec(A_f)$. $X=\bigcup\limits_{i=1}^N D(f_i)\Rightarrow (f_1, ..., f_N)=A$

We used this to proof a special case of $\mathscr{O}$ the sheaf of rings is a sheaf.
I tried to show the implication but I get stuck:
$X=\bigcup\limits_{i=1}^N D(f_i)=\bigcup\limits_{i=1}^N X\backslash V(f_i) = \bigcup\limits_{i=1}^N \{\mathfrak{p}|f_i\not\subset\mathfrak{p}\}$. But I don't know how to do the step to get $A = (f_1, ..., f_N)$.
Comment: Please do not mix words and logical symbols. To me the statement reads as "if this implication holds" (and then no conclusion). I had to read it again to figure out that what you meant.
Comment: Uh, sorry. And thanks.
Answer: Note that if $X = \bigcup_i D(f_i)$ then this is equivalent to saying that $\bigcap_i V(f_i) = \emptyset$.
On the left-hand side, we have that
$$
\bigcap_i V(f_i) = \bigcap_i Spec\big(A/(f_i)\big) = Spec\big(A/(f_1, \ldots, f_n)\big)
$$
On the right-hand side, however, we have $\emptyset$ which is Spec of the zero ring. What can you conclude from this?
Comment: For a given ideal $I \subset A$, there is a bijection between the ideals $J$ such that $I \subset J \subset A$ and the ideals of $A/I$.

If you apply this to the ideal $I = (f_i)$...
Comment: Thanks a lot. I have one more question... I see how the second equation solves the problem, but I don't see the first. Why holds $\bigcap\limits_i V(f_i)=\bigcap\limits_i(a/(f_i))$. Could you please explain me this step?
Comment: I meant $\bigcap\limits_i V(f_i)=\bigcap\limits Spec(A/(f_i))$ :)


I am getting an error as non-static variable this cannot be referenced from a static context Account account1 = new Account(1122, 20000, .045);

Question: I have written this program over and over again, can someone please tell me what I am missing, it looks like its a small error I am not catching.
Here is what I am trying to accomplish:
Design a class named Account that contains:

A private int data field named id for the account(default 0)
A private double data field named balance for the account (default 0)
A private double data field named annualInterestRate that stores the current interest rate (default 0). Assume all accounts have the same interest rate.
A private Date data field named dateCreated that stores the date when the account was created. A no-arg constructor that creates a default account.
A constructor that creates an account with the specific id and initial balance.
The accessor and mutator methods for id, balance, and annualInterestRate.
The accessor method for dateCreated
A method named getMonthlyInterestRate() that returns the monthly interest rate.
A method named withdraw that withdraws a specified amount from the account A method named deposit that deposits a specified amount to the account.

Write a test program that creates an Account object with an account ID of 1122, a balance of $20,000, and an annual interest rate of 4.5%. Use the withdraw method to withdraw $2,500, use the deposit method to deposit $3,000 and print the balance, the monthly interest, and the date when this account was created.
error is non-static variable this cannot be referenced from a static context
Account account1 =  new Account(1122, 20000, .045);
import java.util.Date;
class assignExam {

public static void main(String[] args) {

Account account1 =  new Account(1122, 20000, .045);
account1.withdraw(2500);
account1.deposit(3000);
java.util.Date dateCreated = new java.util.Date();
System.out.println("Date Created:" + dateCreated);
System.out.println("Account ID:" + account1.id);
System.out.println("Balance:" + account1.getBalance());
System.out.println("Interest Rate:" + account1.getAnnualInterestRate());
System.out.println("Balance after withdraw of 2500:" +       account1.getAnnualInterestRate());
System.out.println("Balance after deposit of 3000:" + account1.getAnnualInterestRate());
System.out.println("Monthly Interest:" + account1.id);

System.out.println("Process completed.");
}

class Account {
//define variables
private int id;
private double balance; // balance for account
private double annualInterestRate; //stores the current interest rate
private Date dateCreated; //stores the date account created

//no arg construtor
Account () {
    id = 0;
    balance = 0.0;
    annualInterestRate = 0.0;
}
//constructor with specific id and initial balance
Account(int newId, double newBalance) {
    id = newId;
    balance = newBalance;
}
Account(int newId, double newBalance, double newAnnualInterestRate) {
    id = newId;
    balance = newBalance;
    annualInterestRate = newAnnualInterestRate;
}
//accessor/mutator methods for id, balance, and annualInterestRate
public int getId() {
    return id;
}
public double getBalance() {
    return balance;
}
public double getAnnualInterestRate() {
    return annualInterestRate;
}
public void setId(int newId) {
    id = newId;
}
public void setBalance(double newBalance) {
    balance = newBalance;
}
public void setAnnualInterestRate(double newAnnualInterestRate) {
    annualInterestRate = newAnnualInterestRate;
}
//accessor method for dateCreated
public void setDateCreated(Date newDateCreated) {
    dateCreated = newDateCreated;
}
//define method getMonthlyInterestRate
double getMonthlyInterestRate() {
    return annualInterestRate/12;
}
//define method withdraw
double withdraw(double amount) {
    return balance -= amount;
}
//define method deposit
double deposit(double amount) {
    return balance += amount;
}
}

}

Comment: Does this answer your question? [Non-static variable cannot be referenced from a static context](https://stackoverflow.com/questions/2559527/non-static-variable-cannot-be-referenced-from-a-static-context)
Comment: I can not see public assignExam class. Juat simple add static class Account
Answer: Roberto's answer is correct, but for a bit of context.
You currently have your Account declared as a nested class within your assignExam class.  It is not declared static, which means for an instance of that class to be created, you would need an instance of assignExam to be created as well.
So, you can either make the class static, by using:
static class Account {

Or you could move the account class outside your assignExam class, which will automatically make it an independent class, and thus static, since it is no longer nested within another class.
Answer: Class Account should be static


Random variable on a fractal set

Question: I would like to construct a random variable on a fractal set such as the Cantor set. In other words, I would like to construct a probability measure $\mu$ on $\mathbb{R}^N$ such that I have $\mathrm{Supp}\mu$ a set with a fractal nature, quantified with respect to (for instance) the Hausdorff dimension. I have two general questions:

How can I concretely define such a probability measure? Can I keep properties like Borel sets being measurable still?
How can I explicitly compute expectations of a real measurable function $f$ defined on this probability space (in other words, how can I integrate)?

One straightforward idea I had was to use the $s$ - dimensional Hausdorff (outer) measure restricted to the support set $A$ where $s = \mathrm{dim}_H A$ as the probability measure, assuming the regularity conditions $0 < s < \infty$ and the Hausdorff measure of the set $0 < \mathcal{H^s}(A) < \infty$. But it is not straightforward for me how to proceed with expectation computations, and also whether this yields an "interesting" measure.
I would also be interested in literature that has in the past proposed such generalisations and constructions.
Answer: In general I don't think it will be easy to compute expectations with respect to Hausdorff measure, but you may be able to use something based more on the way your fractal is obtained.  Thus if your fractal is $E = \bigcap_{n=0}^\infty E_n$ where $E_n$ are compact sets and $E_{n+1} \subseteq E_n$, take probability measures $\mu_n$ on each $E_n$, and prove (if it is true) that the sequence $\mu_n$ has a weak-* limit $\mu$, i.e. $\int f \; d\mu = \lim_{n \to \infty} \int f d\mu_n$ exists for each continuous function $f$ on $E_0$.
Then $\mu$ is your measure on $E$, and expectations with respect to it can be computed by taking a limit.

Random variable on a fractal set


Data not set after fetch in react

Question: This is my code for component employ which not set data but gets count rows correct ( empty ).
I want to set the data after fetching from the server-side.
import React, { Component } from 'react';

export class Employ extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            employ: []
        };
    }

    componentDidMount() {
        fetch("api/SampleData/GetEmpl")

            .then(res => res.json())
            .then(
                (result) => {
                    this.setState({
                        employ: result
                    });
                }
            );
    }

    render() {
        return (

Employ Data...

                            EmployeeID
                            FullName
                            EMPCode
                            Mobile
                            Position

                        {this.state.employ.map(emp => (

                                {emp.EmployeeID}
                                {emp.FullName}
                                {emp.EMPCode}
                                {emp.Mobile}
                                {emp.Position}

                        ))}

        );
    }

}

I used Asp.net.Api.core for connecting database(backend).
Comment: Sidenote: When mapping over the employ inside JSX, do not use `key={Math.random()}` as react wont be able to keep track of items on rerenders. Instead you could use `key={emp.EmployeeID}` as long as its a unique value.
Answer: You can use setState as callback function.
import React, { Component } from 'react';

export class Employ extends Component {
    constructor(props) {
        super(props);
        this.state = {
            employ: []
        };
    }

    componentDidMount() {
        fetch("api/SampleData/GetEmpl")
            .then(res => res.json())
                .then(result => {
                    this.setState(() => ({
                        employ: result
                    }))
                })
    }

    render() {
        return (

                ... YOUR JSX CODE GOES HERE ...

        )
    }
}

Data not set after fetch in react


How to calculate $\lim_{n\to+\infty}\frac{\Gamma(n)}{\Gamma\left(n-x\sqrt n\right)}\frac{1}{n^{x\sqrt n}}\,$ given that $x\in\mathbb R$?

Question: How to calculate $\displaystyle\lim_{n\to+\infty}\frac{\Gamma(n)}{\Gamma\left(n-x\sqrt n\right)}\frac{1}{n^{x\sqrt n}}\,$ given that $x\in\mathbb R$?
I know that it should be $e^{-\frac{x^2}{2}}$, but I don't know the steps.
Comment: Use Stirling's approximation.
Comment: @HodossySzabolcs More common would be the interpretation of $y!$ as $\Gamma(y+1)$.
Comment: Take logarithms; then Stirling's approximation (which must be or become your friend)
Comment: @ClaudeLeibovici: Post you comment as an asnwer, I will mark it as correct. Also one will need to use $log(1+x)=x-\frac{x^2}{2}+\omicron(x^3)$.
Comment: What you must do is $\log(n!)-\log((n-x \sqrt n)!)-x \sqrt n \log(n)$ and apply Stirling for $\log(m!)$.
Comment: What do you mean by $(n-x\sqrt n)!$...? Factorial is usually defined for positive integers.
Comment: @ClaudeLeibovici: Yes, that is what I have done, but after a while, you also must use the series expansion of the logarithm. Please post your comment as an answer, so I can mark it.
Comment: @MartinSleziak: just take the integer part, as $n\rightarrow\infty$ that will cause less and less error.
Comment: @HodossySzabolcs Then you should edit your post to clarify that you mean $\lfloor n-x\sqrt n\rfloor !$ rather than $(n-x\sqrt n)!$ (So that users reading your question know what is actually being asked.)
Answer: Let us consider $$A_n=\frac{\Gamma(n)}{\Gamma\left(n-x\sqrt n\right)}\,\frac{1}{n^{x\sqrt n}}$$ Take logarithms $$\log(A_n)=\log\big(\Gamma(n)\big)-\log\big(\Gamma\left(n-x\sqrt n\right)\big)-x \sqrt n \log(n)$$ Now, use Stirling approximation $$\log\big(\Gamma(z)\big) \sim (z-\frac 12)\log( z) - z + \frac12\log(2\pi) $$ Applying it, we then have $$\log(A_n)\sim -x\sqrt{n} +\left(-x\sqrt{n} +n-\frac{1}{2}\right) \log (n)+\left(x\sqrt{n}
   -n+\frac{1}{2}\right) \log \left(n-x\sqrt{n} \right)$$ Now, rewrite $$\log \left(n-x\sqrt{n}\right)=\log(n)+\log(1-\frac x {\sqrt n})\sim \log(n)-\frac x {\sqrt n}-\frac{x^2}{2n}$$ Replacing in the previous expression, after simplifications, $$\log(A_n)\sim -\frac{x}{2 \sqrt{n}}-\left(\frac{1}{4 n}+\frac{1}{2}\right) x^2-\frac{x^3}{2
   \sqrt{n}}$$ So, for infinitely large values of $n$, $\log(A_n)\sim -\frac{x^2}2$


RequireJS not hiding KnockoutJS bindings until loading of everything complete

Question: tl;dr
The issue I am seeing is my initial page (Index.cshtml) has some Knockout code (indexViewModel.js) that is called that initially should be hiding a div on load, but for a few brief seconds the div is indeed not hidden b/c the Knockout code hasn't evaluated yet.

Background & Issue
I just began refactoring my site to use RequireJS. It is an ASP.NET MVC 5 application which uses KnockoutJS, jQuery, and a few jQuery & JavaScript plugins.
Everything worked great prior to the RequireJS refactor. Now when the user loads the Index, the spinner (data-bind="showSpinner" which is false) is shown to the user for about 3 seconds and then the Knockout code is loaded and realizes it should be hidden so then it hides.
So I am wondering how to prevent this "flashing" of hidden elements from happening? In Angular you could do ng-cloak, but I haven't found that equivalent for Knockout or Require.
I know there are some hacks I could do to initially hide things until all modules are loaded, but I don't want to hack my entire application just so things are hidden by default.
My code
Here is my basic setup for my site, using RequireJS, Knockout, jQuery, & ASP.NET MVC.
Index.cshtml

@section scripts
{

}

common.js
require.config({
    baseUrl: "/Scripts/",
    paths: {
        "jquery": "jquery-1.11.2",
        "underscore": "underscore.min",
        "knockout": "knockout-3.3.0.debug",
        "komapping": "knockout.mapping-latest",
        "noUiSlider": "jquery.nouislider.all",
        "bootstrap": "bootstrap"
    },
    shim: {
        "komapping": {
            deps: ['knockout'],
            exports: 'komapping'
        },
        "noUiSlider": {
            deps: ["jquery"],
            exports: '$'
        },
        "bootstrap": {
            deps: ["jquery"]
        }
    }
});

index.js
define(['knockout', 'app/offers/indexViewModel'], function (ko, mvm) {
    return {
        init: function (modelData) {
            var vm = modelData;
            mvm.addMethods(vm);
            ko.applyBindings(vm);
        }
    };
});

indexViewModel.js
define(['knockout', 'jquery'], function (ko, $) {
    return {

        addMethods: function (viewModel) {
            viewModel.showSpinner = ko.observable(false);
            //then a bunch of other KO code, but that observable above is the first thing & i use some jQuery plugins below, that's why i load in jQuery
        }
    };
});

Answer: Try marking the content as "display: none;" in either a stylesheet or an inline style.  Then use Knockout's "visible" binding to control the visibility.  The content will be hidden until Knockout has a chance to evaluate, setting the visibility to whatever your Knockout logic dictates.
RequireJS is probably loading your scripts asynchronously, so the markup is rendering before your JavaScript has a chance to execute.  Therefore you'll need a synchronous way to hide the content until your JavaScript executes.
ngCloak uses the exact same trick: there is a CSS selector that hides any elements with the ngCloak attribute until Angular's JavaScript has a chance to execute.
https://docs.angularjs.org/api/ng/directive/ngCloak
Comment: That is the "hack" I was thinking of (might not necessarily be a hack, I just wasn't sure if there was a more eloquent way of doing it). Although maybe this is the *only* way to accomplish it. I'm hoping to find another way though, I'm sure someone else out there has encountered this. I also thought it was possible my code above was wrong or could be tweaked. Either way, thank you for your answer.
Comment: Yeah, you could wrap the behavior you want into a custom binding called "cloak", for example.  Then your code could look something like ``.  Still not quite as clean as Angular.
Comment: External stylesheet did not work for me, but inline none did


Writing an array to a file in C?

Question: I'm working on a project for university, the basic idea is that I want to check if a file is empty.
void main() {

    FILE* file = fopen("stocksData.csv", "w+");

    fseek(file, 0, SEEK_END);
    unsigned long len = (unsigned long)ftell(file);
    if (len == 0) {  //check if the file is empty
        fclose(file);
        importCarStock();
    }
}

If it is empty, I want it to call this function:
void importCarStock() {
    FILE* file = fopen("stocksData.csv", "w");
    fwrite(carStock, sizeof(char), sizeof(carStock), file);
    fclose(file);

}

And write this array to the file:
int carStock[10] = { 5, 7, 10 };

But the only thing it writes to the file is two small blocks. Any idea what is wrong with this? Thanks in advance.
Comment: Opening the file in `w+` mode will empty it. Use `r` mode.
Comment: Do you want to write the raw binary data to the file? Or as text? Right now you're kind of mixing it, as you open the file in text-mode, but write raw binary data. There are plenty of fil I/O tutorials on the Internet, and any decent book should contain a couple of chapters about it as well. I suggest you take some time to study a little bit more.
Comment: `5, 7, 10` are ASCII codes of something that might look like "two small blocks" in a text viewer.
Comment: Your function is misnamed. Writing to a file is exporting, not importing.
Comment: You're writing a binary file. If you want to write a CSV file, you need to format the numbers. Use `sprintf()` or `fprintf()`.
Comment: It seems Barmar is right. I'm trying to figure out how to use fprintf right now, that seems to be the solution here.
Comment: "figure out how to use fprintf right now" Perhaps in conjunction with a loop.
Answer: fwrite(carStock, sizeof(char), sizeof(carStock), file);
This is the problem. fwrite writes binary data. If you have the array { 5, 7, 10 }, then it will write the bytes 05 00 00 00 07 00 00 00 0A 00 00 00 (assuming a little-endian system). You are seeing 2 blocks because of the bytes 05 and 07, which are control characters (the 0s are null characters and 0A is a line feed).
You need a for loop:
for (int i = 0; i < sizeof carStock / sizeof carStock[0]; i++)
    fprintf(file, "%d ", carStock[i]);

If you want to output numbers to a file, you need to decide whether you want to see these numbers with a text editor or a hex editor. If you store them as text, it's easier to see them with a text editor like Notepad, but reading and writing costs more time and is more error-prone if string to number (and vice versa) conversions are not performed correctly. If you store them in binary, you won't be able to see them with a text editor, you will just see gibberish because your text editor tries to interpret binary data as ASCII/Unicode characters, however they take less space and are faster and easier to read and write.
Here are the bytes of the file generated with the for loop (you can check them with a hex editor):
35 20 37 20 31 30 20
And here are the bytes interpreted as text:
5 7 10
Comment: Thank you so much! That seemed to do the trick, only problem now is that it prints a bunch of 0s after the numbers up to the size of the array, but at least it works.
Comment: The reason it prints a bunch of zeroes is because your array has more elements than you fill it with. You are only filling 3 values, but the array has 10 elements. The `for` loop I wrote writes the entire array. If you want only some of the values (like 3, in your example), you will need to keep track of this number in another variable and replace it in the for loop.

Writing an array to a file in C?


Installing openCV on Lion OS 10.7.4 Xcode 4.3.2

Question: I'm trying to install openCV on university's iMac,
but the problem is our university's network is so strict.
and I couldn't install openCV using MacPorts.
I tried google to look for a way to install but it all failed
i guess because it is kind of old ways and because my network is so strict.
So if anybody knows a way that I can download a ready framework with how to use it inside
Xcode. or at least a framework with how to install it to work with Xcode.
or a way to download from the source and compile it then install it in Xcode
please.
Because I tried the cmake way and I still have no luck to get it work.
thanks in advance.

sources I used:
http://salemsayed.me/?p=240
http://opencv.willowgarage.com/wiki/InstallGuide
http://opencv.willowgarage.com/wiki/Mac_OS_X_OpenCV_Port
http://www.ient.rwth-aachen.de/cms/software/opencv/
Comment: Have you tried Homebrew? It may well have the same issues as MacPorts though! http://mxcl.github.com/homebrew/
Comment: exactly thats why i want a standalone way like downloading installer or something ..
Comment: I managed to install it with Homebrew but I don't know how to get it work with Xcode ... so I can't confirm if the installation is right 100% ....
thanks anyway ..
Answer: I'm using Lion + Xcode 4.x branch, with OpenCV svn trunk. Everything works fine. You have to install cmake first, then get the code from the svn following the instructions at http://code.opencv.org . The compilation process worked fine for me for all the core modules + the Qt module + the GPU module + TBB acceleration.
The instructions are the same as the Linux platform.
After setting up cmake configuration in a terminal (using ccmake for a more interactive tool),
I set the architecture to x86_64 (on my MBP Core 2 Duo), the target directory to /usr/local/(the default), and I have Intel TBB installed in /usr/local/.
Cmake generates the makefiles for you, so you just have to type make -j2 to compile, then sudo make install. If you're working on a workstation, then you have more CPU power, and you can replace the value 2 by more, e.g. 8.
Comment: Actually I managed to install the openCV using homebrew for Mac ..
but how can I make sure that it is installed correctly ?
I want to start working on openCV using Xcode but I don't know if the installation is right ...
if you can tell me what is the steps from the begging to use it with Xcode .. like what kind of project should i choose and how to write a hello world like app to test the openCV .. It would be very helpful.

thanks in advance ..
Comment: To test your installation, create a command line project for C++. Then, in the project settings, add the search path for the header and dylibs (that should be /usr/local/include/ and /usr/local/lib/ respectively). Add also some opencv linker flags under the eponym setting, e.g. -lopencv_core and -lopencv_highgui. In the main.ccp file, include  and  and try to read, display, save an image.


django nested model json import

Question: I am quite new to Django and I may be missunderstanding some concepts, but I can not find a solution to what I am trying to do.
I have a multi table model defined and I have defined the models, views, admin, serializers and urls. It is working perfectly to independtly read and write in all of them through the API.
The code looks something like this:
models.py
class Level1(MySQLNoCountModel):
    name = models.CharField()
...

class Level2(MySQLNoCountModel):

    level1 = models.ForeignKey(
        Level1,
        blank=False,
        null=True,
        on_delete=models.CASCADE
    )

    name = models.CharField()
    )
...

serializers.py
class CreateLevel1Serializer(OrderedModelSerializer):
    name = serializers.CharField()

    def create(self, validated_data):
        obj, created = models.Level1.objects.update_or_create(
            name = validated_data['name'],
            defaults={
            }
        )

class CreateLevel2Serializer(OrderedModelSerializer):
    level1 = serializers.CharField()
    name = serializers.CharField()

    def validate_level1(self, value):
        try:
            return models.Level1.objects.get(
                name=value
            )
        except Exception:
            raise serializers.ValidationError(_('Invalid leve1'))

    def create(self, validated_data):
        obj, created = models.Level2.objects.update_or_create(
            name = validated_data['name'],
            defaults={
                'level1': validated_data.get('level1', True),
            }
        )

With this I can create new elements by sending two consecutive posts to the specific ednpoints:
{
    "name":"name1"
}

{
    "level1":"name1",
    "name":"name2"
}

I am trying to do it in a single operation by inserting something like this:
{
    "name":"name1"
    "level2":[
        {
            "name":"name2"
        },
        {
            "name":"name3"
        }
    ]
}

I have tryied to redefine the level1 serializer like this but It tryes to create the level2 before the level1, resulting on a validation error.
class CreateLevel1Serializer(OrderedModelSerializer):
    name = serializers.CharField()
    level2 = CreateLevel2Serializer(many=True)

What is the correct approach for this?
Answer: I have found a way to do it (don't know if it is the regular one). On the creation of the Level1 we can call the level2 serializer. Something like this:
class CreateLevel1Serializer(OrderedModelSerializer):
name = serializers.CharField()
def create(self, validated_data):
    obj, created = models.Level1.objects.update_or_create(
        name = validated_data['name'],
        defaults={
        }
    )
    for level2 in request.data.get('level2'):
        level2serializer = CreateLevel2Serializer(data=level2)
        r=level2serializer .is_valid()
        level2inst = level2serializer .save()

django nested model json import


Alter the username label in the login block

Question: I want to alter the username label. Instead of username, I want to change it to User ID.
I've written the following code to perform this function, but I'm not sure how to implement it.  When I implement it in the page that contains the login block, nothing happens.
function lae_form_user_login_form_alter(&$form, &$form_state, $form_id) {
 $form['user-login-form']['edit-name']['#title'] = t('User ID');
}

Will this actually work? If it will, how do you implement it?
Answer: Your code needs to go inside a custom module. Assuming your module is called lae then you just need to make one or two small changes to your code:
function lae_form_user_login_form_alter(&$form, &$form_state, $form_id) {
  $form['name']['#title'] = t('User ID');
}

The edit- prefix that you get from the element's ID in HTML is actually provided by Drupal automatically, it's not the name of the key in the form array that identifies the element. Also the elements (at least for this particular form) will normally be at the root of the array so you don't want to reference $form['user-login-form']['edit-name'] (as it most likely doesn't exist).
I would advise downloading and installing the Devel module and using the dpm() function to print a nice representation of your form array to the screen, so that you can inspect it and see the correct array keys you'll need to target to effect a certain element.
// Add this to your form alter function:
dpm($form);

Comment: `hook_form_alter()` does get called for themes as well as modules as it goes, so all you need to is put this code in your theme's template.php file, clear Drupal's cache and you should be good to go. Clearing the cache is probably the only bit you've missed so far. To make sure the hook is being called just add `drupal_set_message('Hook called');` into the function and see if you get the message on the site.
Comment: It's one of Drupal's ['hooks'](http://api.drupal.org/api/drupal/includes!module.inc/group/hooks/7), you define the function with a specific name (in this case `THEMENAME_form_alter`), and Drupal will automatically pick it up for you when the caches are next rebuilt, and the system will call the function when it's appropriate. Each core hook (and many contrib hooks) are well documented (search Google for `hook_form_alter`, `hook_page_alter`, `hook_menu`, etc.). You'll find the function signatures on the individual docs pages
Comment: Thank's for your prompt answer. LAE is actually the name to a zen sub theme that I'm using. I actually added the code to the "template.php" file. When you say, "custom module," do you mean that I need to build my own module and place it in the "/sites/all/modules" folder?
Comment: Once again, thanks. I actually have multiple modules already installed in Drupal 7 to assist with creating this site. I had devel installed before posting this question. I find page_title, metatags, pathauto, ctools & admin_menu to be quite nice additions.
Comment: I'm still very new to drupal, so you'll have to excuse me.  How do you call the above function? Do you just write the name out lae_form_user_login_form_alter() .... and if you call this function, how do you know what to use for the parameters of the function>
Comment: Yes! Thank you so much!!!! After I changed the name of the function to "lae_form_alter(&$form, &$form_state, $form_id)," I refreshed the logged in page (in Chrome) and got output from dpm($form). In my logged out page (in Firefox) it prompted me with "hook called."  Now, I've got a good starting point. I appreciate the help!
Comment: No worries glad to help :)
Comment: Here's the complete solution.  This will change the label text for the username textfield:

    function lae_form_alter(&$form, &$form_state, $form_id)
    {
 $form['name']['#title'] = t('User ID');
    }

It's amazing how simple that is.
Comment: @user6657 That will run for every form on the site...it might be worth adding `if ($form_id == 'the-form-id') {` before that logic, or look at implementing [`hook_form_FORM_ID_alter`](http://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_form_FORM_ID_alter/7) so you don't get any unexpected problems on other forms. (in fact your original question had the right function name in it: `lae_form_user_login_form_alter`
Comment: How do I find the form id for the user login block? I "assumed" the login block was basically a small version of the /user page.
Comment: Just put `drupal_set_mesage($form_id);` into your existing `lae_form_alter` function and all the form ids for the page will print out to the messages area...it should be obvious which one you want to use :)
Answer: You can use the String Overrides module.

Provides a quick and easy way to replace any text on the site.

Features

Easily replace anything that's passed through t()
Locale support, allowing you to override strings in any language
Ability to import/export *.po files, for easy migration from the Locale module
Note that this is not a replacement to Locale as having thousands of overrides can cause more pain then benefit. Use this only if you need a few easy text changes.
Comment: The *String Override* module doesn't allow to decide where the string should be replaced. It changes every occurrence of *username* whenever it is passed to `t()`.


Can I make a temp table with other temp tables

Question: I'm wondering if I can pull together the data from my other temp tables.
I need to be able to run a report for many different people from different departments and then aggregate the data so that I have individual reports, a larger picture of each department, and the entire floor including all departments to get the big picture. I have all the associates id #'s but I will need to separate each associate and department with their different "roles" in the company and most all have multiple roles assigned to them in the database.
So to avoid running a report for each associate, department, security role, function role, and the different task matrix that is important for them (# of calls, emails, task a, b, c, and pass through process a-z) which all depends on the person, etc., I created temp tables for some of the most important for all and will tie in the rest. To avoid having to change the date range of the report every time I pull it, I was hoping to aggregate the temp tables and change the date just the once in the aggregated temp table. Then I can run the query with the rules I need.

No join will work across all tables.
All tables need to be separate so no (union, cross join, or any table joins until the associate/department/role level if needed)
5 temp tables each with 3 indexed columns from the table (requestid, userid, createDT, except for 2(calls & users), maybe more columns later.

Example:
<code>`tmp.notes`; (requestid, userid, createDT)
`tmp.custcont`; (customer contact), (requestid, userid, createDT)
`tmp.emails`; (requestid, userid, createDT)
`tmp.calls`; (requestid, agent_id(= to users username, createDT)
`tmp.users`; (id, personid, username)
</code>
Comment: A temporary table is simply a table that will be automatically removed when the MySQL Session is over. You can do with it whatever you want.
Answer: Once you've created a temporary table, you can use it as you would any other table.  Therefore, you can almost certainly do what you want.


Closed path (for filling) with different strokes

Question: I'd like to create a closed Path, but with different strokes for the elements that make up the path.
So, for instance. I'd like to create a shape from three bezier curves, this shape is closed, so that I can give it a fill. But each of the three bezier curves should have it's own stroke thickness or stroke color.
As far as I know... since I'd like to give it a fill, I have to use one Path object, but the stroke and the stroke thickness can only be set on this very same Path object, so it is used for all three bezier curves.
CombinedGeometry doesn't work either, since it is used inside one single Path object.
So, is there something like a PathCollection object, that I can use in XAML?
Comment: maybe add a picture of what you are trying to achive and we can figure out a way to help you! Or are you planning on something dynamically generated?
Comment: I plan to create an irregular shaped button. But since I couldn't find a decent way to automatically size this irregular shaped button to the sitze of it's content I thought about putting a bezier path to the left and the right of the rectangle containing the content. And to be able to give my button (combined beziers and rectangle) a background and a border I need to be able to fill the shape (background) and to giveparts of the shape a stroke and a stroke thickness.
Comment: I probably go with a closed shape for filling and an identical shape for the stroke/stroke thickness.
Answer: This cannot be done with a single Path, you have to create a separate Path for each element.
LinearGradientBrush, as an example, won't work because it declares a starting and ending X/Y coordinate. If your shape is a rectangle then there are some tricks you can do to exploit this which you can use for animated marquees etc but it doesn't work for arbitrary paths.


Easy fingering for C6-D6-E6 on tenor saxophone

Question: I am looking for an easy fingering for C6-D6-E6 on the tenor saxophone.
I know there are different fingerings for each not possible on the sax and I did study the ultimate fingering chart, which is an excellent resource.
Yet, a friend recommended me to avoid using the palm keys because they kind of slow you down, to which I agree. I also kind of feel like the sax is slipping from my hands when I play the D6, there is no "frontal support". Therefore I am trying to find another grip for D6 without a palm key, so not like this:

I do prefer to use this fingering for E6 because it is easy and fast to continue up the register this way:

So my main question is: is there any grip for D6 without using the palm key?
Comment: As a clarification, the octave numbers refer to absolute (midi) octaves.
Comment: Have you tried adding palm key risers to your instrument?   I have big hands and they make the palm keys much easier to play for me.
Answer: I think what your asking for is an alternative fingering for the palm D. Unfortunately, that's a discomfort you'll need to learn to overcome.
Comment: Wouldn't fingering a low D, Bb, or A produce a high D as an overtone? Not exactly what a beginner is looking for, and no guarantee on the tone, but shouldn't it work?
Answer: I know this question already has an accepted answer, but it's actually lacking in substance, in my opinion.
Also, your reference manual is a good one but it's incomplete as well. I only use it for multiphonics personally. In my opinion, this is a much better resource of alternate fingerings. My teacher recommended playing C + palm D for quick switches between C6 and D6, claiming that it's a bit off but won't be noticed in a quick progression. On my horn it's way off, so I don't do it. Personally, I just play the first harmonic on D5 (which is D6), just like LS97 suggested to you. That is subject to how large the opening on your mouthpiece is, how hard the reed is and so on. I doubt you would be able to get the first harmonic on D5 if your mouthpiece has a small baffle and your reed is below 3.5 strength.
All common fingerings feature at least 1 palm key.
P.S. It would be funny if you were struggling with this progression because you were learning to play a certain passage from Pink Panther at 120BPM (that's when I first had to deal with this problem myself).
Answer: Playing D with the correct fingering should be easy enough.  If you think this is awkward or slow you should try the clarinet, or for some real fun, the bassoon.  :)  Trying to get it some other way is going to not be worth the effort and not sound right and probably be out of tune.
Using the alternate fingering for E (with the jump key) should be used judiciously in my opinion as well, basically I think of it as a bridge between the altissimo register and the "normal" register.  If I'm not going to or coming from altissimo, I'm using "palm" E every time.
Comment: It's almost impossible to play C6->D6->E6 at 120BPM without using an alternate fingering for D6 (according to my teacher).


cannot prove simple conditional probability

Question: Is the next true? If so, why?

P(A∩B|C) = P(A|B∩C) x P(B|C)

I saw as part of solution of an exercise, but I can't prove that is true, how is it possible to arrive to that?
Answer: Via a few steps using conditional probability definition:
$$\begin{align}P(A,B|C)&=\frac{P(A,B,C)}{P(C)}\\ &=\frac{P(A|B,C)P(B,C)}{P(C)}\\ &=\frac{P(A|B,C)P(B|C)P(C)}{P(C)} \\ &=P(A|B,C)P(B|C)\end{align}$$
Intuitionally, you can think of it as a more complex form of $P(A,B)=P(A|B)P(B)$, since you add a global given random variable $C$ to each term here, i.e. it is true for any given set of events $\mathcal{E}$: (e.g. $\mathcal{E}=C,D,E...$)
$$P(A,B|\mathcal{E})=P(A|B,\mathcal{E})P(B|\mathcal{E})$$


hadoop java.io.IOException: while running namenode -format on OSX

Question: I am getting following error while formatting namenode, I have tried using sudo su as mentioned in some other stack overflow solutions but i am still getting this error,please assist.
14/01/16 16:10:41 INFO util.GSet: Computing capacity for map INodeMap
14/01/16 16:10:41 INFO util.GSet: VM type       = 64-bit
14/01/16 16:10:41 INFO util.GSet: 1.0% max memory = 889 MB
14/01/16 16:10:41 INFO util.GSet: capacity      = 2^20 = 1048576 entries
14/01/16 16:10:41 INFO namenode.NameNode: Caching file names occuring more than 10 times
14/01/16 16:10:41 INFO namenode.FSNamesystem: dfs.namenode.safemode.threshold-pct = 0.9990000128746033
14/01/16 16:10:41 INFO namenode.FSNamesystem: dfs.namenode.safemode.min.datanodes = 0
14/01/16 16:10:41 INFO namenode.FSNamesystem: dfs.namenode.safemode.extension     = 30000
14/01/16 16:10:41 INFO namenode.FSNamesystem: Retry cache on namenode is enabled
14/01/16 16:10:41 INFO namenode.FSNamesystem: Retry cache will use 0.03 of total heap and retry cache entry expiry time is 600000 millis
14/01/16 16:10:41 INFO util.GSet: Computing capacity for map Namenode Retry Cache
14/01/16 16:10:41 INFO util.GSet: VM type       = 64-bit
14/01/16 16:10:41 INFO util.GSet: 0.029999999329447746% max memory = 889 MB
14/01/16 16:10:41 INFO util.GSet: capacity      = 2^15 = 32768 entries
14/01/16 16:10:41 FATAL namenode.NameNode: Exception in namenode join
java.io.IOException: Cannot create directory /Users/hadoop/hadoop/bin/hdfs/namenode/current
    at org.apache.hadoop.hdfs.server.common.Storage$StorageDirectory.clearDirectory(Storage.java:301)
    at org.apache.hadoop.hdfs.server.namenode.NNStorage.format(NNStorage.java:523)
    at org.apache.hadoop.hdfs.server.namenode.NNStorage.format(NNStorage.java:544)
    at org.apache.hadoop.hdfs.server.namenode.FSImage.format(FSImage.java:147)
    at org.apache.hadoop.hdfs.server.namenode.NameNode.format(NameNode.java:837)
    at org.apache.hadoop.hdfs.server.namenode.NameNode.createNameNode(NameNode.java:1213)
    at org.apache.hadoop.hdfs.server.namenode.NameNode.main(NameNode.java:1320)
14/01/16 16:10:41 INFO util.ExitUtil: Exiting with status 1
14/01/16 16:10:41 INFO namenode.NameNode: SHUTDOWN_MSG:
/************************************************************
SHUTDOWN_MSG: Shutting down NameNode

I just tried creating directory /Users/hadoop/hadoop/bin/hdfs/namenode/currentbut i found out that bin directory has file named hdfsso its not allowing me to create a directory named hdfs in bin directory so not sure if I should over write this hdfs file or copy it to other location?
Answer: If the directory /Users/hadoop/hadoop/bin/hdfs/namenode/current doesn't exist, you can't create a file there, so make sure you create the directory first.
Ensure you that you have read and execute access to all child directories as well: chmod o+x /Users/hadoop/hadoop/bin/hdfs/namenode/current
Check if hadoop runs under a different username. To find this you can use this command from the command line: ps aux | grep hadoop
Comment: I think i just found out the problem but i still have no solution Let me edit the post and mention what is wrong