What is product ID in Eclipse plugin?

Question: It is said here, that product Id should be set "as defined in your plugin manifest".
What does it mean? That product Id should coincide with plugin Id? But this can't be true, since product can contain many plugins.
How to specify product in plugin manifest?
UPDATE
When editing product file with Eclipse editor, I have 2 places to define product

In upper field I can apparently enter anything I want. Lower field apparently refers the "product" extension of some plugin, allowing of creating new one by button.
What is the relation between these two places?
Answer:
What does it mean? That product Id should coincide with plugin Id?

No. Product Id and Plugin Id are different. In a given product each and every plugin should have unique id. Plugin/Platform loader identifies these plugins by id's.
Refer these links
Product Overview
Product Configuration

How to specify product in plugin manifest?

Plugin Manifest may may or may not refer any products. But any plugin can read product details via org.eclipse.core.runtime.products extension point.
Refer the image
Answer: In your plugin you define the product using the org.eclipse.core.runtime.products extension point - something like:
<extension
     id="product"
     point="org.eclipse.core.runtime.products">
  <product
        name="%product.name"
        application="org.eclipse.e4.ui.workbench.swt.E4Application">
  .. more ...

The product id is then the plugin id plus the value of the id attribute, so something like pluginid.product. This is what you specify in the product configuration. The product configuration editor should show you this id in the list of available products.
Update:
I have not seen a good explanation of what the ID field in the product file is for, possibly something to do with the p2 installation code. I have seen discussions that say it can cause errors if it matches other ids. Using a unique id works.
Comment: Thnaks! And what is the "ID" field in product file editor (see my update)?
Comment: Added a bit on the ID
Answer: Please add this update:
The product id is a top-level handle or identifier for the P2 installation system. Using the product ID and the URL of a online repository, the P2 generic installer application can install a complete Eclipse product from the internet to your platform. Please see the section "Installing a complete product" in the following page of the Eclipse help website:
https://help.eclipse.org/2021-03/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Fguide%2Fp2_director.html&cp%3D2_0_20_2

What is product ID in Eclipse plugin?


Qual é a diferença entre array_walk e array_map?

Question: No PHP, temos duas funções que percorrem o array e aplica uma função determinada para cada elemento: array_walk e array_map.
Exemplo:
$meu_array = array(1, 2, 3);

$callback = function ($value)
{
     return $value * 2;
};

$novo_array = array_map($callback, $meu_array);

var_dump($novo_array);

Saída:
array (size=3)
  0 => int 2
  1 => int 4
  2 => int 6

Exemplo 2:
$novo_array = $meu_array;

$callback = function (&$value)
{
    $value *= 2;
};

array_walk($novo_array, $callback);

var_dump($novo_array);

Saída:
array (size=3)
  0 => int 2
  1 => int 4
  2 => int 6

Além do fato de que uma use passagem por referência e outra não, parece que no final das contas as duas fazem a mesma coisa.
Sendo assim:

Existe alguma diferença entre array_map e array_walk - desconsiderando as diferenças já citadas?
Quando é recomendado utilizar uma ou outra?
Answer: Além de um utilizar referencia e outro retornar um novo array, veja a assinatura de ambos os métodos:
bool array_walk ( array &$array , callable $callback [, mixed $userdata = NULL ] )

array array_map ( callable $callback , array $array1 [, array $... ] )

Ao utilizar o array_walk podemos fornecer para a função callback argumentos extras. O array_walk permite trabalhar com as chaves do array também:
<?php

function mergeValueKey(&$value, $key, $prefix = '')
{
    $value = $prefix . $value . $key;
}

$array = [
    't1' => 'Teste1 ',
    't2' => 'Teste2 ',
    't3' => 'Teste3 ',
];

array_walk($array, 'mergeValueKey');

var_dump($array);

Resultado com array_walk:
array(3) {
  ["t1"]=>
  string(9) "t1Teste1 "
  ["t2"]=>
  string(9) "t2Teste2 "
  ["t3"]=>
  string(9) "t3Teste3 "
}


General method for determining if $Ax^2 + Bx + C$ is square

Question: Is there a general method for solving Diophantine equations in the form $Ax^2 + Bx + C = k^2$, preferably turning them into Pell's equations, when possible? For example, $2x^2 + x + 1 = k^2$ or $5x^2 + 2x + 1 = k^2$. Certain cases have special solutions, but I cannot figure out how these are derived beyond a simple completing the square approach.
A general method for solving the hyperbolic equation $Ax^2 + Bxy + Cy^2 + F = 0$ is given by Dario Alejandro Alpern.
Comment: $2x^2+x+1=k^2$ becomes $4x^2+2x+2=2k^2$, i.e. $(2x+1/2)^2+1.75=2k^2$, i.e. $(4x+1)^2+7=8k^2$. Generally, multiply both sides of $ax^2+bx+c=k^2$ by something to make $a$ a square, then complete the square, multiply both sides by something to make everything integers.
Comment: If $a$ is a square, you might be able to prove $(\sqrt{a}x+k)^2<ax^2+bx+c<(\sqrt{a}x+k+1)^2$ for some $k\in\Bbb Z$, which proves no solutions exist.
Comment: @user236182 This is useful, but what to do with the $7$ left over? I know there are [special cases](https://en.wikipedia.org/wiki/Pell%27s_equation#Transformations) for $\pm 2, \pm 4$.
Comment: You can solve $x^2-dy^2=k$ with $d$ square-free for any integer $k\neq 0$. If a solution exists, then exist infinitely many solutions. Let $(x_k,y_k)$ be the minimal solution of $x^2-dy^2=k$ and let $(x_1,y_1)$ be the minimal solution of $x^2-dy^2=1$. Note $\left(a^2-db^2\right)\left(e^2-df^2\right)=(ae+dbf)^2-d(be+af)^2$. Define $(a,b)\otimes (e,f)=(ae+dbf,be+af)$. Then all positive integer solutions are given by $(x_k,y_k)\otimes (x_1,y_1)^n$ with $n\ge 0$.
Comment: @user236182 Your comments have essentially answered the question. I've asked this last question, but do you mind posting the comments together as an answer so I can accept it?
Comment: @user236182, there is a little more to it than you say. Please see answer
Comment: @WillJagy For a square-free $k$, all the solutions are given that way if and only if $k=\pm 1$ or $\pm k$ is prime?
Comment: @user236182, if you add in $(x_k, -y_k)$ in your notation, it works.  The method I know for guaranteeing locating all necessary seed solutions is the Conway topograph, about which I have posted many answers.
Comment: http://www.artofproblemsolving.com/community/c3046h1048219
Answer: The comments you have been given are almost correct. Once you get to
$$ x^2 - d y^2 = k,     $$ you do need to find the minimal solution to
$U^2 - d V^2 = 1,$ that is with both $U,V > 0.$ The generator of the (oriented) automorphism group of $x^2 - d y^2$ is then
$$
A =
\left(
\begin{array}{cc}
U & dV \\
V & U
\end{array}
\right).
$$
Notice that this has determinant $1,$ with trace $2U.$ The Cayley-Hamilton theorem says, quite correctly, $A^2 - 2 U A + I = 0,$ so $A^2 = 2 U A - I.$
We need to know only one orientation reversing automorphism, which is just $$ (x,y) \mapsto (x,-y) $$
Now, all the solutions for some $k$ are produced by using $A.$ The detail that gets glossed over is that we may require more than one or two "seed" solutions.
Let us display all solutions to $x^2 - 2 y^2 = 119 = 7 \cdot 17.$ For any solution $(x,y),$ we really do get a sequence of new solutions by taking
$$ (x,y) \mapsto (3x+4y,2x+3y),  $$ which comes from $U = 3, V = 2,$ so this time
$$
A =
\left(
\begin{array}{cc}
3 & 4 \\
2 & 3
\end{array}
\right).
$$
This is indicated in the comments.
The trick is that we need four seed solutions.
In all four of the following sequences of solutions, we get, from Cayley-Hamilton applied to $A,$ giving $A^2 = 6 A - I,$ we get
$$ x_{n+2} = 6 x_{n+1} - x_n, $$
$$ y_{n+2} = 6 y_{n+1} - y_n. $$
If we intertwine the four sequences things do not look that simple.
$$ ................................ $$
$$ (11,1) $$
$$ (37,25) $$
$$ (211,149) $$
$$ (1229,869) $$
$$ ................................ $$
$$ (11,-1) $$
$$ (29,19) $$
$$ (163,115) $$
$$ (949,671) $$
$$ (5531,3911) $$
$$ ................................ $$
$$ (13,5) $$
$$ (59,41) $$
$$ (341,241) $$
$$ (1987,1405) $$
$$ ................................ $$
$$ (13,-5) $$
$$ (19,11) $$
$$ (101,71) $$
$$ (587,415) $$
$$ (3421,2419) $$
$$ ................................ $$
Afterthought: when $k=1$ the only seed required is $(1,0).$ When $k=-1$ or $k=p$ or $k = -p$ only two seeds are required, some $(B,C)$ and $(B,-C).$ It is when $k$ (well, squarefree) is the product of primes that are represented by $x^2 - d y^2$ that we require more than two seed solutions. Note that both $x^2 - 2 y^2 = 7$ and $x^2 - 2 y^2 = 17$ have solutions.
Here are all the solutions to $x^2 - 2 y^2 = 119$ with $x,y > 0$ and $y < 12000,$ in numerical order:
<code> x: 11     y: 1
 x: 13     y: 5
 x: 19     y: 11
 x: 29     y: 19
 x: 37     y: 25
 x: 59     y: 41
 x: 101     y: 71
 x: 163     y: 115
 x: 211     y: 149
 x: 341     y: 241
 x: 587     y: 415
 x: 949     y: 671
 x: 1229     y: 869
 x: 1987     y: 1405
 x: 3421     y: 2419
 x: 5531     y: 3911
 x: 7163     y: 5065
 x: 11581     y: 8189
</code>
Note, December. Over a few years of posting related answers, I have settled on  my favorite way to present Conway's Topograph method so as to show the generator ($A$) of the automorphism group of the form, an infinite cyclic subgroup of  $SL_2 \mathbb Z.$ Neither Conway's book nor Stillwell's chapter emphasize that aspect of it. I have also settled on a version of the picture of the river that I like, a straight line with trees growing up, in the direction of positive values of $x^2 - d y^2$ or other quadratic binary form, then trees growing down in the direction of negative values.
Here are some previous MSE questions and  answers.
http://www.maa.org/press/maa-reviews/the-sensual-quadratic-form
Here is a preview for Conway's book, set to the page with the Climbing Lemma
At the moment, Conway's entire book is available as a pdf here
http://www.springer.com/gp/book/9780387955872
A few of the relevant pages in Stillwell are viewable, really everything in pages 87-100 relates. I found this very helpful in clarifying things.
Another quadratic Diophantine equation: How do I proceed?
How to find solutions of $x^2-3y^2=-2$?
Generate solutions of Quadratic Diophantine Equation
Finding all solutions of the Pell-type equation $x^2-5y^2 = -4$
Find all integer solutions for the equation $|5x^2 - y^2| = 4$
Maps of primitive vectors and Conway's river, has anyone built this in SAGE?
Infinitely many systems of $23$ consecutive integers
Finding integers of the form $3x^2 + xy - 5y^2$ where $x$ and $y$ are integers, using diagram via arithmetic progression
Small integral representation as $x^2-2y^2$ in Pell's equation
Solving the equation $ x^2-7y^2=-3 $ over integers
Comment: Do you mind updating your answer so that it includes all the steps to solve the general equation?
Comment: @qwr , putting all the steps is not possible. I show a good portion of the issues in learning Conway's picture method in the several answers linked in. Both Conway and Stillwell prove that the river is periodic, but neither goes so far as to emphasize how all solutions may be found by applying "automorphisms" to the finite set of solutions in a single period, so I push that aspect pretty hard.
Comment: I'm just trying to make sense of [Alpern's](https://www.alpertron.com.ar/METHODS.HTM#Hyperb) sea of variables, which appears (I'm not sure) to be the same thing but with far more algebra invovled
Comment: @qwr , if you begin with $Ax^2 + Bx + C = k^2$ as you initially wrote, you will always arrive at a Pell type equation, $(2Ax + B)^2 - (4A)k^2 = B^2 - 4 AC$ is what you expect when $B$ is odd. Find all solutions to $y^2 - (4A)k^2 = B^2 - 4 AC,$ allowing $y$ both positive and negative, select those that can be written as $2Ax+B.$ What is your own background, and why do you want to know more detail about this topic?
Comment: I have no background in number theory and I only know some basic calculus. I am interested in learning more about number theory.
Comment: @WillJagy, Is it possible to reverse the process? Knowing integer solutions to $X^2-DY^2=k^2$, can we find an integer solution to $X^2-DY^2=1$?


Como modelar um conjunto de 1 a 4 valores predeterminados

Question: Estou modelando uma base MySQL onde as entidades principais são documentos. Entre vários outros campos, esses documentos se relacionam a uma ou mais fases de um determinado projeto.
São 4 valores básicos (vamos chamá-los A, B, C e D), e o valor da propriedade fase é um conjunto de 1 a 4 deles. Por exemplo, um documento pode estar relacionado apenas à fase A, às fases A e B, às fases B, C e D, etc.
Vejo várias maneiras de modelar isso, mas estou em dúvida sobre qual seria a mais adequada. As opções que considerei:

4 colunas "booleanas" (TINYINT(1)), uma para cada fase.
Uma única coluna binária, com 4 bits (BIT(4)).
Uma coluna do tipo set: SET('A','B','C','D').
Tabela de relacionamento.

Vou precisar obter/exibir tanto a lista de fases de um dado documento, quanto a lista de documentos ligados a determinada fase.
Qual seria a estrutura mais adequada neste caso? Quais critérios devo levar em conta para tomar essa decisão?
Answer: A menos que você esteja enfrentando problemas de desempenho, eu iria com a tabela de relacionamento, pois do contrário iria complicar um bocado suas queries. No entanto, se o número de documentos for muito grande em relação às fases, há uma alternativa menos custosa que ainda preserva a normalização dos dados:
Já que o número de conjuntos possíveis é pequeno (16 no máximo), você pode criar uma tabela separada para representar um conjunto. Essa tabela de conjuntos teria basicamente um ID - talvez codificado nesse padrão binário, mas não necessariamente - e mais nada. Então você criaria uma tabela de relacionamento entre cada conjunto e suas fases (1 + 4 + 6 + 4 + 1 = 16 linhas).
Já o documento, esse teria um campo que funcionaria como chave estrangeira pra tabela de conjuntos. Um inteiro de 4 bits é o bastante. Assim cada documento teria um dado ocupando o mínimo de espaço possível, o overhead estaria todo na tabela de conjuntos (+ um join adicional, é claro).
create table fase(
  id    serial primary key,
  nome  text
);

create table conjunto(
  id   tinyint(4) primary key
);

create table fase_conjunto(
  id_fase integer,
  id_conj tinyint(4)
);

create table documento(
  id    serial primary key,
  nome  text,
  fases tinyint(4)
);

Para obter todas as fases de um dado documento:
select f.*
from documento d
  join conjunto c on d.fases = c.id
  join fase_conjunto fc on fc.id_conj = c.id
  join fase f on fc.id_fase = f.id
where d.nome = "d2f12";

E todos os documentos de uma determinada fase:
select d.*
from fase f
  join fase_conjunto fc on fc.id_fase = f.id
  join conjunto c on fc.id_conj = c.id
  join documento d on d.fases = c.id
where f.nome = "Fase 1";

Exemplo no SQLFiddle
Comment: Pensando aqui: se você não fizer questão das *foreign keys*, a tabela `conjunto` é desnecessária. Só não sei se é uma boa ideia, afinal são apenas 16 linhas... De todo modo, dá pra economizar um join, comparando `fc.id_conj` diretamente com `d.fases`.
Comment: Interessante a ideia, mas realmente não tenho tantos documentos para justificar a complexidade. Na verdade duvido que performance seja um problema com qualquer uma das alternativas que coloquei na pergunta. Por isso fiquei meio sem parâmetro para escolher uma delas. Gostei do argumento pró-tabela de relacionamento, para preservar a normalização. As outras opções me parecem mais econômicas (não exigem tabela adicional), mas tirando o SET (que acho que só existe no MySQL), são meio feias e pouco auto-explicativas.
Comment: É, meu principal parâmetro aqui nem foi a eficiência, mas simplificar as *queries*. Minha experiência com BDs em geral é limitada, e imagino que as outras opções complicariam um pouco as consultas. Mas posso estar enganado. Vamos ver se alguém com mais domínio dessa área responde. P.S. Migrar de uma coluna binária (opção 2) para um esquema como este daqui não seria difícil, e vice-versa, de modo que há uma certa flexibilidade caso se venha a descobrir no futuro não ter tomado a decisão certa.
Comment: Eu acho que no fundo quero saber qual opção é mais "elegante". Será que a minha pergunta é baseada em opinião?
Comment: Sei lá... pra mim, "elegante" no contexto de um BD relacional vai sempre significar "normalizado", de modo que eu rejeitaria a coluna binária e talvez o que usa `set` (não tenho experiência, mas uma coluna `set` não violaria a 1ª forma normal?). Quanto às demais, minha preferência pela tabela de relacionamento é pelo fato que ela "homogeniza" as *queries* - enquanto as colunas booleanas exigiriam uma query diferente pra fase A, outra pra fase B, etc (i.e. cada query complexa envolvendo uma fase teria de ser ajustada para cada coluna booleana, não dá pra usar uma só query parametrizada).
Comment: Eu precisaria estudar mais, mas pela pesquisa rápida que fiz há controvérsias quanto a conjuntos violarem ou não a 1NF. Enfim, acho que você tem razão, em termos de elegância a tabela de relacionamento é padrão, e é sempre uma opção segura.


Normal approxiamation to Binomial distribution

Question: A company has $200$ employees. Assume that each employee invites $2$ guests, independently, to attend a promotion seminar with a probability of $0.8$. How many seats should be provided if the company desires to be $99\%$ confident of seating everyone? (Using Normal approximation to binomial distribution)
I am doing it with:
$$
\begin{array}{rcl}
\mathrm{E}(x) =& (400)(0.8) &= 320 \\
\mathrm{Var}(x) =& (400)(0.8)(0.2) &= 64
\end{array}
$$
How should I determine the number of seats then?
Comment: It has been over two years. Would you consider deleting this question post or accept the answer to wrap it up? I assume you have already got your answer here or elsewhere and moved on.
Comment: Hello? Are you there. Again, please accept the answer and "conclude" this post.
Answer: The formula for the normal approximation is
$P(X \leq x)=\Phi\left( \frac{x+0.5-\mu}{\sigma} \right)$
$=\Phi\left( \frac{x+0.5-320}{\sqrt{64}} \right)=0.99$
$\Phi(\cdot )$ is the cdf of the standard normal distribution. $+0.5$ in the numerator is the continuity correction factor.
Taking the inverse function to solve for x.
$\frac{x+0.5-320}{\sqrt{64}}=\Phi ^{-1}\left( 0.99\right)$
$\sqrt{64}=8$ and to get the value of $\Phi ^{-1}\left( 0.99\right)$ you look at a table of the standard normal distribution. You´ll see that the corresponding value is $2.33$. The equation becomes
$\frac{x+0.5-320}{8}=2.33$
Solve for x. The result should be rounded up to a whole number.


isomorphism function

Question: Find an isomorphism $f \colon Q(\zeta^2 _5 )\to Q(\zeta^3 _5)$ that is not the identity function.
I do not know how to solve it when $f$ is not defined like $f(x)=y.$
I know to show $f$ is an isomorphism I first need to show it is a homomorphism which means $f(a+b)=f(a)+f(b)$ and $f(ab)=f(a)f(b)$, then I need to show $f$ is both one-to-one and onto and I know  $\zeta _5 = e^{(2\pi i)/5}$.
Could you please help me how can I solve it?
Answer: Hint: Prove that complex conjugation is an automorphism on $\mathbb{C}$. Then prove that it maps $ζ_5^2$ to $ζ_5^3$.

isomorphism function


Installing GIS tools in R

Question: I am trying to download GIStools in R. I did this through the Packages menu > Install Packages. I then selected GIStools and it appears to have installed it as I get the following message:
> utils:::menuInstallPkgs()
trying URL 'https://mirrors.ebi.ac.uk/CRAN/bin/windows/contrib/3.2/GISTools_0.7-4.zip'
Content type 'application/zip' length 3460038 bytes (3.3 MB)
downloaded 3.3 MB
package 'GISTools' successfully unpacked and MD5 sums checked
The downloaded binary packages are in
C:\Users\MachineX\AppData\Local\Temp\RtmpCCEk3L\downloaded_packages
I didn't select a mirror site from which to d/l the package (was it supposed to prompt me?) When I call the library using library(GIStools) I get the following error:
Error in library(GIStools) : there is no package called 'GIStools'
I'm not sure what I have done wrong - can anyone help? I am using R version 3.2.3. I am totally new to R, so apologies if this seems like a silly question.
Thanks!
Answer: in the console type install.packages('GIStools') make sure you are running rstudio as admin when doing this. This should install just fine make sure you don't have the rstudio screen maximized as the mirror prompt could be hidden.
Comment: Thanks Seekheart, this worked. I'm assuming that it didn't work the first time because I used a lower case 't'? Bit of a school-boy error there!
Comment: @JassiL glad I could help, if you could please close your question now by selecting my answer :)
Comment: @JassiL consider deleting this question if its just a matter of typo.

Installing GIS tools in R


Problem dealing with date/time and timezone

Question: I'm creating event series on a Google Calendar based on information from Google Sheets linked to a Google Form. Dealing with dates is a mess and I'm getting erratic results.
I have a field on the spreadsheet with a start DATE shown as YYYY/MM/DD
I have a field with a start TIME shown as HH:mm
I have a field with an end TIME shown as HH:mm
I understand that internally the time has an year/month/day associated and the DATE also has a time associated that are not shown.
I will eventually need to create a calendar event series using the  DATE part from the DATE and the TIME part from the time which I can change using setHours() setMinutes() methods.
Now my problem is creating a consistent Date object from the DATE cell Value as it seems to change weirdly.
var ssTZ = SpreadsheetApp.getActive().getSpreadsheetTimeZone();
var SSDate = ss.getRange(6,8).getValue();
var dataStart = Utilities.formatDate(SSDate, 'America/Brasilia' , 'MMMM dd, yyyy 12:00:00 Z');
var dataStartTZ = Utilities.formatDate(SSDate, ssTZ , 'MMMM dd, yyyy 12:00:00 Z');
var dataStartSP = Utilities.formatDate(SSDate, 'America/Sao_Paulo' , 'MMMM dd, yyyy 12:00:00 Z');
var dataStartOS = Utilities.formatDate(SSDate, 'GMT-3' , 'MMMM dd, yyyy 12:00:00 Z');

var date = new Date(dataStart);
var dateTZ = new Date(dataStartTZ);
var dateSP = new Date(dataStartSP);
var dateOS = new Date(dataStartOS);

Logger.log("Spreadsheet TimeZone: " + ssTZ);
Logger.log(SSDate);
Logger.log("");
Logger.log(date);
Logger.log(dateTZ);
Logger.log(dateSP);
Logger.log(dateOS);

That code produces the following Log outputs:

[19-07-02 20:39:49:780 BRT] Spreadsheet TimeZone: America/Sao_Paulo
  [19-07-02 20:39:49:781 BRT] Tue Jan 12 00:00:00 GMT-02:00 2016
  [19-07-02 20:39:49:782 BRT]
  [19-07-02 20:39:49:784 BRT] Tue Jan 12 10:00:00 GMT-02:00 2016
  [19-07-02 20:39:49:784 BRT] Tue Jan 12 12:00:00 GMT-02:00 2016
  [19-07-02 20:39:49:785 BRT] Tue Jan 12 12:00:00 GMT-02:00 2016
  [19-07-02 20:39:49:786 BRT] Mon Jan 11 13:00:00 GMT-02:00 2016

which don't make sense since all the timezones used should actually be the same one.
EDIT.... Addedinfo
As requested by @TheMaster the logs from the Text formatted variables are:
  Logger.log(dataStart);
  Logger.log(dataStartTZ);
  Logger.log(dataStartSP);
  Logger.log(dataStartOS);

[19-07-03 12:39:33:099 BRT] January 12, 2016 12:00:00 +0000
[19-07-03 12:39:33:100 BRT] January 12, 2016 12:00:00 -0200
[19-07-03 12:39:33:100 BRT] January 12, 2016 12:00:00 -0200
[19-07-03 12:39:33:100 BRT] January 11, 2016 12:00:00 -0300

The first 3 outputs as explained by @ziganotscha are due to summer time change  to GMT-2 and America/Brasilia not beign recognized as valid timezone.
I'm still puzzled aout why it changes to January 11 when GMT-3 specified as Timezone.
Furthermore if i build the Date object directly from the cell value without formatting I get another diferent time:
var rawDate = new Date(SSDate);

19-07-03 12:39:33:101 BRT] rawDate: Tue Jan 12 2016 00:00:00 GMT-0200 (BRST)

I hate dealing with Dates... so confusing...
EDIT 2 ... More issues with time.
  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Passeios");
  var timeStart = ss.getRange(6,4).getValue();
  var timeEnd = ss.getRange(6,5).getValue();
  var ssTZ = SpreadsheetApp.getActive().getSpreadsheetTimeZone();

  Logger.log("timeStart: " + timeStart );
  Logger.log("timeEnd: " + timeEnd);

  var dateStart = ss.getRange(6,8).getValue();

  var dateStartObj = new Date(Utilities.formatDate(dateStart, 'ssTZ' , 'MMMM dd, yyyy HH:mm:ss Z'));

var timeStartObj= new Date(Utilities.formatDate(timeStart, 'ssTZ' , 'MMMM dd, yyyy HH:mm:ss Z'));

var justTimeStart = Utilities.formatDate(timeStart, ssTZ, 'HH:mm');

Logger.log(" Time Start Object: " + timeStartObj);
Logger.log("Time Start Object Hours: " + timeStartObj.getHours());
Logger.log("Time Start Object Minutes: " + timeStartObj.getMinutes());

Logger.log("Start Time HH:mm: " + justTimeStart)

var hourStart = Utilities.formatDate(timeStart, ssTZ, 'HH');
var minutesStart = Utilities.formatDate(timeStart, ssTZ, 'mm');
var hourEnd = Utilities.formatDate(timeEnd, ssTZ, 'HH');
var minutesEnd = Utilities.formatDate(timeEnd, ssTZ, 'mm');

Logger.log(" TimeZone :" + ssTZ);
Logger.log(hourStart);
Logger.log(minutesStart);
Logger.log(hourEnd);
Logger.log(minutesEnd);

Produces the following log

timeStart: Sat Dec 30 1899 07:06:28 GMT-0300 (BRT)
timeEnd: Sat Dec 30 1899 07:36:28 GMT-0300 (BRT)
Time Start Object: Sat Dec 30 1899 07:06:28 GMT-0300 (BRT)
Time Start Object Hours: 7
Time Start Object Minutes: 6
Start Time HH:mm: 07:00
TimeZone :America/Sao_Paulo
07
00
07
30

The Spreadsheet cell is formatted as HH:mm and it shows
07:00 for start time
07:30 for end time
As you can see there is some 6 minutes and 28 seconds offset that I am not sure where is coming from when logging the cell value or when constructing a Date() object with the cell value.
Formating the cell to just Hours or just Minutes or HH:mm does not carry that offset.
Comment: Log `SSDate, dataStart,dataStartTZ, dataStartSP,dataStartOS` instead
Comment: This is the log for those:Logger.log(dataStart);

    Logger.log(dataStartTZ);
    Logger.log(dataStartSP);
    Logger.log(dataStartOS);

19-07-03 12:27:40:438 BRT] January 12, 2016 12:00:00 +0000
[19-07-03 12:27:40:439 BRT] January 12, 2016 12:00:00 -0200
[19-07-03 12:27:40:440 BRT] January 12, 2016 12:00:00 -0200
[19-07-03 12:27:40:440 BRT] January 11, 2016 12:00:00 -0300
Comment: What's your script timezone? File> project settings ?
Comment: My script timezone is (GMT-03:00) Sao Paulo

But I guess the date I'm using in january is set to GMT-02:00 because at that date summertime was in place and indeed Sao Paulo Time was GMT -02:00 at that moment
Answer: There is a confusion about time zones:
Your time zone is the 'America/Sao_Paulo' time zone - this is why Logger.log(dateTZ); and Logger.log(dateSP); give you the same time - as you expect.
However, keep in mind that in January Sao Paulo observes the Brasilia Summer Time (UTC−02 instead of UTC−03), This is where the difference between Logger.log(dateSP); and comes Logger.log(dateOS); from.
https://www.timeanddate.com/time/zones/brt
As for dataStart - you assign it the time zone 'America/Brasilia', which is not a defined name for a time zone. This is why Apps Script is not accepting the value and gives you UTC+0 timezone.
You can verify that formatDate() uses the time zone as specified by Java SimpleDateFormat:
https://developers.google.com/apps-script/reference/utilities/utilities
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
And java uses the  Olson Timezone Database.
https://www.oracle.com/technetwork/java/javase/dst-faq-138158.html#worldwide
https://en.wikipedia.org/wiki/Time_in_Brazil
Comment: I though summertime was involved on the first 2, but I still do not understand why GMT-3 changes the day from Jan12 to Jan 11 @ 13:00

I also could not call getTimeZone() or setTimeZone() methods on google script, not sure why...

I get "TypeError: Cannot find function getTimeZone in object"
Comment: And...  if I build the Date() from the original cell value without formatting i get a different time...

 var rawDate = new Date(SSDate);
Logger.log("rawDate: " + rawDate);
LOG OUTPUT: rawDate: Tue Jan 12 2016 00:00:00 GMT-0200 (BRST)
Answer: So, Spreadsheet time SSDate is

Tue Jan 12 00:00:00 GMT-02:00 2016

i.e., Jan 12 start at midnight in timezone -2 hours from GMT.
'America/Brasilia' is not a valid timezone and can be ignored.
Both, America/Sao_Paulo and ssTZ as the second argument to Utilities.formatDate() produces the same valid date

January 12, 2016 00:00:00 -0200

When the offset is GMT-3, it is -3 hours  from midnight GMT,  or -1 hour from GMT-2 timezone, the date is

January 11, 2016 23:00:00 -0300

i.e., 11pm on the previous day.
Issue:
Your logs ignore the time part of date because you provided a static time format for all the dates 12:00:00 Z instead of HH:mm:ss.
So,  for example, the last date formatted on GMT-3 becomes

January 11, 2016 12:00:00 -0300

Calling a new Date() changes the above object to local time GMT-2(+1 from GMT-3):

Mon Jan 11 13:00:00 GMT-02:00 2016

Note that  parsing using new Date(timestring) is strongly discouraged.
References:

Timezone format
Javascript#date
Comment: That makes more sense...
I had not realized that 12:00:00 instead of HH:mm:ss would produce such behaviour.
I am indeed trying to use Date() constructors using individual component values but because I'm using dates and times from different cell values I needed to understand the erratic Date() behaviour I was getting.
This helps a lot, thanks.
Comment: I'vejust updated the post with some other weird behaviour on the Time part this time.
Comment: @Pablo Kindly ask a new question
Comment: Just posted new question [here](https://stackoverflow.com/questions/57296496/weird-time-offset-dealing-with-date-time-and-timezone)


How to use Google Fonts in Less CSS?

Question: I'm looking for a solution to embed Google Fonts or any other custom fonts in Less CSS.
How can I embed the given font?
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:400,600,600italic,700,700italic,900,900italic,400italic' rel='stylesheet' type='text/css'>

Comment: i am useing this script for compile less
Answer: Try:
@import (css) url(...)

Keeps the import statement as-is on top.
Comment: Don't forget to remove quotes around your string.
Answer: I would just use an @import command at the top of my CSS file, then you can simply add a new font by adding a pipeline to the end of the font and type the name of any other fonts you want. To use them, simply use the CSS font-family style command:
@import url(http://fonts.googleapis.com/css?family=Playfair+Display+SC | Londrina+Outline);
span {
  font-family: 'Playfair Display SC', serif;
}

HTML
 This is an example text.

Hope this helped!
Answer: Create a file e.g- `google-fonts.css`
inside it add your content
@import url(http://fonts.googleapis.com/css?family=Playfair+Display+SC | Londrina+Outline);

In your .less file add:
@import (inline) "google-fonts.css";

and there you have your google fonts in your stylsheet
Answer: In the pop up box (after you've selected your Google web font):

Click the '@Import' tab (instead of 'Standard') to get the full url
Copy the url
Paste it at the top of your LESS file
Update the font-family name to the imported font name
Save the file. LESS will recompile with the new font
Answer: I'm not sure I understand the question. What do you mean by "embed [...] font in less"?
Anyway, you normally use web fonts in 3 ways:

Reference some standard font (like Arial or Sans Serif), or
Include copies of the font files (ttf, eot, woff, svg, etc) on your website, or
Reference font files from the CDN (such as Google).

To define a font, you need to specify its parameters in standard CSS (for a good example, see A Better @font-face Kit for Open Sans by Quinn Rohlf [it uses a local font in the example]). If you use Google fonts, Google, gives you code to use in your website to define fonts (so does Adobe). There is no need to use LESS for that.
Once you set up your font definitions, you can now reference the font family in your LESS file. The only intersection between LESS and custom fonts is to allow you use font family (and other font settings) via LESS variables, but it assumes that the font is already defined and the actual font CSS definition must point to either local font files or a CDN.
Answer: two ways to do this:

Create a file in your app-folder and name it (say) "googlefonts.css". Update this css file with the code availble on the mentioned url. And finally import this googlefonts.css in your styles.less (or whatever styles code) using @import "./app-folder/googlefonts.css".
As mentioned by @rodrigo calix above; in the googlefonts.css file mention @import url('https://fonts.googleapis.com/css?family=Nunito:400,700&display=swap');
and import googlefonts.css in your styles code using @import "./app-folder/googlefonts.css"

How to use Google Fonts in Less CSS?


ler de ficheiro binario para lista ligada c

Question: Boas pessoal, estou com um problema ao ler a informaçao de um ficheiro binario para introduli-la em memoria numa lista ligada.
PERGUNTAS val;

lista_perguntas * aux = original->next;
lista_perguntas * base = original;
lista_perguntas * novo;

 while (aux != NULL) {    // eu estava com um problema anteriormente que o primeiro elemento da lista era ignorado por isso eu pesquisei e encontrei esta solução que basicamente ignora esse elemento e passa para o segundo pelo que eu percebi
    aux = aux->next;
    base = base->next;
}

 while(fread(&val, sizeof(PERGUNTAS), 1, fp)!=-1){

novo = (lista_perguntas*) malloc(sizeof (lista_perguntas));
novo->valor = val;
novo->next = aux;
base->next = novo;

 }

O meu objetivo seria que lia a informação do ficheiro de cada vez e inseria num novo nó da lista só que o programa está dando erro. Eu ainda não domino muito bem isto de lista por isso agradecia que me iluminassem :).
Obrigado
Answer: Segue um exemplo que talvez solucione seu problema:
Estrutura de dados:
#define PERGUNTA_TAM_MAX   (256)

typedef struct pergunta_s pergunta_t;

struct pergunta_s
{
    char pergunta[ PERGUNTA_TAM_MAX + 1 ];
    pergunta_t * prox;
};

Função para carregar uma lista de perguntas a partir de um arquivo:
int perguntas_carregar( const char * arq, pergunta_t ** perg )
{
    FILE * pf = NULL;
    pergunta_t * p = NULL;
    pergunta_t * pant = NULL;
    pergunta_t * pprim = NULL;
    int n = 0;
    int nread = 0;

    pf = fopen( arq, "rb" );

    if(!pf)
        return ERRO_LEITURA_ARQUIVO;

    while(1)
    {
        p = malloc( sizeof(pergunta_t) );

        nread = fread( p, sizeof(pergunta_t), 1, pf );

        if( nread != 1 )
        {
            free(p);
            break;
        }

        p->prox = NULL;

        if(pant)
            pant->prox = p;
        else
            pprim = p;

        pant = p;

        n++;
    }

    fclose(pf);

    *perg = pprim;

    return n;
}

Espero ter ajudado!


"Romantic Harmony" example; Why does it work?

Question: I was reading some of Ted Greene's work and came across this PDF
http://www.tedgreene.com/images/lessons/chords/RomanticHarmony.pdf
In it, he goes from a vi6 chord (this 6 doesn't mean first inversion, it means the chord with an added major sixth, in this case spelled tonic-major sixth-minor third-fifth) to a I chord. I.e. from a Cm6 chord (spelled C-A-Eb-G) to Eb (spelled Bb-Bb-Eb-G).
I can't understand how this makes sense in the context of tonal harmony. Any help?
Comment: Oh, a half diminished seventh has the diminished fifth and the minor seventh. There should be a name for the chord with a minor third, perfect fifth, and diminished seventh.
Comment: @ToddWilcox -- "There should be a name for the chord with a minor third, perfect fifth, and diminished seventh": parallel with _minor major seventh_ would be _minor diminished seventh_.
Comment: @DavidBowling - reason I posted is that *minor major seventh* can't be the same as *minor diminished seventh*, as one has m7, the other d7, which gives a different note, not only in name, but sound. Agreed, the 'm6' could be 'md7', but not mM7.
Comment: I don't know a lot about this, but one thing that is immediately clear is the major sixth of the vi6 chord is a leading tone to the fifth degree of the tonic. Another question is why that's not called a half diminished 7th chord instead.
Comment: I'm not sure I understand, by diminished seventh you mean minor 7th?
Comment: A major 7th is 11 half steps. A minor seventh is 10 half steps. A diminished 7th is 9 half steps. A minor 6th is 8 half steps. A major 6th is 9 half steps. So a diminished 7th and a major 6th are the same interval. A *half diminished 7th chord* is a minor third, diminished 5th, and minor 7th, like C Eb Gb Bb. A *fully diminished 7th chord* is a minor 3rd, a diminished 5th, and diminished 7th, like C Eb Gb Bbb.
Comment: In the key of Eb major, the I chord is Eb G B**b**, not B natural.
Comment: That's embarrasing, fixed. I think what you call a diminished seventh is what I call a major sixth, thus the chord you describe is the minor 6 chord (in jazz guitar parlance).
Comment: C to A is a major 6th, C to Bbb is a diminished 7th. The fact that Bbb and A are enharmonic means that the two intervals sound the same, and we should all be calling it one or the other name depending on the musical context, and not just using one name or the other all the time based on an arbitrary preference. Anyway, with the correction to Bb the leading tone idea is in play and I'm sure that is at least part of the "resolution" feel that these two chords have.
Comment: @DavidBowling - when you say 'parallel with' do you mean 'it's another way of saying'? R m3 P5 =minor. Never seen a d7, but plenty of m6, so on A - A C E F# = Am6.    mM7 would be A C E G#.
Comment: @Tim -- by "parallel with _minor major seventh_ I mean parallel in nomenclature. A minor major seventh chord specifies triad quality, followed by the name of the seventh interval. I was just pointing out that if you wanted to keep the diminished seventh interval you could call A-C-E-G♭ a _minor diminished seventh_, following the same rules of nomenclature. Agree, I have never seen this before either and would in practice call it an Am6.
Comment: @Tim -- right. Didn't intend to be confusing; parallel in the way the chords are named, but _mM7_ and _m6_ are not at all the same chords. This was only a comment to "There should be a name for...." of ToddWilcox.
Answer: My guess is that he harmonized the 4th mode of Bb Major: the Eb lydian scale is a whole-tone tetrachord, a perfect fifth and a major tetrachord which gives us only two alterations Eb and Bb. In this case the vi chord would have a major 6th. Now i'm not sure vi6-I is a common modal cadence in Lydian (I would have thought II-I was) because the #IV degree (a half-diminished chord) is usually not used, nor is the raised fourth used as the fourth tone of a vi tetrad for that matter.
Answer: An alternative analysis is to treat the tonic in your specific instance as a passing second-inversion to IV. e.g.


Get time in filename save in word macro

Question: I have a word macro that is saving the doc as a pdf and emailing it.  The only problem is that it will overwrite itself on the network drive.  I can't figure out how to get the seconds into the filename with the code below.
Thanks for the help!
dte = Date
savedName = "Night Orders - " & Format(dte, "yyyy-mm-dd")

Response = MsgBox("Save and email the current document?", vbOKCancel, "Are you sure?")
    If Response = vbOK Then

        savePath = saveDir & saveName & ".pdf"
        ActiveDocument.ExportAsFixedFormat OutputFileName:=savePath, _
            ExportFormat:=wdExportFormatPDF, OpenAfterExport:=False, _
            OptimizeFor:=wdExportOptimizeForPrint, Range:=wdExportAllDocument, _
            From:=1, To:=1, Item:=wdExportDocumentContent, IncludeDocProps:=True, _
            KeepIRM:=True, CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
            BitmapMissingFonts:=True, UseISO19005_1:=False

Comment: Have you looked at the VBA function `Time`?
Answer: Try:
savedName = "Night Orders - " & Format(Now, "YYYY-MM-DD-hh-mm-ss")

Get time in filename save in word macro


Is there an upper hierarchical limit to the .htaccess file placement using virtual hosts?

Question: Question background:
I have an Apache 2.4 virtual host environment hosting multiple websites in the following Ubuntu file hierarchy:

/var/www/site-1-folder
/var/www/site-2-folder
/var/www/site-3-folder ...etc

There is a global .htaccess file in

/var/www

and individual .htaccess files in each

/var/www/site-folder

My question: Is there an upper hierarchical limit to the Apache's .htaccess file placement?
For example: Could I place a Wordpress .htaccess set of directives in the root /var/www folder and have it applied to all the sub-folders (being individual virutal sites running Wordpress)?
I am asking because directives set in the 'global' .htaccess file don't seem to work as expected and I would like to know if either my syntax is incorrect, it is not possible, or there is an alternative.
Thanks in advance!
Answer: All the htaccess files you put on your server, provided the config allows them to be applied will be effective. The only downside is that performance degrades as the depth of the tree and hence the number of locations where a htaccess file might be found, and the number of htaccess files relevant to a particular request increases.
A "global" htaccess file is an oxymoron if you have root on the server. You should be pushing as much of the config as possible into the config files which only need to be checked when the webserver starts up; htaccess files are for when you want to provide devolved access to configuration.
Comment: So if I understand correctly, I could migrate .htaccess directives applicable to **all** virtual hosts in **/etc/apache2/apache.conf** and directives pertaining to **individual** virtual hosts in each host's respective **.conf** file?
Comment: Yes….....…......
Comment: Perfect, I'll implement your recommendations- cheers!


Percentages and Averages

Question: I came across the following while doing some questions from my textbook.
For eg. lets say we need to calculate the total percentage of marks for the following subjects:

Maths   64/100
English 78/100
Science 30/50

Total percentage being calculated as (64+78+30)/250 =  68.8 %
The other method I followed was to calculate individual percentages and then take their average

Maths 64/100   = 64%
English 78/100 = 78%
Science 30/50  = 60%

Their average being (64+78+60)/3 = 67.33 %
I know by forming equations I can prove the second method is different from the first, but is there any logical statements that proves the second method is wrong and the first correct.
Comment: You might be interested in Simpson's paradox http://en.wikipedia.org/wiki/Simpson's_paradox
Comment: If the textbook has *defined* "total percentage" as the value computed by the first method, and if you are asked to compute "total percentage", then clearly you need to use the first method (because you've determined that the second gives a different answer). If you're asking which method is *more appropriate* to compute a value worthy of the term "total percentage", then --as @GerryMyerson says-- you must "confront the 'relative importance' question". Each formula says something useful about the data; you have to decide which is *more*-useful for your purposes.
Comment: Given that, as you've stated, the "total percentage" is calculated by the first method, then it must be "correct", right? You have an example for which the second method gives a different answer; that fact alone *proves* that the second formula is "wrong", right?
Comment: @DayLateDon I know the second formula is wrong, but is there any logical statement that says percentages shouldn't be calculated like this, that's what i want to know. I was trying for a shortcut in my exam by following the second method which proved wrong in the end.
Comment: One reason to *suspect* that the answers are going to be different (in general) is that the second formula depends on the number of subjects involved, while the first does not.
Comment: If you're just looking for an intuitive way to see the difference: suppose there are just two subjects. In the first, a student got a *million* points out of a *million*; in the second, she got *zero* points out of *one*. The first method takes into account that the first subject has a lot more weight, giving a "total percentage" of 99.9999%; the second method treats each subject equally, and since the student aced the first and tanked on the second, the method reports an average of 50%.
Comment: @MarkBennet That is seriously an interesting read. But then what method should we follow? Is there some "formal" way which says which method to follow, or is it up to us.
Comment: You have to decide whether it is "right" to treat the three subjects on an equal footing, or treat points earned in the three subjects on an equal footing. If Science is as important as English, then the second method is correct. If 1 mark in Science is equivalent to 1 mark in English (so Science overall is only half as important as English) then the first method is correct. And of course there are other possibilities. You can't say which method to follow until you confront the "relative importance" question.
Comment: @GerryMyerson The problem is this question is given in my textbook, where nothing is mentioned about how to "treat" subjects and points. Because the "conventional" way is to follow the first method, that's why second method is wrong.
Comment: @DayLateDon The text book hasn't defined anything, it just contains questions with respective answers, moreover it said to calculate overall percentage which is guess is the same as total percentage :)
Comment: If anyone is having you compute "overall percentage" without saying *exactly* what that phrase means, then you are well within your rights to be confused. To me, either of the methods you've given --not to mention, *lots* of others-- could reasonably be described as an "overall percentage"; neither is inherently "correct" or "wrong" in this role.
Comment: @DayLateDon that's the main problem, that is why my first thought was there "may" exist some formal text which says which method to follow.
Answer: In my opinion, the second method is a trick.
For the first method, we can simply get the answer is $$\frac{64+78+60}{250}=68.8\%.$$
For the second method, we get the average point of each subject like

Maths $\frac{64}{100}=64\%$
English $\frac{78}{100}=78\%$
Science $\frac{60}{50}=30\%$

Now, we should calculate the average in the following way
$$64\% \times\frac{100}{250}+78\% \times\frac{100}{250}+60\% \times\frac{50}{250}=68.6\%.$$
It called weighted average, and $\frac{100}{250},\frac{100}{250},\frac{50}{250}$ is called weights.
Answer: No, there exists no (meaningful) way to prove the second method wrong.  Science could get weighted twice as much as English and Maths, as in Science could come as twice as important as English and twice as important as Maths, in which case both methods yield the same result.
Comment: But i am getting different answers for the two
Comment: If science is weighted twice as much as the other two, then 50 points in the science category equals 100 in the other categories.  So, then, science percentage marks equal 60, and (((60+64)+78)/300)=.67333... the same result you got.  It will also yield the same result in general.

Percentages and Averages


Prove a fact about a mapping of complete poset to itself

Question: Let M be a poset such that any its totally ordered subset has an upper bound: $\forall U \subseteq M$, $U$ is totally ordered $\exists m \in M: \forall u \in U \ \ u \leq m$. And let $f: M \to M$ be a mapping such that $\forall x \in  M \ \ x \leq f(x) $
Prove that $\exists x_0 \in M: f(x_0)=x_0$
Looks a little scary for me, not sure how to approach the problem.
Comment: @drhab Thank you, I've fixed this.
Answer: HINT: Let $U$ be a totally ordered subset of $M$ that is maximal with respect to inclusion, and let $x_0$ be an upper bound for $U$. (You will have to justify the existence of $U$.)
Answer: Hints:
What can be proved here on base of the lemma of Zorn?
If $m\in M$ is a maximal element then what can be concluded from $m\leq f(m)$?


Move command from another directory

Question: I need to move a file from another directory.
Suppose you are in this directory:  /home/CurDic1
And my file is located in this directory: /usr/CurDic2
I need to write someting like this (I just made it up):
/usr/CurDic2:>cd /home/CurDic1 | mv file1.txt /home/CurDic1/SubDic1

Comment: So ... what language do you want to do that in?
Answer: mv path_to_source_file path_to_destination_file

Answer: You can add a full path to your move command. In your particular case, it will be :
mv /usr/CurDic2/file1.txt .

It is important to know that . is the current directory.
If you want to move to /home/CurDic1/SubDic1, you can do :
mv /usr/CurDic2/file1.txt /home/CurDic1/SubDic1/

Concerning your made up example, | is known as a "pipe" and it is used to redirect the output from the left command to the input of the right column. For example cat file.txt | less while redirect the content of file.txt to the less command which is used to scroll in long textual datas.
However you can do
cd /home/CurDic1; mv file1.txt /home/CurDic1/SubDic1

the ; is a command separator, it means that the first command will be executed and then the next one. You can chain many commands like this : cmd1; cmd2; cmd3; etc

Move command from another directory


Does position in array enumConstants from Class, correspondes to ordinal value of enum?

Question: I designed a generic method, to read/write Set of Enum values as BigInteger
My original implementation
public static <T extends Enum<T>> Set<T> asList(BigInteger integer, Class<T> targetClass) {
    Set<T> enums = new HashSet<T>();
    // Step 0. Sanity check
    if (targetClass == null || integer == null || !targetClass.isEnum())
        return enums;
    // Step 1. Checking each value of target class
    T[] values = targetClass.getEnumConstants();
    for (int i = 0; i < values.length; i++) {
        if (integer.testBit(i))
            enums.add(values[i]);
    }
    // Step 3. Returning final enums
    return enums;
}

But, I switched to :
  public static <T extends Enum<T>> Set<T> asSet(BigInteger integer, Class<T> targetClass) {
    Set<T> enums = new HashSet<T>();
    // Step 0. Sanity check
    if (targetClass == null || integer == null || !targetClass.isEnum())
        return enums;
    // Step 1. Checking each value of target class
    T[] values = targetClass.getEnumConstants();
    for (int i = 0; i < values.length; i++) {
        T value = values[i];
        if (integer.testBit(value.ordinal()))
            enums.add(value);
    }
    // Step 3. Returning final enums
    return enums;
}

I've done so because of Enum.ordinal description in documentation:
 * Returns the ordinal of this enumeration constant (its position
 * in its enum declaration, where the initial constant is assigned
 * an ordinal of zero).

So basically, first value might not always be 0.
In which cases, or on which JVM's does enum initial value is not 0?
Comment: How do you get from "where the initial constant is assigned an ordinal of zero" to "first value might not always be 0"?
Comment: Misread it. Now I see my error.
Answer: You say So basically, first value might not always be 0. how did you come to this conclusion?
The first enum constant always have a ordinal of 0. Of course if you change the order or add a new constant it will change for the same element. Which is why this is a bad idea.
Comment: Thanks, I misread the documentation. I read of zero as or zero, my bad.


How to group views rows by year using date field?

Question: I have a content type with a date field.
I need to output them grouping by year, i.e.
<code>2011

- nodeA 2011-09-01
- nodeB 2011-01-29

2010

- nodeC 2010-12-08
</code>
How can I do that?
Answer:
Add a second date field to the view.
In the configuration of that field

Configure the field to only display the year
Exclude the field from display

In the format settings of the view, group by this field.
Comment: I've already tried this one and it doesn't work. Apparently, the grouping goes over VALUES, not the output of a field.
Comment: This _almost_ worked for me as well, but I did need to follow the additional step given in @cdmo's answer.
Comment: Field is displayed in a "Year" format (Y), then in format settings it is set as a "grouping field". However the year is shown above each row, even when I set the dates to be exactly the same (sic!). My field exact type is "Date (ISO format)" - maybe that is wrong?
Comment: Are you rewriting the field, or using a pre-configured date format? The former will not work, but the latter definitely does.
Comment: See cdmo's comment below...
Answer: @phils suggestion needs an update: just strip html for the field (in the Rewrite Results section).  I can validate that this worked for me where @Oswald's solution did not.
Answer: Disable RDF-Module from Core.
Had the same problem and after searching for hours I finally stumpled upon this hint from KarenS: http://drupal.org/node/1253562#comment-4886998
Just disable the RDF-Module and maybe re-edit your date formats.


Compile error: A first chance exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll

Question: I am getting this error message on my form when it compiles. The form works and it operates as I want it, but the error keeps popping up.
Here is my source code:
Option Strict On
Option Explicit On

Public Class frmEnterMidPoint

    Dim Obj As New frmCustomRanges

    Private Sub txtMidPointValue_TextChanged(sender As Object, e As EventArgs) Handles txtMidPointValue.TextChanged

        'This event runs when the txtMidPointValue is changed.
        'it enables the clear button if it's not empty.

        If txtMidPointValue.Text = "" Then

            btnClear.Enabled = False

        Else

            btnClear.Enabled = True

        End If

    End Sub

    Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click

        'This event runs when the btnOk is pressed. The procedure takes the value
        'entered in the text box and converts to a decimal.  That value
        'is then sent to the frmCustomRanges form Mid label. The procedure
        'also calculates the hourly equivalent.

        'The procedure ends by closing the current form and opening
        'the frmCustomRanges form.

        If IsNumeric(txtMidPointValue.Text) Then

            'Convert number entered to decimal
            Dim decMidPointValue As Decimal = Convert.ToDecimal(txtMidPointValue.Text)

            'Display results as dollar sign for Annual and Hourly
            Obj.lblAnnualMid.Text = decMidPointValue.ToString("C")
            Obj.lblHourlyMid.Text = Convert.ToDecimal(decMidPointValue / 52 / 40).ToString("C")

            'Close current form
            Me.Close()

            'Open frmCustomRanges
            Obj.ShowDialog()

        Else

            MsgBox("You have entered a non-numeric value. Please check value and enter again", vbCritical, "Input Error")

            With txtMidPointValue
                .Text = ""
                .Focus()

            End With

        End If

    End Sub

    Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click

        'This event runs when the btnClear is clicked.
        'The event clears the textbox and sends the foucs
        'back to the textbox

        With txtMidPointValue
            .Text = ""
            .Focus()

        End With

    End Sub

    Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click

        'This even runs when the btnCancel is clicked.
        'The procedure closes the current form and opens the
        'Custom Ranges form.

        'Close current form
        Me.Close()

        'Open the Custom Ranges form
        Obj.ShowDialog()

    End Sub

End Class

Comment: How does the form work if it doesn't compile?
Comment: I'd guess that one of your `Convert.ToDecimal` is throwing the exception. Have you tried wrapping them in a try/catch to isolate where the error is coming from?
Comment: This will happen when you use IsNumeric() and the string is not.  The debugger is confusing you too much.  Right-click the Output window and untick "Exception messages".
Answer: You can use Decimal.TryParse - IsNumeric() is not necessarily the best choice for checking if something is a number which you can use.
Private Sub bnOK_Click(sender As Object, e As EventArgs) Handles bnOK.Click
    Dim decMidPointValue As Decimal
    If Decimal.TryParse(txtMidPointValue.Text, decMidPointValue) Then
        ' decMidPointValue contains the parsed value.
        Obj.lblAnnualMid.Text = decMidPointValue.ToString("C")
        Obj.lblHourlyMid.Text = (decMidPointValue / 52 / 40).ToString("C")
        ' more code...
    Else
        ' could not be parsed as a Decimal; decMidPointValue is zero.
        ' inform user.
    End If
End Sub

Comment: Thank you. I am still feeling my way through vb.net.  This was very helpful
Answer: Try to convert properly.
Dim dec As Decimal
If Decimal.TryParse(txtMidPointValue.Text, dec)
  'dec is now converted
Else
  'dec is not converted - tell the user
End If


Debugging: Run-Time Check Failure #2 - Stack around the variable 'LoggerThread' was corrupted

Question: Debugging: Run-Time Check Failure #2 - Stack around the variable 'LoggerThread' was corrupted.
I can't find a solution :( is there anyway to fix this.
#include <iostream>

using namespace std;

int main()
{
    string LoginMessage = "Please Login";
    string loginsuccess = "Login Correctly";
    float x = 0;
    char afpl[6][7] = {

        "A",
        "B",
        "C",
        "@",
        "*$",
        "$"
    };

    cout << LoginMessage << endl;

    float y = 10;
    cin >> x;

    int i = /* Would be random - */ 20;

    int finalx = x + y * i;
    int temp = finalx;
    int last = temp / i;
    if (last > 5) {
        last = last / 3;
    }

    cout << afpl[last] << "|" << last << "|" << finalx << endl;
    if (finalx == 210) {
        if (last == 3) {
            if (afpl[6][7] = '@') {
                cout << loginsuccess << endl;
            }
        }
    }

}

There is no warnings but just a ERROR , here is the output
'PythonVsCSVsC++.exe' (Win32): Loaded 'C:\Users\MYNAME\source\repos\PythonVsCSVsC++\Debug\PythonVsCSVsC++.exe'. Symbols loaded.
'PythonVsCSVsC++.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ntdll.dll'.
'PythonVsCSVsC++.exe' (Win32): Loaded 'C:\Windows\SysWOW64\kernel32.dll'.
'PythonVsCSVsC++.exe' (Win32): Loaded 'C:\Windows\SysWOW64\KernelBase.dll'.
'PythonVsCSVsC++.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msvcp140d.dll'.
'PythonVsCSVsC++.exe' (Win32): Loaded 'C:\Windows\SysWOW64\vcruntime140d.dll'.
'PythonVsCSVsC++.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ucrtbased.dll'.
The thread 0x188c has exited with code 0 (0x0).
Run-Time Check Failure #2 - Stack around the variable 'x' was corrupted.

How do i fix this issue, i tried finding the fix everywhere and all the solutions didn't fix my problem. Is there anyway to fix this this issue :), this is c++ by the way.
Comment: You have Undefined Behavior here: `if (afpl[6][7] = '@') {` because `afpl[6][7]` is outside of the bounds of your array.  Also, I imagine you meant `==` there instead of `=` (writing out of bounds is what's causing the corrupted stack).
Comment: Cleaned up your code formatting a bit :)
Answer: The line if (afpl[6][7] = '@') is assigning to afpl. I think you meant if (afpl[6][7] == '@'). Additionally afpl[6][7] is out of bounds. That's is undefined behavior and what's causing the corrupted stack (writing in to an incorrect memory location). The array index starts at 0.
Comment: Hey, Thanks! I forgot that the array index started from 0 haha! Thanks for the help! appreciate it!
Comment: @inhumꬰne. Remember to [mark his answer as accepted](https://meta.stackexchange.com/a/5235/510616) if you feel like it was helpful.
Comment: Sorry I'm kinda new to this platform.


Tree view filtering does not return all the files

Question: My tree view populated by folders and files. And I have used below code for filtering tree view but it does not return all the files that match string, just it returns one file.
For example letter "f" there is in 3 files but when I search it returns just 1 file.
private TreeNode FindNodeByValue(TreeNodeCollection nodes, string searchstring)
{

    // Loop through the tree node collection
    foreach (TreeNode node in nodes)
    {
        // Does the value match the search string?
        if (node.Value.ToUpper().Contains (searchstring.ToUpper()))
            // Yes it does match - return it
            return node;
        else
        {
            // No it does not match - search any child nodes of this node
            TreeNode childNode = SearchChildNodes(node, searchstring);
            // If the childNode is not null it was a match
            if (childNode != null)
                // Return the matching node
                return childNode;
        }
    }
    // If the matching node is not found return null
    return null;
}

///
/// This method searches a node's ChildNodes collection to find a matching value
/// with the incoming search string
/// It will iteratively call itself as it drills into each nodes child nodes (if present)
///
/// <param name="parentNode">Parent node to search for a match</param>
/// <param name="searchstring">string to be matched with the Nodes Value property</param>
/// <returns>Treenode of the matching node if found.  If not found it will be null</returns>
private TreeNode SearchChildNodes(TreeNode parentNode, string searchstring)
{
    // Loop through the child nodes of the parentNode passed in
    foreach (TreeNode node in parentNode.ChildNodes)
    {
        // Does the value match the search string?
        if (node.Value.ToUpper().Contains(searchstring.ToUpper()))
            // Yes it does match - return it
            return node;
        else
        {
            // No it does not match - recursively search any child nodes of this node
            TreeNode childNode = SearchChildNodes(node, searchstring);
            // If the childNode is not null it was a match
            if (childNode != null)
                // Return the matching node
                return childNode;
        }
    }
    // If the matching node is not found OR if there were no child nodes then return null
    return null;
}

protected void Button1_Click(object sender, EventArgs e)
{
    TreeNode trnode=FindNodeByValue(TreeView1.Nodes, fieldFilterTxtBx.Text);
    if (trnode != null)
    {
        TreeView1.Nodes.Clear();
      //  TreeNode newnode = new TreeNode("Detail Engineering");
       // TreeView1.Nodes.Add(newnode);
        TreeView1.Nodes.Add(trnode);
        TreeView1.ExpandAll();
    }
    else

{

Label1.Text = "No file found";

}

Answer: It is only returning one value because the function only calls itself recursively if no file is found. You need to add the recursion to this branch of the if statement in SearchChildNodes as well:
if (node.Value.ToUpper().Contains(searchstring.ToUpper()))
// Yes it does match - return it
    return node;
else

You also may need to add the filenames to an array or a Generic.List in order to store more than one at a time.
Comment: thanks,just one file found, is it possible send complete code about how to store more than one in array or generic list
Comment: I'm not going to send complete code, but you would do it where you are calling "FindNodeByValue." You can create a generic.list the same way that you would create any other variable, and then use the instance method ".Add()" to add each value.


Como usar iReport com Oracle?

Question: Estou tendo problemas para adicionar o driver Oracle no iReport Designer, tentei seguir alguns tutoriais, porém não obtive êxito.
Então a minha dúvida é, como eu faço para adicionar e realizar as configurações necessárias para o driver Oracle?
Observação: tente seguir esses passos:
http://community.jaspersoft.com/wiki/connecting-ireport-oracle-datasource
https://www.youtube.com/watch?v=aWePwTz1knI
edit erro:
Answer: Eu geralmente faço assim:

Vou na opção Ferramentas na barra de menus;

Depois na opção IReport e na aba Classpath

Depois clico em adicionar Jars, ai você localiza o driver do oracle. Localizado e adicionado, clica em ok

Após isso, ao você tentar adicionar uma conexão com driver oracle, ele estará habilitado.

Aí você coloca os dados de conexão
Isso é o que eu faço
Espero ter ajudado
Comment: Os dados de conexão variam de empresa para empresa: é só você preencher de acordo com sua necessidade, por exemplo: `jdbc:oracle:thin:@ip-do-servidor:1521:nome-do-banco-ou-servico` No campo Endereço do Servidor (**Server Address**), você o coloca o ip do seu servidor, no **Database**, o nome do banco ou serviço, e finalmente o login e a senha   e clica em test ou save
Comment: verifique também seu tsname
Comment: eu tentei simular o erro e consegui mudando alguma coisa, por exemplo, mudei a porta e deu esse mesmo erro, verifique com detalhe, o nome do banco, a porta, o servidor, enfim.
Comment: Legal!, que bom que funcionou
Comment: poderia me mostrar os dados de conexão também ? Estou tendo o erro: Exception

Message:
    java.sql.SQLException: Listener refused the connection with the following error:
ORA-12505, TNS:listener does not currently know of SID given in connect descriptor
Comment: Eu tentei fazer como você sugeriu, ainda não consegui, eu editei a pergunta e adicionei uma imagem para ilustrar o erro, se você puder olhar e me dar um novo "parecer" a respeito.
Comment: obrigado, funcionou !

Como usar iReport com Oracle?


Ignore the warning less of swap partition while preseed loading

Question: I have the automatisation debian preseed script. Here is partition rules with sharps for swap in my preseed file:
<code>!d-i partman-auto/expert_recipe string                         \
      boot-crypto ::                                          \
              512 512 512  ext2                               \
                      $primary{ }                             \
                      $bootable{ }                            \
                      method{ format } format{ }             \
                      use_filesystem{ } filesystem{ ext2 }    \
                      mountpoint{ /boot }                     \
              .                                               \
              1000 20 2000 ext4                             \
                      $defaultignore{ }                       \
                      $lvmok{ } lv_name{ opt }               \
                      in_vg { kaktusvolumegroup }              \
                      method{ format } format{  }             \
                      use_filesystem{ } filesystem{ ext4 }    \
                      mountpoint{ /opt }                      \
              .                                               \
              1000 20 2000 ext4                             \
                      $defaultignore{ }                       \
                      $lvmok{ } lv_name{ home }               \
                      in_vg { kaktusvolumegroup }              \
                      method{ format } format{  }             \
                      use_filesystem{ } filesystem{ ext4 }    \
                      mountpoint{ /home }                      \
              .                                               \
              8000 80 8000 ext4                             \
                      $defaultignore{ }                       \
                      $primary{ }                             \
                      method{ format } format{  }             \
                      use_filesystem{ } filesystem{ ext4 }    \
                      mountpoint{ / }                         \
              .
        #      1024 60 1024 swap                             \
        #             $defaultignore{ }                       \
        #              method{ swap } format{  }             \
        #      .

</code>

How to go through that yes\no question and not use typing?
Answer: The solution is to add to preseed-file:
<code>d-i partman-basicfilesystems/no_swap boolean false
</code>


Sum of a series using squeeze theorem

Question: How do I find using the Squeeze theorem
$$\lim_{n\to \infty}\sum_{k=1}^n \frac{1}{\sqrt{n^2+k}} \;,$$
using the fact that
$$ \lim_{n\to \infty}\frac{n}{\sqrt{n^2+n}}=1.$$
Thank you very much for your help,
C.G
Answer: Note that
$$\frac{1}{\sqrt{n^2+1}}+\frac{1}{\sqrt{n^2+2}}+\cdots+\frac{1}{\sqrt{n^2+n}}\leq \frac{n}{\sqrt{n^2+1}}$$
because $\sqrt{n^2+1}\leq\sqrt{n^2+k}$ for $k\geq1$.
On the other hand, by a similar reasoning,  using that $\sqrt{n^2+n}\geq\sqrt{n^2+k}$ for $k\geq1$:
$$\frac{n}{\sqrt{n^2+n}}\leq\frac{1}{\sqrt{n^2+1}}+\frac{1}{\sqrt{n^2+2}}+\cdots+\frac{1}{\sqrt{n^2+n}}$$
so in the end,
$$\frac{n}{\sqrt{n^2+n}}\leq \sum_{k=1}^n \frac{1}{\sqrt{n^2+k}}\leq \frac{n}{\sqrt{n^2+1}}$$
and use that $$\lim_{n} \frac{n}{\sqrt{n^2+n}}=1=\lim_{n} \frac{n}{\sqrt{n^2+1}}$$
Comment: Slight mistake in the numerator of the last summation.

Sum of a series using squeeze theorem


Increasing sequence and converging to zero.

Question: Suppose that $x_{0}$ is between $(-1,0)$ and
$$x_{n} = \sqrt{x_{n+1} + 1} - 1$$
for all natural $n$. Prove that  $x_{n}$ is increasing and converging to zero as $n$ grows.
Can someone please help me start this problem?
Thank you.
Comment: Induction to prove it is increasing
Comment: Shouldn't the equation be $-x_n = \sqrt{x_{n+1}+1}$? Otherwise $x_{n+1}$ is not defined for $x_n \lt 0$.
Comment: the sequence is x_n = √ [x_(n+1) +1] - 1. I forgot to put minus 1 after the radical.
Answer: To prove $x_n$ is increasing:
\begin{align*}
x_n &= \sqrt{x_{n+1}-1} \implies x_{n+1} = (x_n+1)^2 - 1 = x_n^2 + 2x_n \\
\implies x_{n+1} - x_n &= x_n(x_n+1) > 0 \qquad \text{where $-1 \lt x_n \lt 0$} \end{align*}
Also, if $x_n$ converges to $x$ we have $$x = \sqrt{x+1}-1 \implies x^2 -x = 0 \implies x = 0 \text{ or } -1$$
And from above work we have $x_{n+1} = x_n(x_n + 2) \lt 0$ for all $-1 \lt x_n \lt 0$.
So $x_n$ is increasing and bounded and thus converges to $0$ when $-1 \lt x_0 \lt 0$


Desempenho em uma tela com 26 formulários

Question: Tenho 26 formulários em uma única tela (Tela Geral) por causa de problemas que estava tendo (aqui). Eu uso uma galeria para chamar um formulário específico pelo título.

O problema é que quando preciso entrar na tela (Tela Geral) onde estão os 26 formulários, ocorre uma grande lentidão.
Não gostaria de ter que voltar a trabalhar com a forma anterior que usava, que eram 26 telas, uma para cada formulário (por causa do problema de rolagem citado no link acima), mas acabou causando essa lentidão inesperada.
Conversamos um pouco na comunidade da Microsoft sobre isso e também coloquei no Stack Overflow em inglês tentando obter novas respostas. Se houver novas ideias/resoluções, fico agradecido.
Answer: No final, foi preferível antes da Tela Geral ter uma tela com 26 botões. Resolvido.


TypeError: this constructor takes no arguments (python)

Question: I made the left file to import from right
but I don't know why I got this error: see image
Comment: Post your code in your question with proper format so we can copy and paste it. Don't post an image of code.
Answer: Instead of __int__, use __init__.
The Python class tutorial is a good syntax reference.
Comment: ty for helpThanks for help
The error was in __init__
Instead of __int__


RDF file not uploaded in virtuoso

Question: I am trying to single upload an .rdf file to virtuoso with the ld_dir command, as follows:
ld_dir('/home', 'filename.rdf', 'http://domain.example/TEST');

The operation seems to be done, although it takes 1 msec; which is not logical.. however when I try to view the content of the grapgh using:
SELECT * FROM <http://domain.example/TEST> WHERE {?p ?o ?s}

it just does not display any results.
Performing the same query on another graph brings out results.
Comment: "Performing the same query on another graph brings out results." Another graph loaded in the same way? "The operation seems to be done, although it takes 1 msec"  I'd be surprised if there's a file named `/home` on a Unix-like system.  That's where the home directories are.  The documentation on [ld_dir](http://docs.openlinksw.com/virtuoso/fn_ld_dir.html) says that it loads all files matching the file mask.  (The example is `ld_dir ('/data8/2848260', '%.gz', 'http://bsbm.org');`.)  I bet you don't have any `/home/filename.rdf`, so it completes very quickly, but you see no data.
Answer: ld_dir command will only bring RDF file's path into the awareness of Virtuoso. It won't make Virtuoso to start 'ingesting' the RDF file. Here are the commands to be typed inside isql console :
code ld_dir('/home', 'filename.rdf', 'http://domain.example/TEST');
set isolation='uncommitted';
rdf_loader_run();

It is the rdf_loader_run(); command which does the trick. And this command took lots of time (already running since few minutes) on my machine - than just 1ms
Source The complete tutorial on RDF data ingestion in Virtuoso

RDF file not uploaded in virtuoso


What is the intuition behind the expected transaction value for a customer in the gamma-gamma model?

Question: Background and Motivation: I was reading the paper RFM and CLV: Using Iso-Value Curves for Customer Base Analysis by Peter S. Fader, Bruce G. S. Hardie and Ka Lok Lee, in an attempt to gain some intuition behind the methods available in software libraries such as lifetimes and BTYD. The paper presents a way to incorporate RFM models in customer lifetime value calculations by using the gamma-gamma model for spend per transaction.
Problem: In the paper, the following formula, to calculate the expected average transaction value for a customer with an average spend of $m_x$ across $x$ transactions, is presented in Eq  4 (p.12):
$$
\begin{align}
\mathbb{E}(M\mid p, q, \gamma, m_x, x) & = \frac{(\gamma + m_xx)p}{px+q-1}\\
& = \bigg(\frac{q-1}{px+q-1}\bigg)\frac{\gamma p}{q-1}+\bigg(\frac{px}{px+q-1}\bigg)m_x\\
\end{align}
$$
I understand that the $q$ parameter is used as the shape parameter in the underlying gamma distribution that models the heterogeneity in mean transaction values across customers, but I'm unable to grasp its effect on the expected average transaction value for a given customer.
Namely, I was able to fit a gamma-gamma model with $q < 1$ and the expected average transaction value for certain customers evaluates to a negative value.
Question: Does the fact that I get negative values for expected transaction values expose some issues with the underlying dataset used to fit the model?
Do models with $q < 1$ make sense, and if so, what should I interpret from a negative expected average transaction value?
Answer: This is a (super) late answer, but I myself was looking for some information related to gamma-gamma models for monetary value, and came across this. The short answer is yes, the negative values for expected transaction values exposes issues with the underlying dataset used to fit the model.
In case it is helpful for you or others with similar questions, I'll try to illustrate why it's concerning to have $q<1$. The purpose of these spend models is to understand observed spend per transaction with the goal of predicting future spend per transaction at the individual level. The use of a gamma distribution was first proposed by Colombo and Jiang (1999) and was motivated by the observation that if transactions are distributed normal, then 1) it is not bounded below by $0$ for any choice of mean and variance parameters, and 2) you get symmetric spend distributions, when the observed data consistently appears to be right skewed.
Following the paper you refer to, a customer with $x$ transactions values $z_1,\dots,z_x$ is modeled such that $z_i \sim \text{Gamma}(p,\nu),$ and we allow for heterogeneity across customers by also having that $\nu \sim \text{Gamma}(q,\gamma)$. A key observation is that conditional on $p$ and $\nu$, a customer's mean transaction value $\delta$ is $\delta = p/\nu$. Now $\nu$ varies across customers, so you may want to know what the mean transaction value $\delta$ is across all individuals. Denote this random variable $D$. It can be shown that
$$E[D|p,q,\gamma] = \frac{p\gamma}{q-1}$$
which says that the mean transaction value for customers is $\frac{p\gamma}{q-1}$ (showing this is a bit involved, but the way to do it is to derive the distribution and show it is an inverse-gamma distribution with specific parameters and find the expected value given that). In any gamma distribution, the parameters are strictly positive, so $p>0,\gamma >0$, so if you have $q<1$, then it must be that the expected transaction value across individuals is negative.
This should be pause for concern: why is the expected transaction value negative? You can try to validate this by thinking of compensating individuals for each transaction, but this is quite odd and there are other models if this is the kind of situation you are dealing with, and so the fact that your model finds $q<1$ should immediately raise some serious concerns for this reason alone.
As a final point, I think it's nice to better understand
$$
\begin{align}
\mathbb{E}(M\mid p, q, \gamma, m_x, x) & = \frac{(\gamma + m_xx)p}{px+q-1}\\
& = \bigg(\frac{q-1}{px+q-1}\bigg)\frac{\gamma p}{q-1}+\bigg(\frac{px}{px+q-1}\bigg)m_x\\
\end{align}
$$
as noting that it is simply the weighted average of the population mean transaction value $E[D|p,q,\gamma] = \frac{p\gamma}{q-1}$ and the observed average transaction value $m_x = \frac{1}{x}\sum_{i=1}^x z_i$ of a given customer, and the weightings can be fully understood from a bayesian framework as having a prior (the mean average transaction value), and the weight you place on it goes down as you observe more data $x$ on an given individual!


Showing every prime ideal is maximal.

Question: I need help with this question number 8, at least some hints or approaches to start with. Sorry for posting an image, I am only doing so , because I don't have a pc to type the question in latex and I don't know how to do so using mobile in any other way.
Comment: I'm voting to close this question as off-topic because this is not a do-my-homework site.
Comment: @ravenchaser This is a highly duplicated question on the site. I found the suggested duplicate (out of a large cluster of duplicates) by searching "finite dimensional prime maximal."  Next time, please try something similar first.
Comment: Also, please remember to include the [source of the problems](https://www.isical.ac.in/~admission/IsiAdmission2017/PreviousQuestion/MMath-PMB-2017.pdf).
Comment: I am sorry but this isn't a homework, I am appearing in an exam and this is one of the 2018 exam paper questions. Should I send you the website link for clarification ?
Comment: https://www.isical.ac.in/~admission/IsiAdmission2017/PreviousQuestion/Questions-MMath.html
Comment: Here is the link of their previous year questions...and assumption is a weak argument.
Answer: Hint:
Consider a prime ideal $\mathfrak p$ of $R$. Observe that $R/\mathfrak p$ is a finite-dimensional $k$-vector space. It is a consequence of the following result, which you can prove:

Let $A\subset B$  be integral domains such that $B$ is a finitely generated $A$-module. Then $A$ is a field if and only if $B$ is a field.

Edit: You can adapt the proof of the left-to-right implication to your context. Here's how:
All you have to show is that any  non-zero element $\bar r\in R/\mathfrak p$ has a reciprocal. So consider multiplication by $\bar r$ in the quotient. Observe it is $k$-linear and injective. Furthermore $R/\mathfrak p$ is finite dimensional. What can you conclude from these elements?
Comment: I haven't studied modules since it was not in my bachelor's syllabus. Is there any other way that involve only ring theory and different integral domain chapters, including field extensions or linear algebra ,without the use of modules ? For example, can I somehow show this is an Principal ideal Domain since every prime ideal is maximal in it ?
Comment: Unfortunately, tere are plenty of examples where it isn't a P.I.D. You only need  $\rightarrow$ for your question. I'll add some more details in a moment.
Answer: If $D$ is an integral domain which is finite dimensional over some subfield
$k \subset D, \tag 1$
that is,
$\dim_k D = n < \infty, \tag 2$
then $D$ is in fact a field.  For given
$0 \ne u \in D, \tag 3$
the set of the first $n$ powers of $u$
$S = \{1_D, u, u^2, \ldots, u^n \} = \{ u^k, \; 0 \le k \le n, \; k \in \Bbb Z \} \subset D, \tag 4$
must contain a linearly dependent subset by virtue of (2); thus there exist
$\alpha_i \in k, \; 0 \le i \le n, \tag 5$
not all $0$, such that
$\displaystyle \sum_0^n \alpha_i u^i = 0; \tag 6$
thus we have
$p(x) = \displaystyle \sum_0^n \alpha_i x^i \in k[x] \tag 7$
with
$p(u) = 0; \tag 8$
now granted that such polynomials exist, we may choose
$m(x) = \displaystyle \sum_0^{\deg m} m_i x^i \in k[x], \; m(u) = 0, \tag 9$
of minimal degree amongst all such $p(x)$; for such $m(x)$,
$m_0 \ne 0 \tag{10}$
lest we write
$m(x) = x \displaystyle \sum_1^{\deg m} m_i x^{i - 1}, \tag{11}$
and hence
$u \displaystyle \sum_1^{\deg m} m_i u^{i - 1} = m(u) = 0, \tag{12}$
which since $u \ne 0$ implies
$\displaystyle \sum_1^{\deg m} m_i u^{i - 1} = 0, \tag{13}$
i.e., $u$ is a zero of
$g(x) = \displaystyle \sum_1^{\deg m} m_i x^{i - 1} \in k[x], \tag{14}$
which contradicts the mininality of the degree of $m(x)$ amongst polynomials satisfied by $u$; thus
$m_0 \ne 0, \tag{15}$
and we have
$\displaystyle \sum_0^{\deg m} m_i u^i = 0, \tag{16}$
or
$u\displaystyle \sum_1^{\deg m} m_i u^{i - 1} = \sum_1^{\deg m} m_i u^i = -m_0, \tag{17}$
whence
$u \left (-m_0^{-1}
\displaystyle \sum_1^{\deg m} m_i u^{i - 1} \right ) = 1, \tag{18}$
that is,
$u^{-1} = -m_0^{-1} \displaystyle \sum_1^{\deg m} m_i u^{i - 1}; \tag{19}$
since every $0 \ne u \in D$ is invertible, we conclude that $D$ is a field; indeed, a field extension of $k$.
We apply this result to the present situation as follows:  if $P$ is prime in $D$, then $D/P$ is an integral domain, and (2) implies
$\dim_k D/P < \infty, \tag{20}$
as well; thus by what we have done above, $D/P$ is a field and hence $P$ is maximal in $D$. $OE\Delta$.
Nota Bene: I must say in closing that if I were writing this proof as an answer to an exam (see comnents to the question itself), I would certainly find a way to make it shorter!  End of Note.
Comment: Thank you for the nice proof. At point (6) can't we conclude u is an unit from there ? I mean, if we expand the summation, and use the fact, that the constant term isn't 0, then it's an unit being an element of K, and if the constant term was 0, then we can take " u" common and apply the same recursive process, eventually each coefficient will be a constant term and they can't be all zero since the combination is not linearly independent.
Comment: @ravenchaser:  well, by the time you've done what you suggested you've basically done what I did--the point is, you have to get to the minimal degree polynomial to ensure the constant term isn't zero.  If you wrote your proof out, it would I think be about as long as mine!  Anyway, thanks for the kind words and also for the "acceptance"!  Cheers!

Showing every prime ideal is maximal.


Fermat's Little Theorem - Reducing Exponents

Question: Just search for the string Reducing Exponents on this page.
In the example it says $7^{147} = ((7^{10})^{14}) \cdot (7^7)$
And since $(7^{10}) \mod 11 = 1$,
$((7^{10})^{14})\cdot(7^7) \mod 11 = (7^7) \mod 11$
How?
Can some please explain?
Because $(a \cdot b) \mod N \neq (a \mod N) \cdot(b \mod N)$ then how does the
above result occur?
Comment: You need to reduce mod N all the way.  (a*b) mod N = ((a mod N) * (b mod N)) mod N.
Comment: Also I really wish "mod" was never ever ever used to denote a function from $\mathbb N$ to $\mathbb N$.
Comment: @Ted Really, you need to look at equivalence classes rather than elements of $\mathbb N$.
Comment: See also the answers to [this question.](http://math.stackexchange.com/questions/64590/distributivity-mod-an-integer)
Comment: @BillDubuque Thanks for the link, that's what I wanted.
Comment: What? $(ab\mod N)=(a\mod N)(b\mod N)$.
Comment: @Ted Thanks a lot.
Answer: Here $7$ and $11$ are relatively prime, and also both $a$ and $b$ are powers of $7$.
Fermats little theorem says that if $p$ is a prime number, then for any integer $a$, $a$ and $p − a$ will be evenly divisible by $p$. This can be expressed in the notation of modular arithmetic as follows:
$$ a^p \hspace{4pt}\equiv \hspace{4pt} a (mod \hspace{4pt} p ) $$  OR
$$ a^{(p-1)} \hspace{4pt}\equiv \hspace{4pt} 1 (mod \hspace{4pt} p ) $$
Applying that to $a=7$ and $p=11$, to get $7^{10} \hspace{4pt} \equiv \hspace{4pt} 1 (mod \hspace{4pt} 11 ) $
Another way to look at $7^{147}$ is by applying $7^{10} \hspace{5pt} 14$ times, one would get $7^{140}$ as $1 (mod \hspace{4pt} 11 )$. What is remaining now is $7^7$ and therefore
$$7^{147} \equiv 7^7 (mod \hspace{4pt} 11 ) $$
An even better way to understand this is
$$ 7^{147}-7^7 = 7^7(7^{140}-1) \equiv 7^7 (mod \hspace{4pt}11)$$
$$

\begin{matrix}
7^2 & \equiv & 5 (mod \hspace{4pt}11)\cr
7^3 & \equiv & 2 (mod \hspace{4pt}11)\cr
7^4 & \equiv & 3 (mod \hspace{4pt}11)\cr
7^5 & \equiv & 10 (mod \hspace{4pt}11)\cr
7^6 & \equiv & 4 (mod \hspace{4pt}11)\cr
7^7 & \equiv & 6 (mod \hspace{4pt}11)\cr
7^8 & \equiv & 9 (mod \hspace{4pt}11)\cr
7^9 & \equiv & 8 (mod \hspace{4pt}11)\cr
7^{10} & \equiv & 1 (mod \hspace{4pt}11)\cr
7^{11}& \equiv & 7 (mod \hspace{4pt}11)\cr
7^{12}& \equiv & 7^{2} (mod \hspace{4pt}11)\cr
\end{matrix}

$$
and if you keep going this way, it cycles back to $7^{147} \equiv 7^{7} \equiv 6 (mod \hspace{4pt} 11)$
Answer: $$7^{10}\equiv1(\mod 11)$$
So,
$$(7^{10})^{14}\equiv1^{14}(\mod 11)$$
Which is:
$$(7^{10})^{14}\equiv1(\mod 11)$$
Multiplying by $7^7$, we get:
$$(7^{10})^{14}(7^7)\equiv1\cdot 7^7(\mod 11)$$
or:
$$(7^{10})^{14}(7^7)\equiv 7^7(\mod 11)$$


Get cron to process QueueWorker items at a specific time

Question: I have a Plugin\QueueWorker that creates a queue of emails to send from nodes that are created/updated throughout the day. I've defined a processItem() method, as well as an arbitrary function (let's call it mymodule_add_to_queue()) that runs $queue->createItem() to add the node to the queue. When cron runs, all the items in the queue get run, which is fine and dandy.
The only problem is that cron is running every hour, and it seems the QueueWorker class will run the process every time, when I only want it to run once, say between 2am and 3am.
I have the code that checks the REQUEST_TIME and the state of the last time it ran and all that, however I don't know where to put it. Even if it goes into hook_cron(), it doesn't appear to make any difference to the default behaviour.
Pseudocode for what kind of thing I'd be expecting to happen is:
<?php

// @file src/Plugin/QueueWorker/MyModuleCronQueueWorkerEmailSend.php
class MyModuleCronQueueWorkerEmailSend extends QueueWorkerBase {
  public function __construct () {
    this.auto_cron = FALSE;
  }
  public function processItem() {
    doSomething();
  }
}

// @file mymodule.module
function mymodule_add_to_queue() {
  $queue = \Drupal::queue('mymodule_queue_worker_email_send');
  $queue->createItem(['foo' => 'bar']);
}

function mymodule_cron() {
  if (some_cron_conditionals()) {
    $queue = \Drupal::queue('mymodule_queue_worker_email_send');
    $queue->process();
  }
}

... this may be completely out of scope though, or there may be a really obvious other method I'm missing. Any thoughts? As always, thanks in advance :)
Answer: Copied from \Drupal\Core\Annotation\QueueWorker, the annotation and placd where the @QueueWorker annotation is documented.
 * Worker plugins are used by some queues for processing the individual items
 * in the queue. In that case, the ID of the worker plugin needs to match the
 * machine name of a queue, so that you can retrieve the queue back end by
 * calling \Drupal\Core\Queue\QueueFactory::get($plugin_id).
 *
 * \Drupal\Core\Cron::processQueues() processes queues that use workers; they
 * can also be processed outside of the cron process.
 *
 * Some queues do not use worker plugins: you can create queues, add items to
 * them, claim them, etc. without using a QueueWorker plugin. However, you will
 * need to take care of processing the items in the queue in that case. You can
 * look at \Drupal\Core\Cron::processQueues() for an example of how to process
 * a queue that uses workers, and adapt it to your queue.

See the last paragraph, the solution is simply to just fill an arbitrary queue and then implement similar logic as Cron::processQueues() for your queue to process the items when you want. Nothing will happen automatically with items of a queue that doesn't have a worker plugin.
Instead of a plugin, you can implement your login in a service instead and call that from your own cron implementation.
Comment: Thanks, that may be a good idea. Is there a simple example you know of of approaching it this way? I can't see anything internally that implements `QueueInterface`, but that seems like the right place to be looking.
Comment: Oh just noticed it's probably about extending `DatabaseQueue`
Comment: I've made an edit to your answer, hope that's okay.
Comment: You should not have to implement anything like that. Just get a queue instance with \Drupal::queue('yourmodule_foobar'); and then use ->createItem() on that. And then in your cron hook, claimItem() and process them.
Answer: Try using https://www.drupal.org/project/ultimate_cron, which should give you a fine-grained control over when each cron task runs.


Template file is not overriding drupal 7 defaults

Question: Why node--type.tpl.php is not working? I've cleared drupal cache 100 times no results. Is there something else i must to do?
Answer: Overriding node templates are done by placing node--'nodetype'.tpl.php templates inside your custom theme folder.
If the template isn't accepted after cache clear, check if the Machine name on admin/structure/types is the same as 'nodetype'.
Answer: Make sure you put node--underscores_between_words.tpl.php and saved it in your active theme directory.
Comment: in my case its news content type. i've used node--news.tpl.php and its not working
Comment: are you trying to style the page or the nodes?
Comment: im trying to style the node. page--front.tpl.php and so works as intended, but node--type.tpl.php not...
Comment: maybe try node--news--page.tpl.php or try node--idnumber.php
Comment: Is the Machine name corresponding to the type on the tpl.php file?
Comment: just noticed machine name was _news. Why drupal it adds by default?
Answer: To override the node templates using node--type.tpl.php in your theme you need to also make sure that your theme overrides the system node.tpl.php template; this can just be a copy of the system node.tpl.php file in your theme if you don't wish to change it. Without it, any other node templates in your theme will be ignored.


def keyword vs rocket ( => ) notation changes function behavior in scala?

Question: I'm in the process of learning Scala and I am trying to understand the reason behind the first method of defining the function throws an error that "+", "v1" and "v2" are not found while the second method listed below works.
Method 1: - using Lambda expressions notation:
val addVectLambda = (v1:Vect3,v2:Vect3):Vect3 => (v1._1 + v2._1, v1._2 + v2._2, v1._3 + v2._3)

Method 2: - using the def keyword:
def addVect (v1:Vect3, v2:Vect3):Vect3 = (v1._1 + v2._1, v1._2 + v2._2, v1._3 + v2._3)

I apologize if this question has been asked already - I've tried to search but couldn't find an answer. Truly appreciate any help / guidance.
Thanks
EDIT: Full code that produces the error message:
type Vect3 = (Double, Double, Double)
val addVectLambda = (v1:Vect3,v2:Vect3):Vect3 => (v1._1 + v2._1, v1._2 + v2._2, v1._3 + v2._3)

The error message:
error: not found: type +
val addVectLambda = (v1:Vect3,v2:Vect3):Vect3 => (v1._1 + v2._1, v1._2 + v2._2, v1._3 + v2._3)
                                                        ^
error: not found: type +
val addVectLambda = (v1:Vect3,v2:Vect3):Vect3 => (v1._1 + v2._1, v1._2 + v2._2, v1._3 + v2._3)
                                                                       ^
error: not found: type +
val addVectLambda = (v1:Vect3,v2:Vect3):Vect3 => (v1._1 + v2._1, v1._2 + v2._2, v1._3 + v2._3)
                                                                                ^
error: not found: value v1
val addVectLambda = (v1:Vect3,v2:Vect3):Vect3 => (v1._1 + v2._1, v1._2 + v2._2, v1._3 + v2._3)
                     ^
error: not found: value v2
val addVectLambda = (v1:Vect3,v2:Vect3):Vect3 => (v1._1 + v2._1, v1._2 + v2._2, v1._3 + v2._3)
                              ^

Answer: That's a bizarre error message that you've got there, but it's hardly your fault... I will first give a simple explanation of what's wrong with your first code snippet, and then I will discuss the strange error message that it produces.

If you wanted to write down a lambda, you would have to do it like this:
type V3 = (Double, Double, Double)
val add = (a: V3, b: V3) => (a._1 + b._1, a._2 + b._2, a._3 + b._3)

If you wanted to ascribe the return type explicitly, you would have to add the type ascription on the right hand side:
val add2 = (a: V3, b: V3) => ((a._1 + b._1, a._2 + b._2, a._3 + b._3) : V3)

another alternative would be to ascribe the type of add3 explicitly:
val add3: (V3, V3) => V3 =
  (a: V3, b: V3) => (a._1 + b._1, a._2 + b._2, a._3 + b._3)

Those are your choices. Just stick to the valid syntax for lambdas, and you should be fine.

What follows now is an explanation of why the weird error message makes sense. However, to understand the explanation, one should know at least about type constructors, type members, rules for infix notation, and implicit conversions.

If you mistakenly try to append the return type right after the arguments of the lambda:
val broken = (a: V3, b: V3): V3 => (a._1 + b._1, a._2 + b._2, a._3 + b._3)

you get a bunch of errors
error: not found: type +

On the first glance, the entire expression seems completely invalid. It is not obvious why this expression should survive the parsing stage of the compilation. However, this is not a compiler bug. We can indeed invent a (fairly contrived) set of definitions such that the above expression becomes valid. Here is one possibility:
import scala.language.implicitConversions
trait +[A, B]
class R
class V3 {
  type _1 = R
  type _2 = R
  type _3 = R
}
val a = new V3
val b = new V3

implicit def conversion(i: (V3, V3)): (V3 => (R + R, R + R, R + R)) = {
  v: V3 =>
  (new +[R, R]{}, new +[R, R]{}, new +[R, R]{})
}

val notBroken = (a: V3, b: V3): V3 => (a._1 + b._1, a._2 + b._2, a._3 + b._3)

println(notBroken)

Here the right hand side of notBroken looks essentially the same as the uncompilable (non)-lambda in your question. However, this is perfectly valid Scala code, and it even runs.
What's going on here:

+ is a binary type constructor written in infix notation
_1 ... _3 are type members of the class V3, set to R
a and b are instances of V3
there is a completely insane implicit conversion from (V3, V3) to the really ugly function type V3 => (R + R, R + R, R + R)
the V3 => (a._1 + b._1, ... , ...) part right from the colon is not a lambda, it's a type ascription
the type ascription forces the implicit conversion

So, it's valid, though, admittedly, not very helpful in less contrived use cases.