Node translation syncing problem with entity references

Question: I have a content type with multilingual support (node translation). This content type also has an entity reference (module: entityreference) field.
My content is:
/node/1 English story 1
/node/2 French  story 1 (translation of #1)
/node/3 English story 2 with reference to #1
/node/4 French  story 2 (translation of #3) **entityreference problem here**

I've configured the reference to be synchronized. The problem is that whenever I translate or edit a node, it'll try to sync the reference to other translations.
So I'll always end up with:
#3 -> #1 (correct)
#4 -> #1 (wrong)

or:
#3 -> #2 (wrong)
#4 -> #2 (correct)

I can solve this by disabling syncing on the reference field but then I will have to be maintaining the references for all translations manually which is a problem in a website with many translations.
Answer: Had the same problem, wrote this little workaround:
function YOURMODULE_i18n_sync_translation($entity_type, $translation, $translation_language, $source, $source_language, $field_names) {
  foreach ($field_names as $field_name) {
    $info = field_info_field($field_name);
    if ($info['type'] == 'entityreference') {
      $items = field_get_items($entity_type, $source, $field_name);
      foreach ($items as $delta => $item) {
        $translations = translation_node_get_translations($item['target_id']);
        if (isset($translations[$translation_language])) {
          list($id, $vid, $bundle) = entity_extract_ids($entity_type, (object) $translations[$translation_language]);
          $translation->{$field_name}['und'][$delta]['target_id'] = $id;
        }
      }
    }
  }

Comment: Note that it works well when changing the source node.
Answer: You should try module "Synchronize entity references" (i18n_entityreference) from project Internationalization contributions (i18n_contrib). So far, for me it looks perfect. It even works with inline entity form widgets.
To install and use it:

Install and enable the module. If you use drush:
drush dl i18n_contrib && drush en i18n_entityreference

(This requires the core module i18n_sync and will enable it automatically if not already done. It is needed for synchronizing field values across translations.)
Configure "Synchronize translations". Basically go to "Structure → Content Types → [your content type]" in the admin menu, switch to tab "Synchronize translations", select your node reference field, and save. See here for details.
Use. If you have existing content, the node reference field will be synced in a language-aware way when you save any node of a translation set for the next time.
Comment: Thanks. Will try this out asap and get back to you. Wondering how it'll play together with https://www.drupal.org/project/cer
Answer: There's a module for that: https://drupal.org/project/i18n_node_reference

Provides i18n field synchronisation for a node_reference field.
The referenced nodes are translated into the correct language. If no
  such language exists, it is ignored. This is the same functionality as
  is supported by the taxonomy reference translation in i18n_taxonomy.
Comment: I use the `entityreference` and not `references` module. So this doesn't apply in my case.
Answer: The code snippet in the second answer won't work when editing the reference in a translation. That's because translation_node_get_translations() accepts a tnid as argument, not a nid. Check the api docs.
Change the call in the above code to something like this and it should work (for nodes only, in this case):
$referenced_node = node_load($item['target_id']);
$translations = translation_node_get_translations($referenced_node->tnid);

NOTE: I couldn't comment on the other answer, so i'm posting this one.


Equations of significance probabilities

Question: Consider a population of independent light bulbs with an exponential
lifetime distribution with mean $\mu$. It is claimed that their expected
lifetime is 1000 hours. A definition of a 100(1−$\alpha$)% confidence interval
obtained from an observation t0 is the set of all $\mu_0$ which are not rejected
in a test of a null hypothesis  $\mu$= $\mu_0$ against an alternative hypothesis $\mu$$\neq$$\mu_0$.

One particular light bulb fails after 622 hours. Solve the equations of
the two significance probabilities Pr(T ≥ 622 |$\mu_0$) = 0.05 (for a test
of  $\mu$= $\mu_0$ versus $\mu$> $\mu_0$) and Pr(T ≤ 622 |$\mu_0$) = 0.05 (for a test of
$\mu$= $\mu_0$ versus $\mu$< $\mu_0$) for $\mu$. Determine the range of values of $\mu$  such
that both of the probabilities Pr(T ≥ 622 | $\mu$) and Pr(T ≤ 622 |$\mu$) are
at least 0.05. (This range gives an equi-tailed 90% confidence interval
for $\mu$.)

I don't seem to understand what they mean by 'solve the equations'. Do I have to find a specific value for T or compute Pr(T ≥ 622 |$\mu_0$), Pr(T ≤ 622 |$\mu_0$)  and compare with 0.05? I believe I will get the second part after I understand this bit.
Answer: I also found the wording somewhat difficult.
For the first problem, you need to find the value of $\mu_0$ such that an exponentially distributed random variable $T$ with mean $\mu_0$ has probability $0.05$ of being $\ge 622$. You probably know what the preceding sentence means. But to make sure, we sketch the calculation.
An exponentially distributed rv with mean $\mu_0$ has density function $\frac{1}{\mu}e^{-t/\mu_0}$ (for $t\ge 0$), and therefore cdf $1-e^{-t/\mu_0}$. So the probability that $T\ge 622$ is $e^{-622/\mu_0}$.
Set this equal to $0.05$ and solve for $\mu_0$.
For the second problem, we want to find $\mu_0$ such that an exponential $T$ with mean $\mu_0$ is $\le 622$ with probability $0.05$.
The range for $\mu_0$ that you will get from the two calculations turns out to be very large. Basically that says you can't learn much about the mean lifetime of lightbulbs by observing a single one.
Comment: It now seems rather simple! Thank you!
Comment: You are welcome. Confidence intervals, and tests at significance level $\alpha$, are quite subtle notions. It will take some time before you are fully comfortable with them.

Equations of significance probabilities


error with JRMP connection establishment

Question: I am getting following exception trace :
java.rmi.ConnectIOException: error during JRMP connection establishment; nested exception is:
    java.net.SocketTimeoutException: Read timed out
    at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:293)
    at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:190)

I read some forums on this but not getting clarity on the root cause of this exception. Is this due to one of the following reasons?

Insufficient memory.
RMI calls getting failed due to increased number of requests to the server causing one               of them to wait and causing time outs for this request to process.
Incompatible jre version or anything related to JRE version.
Any networking related issue.
Firewall related.
Comment: Maybe yes. Try to eliminate some of them by making experiments.
Comment: Which one of the above options best relates to the cause of exception?Any idea on this?
Comment: Hard to say without more information. Do you always get this error or does it sometimes work? Can you ping the remote machine?
Answer:

Insufficient memory.

Not at the client. Possibly at the server, if it causes a failure to allocate a thread for example.

RMI calls getting failed due to increased number of requests to the server causing one of them to wait and causing time outs for this request to process.

No. The error occurs during the connection establishment phase, long before the server-side method implementation gets invoked.

incompatible jre version or anything related to JRE version.

No.

Any networking related issue.

Yes.

Firewall related.

No. That would cause a connect timeout, or in certain obsolete cases a connection refusal, not a read timeout.
Comment: It could certainly be firewall related. Not all firewalls work the same way. I know it makes much more sense to block the connection, but I've seen plenty of cases where firewalls allow a connection and then block the traffic.
Comment: @davmac I would consider that broken.
Answer: I have the same error at client side. Server is reachable and I can open the port via telnet.
When I watched into it with Wireshark on client and server side I see the following:

TCP connection is established

SYN

SYN, ACK

ACK

Client sends: JRMI, Version 2, Stream Protocol

Server reply:  JRMI, ProtocolAck - But this package never reached client side

In my case issue is the connection from MagicDraw client to license server. For other colleages at other locations it helps to use the proxy:
http.proxyHost=xxxx -Dhttp.proxyPort=8080 and the client communicats via HTTP. So maybe this could help you to ommit this issue.
https://docs.oracle.com/javase/7/docs/platform/rmi/spec/rmi-arch6.html
I can not be specific as I don't have access to the source code of Magic Draw.
Answer: I get this error in the case, when a SSH-Client from outside the LAN, holding the SSH-Server, is trying to connect to the server and RMI is involved to let the client execute RMI-methods on the server.
The reason is the unreachability (missing route) of the server.
Seems that all the stated cases are related to that reason.


Is it possible to check and set wx.html2 to use WebKit on Windows?

Question: Is it possible to do a combination of a check and a engine-switch on Windows for wx.html2 in wxPython 126.96.36.199 (development version)?
What I want to achieve is; to let the wx.html2 library use WebKit on Windows if Safari, Chrome or Opera (WebKit/Blink) is installed.
Does anyone have any experience with this and maybe how to achieve it? I also wonder where wx.html2 looks for the engine on each OS and how it asks to render it.
I tried using wx.webkit. But there are so many issues like; lack of documentation and the implementation of the object seems to break on different operating systems.
Comment: The wx phoenix documents give some information on the backends. http://wxpython.org/Phoenix/docs/html/html2.WebView.html#html2-webview
Answer: How does wxPython know to use Webkit? It doesn't, it's parent library, wxWidgets does a compile-time check. It assumes Webkit is installed if it's built on Mac or Linux, and assumes IE is installed if it's on Windows.
If you really want WebKit/Blink, then perhaps consider CEFPython, an embedded Chrome. There's an example at that link of a (very simple) wxPython application.


Convergence of $a_n=1+1/5+1/9+\ldots+\frac{1}{4n-3}$

Question: Show that the sequence $$a_n=1+1/5+1/9+\ldots+\frac{1}{4n-3}$$ does not converge but the sequence $b_n=\frac{a_n}{n}$ converges.
I can show the first part. For the second part, will it be sufficient to just show that $$\lim \frac{a_n}{n}=0?$$
Comment: All you need to show is that $\frac{a_n}{n}$ converges, so it has *some* limit. If you can actually show that $0$ is the limit, you showed convergence as well.
Comment: Yes.${}{}{}{}{}$
Comment: @Christoph so simply showing that $\lim_{n->\infty}\frac{1}{n}(1+1/5+1/9+\ldots+\frac{1}{4n-3})=0$ should be enough ?
Answer: Just note that

$$ a_n = \sum_{i=1}^{n} \frac{1}{4i-3} \sim \int_{1}^{n+1} \frac{dx}{4x-3}=\dots.  $$

For the other one

$$\lim_{n\to \infty} \frac{a_n}{n} \sim \lim_{n\to \infty}\frac{\int_{1}^{n+1} \frac{dx}{4x-3}}{n},  $$

you can use L'hopital's rule.
Comment: @MohammadKhosravi: Thanks for the edit.
Answer: Apply Cesaro-Stolz's theorem for $x_n = \dfrac{1}{4n-3}$, and note that : $b_n = \dfrac{x_1 + x_2 +...+ x_n}{n}$
Answer: An elementary proof: Let $b_n = a_n/n$. Then
$$
b_{n+1} = \frac{n}{n+1}b_n + \frac{1}{4n+1}.
$$
First prove by induction that $\frac{n+1}{n(4n+1)}< b_n$ and then deduce that $0<b_{n+1}< b_n$. Therefore the sequence is bounded below and decreasing, so it is convergent.
Answer: note that $a_{{n}}=\sum _{k=1}^{n}{ \frac{1}{4k-3}}$, then
$\sum _{k=1}^{n}{ \frac{1}{4k-3}}=\frac{1}{4}\sum _{k=1}^{n}{ \frac{1}{k-\frac{3}{4}}}$
$>\frac{1}{4}\sum _{k=1}^{n}{ \frac{1}{k}}$
and the last series is the harmonic series, which does not converge. Therefore $a_{{n}}$ does not converge. Similarily, $b_{{n}}=\frac{1}{4}\sum _{k=1}^{n}{ \frac{1}{n(k-\frac{3}{4})}}$, and
$\frac{1}{4}\sum _{k=1}^{n}{ \frac{1}{n(k-\frac{3}{4})}}<\frac{1}{4}\sum _{k=1}^{n}{ \frac{1}{(k-\frac{3}{4})^2}}=\frac{1}{4}\sum _{k=2}^{n}{ \frac{1}{(k-\frac{3}{4})^2}}+4<\frac{1}{4}\sum_{k=1}^{n}{\frac{1}{k^2}}+4$
and the last series converges. Therefore $b_{{n}}$ also converges.
Comment: It just said that $b_n$ is bounded, How do you deduce that it is convergent?
Comment: $b_{{n}}$ is positive for all $n$, so $b_{{n}}>0$. Together with the fact that $b_{{n}}$ is bounded from above by a positive quantity, we can deduce that it is convergent.
Comment: No! For example if $b_n = 2+(-1)^n$, then $ 1\le b_n\le 3$, it is bounded from above and below, but not convergent!


How to find closed form of a binomial series.

Question: When working on a problem, I needed to find the closed form of the infinite sequence:
$$1 - 2x + 3x^2 - 4x^3 + \cdots$$
I struggled with this for a while and eventually found, through the Internet, that it is equal to $(1+x)^{-2}$.
How could I have approached this in such a way that I would have arrived at the answer myself?
Comment: Just to say, this is not a sequence, but a series.
Answer: There are many ways to get the function from this series. One is to use negative binomial coefficients:
$$
\begin{align}
\sum_{k=0}^\infty(-1)^k\binom{k+1}{1}x^k
&=\sum_{k=0}^\infty(-1)^k\binom{k+1}{k}x^k\\
&=\sum_{k=0}^\infty\binom{-2}{k}x^k\\[4pt]
&=(1+x)^{-2}
\end{align}
$$

Another method would be to subtract the geometric series
$$
\frac1{1+x}=1-x+x^2-x^3+x^4-x^5+\dots
$$
to get
$$
\begin{align}
f(x)-\frac1{1+x}
&=-x+2x^2-3x^3+4x^4-\dots\\
&=-xf(x)
\end{align}
$$
Solving for $f(x)$ gives
$$
f(x)=\frac1{(1+x)^2}
$$
Answer: Method 1.  Differentiate
$$1-x+x^2-x^3+\cdots=\frac1{1+x}\ .$$
Method 2.  Write the sum out this way:
$$\eqalign{
  1-x+x^2-x^3+x^4-\cdots&\cr
  {}-x+x^2-x^3+x^4-\cdots&\cr
  {}+x^2-x^3+x^4-\cdots&\cr
  {}-x^3+x^4-\cdots&\ .\cr}$$
Adding up the first row, then the second and so on by geometric series gives
$$\frac1{1+x}-\frac{x}{1+x}+\frac{x^2}{1+x}-\frac{x^3}{1+x}+\cdots$$
which is another geometric series.
Answer: Let's kick it old school, like Euler - by which I mean blindly manipulate infinite series to reach correct solutions.
Okay, we have the series:
$$A=1-2x+3x^2-4x^3+\ldots.$$
then we think, hey, all those increasing terms are annoying. Notice that $Ax$ is basically shifts the coefficients of $A$, and, since the signs alternate, adding each coefficient to the one after it is going eliminate that annoying increasing-nature of that sum and leave just some residue about the common differences.
So, let's set:
$$B=A+Ax=1-x+x^2-x^3+x^4+\ldots.$$
We see that we have an alternating pattern of coefficients of $1$ and $-1$ - and hey, doing the same thing as before, we can get rid of all the coefficients by adding each coefficient to the next! So, let's do the same thing:
$$B+Bx = 1-0x+0x^2+\ldots = 1.$$
That's a constant! We can work with a constant! So, how did we get there? Well,
$$B=(1+x)A$$
$$1=(1+x)B$$
so
$$1=(1+x)^2 A$$
implying$$\frac{1}{(1+x)^2}=A.$$
What's the takeaway? Well, if you have some funky series, you can try to reduce it by looking at patterns and trying to simplify them (esp. by taking differences between terms - we can use similar methods to relate this to more general generating functions). And if you have an identity you want to prove, think about what defines that number - $\frac{1}{(1+x)^2}$ is the number which, when multiplied by $(1+x)^2$, yields one.
(Okay, all these manipulations are pretty easy to justify as we're working with absolutely convergent series, so it's not real old-school math...)
Comment: What an extremely ironical use of the term "blindly manipulating infinite series". I'm not sure if you're aware, but Euler was actually almost completely blind for the last 17 years of his life.
Answer: Hint
Integrate term by term to obtain a geometric series (this is allowed inside of the convergence radius of the series).
Answer: We can try to find the Taylor Series expansion (http://mathworld.wolfram.com/TaylorSeries.html) about $0$ (also known as a Maclaurin Series (http://mathworld.wolfram.com/MaclaurinSeries.html)) of $(1+x)^{-2}$:
$$\frac{d}{dx} (1+x)^{-2}=-2(1+x)^{-3}\;\;\;\;\;\;\;\;\frac{d^2}{dx^2}(1+x)^{-2}=6(1+x)^{-4}$$
In general:
$$\frac{d^n}{dx^n}(1+x)^{-2}=(-1)^n(n+1)!(1+x)^{-(n+2)}$$
Hence
$$\frac{d^n}{dx^n}(1+x)^{-2}\Big|_{x=0}=(-1)^n(n+1)!$$
Now:
$$(1+x)^{-2}=\sum_{n=0}^{\infty}\frac{d^n}{dx^n}(1+x)^{-2}\Big|_{x=0}\frac{x^n}{n!}=\sum_{n=0}^{\infty}(-1)^n\frac{(n+1)!}{n!}x^n=\sum_{n=0}^{\infty}(-1)^n (n+1)x^n$$
$$=1-2x+3x^2-4x^3+\cdots$$
As we wanted.
Answer: $\begin{aligned} \displaystyle \sum_{k=0}^{\infty} (-1)^{k}(k+1)x^{k} & =\sum_{k=0}^{\infty} \sum_{j=0}^{k}(-1)^{k}x^{k} \\& = \sum_{k=0}^{\infty} \sum_{j=0}^{k}(-1)^{k-j}(-1)^jx^{j}x^{k-j} \\& = \bigg(\sum_{k=0}^{\infty}(-1)^kx^k\bigg)\bigg(\sum_{k=0}^{\infty}(-1)^kx^k\bigg) \\& = \bigg(\frac{1}{1+x}\bigg)\bigg(\frac{1}{1+x}\bigg) \\& = \frac{1}{(1+x)^2}.\end{aligned} $


Private data in node format

Question: The Overall Plan
I'm creating a staff "portal" area for a non-profit. In the future I want to migrate the current static front-end website to Drupal, so I thought it would make sense to develop this portal area as a custom module into the back-end Drupal administration.
About the custom module
The non-profit provides a Child Sponsorship program, allowing supporters to pay a monthly fee which pays the school fees for children in East Africa. So the idea of the portal will be that it will reduce the administration of staff by holding the sponsorship database online. The database is split into two: children who are sponsored and children on the waiting list.  So I want to produce a module where each child is effectively a node. The node will contain sensitive information such as DOB, Address, School Exam Results etc and so isn't AT ALL for public viewing.
However, that when a child is added to the waiting list, a short bio will feed into the front-end website allowing them to be sponsored. This is one reason for trying to build it into Drupal from the beginning. In the future, it is also planned that when a user goes onto the front-end website, chooses a child to sponsor, they will be made a 'user' in Drupal, and given the ability to view certain information about their child such as a school report.
Questions
Is it conventional use of Drupal to build a module specifically for internal use where primarily the data is not for the public or front-end website? Is it an appropriate use?
To me it makes sense that each child functions as a node of content type 'child', however I'm worried about making them actual nodes.....as I said the data is private, and Drupal currently sets node public at URL node/{nid} What is the best solution moving forward with creating this database within Drupal? Could I make an equivalent 'node' style format?
Comment: It's a very appropriate use of Drupal to maintain data that is not meant for public or front-end website use. The idea of roles aids greatly in maintaining levels of access to data in Drupal (anonymous users get one level of access, authenticated users another, admin users a third, and you can add more roles as necessary). If, in the future, you decide you need even finer grained control, [Organic Groups](http://drupal.org/project/og) is great for breaking users and content into groups with a second layer of roles. It doesn't sound necessary for your project, but it's a good system to learn.
Answer: Drupal only sets node/nid as public when you give anonymous users permission to "access content". Additionally, you can use modules like http://drupal.org/project/content_access to specify what roles can access specific content types. Lastly, you can use http://drupal.org/project/field_permissions to specify what roles have access to specific fields on your nodes.
To answer your other questions, I don't think you need to write any custom modules to cover these needs and using Drupal to provide content only to privileged members is a very common use case.

Private data in node format


Posso escrever o ajax e javascript juntos?

Question: algum problema de escrever javascript e ajax juntos pois ambos são escritos dentro das tags  ?
Está ligado com esta questão
Posso por exemplo dentro das tags escrever uma função em javascript e depois uma funçao em ajax?
vem na continuidade desta questão Posso escrever em JavaScript dentro de PHP?
Por bem achei util listar as minhas perguntas semelhantes
Posso escrever em JavaScript dentro de PHP?
Posso fazer o JavaScript escrever PHP?
Comment: Como assim "escrever javascript e ajax juntos"? Ajax é JavaScript...
Comment: AJAX é uma tecnologia que se utiliza do JS, ela não é outra linguagem: https://pt.wikipedia.org/wiki/AJAX_(programa%C3%A7%C3%A3o) Então a pergunta não faz sentido.
Comment: E caso ainda não esteja claro, você nunca "escreve ajax", escreve sempre javascript. O javascript pode envolver ajax (pense em ajax como uma operação), ou não.
Comment: **Atenção** javascript não é = ajax, `XMLHttpRequest` (o ajax) é uma *API* do javascript, então ao "escrever ajax", você já está fazendo javascript, assim como o `FileReader` é outra *API* do javascript.
Comment: Amigo, a definição de AJAX é Asynchronous Javascript and XML, ou seja, Ajax é Javascript, reformule sua pergunta para que fique mais fácil entender o que deseja fazer.
Comment: Respondeu à minha pergunta então javascript = ajax com outras funçoes
Comment: Um pouco de conteúdo sobre ... http://www.linhadecodigo.com.br/artigo/3585/ajax-basico-introducao.aspx
Comment: Bastava teres pesquisado _"Ajax ou Javascript"_ no google, e terias a resposta.
Answer: AJAX é JavaScript, é uma sigla que quer dizer Asynchronous JavaScript and XML, JavaScript e XML assincrono.
Quer seja AJAX nativo (com as ferramentas nativas do JavaScript) ou com a camada abstrata de uma biblioteca como o jQuery, MooTools, Angular ou outra, é JavaScript na mesma. Uma biblioteca pode dar mais métodos e ferramentas mas é tudo escrito em JavaScript.
Assim escrever JavaScript dentro de tags  é correto e consequentemente AJAX também.


Javax validation - constraint composition

Question: i have a little problem with implementing properly my own validation annotation.
Here is sample code:
@Pattern(regexp="[0-9]*")
@Size(min=3, max=10)
@Constraint(validatedBy = SampleValidator.class)
@Documented
@Target({ANNOTATION_TYPE, METHOD, FIELD, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
public @interface MyAnnotation {

    String message() default "Wrong!";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};

    @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
    @Retention(RUNTIME)
    @Documented
    @interface List {
        MyAnnotation[] value();
    }

}

My problem is, I want my annotation to work in the way, that @Size and @Pattern annotation run first and if they're valid then (and only then) run validator provided by @Constraint annotation (SampleValidator.class).
Put it simple:

I want to run SampleValidator only if @Pattern and @Size are valid

(I implementes SampleValidator just as additional validator that should be called only in some specific circumstances)
How can I obtain such behaviour?
Thanks in advance!
Obviously, I can't do anything like that:
@GroupSequence({ Step1.class, Step2.class })
@Constraint(validatedBy = SampleValidator.class, groups = Step1.class) // no 'groups' attribute
@Size(min=3, max=10, groups = Step2.class)
@Pattern(regexp="[0-9]*", groups = Step2.class)
@Documented
@Target({ANNOTATION_TYPE, METHOD, FIELD, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
public @interface MyAnnotation {
    ...
}

Answer: Try adding the @ReportAsSingleViolation annotation.  According to the specification:
"More specifically, if a composed constraint is marked as @ReportAsSingleViolation, the evaluation of the composing constraints stops at the first failing constraint and the error report corresponding to the composed constraint is generated and returned."
http://beanvalidation.org/1.1/spec/#constraintsdefinitionimplementation-constraintcomposition
Answer: The answer is only partly correct. Yes @ReportAsSingleViolation that only one single violations will be generated and validation will stop after first failure in this case. However, the specification gives no guarantee in which order constraints are evaluated. It could be the composing constraints first or the validator specified via @Constraint. If anything you would rely on some implementation detail which could change any time. Also there is no order defined in which @Size and @Pattern are evaluated. Bottom line, you cannot achieve your wanted behaviour with constraint composition.
If you want to guarantee a sequenced execution you need to look at the GroupSequence feature.
Comment: Thanks Hardy, for your response. I don't consider 'GroupSequence' as an proper solution (i did think about using it) but problem with the annotation is : there's no 'groups' attribute in 'Constraint' annotation. 'GroupSequence' would be useful in case of 'Pattern' / 'Size' (those two has 'groups' attribute) validation order, but not Size / Constraint order.
Comment: I am not quite following what you are saying. All constraints support the group attribute. A group attribute is required as per Bean Validation specification. GroupSequences is so far the only way in Bean Validation to enforce a validation order. Anything else would rely on some Bean Validation provider interna.
Comment: I added some extra lines in my post that depicts my point. Regards :)


gnuplot/ awk: ploating bar graph for filtered data

Question: I am using gnuplot combined with AWK to plot 2D bar plot from the following input data:
#Acceptor                DonorH           Donor   Frames         Frac      AvgDist       AvgAng
lig_608@O3          HIE_163@HE2     HIE_163@NE2      498       0.5304       2.8317     153.0580
lig_608@O             GLU_166@H       GLU_166@N      476       0.5069       2.8858     161.7174
lig_608@O1           HIE_41@HE2      HIE_41@NE2      450       0.4792       2.8484     158.5193
THR_26@O             lig_608@H9      lig_608@N1      399       0.4249       2.8312     149.9578
lig_608@O2             THR_26@H        THR_26@N      312       0.3323       2.9029     164.8033
lig_608@O1         ASN_142@HD21     ASN_142@ND2       14       0.0149       2.8445     158.4224
lig_608@O1         GLN_189@HE22     GLN_189@NE2        2       0.0021       2.8562     149.7421
lig_608@O1         GLN_189@HE21     GLN_189@NE2        1       0.0011       2.7285     158.4377
lig_608@O3            GLY_143@H       GLY_143@N        1       0.0011       2.7421     147.8213

My script takes the data from the third and 5th columns considering only the lines where the value from the 5th column > 0.05, producing bar graph
cat <<EOS | gnuplot > graph.png
set term pngcairo size 800,600
set xtics noenhanced
set xlabel "Fraction, %"
set ylabel "H-bond donor, residue"
set key off
set style fill solid 0.5
set boxwidth 0.9
plot "<awk 'NR == 1 || \$5 > 0.05' $file" using 0:5:xtic(3) with boxes
EOS

!EDITED:
within my bash workflow the script looks like
for file in "${output}"/${target}*.log ; do
 file_name3=$(basename "$file")
 file_name2="${file_name3/.log/}"
 file_name="${file_name2/${target}_/}"
echo "vizualisation with Gnuplot!"
cat <<EOS | gnuplot > ${output}/${file_name2}.png
set title "$file_name" font "Century,22" textcolor "#b8860b"
set tics font "Helvetica,12"
#set term pngcairo size 1280,960
set term pngcairo size 800,600
set yrange [0:1]
set xtics noenhanced
set xlabel "Fraction, %"
set ylabel "H-bond donor, residue"
set key off
set style fill solid 0.5
set boxwidth 0.9
plot "<awk 'NR == 1 || \$5 > 0.05' $file" using 0:5:xtic(3) with boxes
EOS
done

This is the image produced from following filtered data:
HIE_163@NE2 0.5304
GLU_166@N 0.5069
HIE_41@NE2 0.4792
lig_608@N1 0.4249
THR_26@N 0.3323

I need to modify my awk searching expression integrated in the
gnuplot that makes selection of the two columns from the whole data.
Instead of taking the index from the third column (Donor) from each
line I need to take it either from the first (#Acceptor) or form the
third (#Donor) column. The index should be taken from one of these
columns depending on the lig_* pattern. E.g. if the data in the
(#Acceptor) column starts from lig* I need to take the value from the
third column (#Donor) of the same line and visa verse (lig* pattern
presents either in the 1st column or in the 3rd but not in the both..)
Taking my example, the filtered data with the updated searching should become:

HIE_163@NE2 0.5304 # the first index from the third column
GLU_166@N 0.5069 # the first index from the third column
HIE_41@NE2 0.4792 # the first index from the third column
THR_26@O 0.4249 # !!!! the first index from the first column !!
THR_26@N 0.3323 # the first index from the third column

Answer: No need for awk, you can do it all in gnuplot (hence platform-independent).
This would be my first attempt. You will filter by plotting the unwanted data at x-value of NaN, however, this will give some warnings: warning: add_tic_user: list sort error which you can ignore.
But this can probably be avoided by some changes.
Edit: the original script would have failed when the first line had a value <0.05 in column 5. Here are two versions which don't have this problem. There will also be no warnings. Maybe these attempts can be further simplified.
For creating an output file simply add this to your script: (check help output)
set term pngcairo size 800,600
set output "myOutputFile.png"

...<your script>...

set output

Data: SO73961783.dat
#Acceptor                DonorH           Donor   Frames         Frac      AvgDist       AvgAng
lig_608@O3          HIE_163@HE2     HIE_163@NE2      498       0.5304       2.8317     153.0580
lig_608@O             GLU_166@H       GLU_166@N      476       0.5069       2.8858     161.7174
lig_608@O1           HIE_41@HE2      HIE_41@NE2      450       0.4792       2.8484     158.5193
THR_26@O             lig_608@H9      lig_608@N1      399       0.4249       2.8312     149.9578
lig_608@O2             THR_26@H        THR_26@N      312       0.3323       2.9029     164.8033
lig_608@O1         ASN_142@HD21     ASN_142@ND2       14       0.0149       2.8445     158.4224
lig_608@O1         GLN_189@HE22     GLN_189@NE2        2       0.0021       2.8562     149.7421
lig_608@O1         GLN_189@HE21     GLN_189@NE2        1       0.0011       2.7285     158.4377
lig_608@O3            GLY_143@H       GLY_143@N        1       0.0011       2.7421     147.8213

Script 1:
Filter your data and write it into a new table. If condition >0.05 is not met, write an empty line. Probably the easiest to understand and gives the shortest final plot command.
### conditional xtic labels
reset session
set termoption noenhanced

FILE = "SO73961783.dat"

set xlabel "Fraction, %"
set ylabel "H-bond donor, residue"
set key off
set style fill solid 0.5
set boxwidth 0.9
set grid y
set xrange[-1:5]

set table $Filtered
    myTic(col1,col2) = strcol(col1)[1:3] eq 'lig' ? strcol(col2) : strcol(col1)
    plot FILE u ((y0=column(5))>0.05 ? sprintf("%g %s",y0,myTic(1,3)) : '') w table
unset table

plot $Filtered u 0:1:xtic(2) w boxes
### end of script

Script 2:
Without extra table, but a more complex plot command. Increase the x-position x0 if a value>0.05 is found (except for the first time) and keep the previous position and and label (i.e. overwrite it) if a value<=0.05 is found.
### conditional xtic labels
reset session
set termoption noenhanced

FILE = "SO73961783.dat"

set xlabel "Fraction, %"
set ylabel "H-bond donor, residue"
set key off
set style fill solid 0.5
set boxwidth 0.9
set grid y
set xrange[-1:5]

myTic(col1,col2) = strcol(col1)[1:3] eq 'lig' ? strcol(col2) : strcol(col1)

plot x0=c=(t0='',0) FILE u ((y0=column(5))>0.05 ? (c==0 ? (c=1,t0=myTic(1,3)) : (x0=x0+1,t0=myTic(1,3))) : (y0=NaN),x0):(y0):xtic(t0) w boxes
### end of script

Result:
Comment: @JamesStarlight actually, I just noticed that the current script above will fail if the first line of your list has a value<0.05 in the 5th column. I will add a more robust solution, and also from input file to output file.
Comment: @JamesStarlight sorry, I am not familiar with bash. I would have to make wild guesses which I cannot test myself since (so far) I am not working under Linux.
Comment: @JamesStarlight probably you can do it all in gnuplot. But I do not fully understand what your bash script is actually doing. Maybe plotting all `.log` files in a directory and create `.png` files for each of them. Then this is maybe be helpful if you want to do it in gnuplot: https://stackoverflow.com/q/67716946/7295599
Comment: @JamesStarlight there are a few examples here on SO. In your case something like `plot $Filtered u 0:1:xtic(2) w boxes, '' 0:1:1 w labels offset 0,1`.
Comment: @JamesStarlight sorry, I forgot the `using` or `u` in the second plot command:  `plot $Filtered u 0:1:xtic(2) w boxes, '' u 0:1:1 w labels offset 0,1`
Comment: The return value of the myTic function returns a string of column data, but should return an integer representing the column number to pass the value to xtic().
Comment: @binzo in principle yes, but have you tried instead `myTic(col1,col2) = strcol(col1)[1:3] eq 'lig' ? col2 : col1`? Although the function is returning a column number it will not place the xtic from the corresponding column, for some reason which is not fully clear to me. The argument of `xtic()` may also contain a string.
Comment: hey many thanks for this elegant sollution! would it be possible to show a version of the script which load a file (from bash) and save it e.g. using file.png as it was shown in my first example? Actually this is my first experience with the gnuplot so ..
Comment: thank you! may you just show a one more example in the similar format which I demonstrated in my first topic beginining with cat < output.png in order that I could understand how to manipulate it within my bash workflow?
Comment: right, thank you! I've just updated my first topic demonstrating how it works in the linux shell :-)
Comment: hey, finally I could integrate you first version in my bash workflow and it seems to me that it works. just one question would it be possible to add the Y values directly above the bars on the plot (e.g. in the first version) ? ;-)
Comment: gnuplot> plot $Filtered u 0:1:xtic(2) w boxes, '' 0:1:1 w labels offset 0,1
                                                  ^
         line 0: unexpected or unrecognized token
Comment: Thank you very much my fried! I have another question related to gnuplot visualisation of bar plots but I will create a new topic in order thet you may share there with your experiences
Comment: here it's, I believe the question might be very trivial for person experienced with gnuplot :-) https://stackoverflow.com/questions/73976330/gnuplot-sort-bars-on-the-bar-graphs
Answer: As you potentially want to do more complicated processing with awk, I would
suggest an alternative way of mixing awk and gnuplot.
Gnuplot supports including inline data in its script files, so you could have awk generate the inline data while supplying the plot-configuration with bash, all done in a sub-shell. For example:
(
printf '$data << EOD\n'

awk 'NR>1 && $5>0.05 { print $1 ~ /^lig/ ? $3 : $1, $5 }' infile

cat << EOS
EOD

set term pngcairo size 1280,960 font ",20"
set output "output.png"

set xtics noenhanced
set ytics 0.02
set grid y
set key off

set style fill solid 0.5
set boxwidth 0.9

set xlabel "Fraction, %"
set ylabel "H-bond donor, residue"

plot "\$data" using 0:2:xtic(1) with boxes, "" using 0:2:2 with labels offset 0,1
EOS
)

Would produce this gnuplot script:
$data << EOD
HIE_163@NE2 0.5304
GLU_166@N 0.5069
HIE_41@NE2 0.4792
THR_26@O 0.4249
THR_26@N 0.3323
EOD

set term pngcairo size 1280,960 font ",20"
set output "output.png"

set xtics noenhanced
set ytics 0.02
set grid y
set key off

set style fill solid 0.5
set boxwidth 0.9

set xlabel "Fraction, %"
set ylabel "H-bond donor, residue"

plot "$data" using 0:2:xtic(1) with boxes, "" using 0:2:2 with labels offset 0,1

Pipe it to Gnuplot, i.e. (...) | gnuplot and get this in output.png:
Comment: @JamesStarlight: Did you try using a bash variables in the heredoc? It works as you would expect.

"does not work" how?  the `using with labels` and offset calculation works here. Try running it with `LC_ALL=C` infront of the gnuplot command. Anyway I updated it to use `offset` instead.
Comment: @JamesStarlight: heredocs require the same start and end, here are some more examples: https://linuxize.com/post/bash-heredoc/
Comment: could you precise if it would be possible to use a bash variable inside the gnuplot sctipt e,g to print the filename directly on the graph. For example set title "$file_name" font "Century,22" textcolor "#b8860b"   print "$file_name" ;-)
Comment: also, this part does not work , "" using 0:(\$2+.01):2 with labels
Comment: Right, thank you it works very well! I've just tried to improve the pipeline adding sort after AWK and it works very well. just a question: what is the difference between <( cat <<'EOG' and  cat << EOS ? I mean only in the second case I could use bash variables directly in the gnuplot script, e.g. set title "$file_name


Axiom of choice implies law of excluded middle

Question: Diaconescu's Theorem states that AC implies the Law of Excluded Middle. Essentially the proof goes by defining $A = \{x \in \{0,1\} : x = 0 \lor p\}$, and $B = \{x \in \{0,1\} : x = 1 \lor p\}$, for a given proposition $p$, and defining a choice function $f : \{A,B\} \rightarrow \{0,1\}$. We then show that no matter what values $f$ takes, either $p$ or $\lnot p$ holds. The full proof can be found here.
What confuses me is why the Axiom of Choice is needed, as we are only choosing from two sets, and finite choice is provable in standard ZF. In addition, I've heard that countable choice does not imply excluded middle, but clearly we are not choosing from more than countably many sets in this proof.
Comment: I think it's because we want to show $\forall p: p \vee \neg p$, not just $p\vee \neg p$ for some particular $p$.
Comment: *Classical* ZF certainly proves finite choice, but does *intuitionistic* ZF?
Comment: Yes, by the same inductive proof. @Noah Schweber
Comment: According to wikipedia it is spelled "Diaconescu".
Answer: Choice from finitely many nonempty sets is indeed provable in standard ZF, but standard ZF is based on classical logic, which includes the law of the excluded middle.
Also, in Diaconescu's proof, the set $\{A,B\}$ cannot be asserted to be a two-element set. It admits a surjective map from, say, $\{0,1\}$, the standard two-element set, but that map might not be bijective since $A$ might equal $B$.  If we had classical logic (excluded middle) available, then we could say that $\{A,B\}$ has either two elements or just one element, and it's finite in either case.  But without the law of the excluded middle, we can't say that.
In intuitionistic set theory, there are several inequivalent notions of finiteness.  The most popular (as far as I can tell) amounts to "surjective image of $\{0,1,\dots,n-1\}$ for some natural number $n$." With this definition, $\{A,B\}$ is finite, but you can't prove choice from finitely many inhabited sets.  The second most popular notion of finite amounts to "bijective image of $\{0,1,\dots,n-1\}$ for some natural number $n$." With this definition, you can (unless I'm overlooking something) prove choice from finitely many inhabited sets (just as in classical ZF), but $\{A,B\}$ can't be proved to be finite.
(Side comment: I wrote "inhabited" where you might have expected "nonempty". The reason is that "nonempty" taken literally means that the set is not empty, i.e., that it's not the case that the set has no elements.  That's the double-negation of "it has an element". Intuitionistically,  the double-negation of a statement is weaker than hte statement itself.  In the discussion of choice, I wanted the sets to actually have elements, not merely to not not have elements.  "Inhabited" has become standard terminology for "having at least one element" in contexts where "nonempty" doesn't do the job.)
Comment: @JeffreyDawson Countable choice would be sufficient if the notion of "countable" were such that $\{A,B\}$ qualifies.  I'm not an expert on the various intuitionistically inequivalent ways of defining "countable", but at least one reasonable-sounding definition, "in bijection with a subset of the natural numbers," doesn't cover $\{A,B\}$.
Comment: Surely $\{A,B\}$ is at most countable, though? So why is countable choice not sufficient?
Answer: The background theory is an important issue. It is not quite right to say that the law of the excluded middle is provable from the axiom of choice. There are two important details:

We are talking about provability in constructive set theories that include separation axioms for undecidable formulas.
We are talking about the axiom of choice as expressed in set theory.

There are other constructive systems, such as constructive type theories, where the relevant form of the axiom of choice does not imply the law of the excluded middle. The implication in Diaconescu's theorem is particular to constructive set theory.
Separately, as described in the Stanford Encyclopedia article at http://plato.stanford.edu/entries/set-theory-constructive/index.html#ConChoPri , the axiom of countable choice does not imply the law of excluded middle even in constructive set theory.
If we try to apply the axiom of countable choice to the set in Diaconescu's theorem, nothing odd happens, because it is easy to write a choice function if we view $\{A, B\}$ as a sequence of two sets. The trick in Diaconescu's theorem is that if we apply choice to the family $\{A, B\}$, the choice function has to be extensional, and the theorem leverages the extensionality.  Replacing the family with a sequence of two sets $A$ and $B$ makes it easier to write a formula for an extensional choice function.
Comment: @ziggurism: In this case, what I mean is that if $U =V$ and $f$ is a choice function then we must have $f(U) = f(V)$. In the proof of Diaconescu's theorem, the trick is to construct $U$ and $V$ in a way that, without knowing the truth value of some statement $P$, we cannot determine whether $U= V$, and moreover so that $U \cap V = \emptyset$ if $P$ is false and $U =V$ if $P$ is true. Then we apply choice to $\{U,V\}$. The choice function has to be extensional, and so by checking whether $f(U) = f(V)$ we are able to tell whether $U = V$ and thus tell whether $P$ is true.
Comment: More generally, in constructive mathematics, sometimes we work with a set modulo an equivalence relation, for example the set of Cauchy sequences of rationals modulo the relation of "having the same limit".  This is called a setoid. An extensional function on the setoid would need to give the same result for any two Cauchy sequences that are equivalent; an intensional function needs to give the same result for identical Cauchy sequences, but possibly not for ones that have the same limit. For example, $f(\alpha) = $ "the first element of $\alpha$" is intensional but not extensional here.
Comment: In his paper "100 Years of Zermelo's Axiom of Choice: What was the Problem with it?", Martin-Löf argues at length that it is necessary to distinguish between the constructively acceptable, intensional forms of the axiom of choice and the non-constructively-acceptable extensional forms. The paper is at https://link.springer.com/chapter/10.1007/978-1-4020-8926-8_10  - the book is at https://doi.org/10.1007/978-1-4020-8926-8
Comment: what does it mean for a choice function to be "extensional"?


Accessing a resource in routes.rb by using attributes other than Id

Question: I have the following in my routes.rb
map.resources :novels do |novel|
  novel.resources :chapters
end

With the above defined route, I can access the chapters by using xxxxx.com/novels/:id/chapters/:id.
But this is not what I want, the Chapter model has another field called number (which corresponds to chapter number). I want to access each chapter through an URL which is something like
xxxx.com/novels/:novel_id/chapters/:chapter_number. How can I accomplish this without explicitly defining a named route?
Right now I'm doing this by using the following named route defined ABOVE map.resources :novels
map.chapter_no 'novels/:novel_id/chapters/:chapter_no', :controller => 'chapters', :action => 'show'

Thanks.
Answer: :id can be almost anything you want. So, leave the routing config untouched and change your action from
class ChaptersControllers
  def show
    @chapter = Chapter.find(params[:id])
  end
end

to (assuming the field you want to search for is called :chapter_no)
class ChaptersControllers
  def show
    @chapter = Chapter.find_by_chapter_no!(params[:id])
  end
end

Also note:

I'm using the bang! finder version (find_by_chapter_no! instead of find_by_chapter_no) to simulate the default find behavior
The field you are searching should have a database index for better performances
Comment: I'm trying to do the same, and I have one grudge with this method: show_chapter_url(chapter) doesn't work anymore. Is there a way around that, you think? Or should I just man up and use show_chapter_url(chapter.chapter_no) (or actually the equivalent in my own app)?


Como preencher espaços null de um array java?

Question: Eu preciso armazenar o primeiro e último nome de uma pessoa dentro de uma variável.
Consegui separar as palavras da String dentro de um array
e pegar o primeiro nome (pelo índice 0) - e agora gostaria de saber como pegar o último nome.
        String nomeCompleto; //variável para pegar o nome completo
        System.out.println("Digite o nome ");
        nomeCompleto = sc.nextLine(); //lendo nome

        //separando o nome completo em nomes separados para obter o primeiro e último nome
        String nome = nomeCompleto;
        String arrayNome[] = new String[5];
        arrayNome = nome.split(" ");

        for (int c = 0; c < 5; c++) {
            System.out.println(arrayNome[c]);
        } //mostrando os valores dentro do array

O programa está lendo todos os valores, porém, ao chegar em um índice que não existe valor, o programa dá erro - acredito que isto ocorre por ser null.
Comment: `c < 5` - quem garante que o array sempre terá 5 elementos? Se tiver mais, vc estará ignorando os restantes, se tiver menos, dará erro de index out of bound (ou seja, nada a ver com `null`). Use `c < arrayNome.length` que garante que sempre percorrerá todos, independente da quantidade.
Comment: Deu certo, obrigado!
Answer: Não fixe o valor do nome em 5 pois nem todo nome terá este tamanho, por exemplo "André Luiz Santos" teria o tamanho de 3 apenas.
Já que está trabalhando com array basta pegar o ultimo elemento que é o tamanho do array -1. Se tamanho igual a 3 o índice do ultimo elemento do array será 2.
Outro ponto a considerar é que o array pode estar vazio e neste caso neste caso o tamanho do array gerado seria 0 e o ultimo elemento neste modelo procuraria 0 - 1 e também dá erro, então recomendo procurar o ultimo nome somente se o tamanho do arrayNome for maior que 1.
Tente desta forma
public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    String nomeCompleto; //variável para pegar o nome completo
    System.out.println("Digite o nome ");
    nomeCompleto = sc.nextLine(); //lendo nome

    //separando o nome completo em nomes separados para obter o primeiro e último nome
    String nome = nomeCompleto;
    //Linha removida pois nem todo nome tem é composto por 5 nomes
    // String arrayNome[] = new String[5];

    //inicia a array com o tamanho adequado para cada nome
    String[] arrayNome = nome.split(" ");

    if(arrayNome.length > 1) {
        String ultimoNome = arrayNome[arrayNome.length - 1]; //Ultimo elemento do array
        System.out.println("O ultimo nome é " + ultimoNome);
    }
}


How can I get value of the button id from jquery ui dialog when user click?

Question: I want to create a jQuery UI dialog dynamically. Number of buttons in dialog depend on my JSON data. I need the button id when user click on it.
var deviceInfo = {
    "devices": [{ "deviceID": "11", "devicename": "test12" },
                { "deviceID": "12", "devicename": "test12" }]
};

for (var x in deviceInfo["devices"]) {
    arrButtons.push({
        text: "DeviceID:" + deviceInfo["devices"][x]["deviceID"],
              id: deviceInfo["devices"][x]["deviceID"], click: function () {
            currentDeviceID = deviceInfo["devices"][x]["deviceID"];
            console.log("selected id:", currentDeviceID);
            $(this).dialog("close");
        }
    });
}

showDeviceID = function (dID) {
    console.log("deviceID", dID);
}

$("#dialog").dialog({
    modal: true,
    dialogClass: 'no-close',
    show: {
        effect: "blind",
        duration: 1000
    },
    hide: {
        effect: "explode",
        duration: 1000
    },
    buttons: arrButtons
});

Every time I get last id. Would you please help me?
Answer: Just use event properties of the click handler.
$('button').click(function(e)
{
   e.target.id; // gives you the id of the button clicked.
}

Comment: Thanks a lot @DinoMyte for your great help. now it's working, I get the button id which on user click. Thanks again.
Answer: Change:
for (var x in deviceInfo["devices"]) {

    arrButtons.push({
        text: "DeviceID:" + deviceInfo["devices"][x]["deviceID"], id: deviceInfo["devices"][x]["deviceID"], click: function () {
            currentDeviceID = deviceInfo["devices"][x]["deviceID"];

            console.log("selected id:", currentDeviceID);

            $(this).dialog("close");
        }
    });

}

For:
for (var x in deviceInfo["devices"]) {
    var device = deviceInfo["devices"][x]["deviceID"];

    arrButtons.push({
        device: {
            click: function () {
                console.log("selected id:", device);
            }
        }
    });

}

Comment: Thank you very much Leo for your comment. Actually I need which button user click. Every button has id and I put it with my device id because I need which device user choose to show.
Comment: Thanks @Leo for your reply. I used your update version but it's show an error like: "Uncaught TypeError: Cannot read property 'apply' of undefined"


Completion of surreal numbers

Question: Surreal number field $\mathbf{No}$ is not complete, there are "gaps".  Does there exists a completion of it?
I know this question depends on axioms of set theory and more, feel free to assume whatever (consistent) axiom system you want.
My motivation comes from this this question. In short, infinite sums are not possible in $\mathbf{No}$ (to my great suprise), but to do measure theory with surreal numbers they should be. Sadly, the formal derivation
$$ C = \sum_{n=1}^\infty x = x+\sum_{n=2}^\infty x = x+\sum_{n=1}^\infty x \Rightarrow C = x+C \Rightarrow C=0 \vee x = 0$$
is a big obstacle. But it is crazy that the above infinite sum would be divergent when $x$ is sufficiently small, like $x=\frac{1}{\omega_1}$. So that gives the question - can completion of $\mathbf{No}$ even exist?
Comment: You need to define what sort of completion you are asking about.  There is the theorem that the reals are the only complete ordered field.  The surreals have higher cardinality, so any completion cannot be an ordered field.  It seems you should be able to do a topological completion by adding points that are limits of any convergent sequence, but I am way out of my depth here.
Comment: The Cauchy criterion on a sequence $(a_n)_{n \in \mathbb N}$ is equivalent to the sequence being eventually constant - take a surreal $\epsilon > 0$ to be smaller than every nonzero $|a_i - a_j|$. I imagine the same should be true if you were to take generalizations of sequences such as nets. Note that a series is equivalent to its sequence of truncated sums.
Comment: The least upper bound property can't hold either; if $x$ is an upper bound for $\mathbb N$, so is $x-1$. This is roughly equivalent to the formal derivation you've given in your question.
Comment: As a general rule of thumb, the surreal numbers are not good for analysis.  That's not what they're built for, and I do not know of even a single instance in which their infinitesimals shed any useful light on analysis.
Comment: But this is just multiplication. What axioms would you choose? It makes more sense to ask a question such as "is there a summation operator such that this and that property holds" than to ask whether mixing keywords would solve a problem that is not stated.
Comment: Thanks for this comment. The order completion of No certainly gives new elements, so Cauchy sequences are just not sufficient. Maybe one can show that order completion of No doesn't admit any field structure, but I'm not sure.
Comment: @DustanLevenstein: What about the Cauchy criterion on an "class length sequence" $(a_n)_{n\in\mathrm{On}}$?
Comment: You just showed that there is no coherent notion of sum which 1) satisfies some compatibility with finite sums 2) makes one non-zero constant sequence summable, with non-zero sum. Your argument is valid in any group. How would the surreal numbers help?
Comment: @nombre If we could weaken the axioms, maybe it would help. The ordinal number arithmetic is really weak algebraically, but powerfull. Things like ω-sum of 1/ω = ω*1/ω = 1. We could maybe define infinite sums as generalized product like the above.
Comment: @RossMillikan It may not be a field, mind you. Ordinal numbers are not a ring, so the completion of surreal numbers could not be a field.
Answer: Analysis on Surreal Numbers mentions the Dedekind completion $^$, basically identifying the gaps as new elements in this collection. Then we can define things like $∞=\{ℝ|\text{all positive infinite surreals}\}$, which is not a surreal number since the right side is a proper class, and, conversely $\frac{1}{∞}=\{0|\text{all positive surreals}\}$. While before the surreals could be defined as ordinal-sized sequences of $+$ and $-$, the gaps are sequences of length $$.
This construction brings back some useful analytic properties, but it is not a field anymore.

Completion of surreal numbers


How to find the total no. of cards if I know the numbers left on putting them in different stacks?

Question: I have a collection of cards, then:

If I put them in stacks of 2, I have 1 left
If I put them in stacks of 3, I have 1 left
If I put them in stacks of 4, I have 1 left
If I put them in stacks of 7, I have 0 left

So how many cards do I have??
Answer: Let the number of cards be $x$. Then you would set up the system of linear congruences as follows:
$$x \equiv 1 \ (mod \ 3)$$
$$x \equiv 1 \ (mod \ 4)$$
$$x \equiv 0 \ (mod \ 7)$$
[Note that the condition of $x \equiv 1 \ (mod \ 2)$ intuitively means that $x$ is odd. This information is already completely contained in the congruence modulo 4.]
[Note also that 3, 4 and 7 are pairwise coprime integers.]
Would you know how to solve this system?
As $x \equiv 1 \ (mod \ 3)$, and $x$ is positive, $x$ could be 1, 4, 7, 10, ... i.e. of the form $3k+1$ where $k$ is a positive integer.
Then you look at which of these possibilities for $x$ are congruent to 1 mod 4, etc.
Answer: See CRT to solve problems like these.
Your first condition is redundant given the third condition.
So you want a number $x$ such that it is of the form $12k+1$ and it should be divisible by $7$. Trying a few values of $k$, we see $49$ works.


How to stop the angular-translate model from loading the JSON file in a test?

Question: My config file is:
angular.module('mean').config(['$routeProvider', '$translateProvider', '$locationProvider',
  function($routeProvider, $translateProvider, $locationProvider) {
    $routeProvider.
      when('/login', {
        templateUrl: '/views/login.html',
        controller: 'LoginController'
      }).
      when('/company', {
        templateUrl: '/views/company/dashboard.html',
        controller: 'CompanyController'
      }).
      otherwise({
          redirectTo: '/login'
      });

    $locationProvider.html5Mode(true);
    $translateProvider.useStaticFilesLoader({
      prefix: '/lang/',
      suffix: '.json'
    });
    $translateProvider.useCookieStorage();
    $translateProvider.preferredLanguage('en-US');
  }
]);

When running my test, it says: WARN [web-server]: 404: /lang/en-US.json
My test doesn't mention or include the translateProvider at all. I just have beforeEach(module('mean'));
So how can I stub out the translateProvider from my testing? I tried beforeEach(module('pascalprecht.translate', function() {}));, but that had no impact.
Thanks!
Comment: Try not to load the angular-translate.js at all. And see what fails then and you will have a better idea which services you need to mock.
Answer: You will need a custom mocked-module, and then you'll have to load it instead of the original one(or after it, this way it will be overridden), in your karma.conf.
scripts/mocks/angular-translate.js:
!(function(angular){
   'use-strict';
    angular.module('pascalprecht.translate', []).
      filter('translate', function(){
             return function(input){return input};
      });
}(window.angular))

karma.conf:
files = [
    JASMINE,
    JASMINE_ADAPTER,
    'scripts/libs/angular.js',
    'scripts/libs/angular-mocks.js',
    'scripts/angular-translate.js', // Real module.
    'scripts/mocks/*.js', //Custom mocks.
    'scripts/specs/*.spec.js' // loads my spec file.
]

Of course you'll have to mock the $translationProvider and it's methods as well, but I trust that I don't have to implement it for you.
This is the proper way to mock this module, you can always use a decorator in the config phase.
scripts/mocks/angular-translate-decorator.js
!(function(angular){
   'use-strict';
    angular.module('pascalprecht.translate.decorator', []).
       .config(function($translationProvider){
           $provide.decorator( '$translationProvider', [ "$delegate", function(  $delegate ){
                $delegate.useStaticFilesLoader = function(){return undefined};

           }
        });
}(window.angular))

This piece of file should also come after the original module at the karma.conf file, as the first one.


Displaying commerce product with all product variations and attributes

Question: I'm building a drupal commerce store using product displays that reference multiple product variations. But i need the product display to show all of its product variations with all attributes one after another, not hiding the attributes by AJAX. And each product variation should have its own add-to-cart-button. So it's a simple, flat design where a customer can see every variation and every attribute at a glance.
I know this could be easily accomplished using views, but for certain reasons views is not an option for me. I need a real node of the productdisplay with its variations.
What's the best and most performant way to achieve this?
EDIT
According to @nvahalic it's a mess to solve my issue without Views. So maybe i have to reconsider my decision not to use Views. To clarify, the products will be displayed like this:

+------------------------------------+
| Title Product 1                    |
| =====================              |
| General Text (for all variations)  |
| General Image (for all variations) |
|                                    |
|    Title Product Variation 1       |
|    =========================       |
|    Text                            |
|    Image                           |
|    *Add to Cart*                   |
|                                    |
|    Title Product Variation 2       |
|    =========================       |
|    Text                            |
|    Image                           |
|    *Add to Cart*                   |
+------------------------------------+
+------------------------------------+
| Title Product 2                    |
| =====================              |
| General Text (for all variations)  |
| General Image (for all variations) |
|                                    |
|    Title Product Variation 1       |
|    =========================       |
|    Text                            |
|    Image                           |
|    *Add to Cart*                   |
|                                    |
|    ...                             |
|    ...                             |
+------------------------------------+

As far as i know when using views to build this structure, i will need something like the module Views Field View to achieve the nested structure consisting of fields belonging to the product display as well as fields belonging to the variants. Since the shop will have very long lists of products, i'm concerned about performance issues coming along with this kind of modules.
Or maybe i got it wrong and such module isn't necessary at all?
EDIT 2
Finally i solved the problem by using the EVA module: i created a view showing the attributes of all products as fields and added am add-to-cart field. This view i attached to my product display – it seems to me this approach is way more performant than using the Views Field View module …
EDIT 3
It is a huge mess: using nested views is not a good idea, because commerce-add-to-cart buttons can not be cached, so caching views does not work as it is discussed here https://www.drupal.org/node/1926888
From my point of view it was a very, very bad choice to use views for this task. Now I can not use views for caching and the module commerce entity cache is not usable neither because the view does not rely on entities.
Comment: Take a look at http://demo.commerceguys.com/ and see how it works
Comment: seems to me like they use views for the product catalog, so it's not the hint that i am looking for.
Answer: If you're insistent on not using Views, you might pull it off like this:

Create a new node type and then add an entity reference field that will reference the product displays for each of your products. Set the values to unlimited.
For each of your individual products, create a product display.
Set the renderer of the entity reference field on the new node you created to "rendered entity"
Theme the product display nodes that are linked to the entity reference field accordingly

  +------+     +------------------+     +----------+
  | Node |1---M| Product Displays |1---1| Products |
  +------+     +------------------+     +----------+
            ^     ^
            |     | Theme this entity appropriately.
            |
            | Set this display rendered to "Rendered entities"

At that point, you should have a list of rendered node entities that would each have their own add to cart form. You could also add a new view mode (using Display Suite) and use that view mode specifically if you still wanted to use the other view modes.
But honestly, this is an extreme amount of work for something that you could accomplish in 30 minutes with Commerce Add to Cart Extras and Views. And regardless of what I said above, that's still my recommendation.
Edit: You're on the right track with Views Field View. If you're worried about performance (how many products do you have?) then you can also:

Use Views cache. It's configurable under Advanced in the right-most column of the view configuration screen.
Enable Views Content Cache.
Implement Redis and perhaps Entity Cache.
Comment: thanks, probably you're right  – it seems a bad way to go without views. Maybe i shouldn't be afraid of views, so I edited my question; i would be glad if you could say something to my concerns about views in the context of my requirements.
Answer: I've just done it in this simple way using views:

Created a views block called "Product variation add to cart buttons"
Added a "Content: Product reference" relationship (Products referenced...)
Added a contextual NID filter (Provide default value, Content ID from URL)
Added the Add to Cart fields
Placed the block under admin/structure
Configured to only display on product/* (which is the basic path pattern for my product displays)

Voila:)


Internet connection speed vs. Programming language speed for HTTP Requests?

Question: I know how to program in Python but I am also interested in learning C++. I have heard that it is much faster than python and for the programs I am writing currently, I would prefer them to run as quickly and efficiently as possible. I know that a lot of that comes from just writing good code but I was also wondering if using another language, such as C++, would help.
While I was pondering this, I realized that since most of my programs will be mainly using the internet (as in implementing Google APIs and using the information from them to submit data to other websites) then maybe the speed of the language doesn't matter if the speed of my internet connection is always going to be relatively the same. I have two ways I am connecting to the internet: Selenium (or some kind of automated browser) for things that require a browser, and just HTTP requests.
How much difference would I see between python and a different language even though the major focus of my programs is on the internet?
Thanks.
Comment: In one word: zero. Python is by all means fast enough for HTTP requests (which, besides, are implemented natively, anyway). Entire content management systems that serve hundreds of users simultaneously are written in scripting languages.
Comment: If you really want to, you could write a first draft in python, then run it through a profiler. After reading the profiler's output, if you still feel that you need to optimize, then optimize your python code. If you want to optimize further, start looking into C++. But like @Damon said, python's requests are written natively i.e. in C. So I don't know how much more performance any C++ you write will be able to get you
Comment: Everyone wants their programs to run as quickly and efficiently as possible. But you also need to consider how easy the program is to write/maintain and the best ways to avoid bugs, etc.
Comment: If you want to learn C++ by doing this little project then by all means do it in C++ to learn it. The issue in terms of performance is of your internet connection speed. Like a lot of programs the I/O times are the true performance bottle necks and not the actual language or virtual machine. The only advantage I can see is if you have a lot of complex processing that needs to happen on the returned data where C++ could give you an advantage.
Comment: Yeah, this is a fairly simple program. Shouldn't take me too long to write. I was just debating which language to use (and if I should start my C++ learning with it)
Comment: Okay. Thanks everyone! I might do what inspectorG4dget and sean suggested.
Comment: In respect of @sean, I do not even recommend C++ for learning purposes here (and this is a C++ programmer with a strong dislike for scripting languages talking!). C++ is a great language, but for such a task it is really the wrong tool. Also, it is better to learn a language like C++ on something that is not so inherently error-prone and possibly harmful. For example, python knows no such thing as a buffer overrun or a dangling pointer, and things that should always work 100% reliably (like a HTTP request) _just work_. Think about language performance when you write something like Facebook.
Comment: about I/O performance in Python and C++: [Why is reading lines from stdin much slower in C++ than Python?](http://stackoverflow.com/questions/9371238/why-is-reading-lines-from-stdin-much-slower-in-c-than-python)
Answer: Scenarios
The main benefit you would get from using language that is compiled to machine code is that you can do lots of byte and bit-magic. Lets say, modifying image data, transforming audio, analysing indices of a genomic sequence database.
Typical tasks
Serving web-pages you typically have problems if a completely different sort: You will be loading a resource from hard disk, serve them directly if its an image or audio, or you will be executing different transformation steps on a text resource until it becomes the final HTML document. The latter will be using template engines, database queries, and so on.
If you look at that you can see that most of the things, say 90-99% are pretty high-level stuff -- in Python you will use an API that is optimized by many, many users for optimal performance (meaning: time and space). "Open a file" will be almost as fast in C as it is in Python, so is reading from it and serving it to some Socket. Transforming text data could be a bit faster in C++ then it is in Python, but... how fast does it have to be? A use is very likely willing to wait 200ms, isnt't he? And that is a lot of time for a nice high-level template engine to transform a bit of text.
What C++ and Python can do for you
A typical Python web-service is much faster to write and a easier to deploy then a server written in C++. If you would do it in C++ you firstly need to handle sockets and connections -- and for those would either use an existing library or write your own handling. If you use an existing library (which I strongly recommend) you are basically not doing anything differently then Python does. If you write your own handling, you have many, many low-level things you can do wrong that will burn the performance you wish for. No, that is not an option.
If you need speed, and Python and the server and template framework is not enough you should re-think your architectural approach. Then take a look at the c10k-problem and write tiny pieces in C. (Look at this c10k very hot topic, too) But I can not see many reasons not to use a high-level language like Python, if you are only looking for performance in a medium-complex web-serving application.
Summary: The difference
If you are just serving files from the hard-drive I guess your Python program would even be faster then your hand-crafted C++-server. If you use a framework written in C or C++ and just drop in your static pages, I guess you get a boost like 2-5fold against Python. Then again, if your web-application is a bit more complex then serving static content, I estimate that the difference will diminish very quickly and you will get 1-2fold speed gain at most.
It's not all about speed...
One note about another difference between C++ and Python one should not forget: Since C++ is really compiled and not as dynamic as Python you would gain a lot of static error analysis by using Python. Writing correct code is always difficult, but can be done in C++ and Python with good tests and static analysis -- the latter is simpler in C++ (my opinion). If that is an issue for you, you may think again, but you asked about speed.


Javascript - Etapas de configurações

Question: Estou com um problema que é: preciso que ao iniciar, meu aplicativo faça uma série de configurações.
Eu tentei fazer usando maquina de estados, e acabei encontrando essa: https://github.com/jakesgordon/javascript-state-machine/
Só que ela não me permite escolher pra onde eu quero que próxima etapa vá, somente na inicialização eu consigo definir isso:
events: [
        { name: 'start', from: ['none', 'getInformations'], to: 'getInformations' },
        { name: 'getInformations', from: 'getInformations', to: 'getTuner' },
        { name: 'getTuner', from: 'getTuner', to: 'getNetworkInfo' },
        { name: 'getNetworkInfo', from: 'getNetworkInfo', to: 'none' }
      ],

No caso, quando alguma etapa der erro, eu não consigo voltar pra ela porque já foi definido pra onde ela iria ir.
Eu realmente preciso criar uma etapa de configuração que eu tenha a flexibilidade de escolher pra onde quero ir e que respeite chamadas assíncronas. Alguém tem alguma dica de como fazer isso? Sem usar maquina de estados, a unica solução que consigo pensar é:
    while (validacao) {
        switch(estado) {
             case: 0:
                 fazAlgumaCoisa();
                 break;
              case 1:
                  fazOutraCoisa();
                  break;
        }
        }

fazAlgumaCoisa() {
   http.get('blablabla:8080').succes(){
     estado = 1;
}
}

Mas não vejo isso como uma solução elegante.. Se alguém poder me dar uma luz, agradeço muito.
EDIT: Digamos que tenho 4 passos que são obrigatórios pra fazer minha aplicação funcionar e preciso executar um após outro:
passo1 -> passo2 -> passo3 -> passo4
Porém, no passo 2, obtive um erro e preciso faze-lo ir para o passo 2 de novo.
Como eu poderia fazer isso?
EDIT2: Depois de algumas lidas em vários lugares, cheguei nesse código (apenas exemplos ilustrativos):
    var nextState = 'stopped';

var states = {

    stopped : function() {
        console.log("in stopped");
        nextState = 'started';

    },

    started : function() {
        console.log("in started");
        nextState = 'finished';
    },

    finished: function () {
        console.log("in finished");
        nextState = 'finished';
        clearInterval(interval);
    }
};

var interval = setInterval(function() {
    states[nextState]();
}, 300);

Não tenho certeza se isso é uma prática boa e como se comporta na memória, mas me parece uma solução agradável, tendo em vista que o setInterval vai ser destruído quando chegar na ultima etapa. Além disso, o acesso as funções será extremamente rápidas já que estou passando o índice correto para o array que contém minhas instruções.
Comment: Não entendi muito bem o que você está querendo fazer. Você pode dar um exemplo concreto? (Muito provavelmente você não precisa de máquina de estados pra fazer o que você quer mas a pergunta é toda sobre máquina de estados)
Comment: Provavelmente eu não precise, mas não consigo pensar em outra solução no momento..
Answer: Você pode escrever sua máquina de estados "na mão" usando funções mutualmente recursivas:
function faz_coisas(onDone){

    function passo1(){
        umaCoisaAssincrona(function(result){
          blah();
          passo2();
        });
    }

    function passo2(){
        ajax({
           onsuccess: passo3,
           onerror: passo2
        });
    }

    function passo3(){
        outracoisa(function(){
            onDone(meu_resultado);
        });
    }

    passo1();
}

//chamando o inicializador:
faz_coisas(function(result){
   console.log("tá tudo pronto");
});

A maneira básica de escrever funções assíncronas em Javascript é através de algo chamado "continuation passing style": suas funções chamam uma função continuação ao invés de retornarem valores normalmente. No caso de passo1, passo2 e passo3, em que o próximo passo é sempre o mesmo isso é bem simples (basta chamar a função de próximo passo diretamente) mas no caso de funções reutilizáveis como "fazer_coisas" você não sabe a priori qual função roda depois de você acabar. O que você pode fazer, então é receber essa continuação como parâmetro (o nosso "onDone").

Agora umas questões mais avançadas: escrevendo o código em continuation-passing-style nós conseguimos fazer qualquer coisa que quisermos. No entando, o nosso programa fica bem menos estruturado feio e chato de escrever - por exemplo, o loop do passo2 tem que ser feito com uma chamada recursiva ao invés de com um while. De uma certa forma, podemos dizer que continuation-passing-style é uma forma bem baixo nível de se programar.
Se você quiser algo mais alto nível e estruturado, você pode dar uma olhada em alguma biblioteca de programação assíncrona (que usa callbacks ou promisses) ou, algo que para mim é o ideal, use um preprocessador de código que extenda a sintaxe de Javascript com generators.
Comment: Não tem problema se as funções estiverem sendo usadas sempre de forma assíncrona. Por exemplo, se o próximo passo estiver sempre depois de um setTimeout ou chamada ajax
Comment: Em relação a recursividade, isso não gera de problemas de memória ? A aplicação no qual estou envolvendo isso é embarcada, e nosso hardware é meio antigo, com poucos recursos...

Vou editar minha pergunta e apresentar algo que cheguei a pensar, você poderia me dizer se é uma abordagem boa ?
Comment: Btw, porque vocês estão usando JS para uma aplicação embarcada? Na minha opinião seria mais apropriado usar algo como Lua. Lua é bem mais leve que Javascript, interage mais facilmente com C ou outras linguagens, tem recursão de cauda (dá pra fazer funções recursivas que nunca estouram a pilha) e corrotinas (dá pra programar de forma assíncrona sem ter que usar callbacks).
Comment: Porque temos a necessidade de carregar mídias feita em HTML.. No caso, exibir um .html e carregar os eventos contido neste. É possível fazer isso usando LUA?
Comment: Bem, os eventos dentro do html estão escritoes em Javascript então a coisa complica...

Javascript - Etapas de configurações


Local extrema of a function

Question: I solved a question to find the local extrema of the function
$$\frac{x^2 - 4}{x^2 - 1}$$
I got $$\frac{dy}{dx}= \frac{6x}{(x^2 - 1)^2}$$
And the second derivative to be
$$\frac{6 - 18x^2}{(x^2 - 1)^3}$$
The critical point putting $\frac{dy}{dx}=0$ is $x=0$
Inserting $x=0$ in the second derivative,
$$\frac{6-0}{0-1} = - 6$$
This should give a local maximum as the second derivative is negative but the answer in my text says its a local minimum,  is there something I'm doing wrong?
Comment: Please use $\LaTeX$ for any equations or math symbols on this website.
Answer: the second derivative computation is wrong. it should be $\frac{-6-18x^2}{(x^2-1)^3}$
hope,That clarifies.
Comment: Thank you, I just saw the mistake.

Local extrema of a function


Excel Hyperlink- When clicked make target cell always upper left hand corner

Question: I have a very wide excel spreadsheet. It's formatted in such a way that there is specific data on each screen page.  I have the first column frozen so I can place hyperlink buttons vertically.  These buttons are hyperlinked to each of the formatted pages in the worksheet.
When I click one of the hyperlink buttons I would like the worksheet to scroll so the target cell in the UPPER LEFT corner of the screen.
I have googled and found this VBA code to place in the "thisworkbook" section of the VBA editor.
<code> Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
     ActiveWindow.ScrollRow = ActiveCell.Row
     ActiveWindow.ScrollColumn = ActiveCell.Column
 End Sub
</code>
This code does not seem to work for me.  If I'm at the far left of the screen and press the hyperlink button it scrolls to the target cell until it gets on the active screen.  So basically it always ends up somewhere on the Upper right of the screen.  However, if I click the hyperlink buttons the require the page to scroll to the left side of the worksheet it does work.
How can I make it so the target cell is ALWAYS in the upper left of screen after I press the hyperlink button?
Also, how do I know the above code is even running?  The hyperlinks seem to be doing the same thing with or without it.  I just cut and pasted the code into the VBA editor (per google) for thisworkbook.  Is that it or do I need to check something so it will be activated?
Thanks in adavance.
Answer: There's a way to do that without using VBA. You can just use a normal hyperlink in the spreadsheet, and link it to "Place in This Document". Make sure you pick the correct Sheet and Type the cell reference that you want to go to (I assume this is A1). This will make sure that whenever you click that particular link, it will always go to that particular spot.
Here's how the edit hyperlink would look in an empty spreadsheet.
Comment: I am currently doing what you have Vf started. However, it does not put the target cell in the upper left corner when the link is pressed. The VBA code is supposed to take care of that. I think the vba code is not executing but I can figure out why. Ideas?
Comment: That's odd, using that method have worked fine for me. Have you run the code on the VBA before? Or did you only just copied it into the worksheet's VBA?
Comment: After more googling it seems if the hyperlink is in a "shape" the VBA code will not run. The hyperlink event is never triggered. I created a normal hyperlink without a shape and the code runs as it should.  Bizarre. No nice buttons :(


Excel 2012 Pivot Table Displayed Data

Question: I am trying to make a simple bug viewer with Excel. I think I need a pivot table for this.
I have attached a screen shot of what I have got so far. What I would like, is instead of the 'Count of x' columns, is the actual data to be displayed.

My data table is formatted as follows:

Thank you very much,
Richard Hughes
Comment: Providing an example data table would be useful. Can you also show us what you are trying to achieve?
Comment: Julian: I have edited my post to add some sample data.
Comment: I am trying to display the bugs by their ids. So in the pivot table, I would like the little + expander by the ids, and then all of the bugs where the 'Parent Id' matches, should display in the expanded section
Comment: At the moment, the bugs display a count of the data, for instance 'Count of Item'- I would like the actual text displayed there instead
Answer: You cannot have the actual text displayed in those columns. The columns show aggregated data. You can have counts and sums, averages, etc.
I think that what you want is the "classic" pivot table view. Go into the pivot table options, Display tab and select "Classic Pivottable Layout".
Then add the data you want to see as "Row Labels" not Values. You might want to keep a count of ID as a value. Is that better?
Comment: Thanks. This is almost what I want, and is good enough for my purposes at the moment. I'll post back if I need anything else. Thanks again!

Excel 2012 Pivot Table Displayed Data


Order of $G$ is 35, are there elements of order 5 and 7 in G?

Question: I have a group of order 35 and I want to know if it contains elements of order 7 and 5. I know that it does and there is a proof that is much longer, but I wanted to know if the following worked to show that it does contain elements of order 5 and 7.
My Approach: Let $|G| = 35$. We know that any group of order 35 is cyclic so $G$ is isomorphic to $C_7$ x $C_5$ and $C_7$ contains an element of order 7 and $C_5$ contains an element of order 5. So, there are elements of order 5 and order 7 in $G$.
Comment: Correct, but the fact that $G$ must be cyclic is not trivial.
Comment: This is correct, but the proof that any group of order $35$ is cyclic is rather more complicated than a direct proof that uses only, e.g. Lagrange's Theorem.
Comment: This follows form [Cauchy's theorem](https://en.wikipedia.org/wiki/Cauchy's_theorem_%28group_theory%29), which is proven there.
Comment: Thanks! It was proved in a book I have so I am allowed to use whatever is in the book. Could you also use the sylow theorems to show that there is one 5-sylow subgroup and one 7-sylow subgroup then these are cyclic and there must be an element of order 5 and element of order 7?
Comment: @DietruchBurde Thanks!!
Comment: Yes, Sylow theorem also works. At the moment I cannot see a direct solution a la Travis!
Answer: You can also show this using an elementary counting argument. First, note by Lagrange's theorem that every element must have order $1$, $5$, $7$, or $35$.
If there is an element of order $35$ then the group is cyclic, so there is some $g$ with order $35$. Then $g^5$ has order $7$, and $g^7$ has order $5$.
Now suppose there is no element of order $35$. Only the identity has order $1$, so every non-identity element must have order $5$ or order $7$.
If there is no element with order $7$, then every non-identity element has order $5$. Therefore $G$ is the union of $n$ subgroups of order $5$. Since $5$ is prime, each pair of subgroups intersects trivially, which means that we must have $|G| = 35 = 4n+1$, but there is no integer $n$ satisfying this equation.
Similarly, if there is no element with order $5$, then every non-identity element has order $7$. Then $G$ is the union of $n$ subgroups of order $7$. Since $7$ is prime, again the subgroups intersect trivially, so $|G| = 35 = 6n+1$. Again, there is no integer $n$ satisfying this equation.
We conclude that $G$ must contain at least one element of order $5$ and at least one element of order $7$.
Comment: @Karthik Yes, but in that paragraph we're assuming that every non-identity element of $G$ has order $5$, hence $xy$ would also have order $5$ unless $x$ and $y$ are inverses of each other in which case $xy$ would have order $1$.
Comment: I don't understand how you'd compare the order of $G$ with $4n + 1$, even if they intersect trivially, there'd be other elements like $xy$ where both have 5 as order.
Answer: It follows by Cauchy's theorem, with $p=5$ and $p=7$. The proof of Cauchy's theorem is elementary. Furthermore we could use the result that all groups of order $pq$ with $p<q$ prime and $p\nmid q-1$ are cyclic - see here.


Find value of the angle x

Question: Find the value of the angle x.

Plus : Someone could recommend me some good book about this subject ?
Comment: @Ragnar: You may be interested in [my comment to the linked question](https://math.stackexchange.com/questions/482180/angle-abd-38-angle-dbc-46-angle-bca-22-angle-acd-48-then-find-an#comment4962470_482180).
Comment: @user21820. Thanks for the link ! When I see things like that, they confirm to me that I am a Martian ! Cheers.
Comment: I tried, but I can't find a solution yet. Is there any particular topic this problem belongs to? Are there any theorem you expect to be useful?
Comment: @Ragnar I don't know the name of this topic in english, in spanish is written "Triángulos II". I don't know any theorem useful to do it. Do you know the topic's name in english of this above ?
Comment: Do you know the law of sines?
Comment: yes ... how shall I use it ?
Comment: I'm trying to solve it using it, but I get very ugly equalities with lots of sines and cosines, and I can't prove the LHS and RHS are the same.
Comment: There's no way with law of sine ...
Comment: Could an algebraic approach be considered ?
Comment: I am not sure what you mean with "this topic". The problems that are really similar to yours all use a variant of the relationship between the angles of size 10, 20 and 40.
Comment: @ClaudeLeibovici: See above comment. Turns out all such problems can be solved by elementary geometry.
Comment: @Phira: See above above comment. The linked question has some crazy angles! =)
Answer: Purely geometric proof

Let the triangle be $\triangle PQR$ with $\angle QPR = 20^\circ$ and $\angle PRQ = 90^\circ$
Let $O$ be on the side $PQ$ such that $O$ is the centre of a regular 18-gon with radius $OQ$ and one side $AB$ lying on $PR$, where $B$ is between $P$ and $A$, which is possible because that side $AB$ and $OQ$ meet at an angle of $20^\circ$
Then $QR$ clearly passes through another vertex $C$ of the 18-gon
Let $D$ be another vertex of the 18-gon such that $CD \perp OA$
Then $CD$ bisects $OA$ because $\triangle OAC$ is equilateral
Thus $CD$ passes through $P$ because $\triangle OPA$ is isosceles since $\angle AOP = \angle PAO$
Thus $\angle QPC = 10^\circ$ and $\angle CQA = 30^\circ$ and so they are the desired points
Therefore $\angle QAC = 20^\circ$
Comment: By the way, a lot of these triangle problems can be solved using some similar regular polygon somewhere. It took me a while to find where I could put the polygon, but after that it was not too hard. And if you like this solution best, you can accept it as the answer. =)
Comment: @EllieKesselman: Hello! Nice to see you here and thanks! I didn't know you were on Math SE too. =)
Comment: Woww !! +1) Nice solution.
Comment: Thanks! It was fun finding it too! =D
Comment: And you might be interested to take a look at http://www.cut-the-knot.org/triangle/80-80-20/index.shtml, which give other such triangle problems. I've never come across yours though.
Comment: I've already seen this problem in your link but not the variances. Thanks and do you know some good book about this subjects ?
Comment: Nice! Do you want to try your skill with [this question](http://math.stackexchange.com/q/482180/35416) as well? Looks kind of similar.
Comment: I don't know of any book on this subject, and I suspect it is too small a topic? I can try the other question but it looks like a different sort of trick is necessary if an elementary geometry proof is possible.
Comment: Hello @user21820 !  That is an awesome answer.  I wish I could transfer up votes from here to EL&U :) You are deserving.
Answer: Claim
The angle is $20°$, as found in a construction performed with Cinderella.

Proof
If you want to proove this, you could use the following computation using sage. All arithmetic is done using exact algebraic numbers, to avoid floating point rounding issues.
def sin_cos(degrees):
    degrees = QQ(degrees)/360
    z = QQbar.zeta(degrees.denominator())^(degrees.numerator())
    return z.imag(), z.real()
sin10, cos10 = sin_cos(10)
sin20, cos20 = sin_cos(20)
sin30, cos30 = sin_cos(30)
sin40, cos40 = sin_cos(40)
lenAB = 1
lenAC = lenAB*cos20
lenBC = lenAB*sin20
lenAF = lenAC/cos10
lenCF = lenAF*sin10
lenBE = lenBC/cos30
lenCE = lenBE*sin30
lenCF/lenCE == sin40/cos40

The result (printed as True) will show that $\angle FEC=40°$. From the angle sum in $\triangle BCE$ one can conclude $\angle BEC=180°-90°-30°=60°$. So you get $\angle BEF=\angle BEC-\angle FEC=60°-40°=20°$ as the experiment suggested.
Comment: Perhaps there's another way to compute the value of x without a software. Anyway, thanks !
Comment: There is indeed! I'm going to give my solution now.
Comment: @Joel: The computations I wrote down for sage could have been performed using a scientific pocket calculator, albeit with reduced precision. Taking the atan of that `lenCF/lenCE` fraction would give the angle of $40°$, which would yield the final result as described in the proof. The above approach is not well suited for computation without any technical aid at all, since these trigonometric functions don't yield easy values. But an easy solution might still exist, and I'm looking forward to what user21820 has come up with.
Comment: It's a purely geometric solution. Give me a few more minutes to finish typing it up and including a diagram. =)
Answer: Construction: Construct $\triangle$ PQR $\cong$ $\triangle$ ABC. Construct $\angle$s PST and PSU both equal to 30  intersecting sides PR and PQ at points T and  U respectively.
Proof: $\angle$ USQ=70. US=UQ. $\triangle$ PTS $\cong$ $\triangle$ PUS. $\triangle$ POT $\cong$ $\triangle$ POU.
$\angle$ POT = $\angle$ POU=90.
Therefore TS=US. $\triangle$ UST is an equilateral triangle and $\angle$s PTO and PUO are both equal to 80. Therefore, $\angle$s UTQ and UQT are both equal to 40.
Therefore, $\angle$ QTS=20 and $\angle$ RQT=30
Now $\triangle$ BCE $\cong$ QRT and $\triangle$ DCE $\cong$ SRT.
That proves x=20.
Comment: Looks good! Welcome to Math SE! If you want an account on Math SE, and you still can access your profile page, you can register. Otherwise you may lose access to your unregistered account.

Find value of the angle x


Non-empty string as route parameter

Question: I'm creating a search results page using the Search API. I want to set an url like this:
    /search/{text}

How should i set up my route? It must accept any combination of characters, including non-ascii, spaces, numbers, etc, but it must not be empty.
This is my current routing rule. As you can see, there is no restriction for the text parameter:
    my.search.results:
      path: '/search/{text}'
      defaults:
        text: NULL
        _controller: '\Drupal\my\Controller\SearchController::results'
        _title: 'Search Results'
      requirements:
        _permission: 'access content'

Comment: Symfony placeholders are required unless told otherwise - just remove the default value?
Comment: I think you might want to set text to `\w+`, but I am not 100% certain. See: http://symfony.com/doc/current/routing/requirements.html Plus, it should go under requirements.
Comment: \w+ will fail if there is a space (%20) between words. Removing the default value will do the trick.
Answer: As long as a default value isn't provided in the route definition, every route placeholder is required. Defining the route as follow is sufficient.
my.search.results:
  path: '/search/{text}'
  defaults:
    _controller: '\Drupal\my\Controller\SearchController::results'
    _title: 'Search Results'
  requirements:
    _permission: 'access content

See, for example, the definition of the dblog.event route in the dblog.routing.yml file.
dblog.event:
  path: '/admin/reports/dblog/event/{event_id}'
  defaults:
    _controller: '\Drupal\dblog\Controller\DbLogController::eventDetails'
    _title: 'Details'
  requirements:
    _permission: 'access site reports'

The controller associated to that route, DbLogController::eventDetails(), doesn't check the value of $event_id is an empty string, simply because it won't get an empty string for that parameter.
public function eventDetails($event_id) {
  $dblog = $this->database->query('SELECT w.*, u.uid FROM {watchdog} w LEFT JOIN {users} u ON u.uid = w.uid WHERE w.wid = :id', [
    ':id' => $event_id,
  ])
    ->fetchObject();
  if (empty($dblog)) {
    throw new NotFoundHttpException();
  }
  // …
}

Non-empty string as route parameter


JavaFX how to push edited data to database

Question: I need one more thing in my gui,and I don't know how I can do it.
I need to update data (after editing) by click on save button. How i can make it?
Answer: Have you tried this
<code>Button saveButton = new Button("Save");
saveButton.setOnAction(event -> updateData());
</code>


Question related to the security of RSA method

Question: I learned about the RSA method, where if B wants to send a message $M$, say $0 \leq M <n = pq$ to A with public key $(n,e)$, then B sends $M'= M^e (mod \ n)$. Then A can decode this message using private key $d$ chosen such that $ed \equiv 1 \ mod \ ((p-1)(q-1) )$.
I can see that once someone figures out what the factorization of $n$ is, then it is easy to crack it. And I know that if $n$ is large then factoring is difficult.
If we wanted to decode $M'$, even if we don't know the factorization, we could just let the computer run to compute $x^e (mod \ n)$ for each $x$ until it matches $M'$. I thought maybe this could be done faster than finding the factorization of $n$, but I wasn't really sure. Is it as difficult (or time consuming) as factoring $n$? Could someone please explain to me this part?
Thank you very much!!
Answer: For typical key sizes, there are way too many possible plaintexts to encrypt to create a complete table in practical time periods.  We are usually talking about numbers on the order of $10$ raised to three- or four-digit exponents.  Even if encrypting a plaintext was a single machine operation, even $10^{100}$ messages takes too long to create a complete table.  It would be far easier (though of course far from being actually easy!) to approach the problem by factorization.


GridView v. Repeater issues

Question: I have a GridView with bound rows from a data source and I placed a link button at the end of each row.  When I click that link button I would find the named controls within the grid and get their values.  I decided to try and use a Repeater control with the same named controls in the Repeater and same data source but I am not able to execute the same click event and use RepeaterItemEventArgs, only EventArgs is available in the method signature.  Without the RepeaterItem I can't find the control.
This code compiles but when I click the row I get this error: CS0123: No overload for 'BtnAssign' matches delegate 'System.EventHandler'  So I discovered that what I needed was to change the second parameter to EventArgs.  This fixes the error at run time and I am able to step into this method but the method has to be changed in order to compile.  I no longer have access to e.Item.  Ideas?
<code>protected void BtnAssign(object sender,  RepeaterItemEventArgs e)
    {
        var miscItem = new SLWorkOrderItem();
        string theAmountLabelText = "";

        // Repeater Code
        if (e.Item.ItemType == ListItemType.Item)
        {
            var theAmountLabel = e.Item.FindControl("lblAmount") as Label;

        }
    }
</code>
Comment: I'm really sure that a `GridView` and a `Repeater` have different arguments for that event. You might be better off with having the be separate functions.
Comment: Which control does fire BtnAssign event? Please post the mark up.
Answer: I am guessing you are trying to execute this on the ItemCommand Event?
In that case: You would use RepeaterCommandEventArgs not RepeaterItemEventArgs.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeateritemeventargs.aspx
RepeaterItemEventArgs is used in ItemCreated.
<code>            OnItemCommand="BtnAssign"

            protected void BtnAssign(object source, RepeaterCommandEventArgs e)
                {

                }
</code>

GridView v. Repeater issues