Producing a large list of irreducible polynomials of given degree over a specific finite field using a CAS?

Question: I'm curious if there are computer algebra systems that allows one to easily produce a list of irreducible polynomials of a given degree $n$ in $\mathbb{F}_p[X]$, where $p$ is a specific prime. Does Sage or GAP have any built-in capabilities to return this list? I've been trying to see if either of these can return of a list of polynomials of given degree, and then filtering said list by some built in function or method such as is_irreducible, but can't find anything in the documentation.
I can do it in a round about way constructing $X^{p^n}-X$ over $\mathbb{F}_p$ and factoring, but this does not return very convenient results, and produces many factors of lower degree. For example, I can find the $116$ irreducible polynomials of degree $6$ in $\mathbb{F}_3[X]$ with
sage: R = GF(3)['x']
sage: factor(R(x^(3^6)-x))

and reading off the factors of degree $6$, but it's not in a convenient list form, and also produces all irreducible polynomials of degrees $1,2,3$ as well.
Answer: GAP has a function AllIrreducibleMonicPolynomials(<degree>,<field>) that does exactly what you want. In your example:
gap> l:=AllIrreducibleMonicPolynomials(6,GF(3));
[ x^6+x^5+x^4+Z(3)^0, x^6-x^5+x^4+Z(3)^0, x^6-x^4+Z(3)^0, x^6-x^5+x^3+Z(3)^0,
  x^6+x^4+x^3+Z(3)^0, x^6-x^5-x^4+x^3+Z(3)^0, x^6+x^5-x^3+Z(3)^0,
  [ ... and so on]

The function is used for example in enumerating conjugacy classes of GL.
Comment: Thank you, just what I was looking for.


url setting for directry

Question: I want to make a setting for the url. If a user entered url in address bar like this "folder.mysitedomain.com"
   then it should be open files from second layer directory named 'folder' of the 'mysitedomain.com'(root directory) at server.
   A user can also put url just like this "mysitedomain.com/folder" then it also done as above.
   Url will show as well as user entered.
   This should be dynamically, for example directories are creating accrording to separate user accounts, so the name of the directory may be anything as dynamically.
I think it is for .htaccess  files setting. is there ?
   I have no idea about this that what i should to do and how to search this in Google and any searching site.
Help should be happily.
Answer: I'm not completely sure what you're trying to do but I think you should check out glob
http://php.net/manual/en/function.glob.php
That should get you started anyway.

url setting for directry


Basic question with respect to Drupal form API

Question: I am learning the Drupal Form API. I am new to HTML and PHP also.
I read in a book how to define a form in Drupal, where they used the following example:
/**
* Define a form.
*/
function formexample_nameform() {
  $form['user_name'] = array(
    '#title' => t('Your Name'),
    '#type' => 'textfield',
    '#description' => t('Please enter your name.'),
  );
}

What will the HTML equivalent of above example be?
Similarly, to validate the form they did it as follows:
/**
 * Validate the form.
 */
function formexample_nameform_validate($form, &$form_state) {
  if ($form_state['values']['user_name'] == 'King Kong') {
    // We notify the form API that this field has failed validation.
    form_set_error('user_name',t('King Kong is not allowed to use this form.'));
  }
}

What will be HTML equivalent of both of these functions?
Answer: The HTML produced from the first function (the form builder) can be roughly seen checking the code for the theme functions, which are at least two: theme_textfield(), and theme_form(). The exact output can change basing on the theme being used, and third-party modules installed on the site.
For the validation handler, the function that adds the class for form fields with a validation error is _form_set_error(), while the list of the validation error messages are set with form_set_error(), which uses the following snippet:
  if ($message) {
    drupal_set_message($message, 'error');
  }

The messages that are set with drupal_set_message() are then output with theme_status_messages().
Also in this case, the real output depends from the theme being used, and from other modules installed on the Drupal site; both can alter the output used for the rendering.
Answer: If I understand well your question, you are reading a book that does not explain the relation between common html forms/behaviors facing same things in Drupal.
The html equivalent of your first function is a text field. An html example:
User Name:
<input type="text" value="" name="user_name">

see following guide for more information about text fields: http://www.tizag.com/htmlT/htmltextfields.php and other html form elements: http://www.tizag.com/htmlT/forms.php
And regarding your second function, (if I am not wrong) there is no equivalent in html4 for validations in a web page. a common ways is to use javascript (one example: http://www.tizag.com/javascriptT/javascriptform.php or server side languages/technics like php (one example: http://www.html-form-guide.com/php-form/php-form-validation.html). with html you can build forms, not validate forms.
one note, if you are interested in Drupal and forms, an alternative is build forms using CCK module http://drupal.org/project/cck (without coding) for Drupal 6, or just use Drupal 7.
Also, if you are new in Drupal, HTML and PHP, alternatively you can start to learn Drupal without coding or touch APIs, HTML and PHP http://drupal.org/documentation/customization/tutorials/beginners-cookbook (Drupal 6), http://drupal.org/node/1062604 (Drupal 7)
Comment: moon.watcher thanks you understood it correctly.The book is Pro Drupal Development. www.apress.com/9781430228387


Uniqueness of limit point of a Cauchy Sequence

Question: I'm trying to show that the closure of a Cauchy sequence is countable, and the hint for the question is to show that if $(x_n)$ is Cauchy, then it has at most one limit point.
I'm a little bit confused between the idea between the idea of a limit point of a set and a limit of a sequence. I know that if $\{x_1,x_2,...\}$ is a set, then $x$ is a limit point if $\forall r >0, \exists x_k \neq x $ such that $x_k \in B_r(x)$.
Now I also know what a limit of a sequence is, but since this isn't necessarily a complete metric space we don't know if $(x_n)$ converges. My first thought was to use the fact that Cauchy sequences are bounded, but I don't know where to go with that.
Would appreciate any hints!
Comment: So if you have two limit points, the two limit points must be separated at some distance…so why is it impossible to get all points as close as you want no matter how large you make the n to be?
Comment: Using boundedness is clearly not sufficient. But Cauchy sequence means that the members get closer and closer with each other for sufficiently large N.
Comment: Off the top of my head, let $x$, $y$ be limit points with distance $r$ between them. Since they are limit points, there are infinitely many points from $(x_n)$ in both $B_{r/2}(y)$ and $B_{r/2}(x)$...then take a point in one of the balls, use the Cauchy property and maybe the triangle inequality to get a contradiction between the distance of the limit points?
Answer: Note that from your definition of the limit point of a sequence it follows that each neighborhood of a limit point contains infinitely many terms of the sequence. You can use this statement for your proof as follows:
Suppose for the sake of contradiction that your cauchy sequence $(x_n)$ has two limit points $x \neq y$. Then $\varepsilon := d(x,y) > 0$, by the definiteness of the metric. Since $(x_n)$ is Cauchy, there exists $N \in \mathbb{N}$ such that for all $n, m \geq N$ you have $$d(x_n, x_m) < \frac{\varepsilon}{ 4}.$$ Furthermore, since $x$ is a limit point you find $x_n \in B_{\frac{\varepsilon}{4}}(x)$ with $n \geq N$. But then, for all $m \geq N$ you have
$$
d(x_m, x) \leq d(x_m, x_n) + d(x_n, x) < \frac{\varepsilon}{2}.
$$
So, for all $m \geq N$ this gives you $x_m \in B_{\frac{\varepsilon}{2}}(x)$ which contradicts the assumption that $y$ is another limit point.
Comment: That's a contradiction because the rest of the sequence ($x_m$ with $m > N$) being in that ball around $x$ necessarily means they can't be in $B_{\epsilon /2}(y)$ right?
Comment: Correct! Per constructionem, we have $B_{\varepsilon/2}(x) \cap B_{\varepsilon/2}(y) = \emptyset$.
Answer: The limit point of a set :

Given a set $A$, a limit point of $A$ is a point such that there exists a sequence in $A$, converging to that point. Alternatively, every neighbourhood of a limit point contains at least one point in $A$ that isn't the limit point itself.

The limit of a sequence is given via the epsilon-delta definition.
These notions coincide when you treat a convergent sequence as a set (you can check this yourself). However, they don't coincide in general: For example, the limit points of the set $\{( -1)^n\}$ are $-1$ and $1$, although  the limit of the sequence $\{ (-1)^n\}$ doesn't exist.
In the case of your question, you can do it in a few steps as follows  (I'll leave the steps, but there are comments):
1) Treating the Cauchy sequence as a sequence, all it's subsequences are also Cauchy.
2) If a Cauchy sequence converges to a given point , then all it's subsequences also converge to the same point.
The crucial one:
3) If a Cauchy sequence has a convergent subsequence, then it also converges (to the same point!)
From this, we are done:
Treat the Cauchy sequence $C$ as a set. Suppose it's not convergent, then I claim it has no limit points. Suppose it had, then there would be a subsequence $D$ of $C$ converging to that point. But then, by $3$,  $C$ would also have to converge to that point, and this is a contradiction.
If $C$ is convergent, then any subsequence of $C$ must also converge to that point. In short, the limit point is unique.
Hence, this completes the proof. If you do not get it yet, please inform me.
Comment: @Excalibur42: This follows directly from the definition of the limit point: For each $k \in \mathbb{N}$ you can choose $x_{n_k} \in B_{1/k}(x)$ and per constructionem this is a convergent subsequence.
Comment: Why is it the case that if there were a limit point, we could find a subsequence converging to it?
Comment: wait… does your proof require the Cauchy sequence to have a convergent subsequence? That will be a problem…since we can take the rational as a metric space and we can make a continued fraction that converges to sqrt(2)…but it converges to no where in R?
Comment: If you take continued fractions converging to $\sqrt 2$, then either *all* the subsequences will converge to $\sqrt 2$, or *none* of these sequences are convergent (since we are restricting ourselves to rationals).
Comment: Oh I see… you are using the fact that if it is a limit point then there is a subsequence converge to that.
Comment: Correct, that is by definition.


content field user reference populated by view (views2)?

Question: Drupal-6.22
I have numerous content types where one or more users are associated with the type.  On the bottom of the field definition page there is an advanced section where it asks for the name of the view to provide the content.  I've created a view but it is not showing in the drop down in this area. What does one have to do in order to make a view available for this content field drop down?
The field area reads: Advanced - Users that can be referenced (View)
Please provide a URL where this is explained?
Thanks
Answer: The way I understand it, CCK will list all views on your site that return USERS, so, make sure your view is of type USER not NODE.


Music Store Etiquette

Question: A music store that sells high end instruments is faced with a dilemma.
It is their responsibility to sell you instruments.  But you cannot buy an instrument without trying it out for some period of time.
At the same time, the store has to draw the line somewhere: For example, if they have a $4,000 guitar for sale, they cannot let everyone come in and play the instrument for a few hours everyday because it will degrade the quality of the guitar.
But if I want to buy a $4,000 guitar, for example, I am going to have to get a good feel for it.
What is an appropriate balance?  If I go into a store and am interested in boutique instruments, how much "playtime" is reasonable per instrument?
The reason I ask is that yesterday I went into a store and played 4 different high end guitars (between 2 and 4 thousand dollars each).  I was asked to leave after an hour and was told specifically that 1 hour is ample time, which I disagree with.  I can't make a $4,000 purchase decision with 15 minutes on each instrument.  But I understand that they need to keep their instruments in good condition in order to sell them.
Comment: It may be hard to answer this, because clearly you know what you intended, but did anything in your behaviour, demeanor, age, etc. suggest to them that you had no intention or no possibility of buying the guitar? At face value their behaviour is poor, so I wonder if there is a reason not covered in the question.
Comment: Is this an acoustic or electric guitar?  Either way they shouldn't ask you to leave if they want to make a sale, but the cultures in shopping can be pretty different.
Answer: If a customer hasn't made his decision after an hour, etiquette dictates you offer him a cup of coffee, not ask him to leave. I've had a lot of experience buying instruments, though mostly pianos, and have found 15 minutes of play time not to be nearly enough to purchase something in that price range. In fact, especially if the store has a wide selection, I've often stayed until listener fatigue sets in, only to come back at a later date. Some instruments I was even allowed to try at home for a week.
Not taking the time you need or feel comfortable with benefits neither you nor the store. Guitars don't significantly degrade in 15 minutes either. If they did, you'd have to acquire a new one every other week. In that sense, I don't think 'an appropriate balance' really applies here.
Of course, if the store suspects you of abusing the venue as a free studio with no intention of ever buying something, asking someone to leave is completely reasonable. As for not leaving that impression, it might help to take notes or to bring someone to listen while you play and vice versa, which I strongly recommend anyway.
Comment: I was going to provide an answer, but it'd be exactly this. The "reasonable playtime per instrument" is whatever amount of time it takes for you to be confident that you're buying what you want. Like any other large purchase you are entitled to do whatever you need to provided it's not harmful to the instruments; it's the same as test driving a car a few times to get a feel for it. I've bought a few guitars in the ~$2,000 price range and if the store gave me a "buy it or get out" ultimatum, that wouldn't be any place I'd care to do business with personally.
Comment: Upvoted for being the answer I was going to write too.  The store should ideally have somewhere for you to audition the instrument without disturbing other customers - but "throwing you out" after an hour is disgusting.  That shop doesn't deserve your money, to be honest.
Comment: As long as you are not demonstrably damaging the instrument while you're auditioning it, you should have the time you need to make an informed decision.  Simply playing the instrument is not harmful.  It sounds to me like this is not what I would call a true music store; more like a product pushing store.  I'd look for a better vendor, if possible.
Answer: There are 2 parts to this, and both of them put the guitar store in the wrong unless you were rude or in some way threatening the guitars.
I absolutely go with the belief that they have that guitar for the express purpose of selling it.  If they ask you to leave they're damaging that chance in many ways.  I highly doubt there's an endless line of people for that one guitar, and if there is, they should buy a second one :P
They can't sell you on price
The fact of modern life is that you can probably get whatever guitar they have cheaper on-line.  Unless it's custom made by them, which I highly doubt, the price alone ain't gonna cut it.  What they have to sell you on is 2 things.
service
Do you get a free setup, will they tell you how to best keep it in good shape, do they offer guarantees? basically everything you can't get online
trust/enjoyment
If you like the people selling, you are more likely to buy from them.  on top of that you are more likely to trust that they're not selling you a fake, that they value your purchase and that they have advised you on the best guitar for your needs
The appropriate balance is as much as you want to play.  You're the one with the money that they ultimately want so they need to accept that you will take time to make your decision.  I tried out one of my guitars once every few months for 2 years before I finally bought it.  It was a 7 string so I had to really get used to it!  but after all that time they finally made the sale, and every time I need strings etc I'd go back.
As for the good condition thing, if they're genuine at that level there's not much a customer can do to degredate the quality unless they drop it, but in that case they have insurance, and possibly a court case for you ;)
Answer: This is an interesting question. I don't really know if there's a right or wrong answer for this, but here's my take.
I don't think anyone can get a true "feel" for an instrument after trying it out in a music store for an hour. It takes months, if not years, to really get the true feel, break it in, and make it truly your own. However, it has usually only taken me moments in a store/at a convention to determine if an instrument is even worth the time to break in. I would almost relate it to buying a house - you might see 15-20 houses, but there's always that one that you walk into and say "yes, this is the one." It just feels right from the moment you play it.
My recommendation would be to try many of them out. You'll get an idea of which one feels the best when you've compared them to many others. You'll likely find yourself going back to one or two that exclusively feel pretty great to play. In the end, it shouldn't necessarily be the price tag of the instrument that determines if you make the purchase, but your personal compatibility with it. A great instrument will not hinder your natural approach, but help make it easier & better. That should be a relatively quick thing to determine -- I wouldn't spend too long hanging on the minutiae or you'll find yourself never purchasing a decent instrument.
As for etiquette, I suppose that just depends on the store's policies. I'm sure the store sees plenty of "customers" who play high-end equipment for hours and walk out with a set of strings. If they give you issues about playing, you always have the option of taking your business to a store that shares that spirit. Otherwise, as I said above, make the decision from the heart. In the end, you're the one who will be playing it for the next x years, so no amount of reviews or research will ever compare to the feel.
Comment: Good analogy. When buying a house (or a car) you wouldn't normally expect to spend multiple hours in it - you might reasonably get an hour to poke around and you might come back for a second look.
Answer: We'll go on the assumption that you're not experimenting to see how far you can bend the whammy bar   :-) .   Certainly musical instrument tryout etiquette varies across instrument types.  Reputable (orchestral) string dealers have no problem letting clients take $20k or $50k instruments home for a week, for example.
On the other hand, if you showed up every day or twice a week, played for a couple hours, and left, then regardless of the instrument class or cost the manager would toss you out.
Don't disregard the importance of appearance.  Even in the world of punk-rock guitarists and drummers, if you show up at the store looking slightly wasted and wearing clothes that looked like dumpster reclaims (and smelling same),  you are not going to look to the sales force like a serious buyer.
Answer: While trying the instrument, you are consuming the acoustic space of the shop, others cannot try. Only one instrument can be played and heard well at time.
As a result, reaction may depend if there are more people waiting. If there is a queue, you are not polite with other buyers, and the seller may try to correct the situation one or another way.
If you just make random sounds or play really badly, the seller may stop you earlier suspecting you are not professional enough to be seriously interested in buying expensive instrument. Matters also how are you dressed.
Answer: Maybe you can show them your intent by waving with the money so they believe you actually want to buy instead of just dreaming.
Quality instruments will not degrade that fast, infact, it needs some playtine to get ultra smooth. Besides, when you buy a guitar you will get a few sets of new string any way. So don't worry about string quality.
Comment: i agree with your first point, showing that you are serious by indicating that you have money to spend, rather than time to kill might get you some more leeway.  I Don't see any relevance at all in your last sentence.
Comment: The 2nd section is that I'm stating that having customers test a guitar isn't going to degrade the quality of the guitar at all.
Comment: ok, but that goes without saying, I still don't see any relevance in such an obvious statement.

Music Store Etiquette


Log-Log Regression - Dummy Variable and Index

Question: I have the following log-log regression equation (natural log was used):
<code>ln(Sales Index) = B0 + B1 * ln(advertising spend) + B2 * (January) .... + e
</code>
where advertising spend is a continuous variable (is never zero) and January is a dummy variable.  The Sales Index is never zero either.
I understand how to interpret the coefficient B1.  Where I am getting stuck is in interpreting coefficient B2 (when January = 1).  I've looked at the following questions for guidance:
Interpreting logarithmically transformed coefficients in linear regression
Interpretation of log transformed predictor
How to use index in a multiple regression
Is it correct to say that when January = 1, B2 = 0.4 and ln(Sales Index) = 0.35 then:
1)  firstly, you need to take exp(0.4) = 1.4918.
2)  this is then the multiplier of ln(Sales Index), so 1.4918 * 0.35 means that if it is January this leads to a 52.21% increase in the Sales Index (holding all other x variables constant)?
Answer: The interpretation of a dummy variable in a model with a logged dependent variable is in a sense asymmetric: it depends on whether you're turning January "on" (from 0 to 1) or turning January "off."
Let $Y$ be your sales index and $X$ your January dummy. I think it's fair to describe your model as the following (I'm going to follow convention and play it loose with subscripts). I'm omitting the advertising spend component because you've mentioned that you understand how to interpret that. We've got:
$$ \log{Y} = \alpha + \beta X + \epsilon $$
If we exponentiate both sides, this is
$$ Y = e^{\alpha + \epsilon} $$ when January is "off", and
$$ Y = e^{\alpha + \beta + \epsilon} $$ when January is "on"
Now if we want to compare the difference between two numbers, A and B, relative to B,  we calculate (A-B)/B, right? I say 15 is 50% larger than 10 because (15-10)/10 = 0.5; let's use this framework on the expressions above.
Difference going from January "off" to January "on" =
$$ \frac{e^{\alpha + \beta + \epsilon} - e^{\alpha + \epsilon}}{e^{\alpha + \epsilon}} = e^\beta - 1  $$
Difference going from January "on" to January "off" =
$$ \frac{e^{\alpha + \epsilon} - e^{\alpha +  \beta + \epsilon}}{e^{\alpha +  \beta + \epsilon}} = e^{-\beta} - 1  $$
Perhaps you see where this is going. Let's choose a value for $\beta$, say $0.3.$ Then going from off to on increases $Y$ by $e^{0.3} - 1= 0.35$, an increase of 35 percent. But going the other way decreases $Y$ by $-(e^{-0.3} - 1) = 0.26$, a decrease of 26 percent. Notably, neither of these matches your coefficient of 0.3!
And of course, this has all ignored the the error in estimating your regression parameters. That's fine if you're really interested in estimating changes not in $Y$, but in $\log{Y}$. It seems however that you care about $Y$ itself, and that invokes another problem: retransformation bias in log-linear models. That will bias your predictions of $Y$ downwards, and is independent of whether your independent variables are continuous or not, so I won't discuss that topic here.
Answer: When you include dummy variables for categories, you generally leave one dummy out so that the design matrix $X$ is not rank deficient. (This is an extremely important, somewhat abstract concept.)

Let's say you have dummies for Jan, Feb, ..., Nov, that is, you leave out the dummy for December.
The coefficient on Jan is then the effect of being in Jan relative to December.
Eg. if $b_2$ were .02, it would imply that sales are about 2% higher in January than December.

Changes in logs is conceptually similar to percent changes in levels.

Side note:
For $y_2$ near $y_1$, you have:
$$\log y_2 - \log y_1 \approx \frac{y_2 - y_1} {y_1}$$
That is, the log difference is close to the percent change (you can prove this using first order Taylor expand to linearize the log near 1). Eg. $\log(2.02) - \log(2) = .01$. As $y_2$ and $y_1$ get farther apart though, that approximation breaks down. Eg. $\log(1.4) - \log(1) = .3365$. 1.4 is 40% higher than 1, but the log difference is only .3365.
Answer: On way to interpret the coefficient with the dummy variable is as a variable intercept. Something similar is explained here: Confusion of "slope" and "intercept" in linear regression
If you back transform to a linear scale then the intercept plays a role as a multiplicative constant.
$$\ln(\text{Sales Index}) = B_0 + B_1 * \ln(\text{advertising spend}) + B_2  (January) + \dots + \epsilon$$
which is equivalent to
$$\text{Sales Index} = \text{advertising spend}^{B_1} * \ln(B_0 + B_2  (\text {January}) + \dots) + \epsilon^\prime$$
This term $\ln(B_0 + B_2  (\text {January}) + \dots)$ will be having different values for different months
$$ln(B_0 + B_2  (\text {January}) + \dots) = \begin{cases} \ln(B_0 + B_2) & \quad \text{if it is January} \\
\ln(B_0 + B_3) & \quad \text{if it is Febuary} \\
\ln(B_0 + B_4) & \quad \text{if it is March} \\
\ln(B_0 + B_5) & \quad \text{if it is April} \\
\dots\\
\ln(B_0 + B_{13}) & \quad \text{if it is December} \\
\end{cases}$$
Answer: Also worth having a look at "Halvorsen, R., & Palmquist, R. (1980). The interpretation of dummy variables in semilogarithmic equations. American economic review, 70(3), 474-475."


Incluir extremos no BETWEEN e Listar valores faltantes na consulta SQL

Question: Seguinte. Imagine que eu tenha no banco no campo de meses pagos os seguintes lançamentos: 2015-03, 2015-04, 2015-7, 2015-9.
Se estipulassemos um período por exemplo: de 2015-02 até hoje (2015-9). Quais são os meses que faltam, ou seja, quais meses ainda não foram pagos.
A query que apresento aqui traz os meses pagos DENTRO do período.
Mas o que eu preciso NÃO SÃO os meses pagos, mas SIM os MESES NÃO PAGOS e DENTRO do período. Ou seja, 2015-2, 2015-5, 2015-6, 2015-8.
 SELECT pagamentos.idPagamentos, pagamentos.mesReferencia FROM pagamentos, planosclientes
 WHERE
        pagamentos.idPlanoClientes = planosclientes.idPlanosClientes AND
        pagamentos.idPlanoClientes = 8 AND
        pagamentos.mesReferencia BETWEEN DATE_FORMAT(planosclientes.dataInstalacao, '%Y%-%m') AND DATE_FORMAT(CURRENT_DATE(), '%Y%-%m')
 ORDER BY pagamentos.mesReferencia

Como fazer nesse caso?
Comment: Carlos acho que não entendi direito o que precisa, você quer os extremos, não seria só usar os sinais de < e > em vez de between? porque creio eu que não tem extremo após o curdate() nessa dataInstalação, ou tem ?
Comment: Alterei a pergunta para ficar mais fácil a interpretação!
Answer: Uma possível solução é usar DATEADD, tirando um mês da dataInstalacao e adicionando um mês na CURRENT_DATE().
SELECT pagamentos.idPagamentos, pagamentos.mesReferencia
FROM pagamentos, planosclientes
WHERE pagamentos.idPlanoClientes = planosclientes.idPlanosClientes
   AND pagamentos.idPlanoClientes = 8
   AND pagamentos.mesReferencia
      BETWEEN FORMAT(DATEADD(mm,-1,planosclientes.dataInstalacao), 'yyyy-MM')
      AND FORMAT(DATEADD(mm,1,CURRENT_DATE()), 'yyyy-MM') ;

UPDATE 2
Função DATE_FORMAT e DATE_ADD (para MYSQL):
BETWEEN DATE_FORMAT(DATE_ADD(planosclientes.dataInstalacao, -1 INTEVAL MONTH), '%Y-%M')
    AND DATE_FORMAT(DATE_ADD(CURRENT_DATE, INTERVAL 1 MONTH), '%Y-%M')

No entanto, BETWEEN inclui os limites, ou seja, não seria necessário fazer nenhum ajuste de data.
Porém percebi que você está fazendo between entre varcharo que não dará certo.
Sendo assim, você deve fazer o CAST para dates dos valores a serem comparados e para isso o código ficaria assim:
AND CAST(CONCAT(pagamentos.mesReferencia, '01') as DATE)
   BETWEEN CAST(CONCAT(FORMAT(planosclientes.dataInstalacao), '%Y-%m'), '01') as DATE)
   AND CURRENT_DATE()

Comment: Esse mm, -1 esta dano erro: ...#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-1,planosclientes.dataInstalacao), '%Y%-%m') AND DATE_FORMAT(DATE_ADD(mm,1,CURRE' at line 5
Comment: No seu comentário o código está errado... Ajustei também a resposta.
`pagamentos.mesReferencia BETWEEN format(dateadd(mm,-1,dataInstalacao), 'yyyy-MM')
    AND format(dateadd(mm,1,GETDATE()), 'yyyy-MM')`
Comment: Mensagem do MySQL: Documentação

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-1,planosclientes.dataInstalacao), 'y-m') AND FORMAT(DATEA_DD(mm,1,CURRENT_DATE(' at line 5
Comment: atualizei a pergunta mostrando o erro que dá!
Comment: Carlos, cometi um engano... Agora que vi que você está usando MySQL. O código que coloquei na resposta é para SQL.
Em MySQL `BETWEEN` inclui os limites. Opcionalmente você pode usar os operadores `>=` e `<=`.
A função `DATE_ADD` do mysql usa a seguinte sintaxe (exemplo usando o seu código):
`DATE_ADD(planosclientes.dataInstalacao, INTERVAL 1 MONTH)`
Answer: Até onde entendi você quer < esses > <------Periodo------> < e esses> certo? vamos lá:
     SELECT pagamentos.idPagamentos, pagamentos.mesReferencia FROM pagamentos, planosclientes
 WHERE
        pagamentos.idPlanoClientes = planosclientes.idPlanosClientes AND
        pagamentos.idPlanoClientes = 8 AND
        pagamentos.mesReferencia < DATE_FORMAT(planosclientes.dataInstalacao, '%Y%-%m') AND
        pagamentos.mesReferencia > DATE_FORMAT(CURRENT_DATE(), '%Y%-%m')
 ORDER BY pagamentos.mesReferencia;

Ou seja os menores < que dataInstalacao e os maiores > que o curdate() (dia atual) assim teremos os chamados "extremos"
Comment: Não! Seguinte.Imagine que eu tenha no banco no campo de ***meses pagos*** os seguintes lançamentos: 2015-03, 2015-04, 2015-7, 2015-9. Se estipularmos um período por exemplo: de 2015-02 até hoje (2015-9). Quais são os meses que faltam, ou seja, quais meses ***ainda não foram pagos***. A ***query*** que apresentei no final da pergunta traz os meses pagos ***DENTRO*** do período. O que eu preciso são dos meses ***NÃO*** pagos e ***DENTRO*** do período. Ou seja, 2015-2, 2015-5, 2015-6, 2015-8. Melhorou?
Comment: Entendi, segunda faço uns testes de SQL então


Using generated image as link to be used in forums?

Question: I came across php image functions and I've successfully managed to create signature with php now after generating how to let users to use the generated image as link on their signatures or w/e?
 <?php
    $dest = imagecreatefromjpeg('test.jpg');
    $src = imagecreatefrompng('blade_02.png');

    imagealphablending($dest, false);
    imagesavealpha($dest, true);
    $black = imagecolorallocate($src, 0, 0, 0);
    imagecolortransparent($src, $black);
    imagecopymerge($dest, $src, 17, 13, 0, 0, 60, 0, 0);
    imagecopymerge($dest, $src, 168, 70, 0, 0, 60, 100, 100);
    $font_black = imagecolorallocate($dest, 2, 1, 8);
    imagestring($dest, 3,357,19, "118" , $font_black);

    header('Content-Type: image/png');
    imagepng($dest);

    imagedestroy($dest);
    imagedestroy($src);

    ?>

html

<IMG STYLE="position:absolute; TOP:163px; LEFT:512px;" SRC="<?php  echo $wep_icon; ?>" onmouseover="TagToTip('Span2')">
<?php echo $seal_type[0]; ?>

 <?php echo $seal_wep; ?>

<?php echo $Degree_wep; ?>

Comment: This question is too unclear. What exactly is your problem?
Answer: If you are saving the image to a file, simply give them the link to that file.
If you are saving the data used to generate the image in a DB, give them a link to the file that'll build the image, appending the query string on the end that you use to pull the data out of the database.
EDIT
From the code you have provided, you appear to create the image, and then destroy the files. Try this:
imagepng($dest, 'the_new_file.png');

This will save the file to the filesystem instead of just showing it to the screen
You can see more about imagepng and it's options here: http://php.net/manual/en/function.imagepng.php
Comment: Well how to save the image to a file then upon generating ?
Comment: Thanks now I've another question what If I'm using html to generate images is it possible to save it too ? I attached the code at the main post again I want to save the image including all the images written over it.
Comment: Sorry, I don't understand, HTML so save an image? Also that extra code you posted is a little pointless when it's just a few variables.
Comment: Actually it's not pointless since it retrieves some variables from database , view image and write those variables over it.So is it possible to save such image via html  ?
Comment: Yes, but you posted it out of context - so it's no help. And yes, I know html. You asked about saving an image with HTML, you can't. A *user* can save it when presented on the page, or *you* can save it with PHP. You need to be clearer with what you are asking me.
Comment: Well as my first question it's done already and now I'm asking my 2nd question after writing variables / putting images over it how it's possible to save the image including what was written over via php or html ?.If it's not possible with html then how to save it with php with all variables / images over it ? Thanks again for your time
Comment: It'd be better to create a new question rather than tagging it onto this one


How can I set an element's display to 'block' ? (more below)

Question: I added a event listener to a button, which would change the css of the #popUpForm, but it only works, if I add inline css to the #popUpForm. How could I do it, If i want to set the display of the element in the css?

const addBtn = document.querySelector('#addItem')

addBtn.addEventListener('click', function() {
  document.querySelector('#popUpForm').style.display = 'block'
})
#popUpForm {
  width: 350px;
  height: 500px;
  display: none; /* change this */
}
<input id="addItem" type="button" value="+">

  Some stuff

Comment: Your code works. I made a snippet and it works as expected
Answer: Your code works, but I would still recommend a class

const addBtn = document.querySelector('#addItem')

addBtn.addEventListener('click', function() {
  document.querySelector('#popUpForm').classList.toggle("hide"); // or classList.remove("hide")
})
#popUpForm {
  width: 350px;
  height: 500px;
}

.hide {
  display: none;
}
<input id="addItem" type="button" value="+">

  Here is some stuff

Answer: You can use jQuery show/hide methods:
$('#popUpForm').hide();
$('#popUpForm').show();

Or using VanilaJs:
const hide = (elem) => {
   elem.style.display = 'none';
 }

const show = (elem) => {
    elem.style.display = 'block';
}

 // usage
 // hide element

 hide(document.querySelector('#popUpForm'));

// show element

show(document.querySelector('#popUpForm'));


Is it legal to throw an alley-oop to yourself in a real game?

Question: In this video, a college basketball player steals the ball, races down court, and avoids the defender by throwing a pass to himself off the backboard.
http://www.youtube.com/watch?feature=player_embedded&v=jtfNegUxAcY
In all the (disorganized) basketball games I've played in, a shot had to hit the rim before the shooter was allowed to rebound. And that looks like a shot to me.
Obviously the officials allowed it, but I couldn't find an explicit mention in the NCAA Rulebook. Is this ruled as a shot, and if so, why is it legal? I'd be interested in the answer for any level of basketball, though NCAA is the most relevant.
Comment: I know this sounds cynical, but a lot of rules get relaxed if they make for more viewers. Advertisers love plays that get people on their feet.
Comment: I guess the video became private. It says: "This video is unavailable".
Comment: Broken link to the video :/
Comment: @Michael Myers Could you please add another video as the linked video is unavailable.
Comment: Found an e-book that includes this question. https://books.google.com/books?id=lENPDwAAQBAJ
Comment: @user257138: As long as the e-book includes links to the original Sports.SE source and authors, that's legal under the CC BY-SA license.
Answer: For the NCAA, it is scored as follows (from page 10 of the 2011 Official Basketball
Statisticians' Manual):

A.R.15. Adams throws a pass to himself or herself off the backboard, and then shoots and makes the basket. Ruling: Credit Adams with a FGA and FGM, but no assist
  or rebound.

For the NBA, according to this Q&A (from 2009) with Bernie Fryer (Vice President of Referee Operations and Director of Officials in the NBA), it is also allowed:

Are you allowed to throw the ball off the backboard, grab your own rebound and dunk it without landing?
  -- Blaise
  Bernie's answer: Yes. Under the traveling rule, a player who attempts a shot or pass may not be the first to touch the ball unless it touches the backboard, rim or another player. Therefore, a player can intentionally pass the ball to himself off the backboard or rim.

Actually, a week or so ago Kobe Bryant was double teamed near the 3-point line, had no one to pass to and had already picked up his dribble. He was about to fall down, which would have been traveling, instead he alertly threw the ball off the backboard, caught it and dribbled back to the top of the key. This wasn't an alley-oop but was similar. Michael Jordan was famous for doing the same thing on occasion.
Answer: It is legal to throw the ball off the backboard as a pass to yourself.  The only time it is illegal is when attempting a free throw.  While attempting a free throw the ball must hit the rim as well.
For reference, see Section III - Dribble of NBA Rule 10.
Answer: It is definitely legal in the NBA. I'm not sure about the NCAA.
source: YouTube video of Kobe Bryant
Comment: For what it's worth, video of it happening and not being called doesn't prove it is allowed within the rules; it simply shows that in this anecdotal case it wasn't called.
Answer: In FIBA games, deliberately throwing the ball on the backboard without attempting a shot is equivalent to the player bouncing the ball on the floor.
It is then allowed only if you hadn't dribbled yet, in which case, you can dribble no more after you catch the ball again, but you can only pass or shoot. In all other circumstances (for example if you had already dribbled, or if you start dribbling after catching the ball) is a double dribble violation.
See art. 24 of FIBA's "Offical Basketball Rules 2017 - Official Interpretations - valid as of 1st February 2018".

Art. 24 Dribbling
24-1 Statement. If a player deliberately throws the
  ball against a backboard (not attempting a legitimate shot for a field
  goal) this is considered as if the player has bounced the ball on the
  floor. If the player then touches the ball again before it has touched
  (or been touched by) another player, this is considered as a dribble.
24-2 Example: A1 has not yet dribbled when A1 throws the ball against
  the backboard and catches it again before another player has touched
  the ball.
Interpretation: After catching the ball A1 may shoot or pass
  but may not begin a new dribble.
24-3 Example: After ending a dribble
  either in the continuous motion or standing still, A1 throws the ball
  against the backboard and catches or touches it again before it has
  touched another player.
Interpretation: A1 has committed a double dribble violation.
Comment: Actually that changed in the rules of 2018 and it is now legal also in FIBA
Answer: While you can catch your own air ball, it must be an attempted shot, and not an attempt to pass to yourself. Generally it's clear what the player was attempting to do. When it's not clear, it's up to the referee's judgement what the player's intent was. I am a certified official in high school and college.
Comment: Welcome to Sports SE! As a certified official, is there a standardized set of rules that you adhere to, or is it dependent on the league(s) you officiate in?
Comment: Please provide relevant links to support your answer.
Comment: I don't understand why this is downvoted... it's the correct answer according to NFHS.
Comment: @JeffWidman It's was downvoted due to [lack of evidence](https://sports.meta.stackexchange.com/a/899).


Adding ThirdPartySetting to webform entity results in wrong module dependency

Question: I added my ThirdPartySetting to webform element like this:
Added my config schema to file config/schema/mymodule.schema.yml like this:
webform.settings.third_party.mymodule:
  type: mapping
  label: 'Webform mymodule configuration'
  mapping:
    settings:
      type: mapping
      label: 'mymodule settings'
      mapping:
        email_element:
          type: string
          label: 'E-mail element'

and then in mymodule.module I've altered webform settings form like this:
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id === 'webform_settings_form') {
    $entity = $form_state->getFormObject()->getEntity();
    $elements = $entity->getElementsInitializedAndFlattened();
    $options = [];
    foreach ($elements as $element_name => $element) {
      $options[$element_name] = $element['#title'];
    }
    $form['third_party_settings']['email_element'] = [
      '#type' => 'details',
      '#title' => t('E-mail element'),
      '#open' => TRUE,
    ];
    $form['third_party_settings']['email_element']['email_element'] = [
      '#type' => 'select',
      '#options' => $options,
      '#title' => t('E-mail element'),
      '#default_value' => $entity->getThirdPartySetting('mymodule', 'email_element'),
    ];
    $form['actions']['submit']['#submit'][] = '_mymodule_form_submit';
  }
}

function _mymodule_form_submit(&$form, FormStateInterface $form_state) {
  /** @var \Drupal\webform\WebformInterface $entity */
  if ($entity = $form_state->getFormObject()->getEntity()) {
    $entity->setThirdPartySetting('mymodule', 'email_element', $form_state->getValue(['third_party_settings','email_element','email_element']));
    $entity->save();
  }
}

This works fine, but when I export my configuration, I see that dummy module has been added to my module dependencies.
 dependencies:
   module:
+    - mymodule
+    - email_element

This also reflects in third_party_settings
+third_party_settings:
+  email_element:
+    email_element: e_mail
+  mymodule:
+    email_element: e_mail

What am I doing wrong?
Answer: Please use hook_webform_third_party_settings_form_alter() in mymodule.module and discard the submit handler which should solve that:
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_webform_third_party_settings_form_alter().
 */
function mymodule_webform_third_party_settings_form_alter(&$form, FormStateInterface $form_state) {

  /** @var \Drupal\webform\WebformInterface $webform */
  $webform = $form_state->getFormObject()->getEntity();

  // Do stuff.

  $form['third_party_settings']['email_element'] = [
    '#type' => 'select',
    '#options' => $options,
    '#title' => t('E-mail element'),
    '#default_value' => $webform->getThirdPartySetting('mymodule', 'email_element'),
  ];

  // Do not add submit handler.
}

Webform's WebformThirdPartySettingsManagerInterface wraps Core's ThirdPartySettingsInterface which is why I think you're seeing that behaviour.
Comment: Unfortunately, this doesn't work for me. Adding select element like this leads to warning: `Warning: Invalid argument supplied for foreach() in Drupal\webform\EntitySettings\WebformEntitySettingsGeneralForm->save() (line 549 of modules/contrib/webform/src/EntitySettings/WebformEntitySettingsGeneralForm.php).` If I wrap it in details element, there's no error, but the settings isn't saved. I also tried to use `\Drupal::service('webform.third_party_settings_manager');` as used in `honeypot_webform_third_party_settings_form_alter()`, but that didn't help.
Answer: Answer from @baikho is almost correct. In the end this worked for me:
function mymodule_webform_third_party_settings_form_alter(&$form, FormStateInterface $form_state) {

  /** @var \Drupal\webform\WebformInterface $webform */
  $webform = $form_state->getFormObject()->getEntity();
  $elements = $webform->getElementsInitializedAndFlattened();
  $options = [];
  foreach ($elements as $element_name => $element) {
    $options[$element_name] = $element['#title'];
  }

  $form['third_party_settings']['mymodule'] = [
    '#type' => 'details',
    '#title' => t('My module'),
    '#open' => TRUE,
  ];

  $form['third_party_settings']['mymodule']['email_element'] = [
    '#type' => 'select',
    '#options' => $options,
    '#title' => t('E-mail element'),
    '#default_value' => $webform->getThirdPartySetting('mymodule', 'email_element'),
  ];
}

And warning for anyone finding this in the future - if you do it wrong like I did, just download your database from another environment and start again, otherwise you might end up pulling your hair.


Manipulate variables in Python

Question: Is it possible to manipulate a variable, for example:
file = "/Python/work.txt"
to just list work.txt, without /Python? excluding everything on the left of the "/"?
Thank you
Comment: BTW, that's not valid Python syntax: you forgot the quotes.
Comment: Since you're using Python 3, I recommend that you become familiar with the awesome [`pathlib`](https://docs.python.org/3/library/pathlib.html) module, which is very handy for all sorts of path manipulation tasks.
Answer: Of course! Simply do this:
file = "/Python/work.txt"
excluded = file.split("/")[-1]

This would return "work.txt" in the excluded variable.
Comment: No. Use the `os` module. The code won't be portable if you hardcode the separator.
Comment: It's a good idea to do a search for duplicates when you see a question that's probably been asked before.
Comment: @timgeb `os` is old-school. All the cool kids use `pathlib`. ;)

Manipulate variables in Python


What are the list of OS that have Python preinstalled and which versions?

Question: As I am moving from C# to Python, I was wondering if there is a list of the pre-installed versions of Python on different Operating Systems like Windows, Linux, etc...
Comment: This question doesn't really make sense.

"Linux" isn't an operating system, in the sense you're talking about. The hundreds of different distros all have different preinstalled software. Almost all have Python, but they all have different versions.

Even with a coherent single OS, like Mac OS X, each different version comes with a different version of Python pre-installed (e.g., Panther had 2.4; Lion has 2.5, 2.6, and 2.7).

And even "Python" isn't just a single thing. Windows doesn't come with C Python, but I believe you can run IronPython scripts.
Comment: @abarnert IronPython isn't available by default, and you can install CPython.
Comment: @Marcin: Of course you can install CPython. Meanwhile, I thought the IronPython runtime came with .NET 3 and later, just no interactive interpreter (and no Visual Studio integration) unless you install it. But it doesn't really matter.
Answer: There is no such list. However, I think you can safely assume every generic, modern Linux distro will have Python installed (every recent (>2years) with Python 2.5 at least), as well as most Unix SOs (FreeBSD, Solaris etc.). Mac OS X also comes with Python. OTOH you cannot expect it from most Window machines - just a few have Python by default. This usually is no problem, however, because Python is fairly easy to install and, in the end, you can rely on things such as py2exe and cx_freeze.
This is, of course, a rule of thumb, not a really precise answer. Nonetheless, I find that those assumptions make sense enough.
Comment: Thanks a lot. I also heard that python 2.7 is in newer versions of UNIX, also do you know if a newer version of python is installed and the program runs an older version does the user must have older version of Python too?
Comment: @MohamedTarek absolutely most of the time, it is no problem. A program written to e.g. Python 2.5 will run flawlessly in a Python 2.7 interpreter. AFAIK the 2.x series is backward compatible but even if you find some little problems, they will be restricted and localized. I, for one, never found such a problem. OTOH, if the machine just has a Python 3.x interpreter (which is very improbable, since Python 3 is not widely used yet) then it will not run Python 2.x programs.


How can I enforce maintenance_mode at all times in a specific environment?

Question: In Drupal 7, we could override the $conf variables in settings.php to force a site (e.g. development) in maintenance mode. In Drupal 8, this has changed to $config, but the maintenance mode variable is not part of the configuration anymore. How can I force system.maintenance_mode in a specific environment's configuration?
Comment: It's in state now, normally you'd set that with `\Drupal::state()->set('system.maintenance_mode', TRUE);` but there doesn't seem to be a direct way to override state from settings.php
Comment: Thanks. Indeed that call doesn't work from within settings.php
Comment: Yeah the service container hasn't been initialised by that point so services aren't available :/
Comment: Is there an alternative way of doing this?
Comment: There are any number of hacks (e.g. stuff a var into config, read it back in an early page build hook, set state var based on it) but I don't know what the right way to do it is, "right way" as in plays nicely with cache, doesn't cause problems with random unknown stuff being inside config, etc
Answer: I think you might want to take a different approach.
The maintenance mode is now a state in Drupal 8, not a configuration. The difference is a state is a ephemeral state that's specific to the current environment (see the state API docs for more info).
As such, you might want to replace the State service with your own service class that uses the StateInterface interface if you're looking to fundamentally alter the way state behavior (which could lead to unforeseen problems).
Another tact might involve some sort one-time toggling of state (e.g. programmatically as shown above, a drush state-set / drupal state:override) based on some event (e.g. deployment of site).
Comment: Thanks for the suggestions. A one time toggle during deployment is an alternative but it does not enforce maintenance mode at all times... for instance someone with proper privileges could turn off maintenance mode in the interface. As Shawn Conn mentions, replacing the State service seems a bit risky. I've updated the question title to better reflect what I'm trying to achieve.


Zend Framework, PHPUnit and transactions

Question: i want to use PHP Unit inside a Zend Framework application. I need to make several database writing operations inside the tests.
I want to start an MySQL transaction in the setUpBeforeClass() method. That is possible, but if I try to rollback the transaction in the tearDownAfterClass() method he throws an exception with the message 'There is no active transaction'. And the test methods does the writing operations in the database.
But if i start the transaction in the test method itselfs. It works like I want.
I don't understand why it reacts like this. Knows anyone an explanation?
<?php

class ConferenceControllerTest
extends PHPUnit_Framework_TestCase
{

    /**
     * A database connection.
     * @var Zend_Db_Adapter_Pdo_Mysql
     */
    protected static $hostDb = null;

    public static function setUpBeforeClass()
    {
        static::$hostDb = Zend_Registry::get('db_host');
        static::$hostDb->beginTransaction();
        // The transaction for the Adapter is activated. But not inside the tests anymore.
    }

    public function testTest1()
    {
        // At this position teh transaction is not setted anymor? Why?
        static::$hostDb->beginTransaction();

        $sql = 'INSERT INTO test(test) VALUES(5);';
        static::$hostDb->exec($sql);
    }

    public static function tearDownAfterClass()
    {
        try
        {
            static::$hostDb->rollBack();
        }
        catch(Exception $exception)
        {
            $message = $exception->getMessage();
            Zend_Debug::dump($message);
        }
    }

}

Answer: I think you may be running into phpUnit's feature to backup statics and other globals between each unit test, see the "globals" section of the Fixtures chapter of the manual
The quick-hack fix would be to add this line, in the comments just above your class:
  * @backupStaticAttributes disabled
That still leaves you with the xUnit Patterns book would call a nasty smell. I'm assuming you have a few testXXX functions that you expect to run in a certain order, each depending on the result of the previous one? That requires using @depends on each function, and it is easy to get wrong.
The alternative approach is a single long unit test function, and put the DB code in setUp() and tearDown():
public function setUp()
{
    $this->db = Zend_Registry::get('db_host');
    $this->db->beginTransaction();
}

public function tearDown()
{
    try
    {
        $this->db->rollBack();
    }
    catch(Exception $exception)
    {
        $message = $exception->getMessage();
        Zend_Debug::dump($message);
    }

public function testTestVariousDBActions()
{
    $sql = 'INSERT INTO test(test) VALUES(5);';
    $this->db->exec($sql);

    //another DB action
    $this->assertEquals(...)

    //another DB action
    $this->assertEquals(...)

    //...
}

The advantage of this is that if any assert fails none of the subsequent ones will be attempted. But tearDown() will always be called so the database is restored.
The disadvantage could be you get a Very Long Function. Use refactoring to deal with this (e.g. if you really want each action and its test in its own function, refactor so it looks like that and have testTestVariousDBActions() call each of them in turn).


Generalization of Buffons 'noodle'

Question: I had read an interesting paper a few years back on Buffons 'noodle' (https://doi.org/10.2307/2317945) and when attempting a problem recently I thought I could use it as a tool.
I have provided a short summary of the background information in the first header which can be skipped if you are already aware of the problem.
Buffon's needle & noodle
Needle
The theorem developed in the paper is a substantial generalization of the famous Buffons needle problem that says given a grid of parallel lines separated by a common distance $d$ the probability that a uniformly 'randomly' thrown 'needle' of length $l\leq a$ will intersect of the lines is $$P=\frac{2l}{\pi d}$$.
'Randomly' is only in quotations since the original problem refers to a infinite grid and a uniform random distribution over R^2 doesn't make much sense, so for the problem's sake often only a small finite grid is considered WLOG.
The noodle
Ramaley derives a theorem that generalized the above fact by proving that the expected number of a 'squiggly noodle' of length $l$ (this time not constrained) on the same parallel grid with distances $d$ is $$E=\frac{2l}{\pi d}$$.
'Squiggly noodle' here can be mathematically understood as any rectifiable curve which can be approximated uniformly by a sequence of line segments.
My question
How can we extend this notion of Ramaley's noodles to a rectangular grid of length $a$ and $b$ or maybe even further for any tiling pattern?
I would greatly appreciate some hints on how I can approach solving this as I wanted to work on it as a mini project for some research experience.
 Motivation (not strictly relevant to the problem)
I was inspired to try and prove this myself for the rectangular case as it was very similar to a problem I was trying to solve which involved a convex shape being thrown 'randomly' on a grid. (Note this is basically identical to the theorem of Gnedenko which Ramaley references in the paper but with a grid instead of the parallel lines they used).
My conjecture was that due to the startling similarity of Ramaleys generalization, the rectangular grid problem would also have a similar structure to the rectangular grid version of Buffon's needle (which has been solved sometimes referred to as the Laplace extension of Buffon's needle).
The Laplace problem says that for a rectangular grid of length $a$, breadth $b$ and 'needle' of length $l \leq \min\{a,b\}$ the probability the needle intersects with the grid is
$$P(A \text{ or }B)=P(A)+P(B) - P(A \cap B)=\frac{2l(a+b)-l^2}{\pi ab}$$
Where events $A$ and $B$ can be interpreted as the event in which the needle intersects the parallel lines separated at distance $a,b$ respectively.
I had thought maybe the Expected value for line crossings would simply be in the same structure for the 'noodle'.I thought to check with Monte Carlo simulations before attempting to 'prove' it and the formula doesn't appear to hold and seems to undercount.
Comment: Yes, E(A) +E(B) is the mean intersection count. For the other question, it helps to know what a Minkowsky sum is (maybe I'll expand in an answer) . Btw, does this question relate to your recent question about Poisson distribution? It sounds like you are working on a stochastic geometry project :-)
Comment: Ah, this (the noodle) is a well known identity and used in stereology to estimate the length of the noodles :-) I don't have time right now, but as long as the noodle has random orientation (uniform random rotation), it does not matter for the expected number of intersections if you use a rectangular grid, it only matters for the variance of the number of intersections. You can just sum the two expectations from the horizontal and the vertical grid. I'll come back at some later point.
Comment: Do you want the mean number of intersection points (can be many, and is easy), or are you after counting "intersect or not" (more tedious)?
Comment: I think mean number of intersection points would just be E(A)+E(B) right? In the question I was really just looking to verify a formula for that exactly. But since then I've just been toying around with this setup too. It would be interesting to determine probability of "intersect or not" too. Do you have any ideas for counting that?
Comment: Well I've heard of a minkowsky sum, but just the basic definition and saw it in a few analysis problems nothing very deep. Thanks for you help with that other problem it was so tough to find a reference. They aren't related however just happens to be I'm stumbling across some probability after a long time. For this question in particular the problem I was trying to solve is basically exactly the same one Gndecko did in that reference but just for the 2d grid case. I left it a bit vague cuz i wanted to try to fill in the details. But now it seems like it's quite complicated.
Comment: Oh i just read your second comment with the hint i will try and approach it with that when i have some free time between school applications. Thanks again you've been really helpful.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/147596/discussion-between-ute-and-bhoris-dhanjal).
Answer: Here is an example of a simulation with the dimensions of the grid being $a=b=1$ and the lines being of size $l=0.6$.
I made the simulation by generating lines based on uniformly distributed starting points and uniformly distributed directions.
A potential analytical computation may use the same approach and integrate $$\int_0^a\int_0^b f(x,y) \, dx \, dy $$ where $f(x,y)$ is the probability that a certain starting point generates a line withing the $a$ by $b$ rectangle. For the grid of parallel lines this can be computed, but for the rectangular grid this seems more difficult.

I chose the parameters in the above simulation to show the interesting pattern where the highest density is neither at the center, nor the edge. Depending on the length of the needles, this can change a lot. Long needles with size $\approx 1$ will only not cross the gridlines when they start near the edge (from the middle they will cross the boundary gridlines whatever the direction), short needles with size $l \ll 1$ will always be inside the box when they are at the center, but not when they are at the edges. The size $l=0.6$ is a situation in between both cases.
I guess that an analytical approach will need to consider multiple ranges and add them up. It is not gonna be a simple formula.
Comment: What you simulated is the Laplace extension to Buffons needle. That already has an exact solution I've mentioned it in the question. Here's a reference https://www.maa.org/programs/faculty-and-departments/classroom-capsules-and-notes/on-laplaces-extension-of-the-buffon-needle-problem
Comment: Ah, I missed that part. That solution seems simple and takes the sum of probabilities of crossing either vertical/horizontal line minus the probability of crossing both (although adjustments need to be made for l>a and l>b). Now I am not sure what the question is, how does this Laplace extension not answer your problem?
Comment: Cause that's for the straight needle case. I was trying to solve it for the wiggly noodle (i.e. uniformly approximatef rectifiable curve) case. I think i can use that to solve the problem for any arbitrary convex shape thrown onto a grid.
Comment: @BhorisDhanjal the expectation for the expected number of times that a wiggly noodle crosses a line is just the same as the sum of the expectations that it's individual needles cross a line. (There might be details like considerations about what to do when a needle crosses multiple lines, but basically it is just multiplying the expectation for a single needle).
Comment: Yea that's what I thought too but my code didn't match up. Maybe I should try it again could have been a mistake in the program. I don't really see any reason why the proof for grid modified in the same way as Ramaley's shouldn't work.
Comment: @BhorisDhanjal maybe it is in the details that I shortly mentioned. Could you express more precisely what expectation value you are estimating with your code. You mention 'the expected number', but what is that exactly? If you regard the expected value of line crossings then, depending on the interpretation you should use: $$P(A)+P(B)$$ instead of $$P(A)+P(B) - P(A \cap B)$$ The latter counts multiple line crossings by the same needle segment of the noodle, as a single line crossing.

Generalization of Buffons 'noodle'


Distinguishing between what makes up R-squared

Question: I am interested in the relationship between religiosity and religious distrust (would you dislike having as neighbours people of different religions).
One of my main goals is to make the role of each individual religion insignificant; according to my argument monotheism leads to distrust, regardless of the particular religion. However, religions explain about 53% of my variation in religious distrust according to the R-squared.
I wanted to include variables that would 'take away'  from this influence of religion in terms of explanatory variable. For example, economic inequality in most Muslim countries might be a reason for differences in distrust, or the number of times people pray, which is less in Protestant countries. So I added as independent variables: Economic inequality, urbanization, separation church/state, number of times people pray, and education. When I include these in a model without religion I get an R-squared of about 37%.
When I include all these independent variables + religion, religion becomes significant again, I think because religion incorporates much more explanation than either single one of my other independent variables. My R-squared in this model is, again, 53.
My question is, is there any way to support the claim that although religion might matter, my independent variables 'take away'  at least some of its explanatory value?
So:

religion alone explain 53%;
my independent variables explain 37% alone;
together they explain 53% again

Could I say that of the 53% religion used to explain, 37% / 53% is now explained by my other independent variables? So in a sense, I took away about 2/3 of the explanatory value of religion by introducing other variables? Or is this not statistically valid, because they might for example explain different parts of the variation in my dependent variable?
Answer: I assume you are doing some sort of a linear regression since you're using R-squared? Keep in mind that the order in which variables are added to your model might make a difference. Particularly if any of your variables are correlated and/or collinear (the latter you can test by calculating the Variance Inflation Factor (VIF)). Ideally you'd want to include explanatory variables that are independent.
However, if you want to keep all your explanatory variables, an idea would be to try models with the variables added in different orders, and then look at your ANOVA table, as well as the significance of your coefficients.
Maybe you can share the type of model and type of data that you're using as it will probably help in answering your question.
Comment: Thanks! My model is indeed linear. My variables are all numerical, except for religion which is categorical ( Sunni, Shia.. etc) . I have checked for multicollinearity and the only variables that really correlate are education and how many times people pray (inversely) , which makes sense, as modern countries tend to have better education and are less religious. I have found the 'relaimpo'  package which tells me this: Relative Importance Metrics
Religion  0.30024710; urbanization 0.06477207 ; Separation C/S       0.10016121; Pray; 0.10701489; Education 0.04267369
Inequality  0.03112785
Comment: My regular R-squared ( not adjusted) is 64%, so from this I read that about half of that is explained by religion, and the rest by my other independent variables
Comment: What method did you apply to check for multicollinearity? Because it is strange that your R^2 does not increase when you add more explanatory variables. That in itself points to collinearity.
Comment: Other options are to examine the partial R^2 for your different explanatory variables, or compare the RMSEs from your different models (the latter is more to try and better understand how well your model fits, beyond just R^2)
Comment: Oh, and yeah, I do like the `relaimpo` package myself too. What does it tell you for the model without religion?
Comment: Okay, I will look into that! Without religion:
Urabanization 0.08315505
Separation       0.15078493
Pray        0.12375250
Education  0.05474003
Economic Inequality    0.05860660
.. For R^2 of 49%

Why would I perform relaimpo for both models? Thanks again @Geraldine
Comment: Well I couldn' t include religion in my multicollinearity because it is categorical ( or I didnt figure that out rather) But the other variables are not correlated.. I used  a cor(mydataframe)


NSJSONSerialization crashing app

Question: I have a dictionary that when I log it shows...
{
    Date = "2013-04-30 17:17:18 +0000";
    Description = Kb;
    EventID = "92193e58-c04a-4233-9a6c-1332bc056b20";
    Title = Keyboard;
}

I'm trying to turn it into NSData for a JSON web service like this...
- (NSData *)JSONRepresentation
{
    NSDictionary *dictionary = [self dictionaryObject];

    NSError *jsonError;

    NSData *JSONData = [NSJSONSerialization dataWithJSONObject:dictionary
                                                       options:0
                                                         error:&jsonError];  //This is where the error occurs.

    return JSONData;
}

But every time I run it the app just crashes.
The dictionary is formed properly, the app just crashes at this line.
In AppCode I get the crash report...
EXC_BREAKPOINT (code=EXC_ARM_BREAKPOINT, subcode=0xdefe))

In Xcode the app just stops and if I try to continue it stops with an error...
EXC_BAD_ACCESS (code=1, address=0x0)

Comment: NSDate will break it. Other values should be OK. Here is the list from the docs: `All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.`
Comment: Can you provide a bit more context, e.g. the surrounding lines?  Where is `jsonError` declared?
Comment: Where does the debugger show it blowing up?
Comment: On the line `NSData *JSONData = [NSJSON....`. It stops at that line. In the debugger after the crash I printed out the dictionary so the dictionary is definitely correct.
Comment: Added the entire function.
Comment: NSLog "dictionary" just before the call.
Comment: Does this project use ARC or not?
Comment: @HotLicks That's what I have done. It is printed in the question.
Comment: @Jim yes it uses ARC.
Comment: Are your keys NSString instances? If not this will probably not work.
Comment: @sosborn They are NSString and NSDate instances. Does the NSDate break it? Shouldn't that just display the error in the jsonError? Will try changing it to NSString now.
Comment: D'oh! Thanks, I have changed it now... and it works! Thanks very much! Not sure why it doesn't just populate the NSError that is passed in though?! Stick it as an answer and I'll accept it :)
Comment: Thanks. By the way I know this because I got burned by it last night :)
Answer: Your keys are invalid objects for converting to JSON. From the docs:

An object that may be converted to JSON must have the following
  properties:
The top level object is an NSArray or NSDictionary. All objects are
  instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull. All
  dictionary keys are instances of NSString. Numbers are not NaN or
  infinity.
Comment: Thanks very much. The NSDate object was causing the crash.
Comment: Great. I had a swift enum that I forgot to pass as a string rawValue which caused this crash for me.
Answer: check before, if the dictionary is invalid to convert, return.:
if (![NSJSONSerialization isValidJSONObject:dictionary]) { return; }

NSJSONSerialization crashing app


What is a "Naturstimme?"

Question: At a recent audition, the conductor of the choral ensemble said that my voice had a Naturstimme-like quality. (The conductor is, of course, German.) However, I can't seem to find a good definition of what exactly constitutes a Naturstimme?
Is this a good thing, or is it a sign that my voice needs a lot of extra work?
Answer: In this context, "Naturstimme" means "untrained voice". It's neither a compliment nor a detraction.
I believe that he is pointing out that you do not sound like a classically-trained singer who learns to sing in the operatic manner. Whether he would prefer a "Naturstimme" or a "Kunstgesangstimme" (an "art-song-trained" voice) for his choir is another matter.
There is a vocal technique forum discussion on this very subject that I read in looking for this answer. The entire forum and the discussion are in German.
Was heißt "Naturstimme"?

What is a "Naturstimme?"


JS not working in FireFox but works in Chrome & I.E

Question: I know there are question like this but I still can't find a fix, I've looked through the console and can't see anything. There are two images, one which should appear on set coordinates, and another which follows the mouse, the one which is mean't to follow the mouse does not show up but the other one does.
Main.js
/**
* Created with JetBrains WebStorm.
* User: Script47
* Date: 22/09/13
* Time: 00:54
*/

function drawAvatars() {

// Create variable for the canvas & create a new object for image
var gameCanvas = document.getElementById("gameCanvas");
var userImage = new Image();

// The source of the images
userImage.src = ("Images/userImage.png");

// Create an event listener then call function redrawAvatar
gameCanvas.addEventListener("mousemove", redrawAvatar);
}

function redrawAvatar(mouseEvent) {

var gameCanvas = document.getElementById("gameCanvas");
var userImage = new Image();
var enemyImage = new Image();
var score = 0;

userImage.src = ("Images/userImage.png");
enemyImage.src = ("Images/enemyImage.png");

// Erase canvas sort of refresh, then re-draw image following the coordinates of the mouse in the canvas
gameCanvas.width = 400;
gameCanvas.getContext("2d").drawImage(userImage, mouseEvent.offsetX, mouseEvent.offsetY);
gameCanvas.getContext("2d").drawImage(enemyImage, 150, 150);

// Simple hit detection to see if user image hits enemy image
if (mouseEvent.offsetX > 130 && mouseEvent.offsetX < 175 && mouseEvent.offsetY > 130 && mouseEvent.offsetY < 175) {
    score++;
    alert("You hit the enemy!\n You score is: " +score);
}
}

Index.html
<!DOCTYPE html>

<title>Avoid Me | Game</title>
<link rel="stylesheet" type="text/css" href="CSS/styles.css">

Avoid Me!

<canvas id="gameCanvas" height="300" width="400" onclick="drawAvatars();">

Notice: Browser does not support canvas!

</canvas>

JsFiddle
Comment: a fiddle would indeed help a lot
Comment: a Fiddle will be more than enough..
Comment: Open FireFox then go to this URL: http://script47.tk/temp/Avoid%20Me!/
Comment: It doesn't really work for me in Chrome either :-) Can you check it?
Comment: @kobigurk, This is the error I get in Chrome: Uncaught TypeError: Property 'src' of object # is not a function
Comment: Use enemyImage.src = "Images/enemyImage.png"; instead of

enemyImage.src("Images/enemyImage.png");

For firefox, use pageX, and pageY, offset positions will work for chrome not for firefox (in this case)
Answer: (Basing this off the code in the link you provided.)
In your mouseMovement function, you use mouseEvent.offsetX and mouseEvent.offsetY to get the player's position, but Firefox unfortunately doesn't support those properties. Unfortunately, IIRC, the only thing that works cross-browser is to get the position of the canvas, and subtract it from the event's pageX/pageY properties. You can use the canvas's getBoundingClientRect() method to find its position on the page.
This is is an example of a version of the function that should work in Firefox as well:
function mouseMovement(mouseEvent) {
    var canvasPosition = gameCanvas.getBoundingClientRect();

    userImageX = mouseEvent.pageX - canvasPosition.left;
    userImageY = mouseEvent.pageY - canvasPosition.top;
}


When providing default settings for elements in a field widget, what is the syntax for multiple value checkboxes?

Question: I have a field widget with three different settings, two of them are just string values but the third is multiple checkboxes.
This page describes how to set default settings, simple enough for integer or string and single value fields, but I'm not sure how to set default values for some of the checkboxes in the multiple checkbox element.
Below is the function where i need to set some of the values in the multiple checkboxes element to true. I can just put 'checkboxes_element' => '', as a default value which makes them all unticked, but i need to set some of those checkboxes as true for the default value.
<code>/**
 * {@inheritdoc}
 */
 public static function defaultSettings() {
  return [
    // Create the custom setting 'size', and
    // assign a default value of 60
    'size' => 60,
  ] + parent::defaultSettings();
}
</code>
Comment: It's simply an array of the keys which correspond to the checkboxes you want to be checked
Comment: Thank you Clive, I was overthinking this when I couldnt find examples, works perfectly :)
Answer: Thanks to Clive, much easier than I was expecting, the default settings function should just look like the following, replacing the options in the array with the relevant keys:
<code> public static function defaultSettings() {
    return [
      'checkboxes_options' => array('option1', 'option5', 'option9'),
    ] + parent::defaultSettings();
  }
</code>


Why are substitutions commonly made right at the end of the game?

Question: I often see the manager of a winning team making substitutions as the end of  the game nears (sometimes as late as during injury time).
The player being replaced is not injured, and doesn't time get added on to make up for the time lost for the substitution to take place?
So, what are the tactics behind this? Is it related to giving the player another cap? (perhaps pay related for an appearance?) Is it a mind-game to try and break up a run of play which may have been in the opponents favour?
Comment: @you786 Not to disagree with you but I just want to point out that in football the situation is quite different in the sense that, the time is really little to do anything meaningful for a youngster. In basketball really short time could actually have a lot of meaning as clock stops very often. That's not the case in football, especially not in the injury time.
Comment: In basketball, coaches put in bench players in 'garbage time' to a) teach them to play under real game conditions b) let them try to impress the coach c) give them the 'pride' of being able to say that they played in X games. This is especially evident in playoffs. For example, in the 2001 NBA playoffs, the 76ers coach Larry Brown knew that losing was inevitable. So he took out his stars and put in bench players so they could say that they played in the NBA playoffs.
Answer: I always thought those substitutions are just used to buy time. The clock doesn't stop during a sub, the player that is substituted never hurries, so it buys some time for the team. The referee has to add the time to overtime, but it will not be the same amount.
Comment: I've heard (on the grapevine... I couldn't find a reliable internet source), that the referee adds 30 seconds per substitution.
Comment: @Matt - 30 seconds is about average, I believe. The laws of the game state that the allowance is made in either period for all time lost through:
• substitutions
• assessment of injury to players
• removal of injured players from the field of play for treatment
• wasting time
• any other cause
The allowance for time lost is at the discretion of the referee.  So basically, whatever the ref thinks is correct.
Answer: I have often wondered about this myself.  I cannot bring up any references for this, but I can bring up logical conjecture.
In such a situation, one of five conditions will apply:

You are ahead of your opponent by a large margin they can not feasibly come back from

Put younger players in there to get them some playing time, more experience.  Protect your star players from unnecessary injury during inconsequential minutes.

You are ahead of your opponent by a margin they could feasible come back from

Put a fresh pair of legs out there to increase your odds of thwarting your opponent's attempt to tie or win the game.

Your opponent is ahead of you by a significant margin you cannot feasibly come back from

Put younger players in there to get them some playing time, more experience. Protect your star players from unnecessary injury during inconsequential minutes.
Your opponent is ahead of you by a margin you could feasible come back from

Put a fresh pair of legs out there to increase your odds of tying or winning the game.

You and your opponent are tied

Put a fresh pair of legs out there on offense or defense where you feel it is necessary. (Sort of a combination of the two other 'fresh legs' responses.)

This has been my theory on that.  Sometimes you'll see it in other sports too. You see it in baseball and American football often. At the end of the game, some people just get tired and have to come out.  The benefits you lose by taking out your senior/star players are gained by the fresh energy of the incomer, as well as their willingness to impress (after all, they'd like to start earlier.)
In football, where you often have a limited of subs, why not use them to your advantage when you need them the most. Similar to how in american football most teams use their time outs at the end for strategic purposes.
Comment: @Dunk the reason why he's the only person who mentioned that is perhaps that others wanted to add on to what corsiKa wrote, instead of redundantly restate it. ;)
Comment: Well the injury time is typically 5 minutes or so, so at the 89th minute you have 5 minutes left. I think it would apply less when there's 15 minutes to go. Your fresh legs are out there so they can burst onto the scene. It's like the difference between sprinting and distance. You give it all you have in sprinting. If you did distance like you sprinted, you'd exhaust very quickly. These fresh legs go out there and sprint, giving them a huge advantage. But the longer they're out there, the less effective they are. I'd say you only want them out for 5, maybe 8 minutes.
Comment: +1 - Out of all the answers, I am shocked that you are the only person who mentioned the 99.99% of the reason. It is to prevent your key players from unnecessarily getting hurt. PERIOD.
Comment: I can see substitutions been made when you have 5/10/15+ minutes left for these reasons, but I'm literally talking about substitutions being made in the 89/90th minutes/ during injury time. Surely if the motivation of the manager was for these reasons, they would do it sooner?
Comment: Aye, you have a point there; I forgot how long injury time can be these days.
Comment: I see your points if there are a lot of time ahead. Football is a game that is usually not solved in a couple of minutes. So a last minute subs is usually to make the game freeze. None of the other condition applies to professional football. last minute subs most of the time, doesn't even touch the ball.
Answer: In addition to other answers, manager do sub players already on a Yellow to avoid the chance of getting a second Yellow i.e. a sending off. It's also a known opposition tactic to provoke such players into getting that second yellow.
In some tournaments getting a red means a ban for a few matches as well.
Now as you're specifically referring to 89th minute substitutions, I imagine it could also be to give a "match feel" to the benched players and perhaps a bonus goal from one of them.
Torres came on in the 80th minute and scored the winner for Chelsea against Barca in the 2012 UEFA CL semi-final
Answer: I'll not repeat what the other answers have already correctly stated but I will provide an answer relating to a subpart of your question:

Is it related to giving the player another cap? (perhaps pay related for an appearance?)

This can, indeed, be a factor.  Although it's less likely that a manager brings on a player to earn his appearance fee, the number of caps a player has earned in a season can be important.
Sometimes a club may loan a player to another team but, as a requirement, they may stipulate that the loanee player must complete a certain number of minutes or games for the agreement to go through.
More often though, is that certain competitions will only give winners' medals to players who have made a certain number of caps in the said competition.
One example that springs to mind is when Martin Keown needed one more cap to qualify for a EPL medal with Arsenal. Ray Parlour jokingly pretended to get ready to come on as their last substitution to frighten him (Keown) into thinking he wasn't going to play and get his medal.
Another point not mentioned is that sometimes a manager will bring off a star performer in the final minutes/seconds of the game so that they get the ovation that they deserve.
Answer: In addition to all these answers I'd also like to point out that a sub in the OT could also serve to "cool down" a hellbent fierce opposition who's trying desperately to get a goal. With some 30 sec.s of pause, you give your players some little time to catch their breath, hopefully help them think properly while the opposition will most certainly be annoyed by the pause and will be force to remount an attacking position. With only a couple of minutes to go, it could take them sometime to get back in to the rhythm.
Answer: Wikipedia states:

In association football, a substitute is a player who is brought on to
  the pitch during a match in exchange for an existing player.
  Substitutions are generally made to replace a player who has become
  tired or injured, or who is not performing well; there may also be
  tactical reasons such as bringing a striker on in place of a defender
  when goals are needed. Players who are noted for scoring important
  goals when coming off the bench or frequently making appearances as a
  substitute are often known as "super subs".
Most competitions only allow each team to make a maximum of three
  substitutions during a game, although more substitutions are often
  permitted in non-competitive fixtures such as friendlies

Strictly as conjecture, a manager in this situation (large lead, with an almost sure victory) may want to reward some of his bench players for practicing hard against the starters, so he grants them playing time with the outcome already assured. The desire to reduce the risk of injury to key starters might also be a factor.
Answer: The other answers are all good, but I wanted to emphasize that "fresh legs" are good for more than just running.  Changing the composition of the team, even by one member, can have a great effect on momentum.  You play differently with a new player, and the other team responds differently (or fails to, and you take advantage of it).
Some guy running up the field, taking a shot, running all the way back to defend, then up again (etc.) because he's only got 5 minutes can be pretty inspiring and provoke a last boost of energy from the other members of the team.  This effect can be surprisingly strong and you'll often see a team losing thoroughly that equally thoroughly dominates the end of game after a sub.
Answer: In soccer, an injured player may only be substituted for if the coach hasn't already used up his maximum 3 substitutions. Many coaches bring out subs #1 and #2 at, say, 55' and 70', then defer the 3rd and final substitution until there is so little time remaining in the game as to make a game-ending injury to one of his players a remote possibility. In, say, the 89th minute, a coach can comfortably use his final sub, knowing that he's making a very calculated gamble owing to their being so little time remaining. A coach deploying all 3 subs prior to the 80' mark is vulnerable to an injury requiring his team to play the balance of the game with ten men. These substitutions are almost always the 3rd and final substitution. The previous answers are valid only with respect to the player chosen to go in and the one removed.
Answer: As far as I am concerned substitutes are used late on for one thing i.e. to appease the dressing room. I say this as all players get an appearance fee. Paying to 14 players instead of 11 makes the collective team happier
Answer: One additional reason would be to avoid a second yellow card turning to red and then a ban.


sh: syntax error near unexpected token `}'

Question: I feel like a real moron posting a syntax error question but I really don't know how to fix this one
I'm trying to setup a build process in my node package.json file with the following script
"scripts": {
  "build": "NODE_ENV=production { echo '// mypkg-x.y.z'; browserify -r ./client/main.js:mypkg | uglifyjs -cm; } > dist/mypkg.min.js"
}

which runs the following in sh
NODE_ENV=production { echo '// mypkg-0.0.0'; browserify -r ./client/main.js:mypkg | uglifyjs -cm; } > dist/mypkg.min.js

sh error outupt
sh: -c: line 0: syntax error near unexpected token `}'

When I run the command in bash it works just fine, but nodejs uses sh :{

End Goal
I am browserifying some javascript code and I want to prefix the bundled output with the package's name/version
// mypkg-x.y.z
<bundle output here>

Comment: What about making a symlink so that bash is used instead (`mkdir -p ~/bin && ln -s /bin/bash ~/bin/sh && export PATH=$HOME/bin:$PATH `)? Also make sure to add the export to your `~/.bash_profile`/`~.bashrc` to make it permanent.
Comment: I'd rather not do that. I don't want to have to modify every environment my package is built on.
Comment: Apologies if this is a silly question, but is this an `npm` script? I don't recognize the `build` attribute, but I use many similar scripts that do the same thing you're trying to do but I use `postinstall`.
Comment: Well, file a [new issue](https://github.com/npm/npm/issues/new) about it or [submit a pull request](https://github.com/npm/npm/pulls) then.
Comment: @mscdex it's not an npm issue. There's a syntax error in the `sh` script I've written. I just don't know where.
Comment: @Antiga you can define your own scripts and run them using `npm run build` or `npm run myscript`
Answer: Add a semicolon after you set NODE_ENV:
"build": "NODE_ENV=production; { echo '// mypkg-x.y.z'; browserify -r ./client/main.js:mypkg | uglifyjs -cm; } > dist/mypkg.min.js"

Comment: Nailed it. Thanks, @Ray.
Answer: @Ray's answer worked great, I just wanted to post an alternate solution to the same problem
// this works too !
{ echo '// mypkg-0.0.0'; NODE_ENV=production browserify -r ./client/main.js:mypkg | uglifyjs -cm; } > dist/mypkg.min.js

To highlight the difference, all I did was move the NODE_ENV=production bit to just before the browserify bit. In this case, no semicolon is needed.
This is actually a little specific to my use case too, as the environment variable is only needed for that part of the build process.


Invalidate Internal Page Cache at certain times in a day for anonymous users

Question: Let say I have a webshop open from 9am to 11am (data coming from config).
When the shop is closed, I would like to display a message (shop closed) and when the shop is open, my commerce product should be available. (only for 'lunch' bundle)
I have tried to update the following code: https://cornel.co/article/drupal8/page-cache-cookies-or-anything-available-http-request
Here is my try (edited with a comment from 4k4:
protected function getCacheId(Request $request)
{
    if (! isset($this->cid)) {
        $cid_parts = [
            $request->getSchemeAndHttpHost() . $request->getRequestUri(),
            $request->getRequestFormat(NULL)
        ];
        // Only cache by State of Store for some path
        if (strpos($request->getPathInfo(), '/lunches/') != false) {
            $store_state = get_store_state();
            $cid_parts[] = $store_state['context']; //return a string like 'open' or 'close:9:30:11:00' if closed (like before 9:30 am or after 11:00am)
        }
        $this->cid = implode(':', $cid_parts);
    }
    return $this->cid;
}

As stated by 4k4, I must create a new context which will bubble up and will invalidate the Internal Cache page.
Here is the code of
class StateStoreCacheContext implements CacheContextInterface

stored in mymodule/src/CacheContext/StateStoreCacheContext.php
public function getContext()
{
    $storeState=get_store_state();
    return $storeState['context']; //return a string like 'open' or 'close:9:30:11:00' if closed (like before 9:30 am or after 11:00am)
}

And here is mys service declaration:
services:
   cache_context.state_store_context:
    class: Drupal\mymodule\CacheContext\StateStoreCacheContext
    arguments: []
    tags:
      - { name: cache.context }

And here is the way I add my context to my page (in mythem_preprocess_node(&$vars))
$vars['#cache']['contexts'][] = 'state_store_context';

Unfortunately, my page cache is not invalidate for anonymous users (but it is ok for logged-in users)
Comment: The cache context doesn't exist, you have to create a custom one and add it to the node, a preprocess hook is OK for this. BTW you can't rely on the route name being present in the middleware, it's only there when storing the cache item but not when retrieving it. So better use the path to check the node type.
Comment: Is this really about invalidating the whole page cache or is it more about displaying a certain message at certain times?
Comment: @leymannx: it is about invalidating the whole cache page
Comment: @4k4 I have 2 issues regarding creating a context: 1-I will have to implement `get_context()` with exactly the same logic as in `getCacheId()` (see upper)=>looks weird 2-My idea is to keep the internal page cache module, I have read somewhere else that it doesn't deal with context. Thank you for the route not being present, I will update the code
Comment: Yes, a custom cache context with exactly the same logic. You need the cache context for all other caches in Drupal like the entity render cache and the dynamic page cache and if you add the context to the node it will bubble up to all cache levels. With one exception, the Internal Page Cache, for which you are trying to find a solution in getCacheId().
Comment: @4k4 I get it: Contexts are for dynamic caching. I would like to focus my question only for anonymous user and internal page cache: how to invalidate this page cache when the store is closed or opened?
Comment: But the internal page cache for anonymous users gets the result from the dynamic cache and you need to make sure this delivers the correct result by adding the cache context. BTW invalidating is the wrong term here, you vary the cache id by a context and you have to do this in two places because one of the caches doesn't understand the standard Drupal way to do this (and wouldn't be able to run most contexts, because it is too early in the bootstrap process).
Comment: I've tried similar solutions, and finally switched over to adding custom cache tags, and invalidating those cache tags by cron. E.g. I added a `$variables['#cache']['tags'][] = 'MIDNIGHT';` in preprocess and invalidated it with a corresponding `\Drupal\Core\Cache\Cache::invalidateTags(array('MIDNIGHT'));` in the `hook_cron` of the same module
Answer: You have to add a cache context as well. See both answers in this topic:
How do I create a cache context in Drupal 8 that varies on user/node field data?
You add a variation to the CID of the Internal Page Cache and a custom cache context to the node, so that it can bubble up to all elements which are dynamically cached. The difference is, CIDs can't bubble up, contexts can, and so vary all render elements no matter how deep they are nested.
Comment: I have tried what you say (also tried to add a cache key as described in your link) but unfortunately, this is not working for anonymous. I have updated my question with all your comments.
Comment: What do you mean by not working. Did you check the database for the cache items, whether they vary by the cache keys/contexts you've added? Or the result in the browser? This is not so easy to debug because the browser caches anonymous requests, too. For debugging (and production as well) you have to adjust the browser and proxy cache max-age: /admin/config/development/performance


Big Views query and PHP memory limits

Question: I have a custom table, from which I create a paged table using views and data module.
When I get somewhere over 15000 rows, PHP runs out of memory. Is there any way to avoid this?
Thanks
Comment: It is feasible, can you post the SQL from the query?  Also, what row format (content, fields, etc)?  There is one quirk I know of, but I am not sure if you are experiencing it.
Comment: I think this should be the base query that's run when I open the page: http://pastebin.com/daJ598Uj
Comment: Are you displaying 15000 rows in a page in view?
Comment: Yes, 26.000 right now, 50 per page.
Comment: @Maiagallo Can you paste the entire query, including the JOINs?
Comment: I'm not really sure on how to get the entire query. I think there shouldn't be any JOINs: it's just data coming straight from a custom table.
Answer: Sounds like your memory limit on your server is too low.
Have a look under Reports >> Status report what it is.
Default on most servers are 32M. This is too low.
If you do not manage your own server then go beg your server admin to increase it. I can't give you a number, best to increase in 32Mb steps until you are happy.
I normally set mine to 256Mb during development and drop it to 128Mb on fairly large sites (this is just a guideline what I do).
If your server admin does not want to change it then first answer would be to get a new provider, which I know is not always the correct route. But read here how you might be able to set it yourself. Increase PHP settings
Comment: Of course it's a memory limit problem... I just found out that my hosting increased the memory limit, so I went from 128M to 256M, but it didn't help much: with 16.000 records I have 132M peak, with 27.000 records 192M peak. This means 5M of ram every thousand record. I'm looking for a way to reduce the memory used per record, as I'll need to get up to a hundred thousands probably...

Big Views query and PHP memory limits


Jogar Dados de Query Para DataGridView em C#

Question: Olá pessoal estou enfrentando problemas com uma listagem.
Tenho um DataGridView carregando uma lista de produtos automaticamente e um combobox com os nomes das categorias, a ideia é que, quando selecionar uma categoria e clicar no botão listar, o DataGridView carregue somente os produtos daquela lista. Criei uma query, executei separadamente e ela funciona, o problema é, como passar o texto da combobox como parâmetro na hora de chamar a query?
deveria ser algo assim, mas dá erro
private void btListar_Click(object sender, EventArgs e)
{
    string sCategoria = cbCategoriaProduto.Text;
    this.tabelaEstoqueTableAdapter.FillByCategoria(
          this.baseDadosInfoMasterDataSet.TabelaEstoque, sCategoria);
}

Consegui passar o parâmetro, eu estava fazendo errado, o correto era:
this.tabelaEstoqueTableAdapter.FillByCategoria(
     this.baseDadosInfoMasterDataSet.TabelaEstoque,
     "%" + cbCategoriaProduto.Text + "%");

Mas não mostra nenhum dado no datagridview :/
Comment: Não coloque a solução no corpo da pergunta, publique uma nova resposta com a solução.
Answer: Desculpem-me por ter respondido na mesma pergunta.
Resolvi meu problema agora, depois de algumas horas tentando.
O jeito certo de chamar minha query foi:
this.tabelaEstoqueTableAdapter.FillByCategoria(
     this.baseDadosInfoMasterDataSet.TabelaEstoque,
     cbCategoriaProduto.Text);

De chamando entre "%" não dava certo, acredito que só funcione para selects com o LIKE. Agora deu certo.