ggplot, ggsave & coord_map/quickmap: how to save large spatial objects and get the projection right?

Question: I have a largish polyline shapefile (Bavarian rivers, which can be accessed here) which I would like to plot and save via ggplot. This can easily be done via e.g. this code:
library(ggplot2)
library(rgdal)
library(sp)
library(rgeos)

riv <- readOGR(paste0(getwd(),"\\rivers_bavaria","rivers_bavaria"))
riv1 <- subset(riv,WDM=="1310"|WDM=="1320")
riv2 <- subset(riv,WDM=="1330")

p <- ggplot() +
  geom_line(data=riv1, aes(x=long, y=lat, group=group), color="dodgerblue", size=1) +
  geom_line(data=riv2, aes(x=long, y=lat, group=group), color="dodgerblue")

ggsave(paste0(getwd(),"\\riv.tiff",p,device="tiff",units="cm",dpi=300)

This is not exactly efficient, due to the large file size, but it works. However, without further specifying aspect ratio or projection, the dimensions of the output file are defined by the plot window - not desirable for maps. This can be remedied by using coord_quickmap().
p1 <- ggplot() +
  geom_line(data=riv1, aes(x=long, y=lat, group=group), color="dodgerblue", size=1) +
  geom_line(data=riv2, aes(x=long, y=lat, group=group), color="dodgerblue") +
  coord_quickmap()
p1

Unfortunately, the projection is completely off. I have tried coord_map() for a better result, but due to the large file size, it takes forever and is therefore not a realistic option. Simplifying the polyline via gLinemerge() produces a much smaller object, but cannot be handled by ggplot, as it is a SpatialLines object. Using fortify() or data.frame() to coerce it into a ggplot-friendly data frame format also produces Error: ggplot2 doesn't know how to deal with data of class SpatialLines.
I'm therefore desperately looking for a workflow that will allow me to plot and save this kind of spatial data in good quality with ggplot. Any suggestions will be much appreciated!
Comment: Do you mind an `sf` solution? It makes what you're doing—subsetting, changing projections, plotting in ggplot—very easy and straightforward
Comment: Yes, please - otherwise all my previous work goes to waste!
Answer: Here's a quick walkthrough with sf. I recommend the sf vignettes and docs to see more details of any of the functions. I'm first reading the shapefile in as an sf object using sf::st_read, then filtering, mutating, and selecting the same as you would in dplyr to get a smaller version of the shape.
library(tidyverse)
library(sf)

rivers_sf <- st_read("rivers_bavaria/rivers_bavaria.shp") %>%
  filter(WDM %in% c("1310", "1320", "1330")) %>%
  mutate(name2 = ifelse(WDM == "1330", "river 2", "river 1")) %>%
  select(name2, NAM, geometry)

The object is pretty big, and will be very slow to plot, so I simplified it by uniting the geometries by name, then using st_simplify. There's also rmapshaper::ms_simplify, which uses Mapshaper and which I prefer for better control over how much information you keep. Then to show a CRS transformation, I picked a projection from Spatial Reference for Germany.
riv_simple <- rivers_sf %>%
  group_by(name2, NAM) %>%
  summarise(geometry = st_union(geometry)) %>%
  ungroup() %>%
  st_simplify(preserveTopology = T, dTolerance = 1e6) %>%
  st_transform(31493)

The dev version of ggplot2 on GitHub has a function geom_sf for plotting different types of sf objects. To get this version, run devtools::install_github("tidyverse/ggplot2").
geom_sf has some quirks, and works a little differently from other geoms, but it's pretty versatile. I believe it's being included in the next CRAN release. geom_sf has corresponding stat_sf and coord_sf. By default, it plots graticule lines; to turn those off, add coord_sf(ndiscr = F).
ggplot(riv_simple) +
  geom_sf(aes(size = name2), color = "dodgerblue", show.legend = "line") +
  scale_size_manual(values = c("river 1" = 1, "river 2" = 0.5)) +
  theme_minimal() +
  coord_sf(ndiscr = F)

Hope that helps you get started!
Comment: Thanks a lot for your work! I really like the easy table format of the sf objects. Unfortunately, I was not able to install the dev version of ggplot (following [this](https://stackoverflow.com/questions/9656016/how-to-install-development-version-of-r-packages-github-repository) advice). Is there no other way to simplify large spatial objects for plotting with ggplot?
Comment: That post is outdated; I'll amend my answer. The `tidyverse` repos are now at "tidyverse/ggplot2" (or fill in whatever other package name in the ecosystem), not "hadley/ggplot2"


How do setup mod_http_upload in ejabberd

Question: In ejabberd 18.01-2, installed in lxc container Ubuntu 18.04 Bionic LTS using apt, I'm trying to setup mod_http_upload.
In the section listen, I have
listen:
  -
    port: 5444
    module: ejabberd_http
    tls: true
    request_handlers:
      "/upload": mod_http_upload

In the configuration file, commented port was 5444, however, in the current documentation, it is 5443, so I am not sure which one is right.
In the modules section, I have
modules:
  mod_http_upload:
    host: "upload.ejabberd.forumanalogue.fr"
    max_size: infinity
    thumbnail: true
    put_url: "https://ejabberd.forumanalogue.fr:5444/upload"
    docroot: "/ejabberd/upload"

When I start the service, I can see an odd message in the logs
2019-11-11 21:02:35.287 [warning] <0.367.0>@ejabberd_pkix:handle_call:255 No certificate found matching 'upload.ejabberd.forumanalogue.fr': strictly configured clients or servers will reject connections with this host; obtain a certificate for this (sub)domain from any trusted CA such as Let's Encrypt (www.letsencrypt.org)

It is strange because I have a signed wildcard certificate.
certfiles:
  - "/etc/letsencrypt/live/forumanalogue.fr/*.pem"

I can see the service with my client (Gajim) but when I try to send a file to another local account, I receive an error Access denied by service policy, see the complete log:
<iq xml:lang='en' firstname.lastname@example.com/gajim.HCLJ4BZI' from='upload.ejabberd.forumanalogue.fr' type='error' id='1dd35274-90e9-4b3b-9608-0fab59afe34e'>
<request xmlns='urn:xmpp:http:upload'>
<filename>a.out</filename>
<size>27232</size>
<content-type>application/octet-stream</content-type>
</request>
<error code='403' type='auth'>
<forbidden xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>
<text xml:lang='en' xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'>Access denied by service policy</text>
</error>
</iq>

I had to enable debug logging in order to see something. It is quite verbose, but I think that the relevant part, which is non redundant with the client message, is
2019-11-11 20:53:08.329 [debug] <0.501.0>@mod_http_upload:process_slot_request:544 Denying HTTP upload slot request from email@example.com/gajim.HCLJ4BZI

Thank you for your help.
Answer: I tried with ejabberd 18.01, a configuration similar to yours, and it works for me.
Looking at the source code, that "process_slot_request:544 " error means that the account attempting to use the upload feature is not allowed by the "local" Access rule in the vhost it sended it to. Probably it's a remote account. Remote to that upload service. In other words, the service upload.whatever can only be used by accounts like user12@whatever.
In your case, you are attempting to use upload.ejabberd.forumanalogue.fr from account email@example.com, which is not local to that upload service.
Several ideas, I hope one of them suits your specific setup:
A) don't mess with vhosts. If it's forumanalogue.fr, keep it that everywhere
B) use @HOST@ in host and put_url options
C) Or if you really want to mess with hosts, then add Access rights so accounts in that vhost are considered "local" to the upload service.


Checking my proof of finding a limit

Question: I'm trying to find all the $a\in \mathbb R$ values which we get the following limit:
$$L=\lim_{x\to a} \frac{x^2+ax-2a}{(x^2-1)(x+a)}$$
to be finite. I don't see any problem just inserting $a$ into the limit so we get $\frac{1}{a+1}$ so for $a\neq -1$ we get a finite limit. Is it that easy?
Comment: What do you get if $a=-1$?
Comment: @NickGuerrero oops, I meant $a\neq -1$. Will edit.
Comment: What is in the case $$a=1$$?
Comment: @Dr.SonnhardGraubner we get $\frac{3}{4}$ no?
Answer: Your result $$\frac{2a^2-2a}{(a^2-1)2a}$$ can be written as $$\frac{2a(a-1)}{(a-1)(a+1)2a}=\frac{1}{a+1}$$ if $$a\ne -1$$
Comment: My question is if its correct to just insert $a$ into the equation?
Comment: Yes this is correct if the denominator $$(a^2-1)2a$$ is not zero.
Answer: In this case, as long as we don't have $\frac{0}{0}$ or $\frac{\infty}{\infty}$, yes it is that easy and inserting $a$ is enough. And the answer becomes $a \in \mathbb{R}-\{-1\}$.
EDIT: By the warning from fleablood, we should also consider the case where we can have $\frac{0}{0}$. Here, note that in order for nominator to be $0$, we must have $2a^2-2a = 0 \implies a = 0 \lor a = 1$.
Case 1: $a = 0$. In this case, we have
$$\lim_{x \to 0}\frac{x^2}{(x^2-1)x} = \lim_{x \to 0}\frac{x}{(x^2-1)} = 0 \ne \frac{1}{a+1} = 1$$
Case 2: $a = 1$. In this case, we have
$$\lim_{x \to 1}\frac{x^2+x-2}{(x^2-1)(x+1)} = \lim_{x \to 1}\frac{(x+2)(x-1)}{(x^2-1)(x+1)} =  \lim_{x \to 1}\frac{(x+2)}{(x+1)^2} = \frac{3}{4} \ne \frac{1}{a+1} = \frac{1}{2}$$
Comment: But you *DO* get $\frac 00$ if $a = 1$ and $x=a$.
Comment: For $a = 1$, we have $\lim_{x \to 1}\frac{(x+2)(x-1)}{(x+1)^2(x-1)} = \lim_{x \to 1} \frac{x+2}{(x+1)^2} = \frac{3}{4}$. I think you are right because it is not $\frac{1}{2}$, in which we insert $a$.

Checking my proof of finding a limit


Tukey's comparisons for proportions

Question: Question: What is an appropriate extension of Tukey's method to proportions?
Normal situation
In one-way ANOVA problems
$$
y_{ij} = \mu_i + \epsilon_{ij}, \quad i=1,\ldots,m
$$
Tukey's studentized range statistic is often applied to pairwise differences $\mu_l - \mu_k$ is applied to correct for the multiple testing of $m(m-1)/2$ differences. Scheffe's book (the one I have easy access to) formulates this as follows (p. 73, search "T-method" in Amazon look inside): if the OLS estimates $\hat\mu_i$ are normally distributed and independent of each other,
$$
\hat\mu_i \sim N(\mu_i,a^2\sigma^2);
$$
where $a^2$ is known, $s^2$ is an independent estimate of $\sigma^2$ with $\nu$ degrees of freedom, and $q_{\alpha,m,\nu}$ is the studentized range statistic for $m$ comparisons with $\nu$ degrees of freedom, then the probability is $1-\alpha$ that all $m(m-1)/2$ differences simultaneously satisfy
$$
\hat\mu_k - \hat\mu_l - Ts \le \mu_k - \mu_l \le \hat\mu_k - \hat\mu_l + Ts; \quad T = a q_{\alpha,m,\nu}
$$
Scheffe argues that for the purposes of pairwise comparisons, the Tukey's method works best (as compared to Bonferroni that works for everything, and Scheffe's method that works for arbitrary contrasts). I am not particularly surprised: Tukey's method uses the specific information while other methods sacrifice power for generality.
Anyway.
I need to work with proportions, so instead of $\hat\mu_i$ that are homoskedastic in Scheffe's formulation, I have estimates of proportions $\hat p_i$ that are hopelessly heteroskedastic. (I also have a complex survey design, and the group sizes are different, so I don't see any particularly good way to stabilize the variance with arcsine or logit transformations.)
Literature review
(1) There's a related question on CV, however I am not fully comfortable using the proposed procedure without a solid reference. It was presented as a kludge rather than a methodology (i.e., I'd like to see a reference to JASA/Biometrika paper or a textbook), although I am sure it is reasonably correct. The plugs that it makes are:

car::ANOVA which works with asymptotically normal coefficients out of glm (which in my case would be svyglm)
lsmeans which is a port of a SAS LSMEANS statement in PROC LOGISTIC / PROC SVYLOGISTIC.

(2) Alternatively, the NIST website offers a description of the Marascuilo procedure -- again unfortunately without a reference. The procedure is based on referring the absolute values $\hat p_k - \hat p_l$ to
$$
r_{kl} = \sqrt{\chi^2_{1-\alpha;m-1}}\sqrt{\frac{\hat p_k(1-\hat p_k)}{n_k}+\frac{\hat p_l(1-\hat p_l)}{n_l}}
$$
Answer:
The reference for the Marascuilo procedure appears to be "Nonparametric post
hoc comparisons for trend", Psychological Bulletin,
1967;67:401-412.   It's not really a version of the Tukey procedure; the $\chi^2_{m-1}$ comes from comparing the variance of the $\hat p_i$ around their mean to the expected value under the strong null of all $p_i=p$.
For large $m$ (and large enough $n_k\, n_l$ to approximate $t$ by Normal) critical values in the right tail will scale as $\sqrt{m}$, whereas the studentised range critical values will scale as $\log m$, so I'd expect the Marascuilo procedure to to be quite conservative in that setting.
If this were actually binomial data I'd recommend simulations to evaluate the distribution of
$$\max_{p\in[0,1]} \max_{k,l} |\hat p_k-\hat p_l|$$
for constant $n_i$, all $p_i=p$, or
$$\max_{p\in[0,1]} \max_{k,l} \left|\frac{\hat p_k-\hat p_l}{\sqrt{1/n_k+1/n_l}}\right|$$
for varying $n_i$.  (That is, not dividing by the estimated standard error, because the outer maximum is then not well-defined)

If you can't simulate under the null (and it sounds like you can't with complex sampling), I don't know what to recommend -- the useful simplification with binomial data is they are homoscedastic under the null hypothesis.

Tukey's comparisons for proportions


Verificar hora atual do smartphone

Question: Estou querendo sempre verificar a hora atual do meu dispositivo e com isso exibir uma notificação. Porém utilizando este código, só consigo pegar a hora que abro o app
Como posso fazer essa verificação em segundo plano, e quando chegar na hora determinada o app me mande a notificação.
Agradeço desde já
 SimpleDateFormat dateFormat_hora = new SimpleDateFormat("HH:mm:ss");

    Date data = new Date();

    Calendar  cal = Calendar.getInstance();
    cal.setTime(data);
    Date data_atual = cal.getTime();

    String hora_atual = dateFormat_hora.format(data_atual);

    TextView horaatual = (TextView) findViewById(R.id.horaatual);
    horaatual.setText(hora_atual);

Comment: Veja [isto](http://pt.stackoverflow.com/a/105275/2541)
Answer: Amigo, você pode resolver seu problema utilizando a classe AlarmManager (https://developer.android.com/reference/android/app/AlarmManager.html).
Com ela é possível agendar a execução de um código, inclusive com repetição dentro de um determinado período de tempo. No seu caso poderia ser a exibição da notificação desejada.
Aqui você encontra um exemplo da utilização da classe:
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
...
alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

// configura o alarme para disparar as 8:30
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 30);

// setRepeating() para especificar um intervalo de repetição -- 20 minutos, por exemplo

alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
        1000 * 60 * 20, alarmIntent);

Fonte: https://developer.android.com/training/scheduling/alarms.html - com código fonte de exemplo para download.
Comment: Resposta foi adequada conforme sugestão.
Answer: Nao sei se percebi bem o que você quer, mas se for para ter a hora corrente em um textview podes fazer o seguinte:
package mz.co.oncreate.timetest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Thread myThread = null;
    Runnable runnable = new CountDownRunner();
    myThread= new Thread(runnable);
    myThread.start();
}

public void doWork() {
    runOnUiThread(new Runnable() {
        public void run() {
            try{
                TextView horaCorrente= (TextView)findViewById(R.id.horaLbl);
                Date dt = new Date();
                int hora = dt.getHours();
                int minutos = dt.getMinutes();
                int segundos = dt.getSeconds();
                String curTime = hora + ":" + minutos + ":" + segundos;
                horaCorrente.setText(curTime);
            }catch (Exception e) {}
        }
    });
}

class CountDownRunner implements Runnable{
    public void run() {
        while(!Thread.currentThread().isInterrupted()){
            try {
                doWork();
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }catch(Exception e){
            }
        }
    }
}
}

De seguida eh so você fazer a sua implementação para a notificação " antes de: horaCorrente.setText(curTime); "

Verificar hora atual do smartphone


How many users will connect to my Server (simplified)?

Question: This is a simplification of question: How many users will connect to my Server?, in which I'm trying to make it simpler and more defined.
I have 5 days in a week.
Each day has 6 temporal slots of 1 hour.
There are 4 working-groups.
Each group must fill exactly 2 slots in a week, each one with a working unit.
The work of a group doesn't exclude (and doesn't influence in any way) the work of another group in the same slot.
Each week has always 4 * 2 = 8 working units, which are randomly distributed in the available slots. The only constraint is that the working units of the same group can't fill the same slot.
I define a measure, the overlap, which is the maximum number of working unit contained in the same slot. Given the constraint the maximum overlap of a week is 4, i.e. all the groups fill a given slot with their own working unit.
For example, if in the slot of one day there are 3 working units, and there aren't in the whole week more working units for a given slot, the overlap of this week is 3. Also, if there are two days, each one with a slot containing 3 working units, the overlap is 3. Again, if there is one slot with 3 working units and many other slots with 2 working units, the overlap is always 3.
I'd like to calculate:

P(overlap = 0)
P(overlap = N)
P(overlap < N)

Thanks,
   Riccardo
Comment: Clarifications: does slot filling takes place on a daily basis, or is the slot "booked" in the beginning of the week for the whole week, or for some days of it? You write "the slot of Monday" and then "the overlap of this _week_" which confuses.
Comment: Also, does each working unit requires two slots, or it can fill only one slot?
Comment: question updated to be more precise, Alecos is it ok?
Comment: I think so. I will post a tentative answer and we will take it from there.
Comment: One more clarification: when you say "must fill a slot in a week" you mean one slot of one hour during any one day of the week, or, say, "they fill the 10:00-11:00 with one working unit starting Monday, and they continue to be in that slot until and including Friday"?
Comment: yes, I'm adding another clarification sentence.
Comment: Although an answer has been posted, I will try to re-phrase my requested clarification : when you write "one working unit takes up one slot", do you mean one _temporal_ slot (i.e. just one hour over the week), or _one temporal slot per day_ ? And if this latter is the case, is this slot the same every day (i.e. the 10-11 slot), or can it change from day to day?
Comment: Consider only one working group: it has only two working units to spend in a week and one is not influenced by the other. The only constraint is that the two working units are not in the same slot. ,  are both valid asignments for a working group. The valid assignments are in the form of: , where x, y in Slot AND x != y. The only invalid assignments are in the form of: , where x in Slot.
Answer: Let number of total slots be $n$ ($= 5*6$ in your case). Let number of groups be $m$ (4 in your case).
Think of $n$ distinguishable bins where you want to fill $2m$ distinguishable balls.
$P(\{\textrm{overlap} \leq N\}) :=$ Probability that there is at most N balls in any bin after filling the $n$ bins with $2m$ balls. Note that  $1\leq N\leq m$.
\begin{align*}
P(\{\textrm{overlap} \leq N\}) &= \frac{\sum_{\left\{k_i: N \geq k_i\geq 0, \sum_{i=1}^{n} k_i = 2m\right\}}{2m \choose {k_1,k_2,...,k_{n}}}}{\sum_{\left\{k_i: m \geq k_i\geq 0, \sum_{i=1}^{n} k_i = 2m\right\}}{2m \choose {k_1,k_2,...,k_{n}}}}\\
\end{align*}
Using this, we can compute any other probability. For example, $P(\{\textrm{overlap} \leq m\}) = 1$. When $2m \leq n$,
$$P(\{\textrm{overlap} \leq 1\}) = \frac{{n \choose 2m}{(2m)!}}{\sum_{\left\{k_i: m \geq k_i\geq 0, \sum_{i=1}^{n} k_i = 2m\right\}}{2m \choose {k_1,k_2,...,k_{n}}}}$$
Also for non cumulative probabilities, $P(\textrm{overlap} = r) = P(\{\textrm{overlap} \leq r\}) - P(\{\textrm{overlap} \leq r-1\})$ where $r$ is a positive integer between $1$ to $m$.
Comment: Thank you, I can't understand where you take into account that the same working group can't spend two working units in the same slot.
Comment: a couple of question for the summatory in the first formula. 1) do you mean the sum, for k_i from 0 to m, but why do you introduce K_i = 2m? 2) the lower part of binomial is meant to be k_i or am I wrong?
Comment: I do not need to take into account that a group cannot spend two working units in the same slot. This is because, I have not attributed which working unit belongs to which group. My computation is agnostic to this.  For instance, lets say there are 4 units in the same slot and 4 more in another slot. You can map this to working groups such that no group will have two units in the same slot. In general, my claim is that for any assignment of working units to the slots, I can map them to the group so that no group has more than one unit in a slot.
Comment: 1. This is the multinomial formula. $k_i$ represents the number of distinguishable working units allotted to the $i^{th}$ slot of a total of $n$ slots. So, for some slot $j$ where no working units are assigned, $k_j = 0$. The total number of distinguishable working units is $2m$ where $m$ is the number of working groups.
Comment: I'm a bit in trouble with your notation, could you please expand the following formula, using N=2? \begin{align*}
\sum_{\left\{k_i: N \geq k_i\geq 0, \sum_{i=1}^{n} k_i = 2m\right\}}{2m \choose {k_1,k_2,...,k_{n}}}\\
\end{align*}
Comment: (I'm using this page as reference: http://en.wikipedia.org/wiki/Multinomial_theorem)
Comment: ${2m \choose {k_1,k_2,...,k_n}}$ is the number of ways 2m distinguishable working units can be partitioned into n slots with exactly $k_i, i=1,...,n$ in each of the slots. Now we need $k_i \geq 0$ since they represent the number of units in a slot. We also need $k_i \leq N$ since we want the "overlap" less than $N$. Also, since we have $2m$ distinguishable working units, we need the sum of these counts $k_i$ to be equal to $2m$. Any such n-tuple of $k_i$ is a valid solution. We are summing over all of these.
Comment: Ok, I figured out how to expand the formula. Now I have only to understand how to generate all the valid n-tuples of k... probably with a software...


If $\dfrac{x}{y}\in A$ for $x,~y\in A,~x<y$ and $\sup A<1$, prove $\sup A\in A.$

Question:
Let $A$ be a non empty subset of positive reals, such that $\dfrac{x}{y}\in A$ whenever $x,~y\in A,~x<y.$ If $\sup A<1$, prove that $\sup A\in A.$

Attempt. If $\sup A\notin A$, then we could find a sequence $0<a_1<a_2<\ldots<1$ of $A$ such that $a_n \to \sup A$. Of course, for all $k$ we have $\dfrac{a_{k}}{a_{k+1}}\in A$, so I thought by telescoping to reach $\sup A$, but I got nowhere.
Thanks in advance for the help.
Answer: Suppose that $\sup A\notin A$. Then $A$ has some sequence $(a_n)_{n\in\mathbb N}$ such that $\lim_{n\to\infty}a_n=\sup A$. We can assume, without loss of generality (since $\sup A\notin A$) that the sequence is strictly increasing. Then$$\lim_{n\to\infty}\frac{a_n}{a_{n+1}}=\frac{\sup A}{\sup A}=1.\tag1$$But the sequence $\left(\frac{a_n}{a_{n+1}}\right)_{n\in\mathbb N}$ is a sequence of elements of $A$ and therefore its limit should be smaller than or equal to $\sup A$. And we are assuming that $\sup A<1$. So, the equality $(1)$ allows us to reach a contradiction.


I don't understand how the notes in this picture are to be played

Question: I'm learning how to play the piano and I don't understand the fingering of the notes in the picture below. I'm not understanding how you're supposed to use the 2nd and 3rd finger twice. I guess that's not what this means but I'm not sure what they are trying to say. Could anyone explain the fingering they would use to play this? Thanks
Comment: @trkly: This depends on the context, which is missing from the question.
Comment: The answer given is correct. However, this isn't the usual way to write this--normally the bottom two notes would be written on the lower clef. What piece of music is this from?
Comment: Everything else aside, what is that from? It does not seem like anything someone teaching someone else piano would be giving as exercise.
Answer: The left hand has wandered into treble clef territory here.  You'll play the bottom two notes with the left hand, and the other three with the right hand.
Comment: Another cue is the fact that the bottom staff is empty, no notes and no rests, so the left hand has to be somewhere else.
Comment: This is clearly the editor's intention, but I'm sure most players would ignore that and play it with one hand (unless there's some other reason, not visible in the graphic)..
Comment: You could also mention, that the space does not permit the note heads to be horizontally aligned and so some were pushed behind.
Comment: @PiedPiper - One possibility would be that the previous measure showing separate voices (so to speak) leading to the two-handed chord.  At any rate, I'm just telling OP how to read what was written.
Comment: @aparente001 That's the kind of other reason I was thinking about. I was not trying to pick holes in your perfectly good answer, just add to it.
Comment: @PiedPiper - Oh, okay, thanks.  Now if I could just figure out why it's gotten 29 votes....
Comment: @PiedPiper But then you should mention that the bottom two notes may be played with a single finger (a thumb lying across two keys); although there's only five notes, the position with a separate finger for each note/key might be too awkward for players with small hands
Comment: @Ansa211 - Do you mean the other way around?  Do you mean thick fingers and big hands could have trouble with a separate finger for each key?
Comment: @aparente001 No, I actually mean that someone with a small hand would find it much easier to place the thumb slightly sideways across two white keys than to play "d" and "f" with fingers 2 and 3 while holding down all the remaining fingers as well. (Assuming there  are no accidentals on the c's and d's in the signature.)
Answer: This is a chord of 5 notes:
The fingerings for the r.h.  usually are written above the notes, and the fingerings for the l.h. below the notes!
There's absolutely  no reason that you couldn't play this chord only with one hand c=1,d=2,f=3,g=4,a=5 (r.h.)
but you can also play a cluster of 3 tones with the fist (r.h.)
or 2 neighbor keys with the thumb (r.h.: c and d => 1,  f,g,a => 3,4,5 ... l.h.: c,d,f -> 5,4,2  g and a => 1)
Mind: musicians are autonom human beings and not the slaves of any composer or editor.
Fingerings are meant as a proposition or an option. If you find your own fingerings more practicable or more comfortable so use your own ideas.
And don't forget: there are always misprints and errors in the notation of chords and (not too seldom!) in the fingerings.
But in your example the intention and indication is clear.
Comment: Fingering notations are really only a guideline. Not all hands and neuro-muscular systems are created alike.
Comment: You're assuming this is in the key of C (or A minor).  Since we can't see the key signature, we don't actually know.  If some of these notes are sharp or flat, it might be a bit awkward to hit them all with one hand.
Answer: You can tell, here, from way the numbers are written. The upper group shows 2,3,4 going up, just like the fingers on your right hand. The lower group shows 2,3 going down, just like the fingers on your left hand.


Running Cron every 2 weeks on saturday

Question: we have a cron job that run every Saturday at 01:00 (0 1 * * 6) we want to modified to run every 2 weeks on Saturday at 01:00.
Thanks.
Answer: The simplest way is to wrap your job in a script
<code> week=$(date +%V); if [ $(( $week % 2 )) -eq 0 ]; then echo "run program"; fi
</code>
Then just run the wrapper every week... Change the 0 to a 1 for odd weeks..

Running Cron every 2 weeks on saturday


Fornecedor desconhecido

Question: Eu terminei um aplicativo na plataforma C# Windows Forms e quero publicá-lo em um site, mas o aplicativo precisa de permissão de administrador para conectar com o servidor e baixar para uma pasta do Windows. Então exportei o meu certificado de segurança, e fui abrir o certificado e deu tudo ok. Mas no momento que eu executo o aplicativo sempre fica aparecendo "Fornecedor Desconhecido" como mostra a imagem.
Comment: Dê mais detalhes. Só com isto não tem como saber o que está acontecendo. Pense. Você conseguiria resolver o problemas só com estas informações?
Answer: Como não há detalhes da instalação o problema pode ser outro mas vou dizer um dos problemas possíveis.
Qual o propósito de um certificado?
Se uma pessoa disser que pode cuidar da sua casa, você deixa?
Provavelmente não.
Se ela apresentar uma carta qualquer dizendo que ela é confiável, você aceita?
Acho que ainda não.
Foi exatamente o que você fez.
Como resolver?
Para resolver isto você terá que comprar um certificado confiável por todos. Um certificado emitido por alguém que pode dizer quem é você. Tem que ser uma autoridade certificadora.
O sistema operacional tem algumas autoridades certificadoras confiáveis instaladas nele. É possível instalar outras.
Então claro que é possível tornar você uma pessoa confiável mas terá que fazer isto em cada computador que for instalar a aplicação (isto pode ser feito através de redes completas em determinadas situações). Se vai publicar a aplicação em um site, duvido que esta seja uma solução. Em todo caso é possível oferecer uma forma das pessoas fazerem isto. Será algo complicado para quase todo mundo fazer, dificilmente elas farão mesmo que saibam como. A não ser que ela já confie em você.
O processo todo pode ser visto no artigo da Wikipedia. Lá tem uma lista de autoridades certificadoras. E é claro que você terá que fornecer provas de quem você é, além de pagar pelo certificado e deverá renovar anualmente.
Essa resposta no SO indica algumas formas para certificação grátis se o projeto for open source. E aparentemente as coisas mudaram desde a resposta original aqui e está mais fácil obter um certificado gratuito.
Fora isto terá que conviver com esta mensagem. É preciso deixar claro para o usuário que ele pode estar instalando algo de uma pessoa não confiável, que é risco dela aceitar e que o autor não poderá ser localizado em caso de danos (muitas pessoas não percebem que o certificado serve basicamente para isto).
Artigo interessante sobre o assunto.
Mais informações.
Veja também este assunto relacionado (mas o tipo de certificado é diferente).
Coloquei no GitHub para referência futura.

Fornecedor desconhecido


Definir largura de  ou  no HTML5

Question: Preciso definir a largura de uma coluna em uma table, mas o width (inline) no HTML5 não é suportado, conforme a documentação: HTML  Tag
Neste caso, não pode ser feito inline ? Quais as opções ?
Como em e-mail marketing, tudo deve ser inline, e agora !?
Comment: Sem problemas meu jovem, agora ficou mais fácil de entender mesmo rss. Já até editei minha resposta com a sua solução. Se vc quiser trabalha com um CSS externo vc tb pode, depois usa um compilador que pega seu css e coloca direto nas tag como eu fiz no exemplo. Aqui mesmo tem uma ferramente online que ajuda nisso, ela pega seu .css e coloca na tag pra vc no arquivo inteiro. http://divtable.com/table-styler/
Answer: EDIT:
Para fazer o estilo direto na tag vc pode usar o style="" para colocar o width
Vai ficar dessa forma:

        100px
        200px

RBZ acredito que nesse link a fonte se refere ao width direto na tag tipo:
 isso é errado mesmo!

Repare que todos os atributos do link são de propriedades da tag  como colspan, nowrap, align etc. Isso não se refere ao width do CSS!
Palavras da documentação da Mozilla: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table

Usage Note: Do not use this attribute, as it has been deprecated. The rules should be defined and styled using CSS. Use the width property instead.

Ou seja, use o width pelo CSS. Como no exemplo abaixo.

.gg {
  width: 100px;
}
.ggg {
  width: 200px;
}

    100px
    200px

Answer: Só um adendo, prefira pegar referências direto no
https://www.w3.org/ ou no
https://developer.mozilla.org
são mais confiáveis
Voltando à sua dúvida, por que não usar o css? O atributo width é totalmente suportado pelo elemento TD. O HTML5 não incentiva a usar esses atributos nas tags, veja o elemento font que foi descontinuado, tudo isso para focar estilos onde deve ser, no CSS
Veja esse exemplo de como usar no CSS de forma simples:

table { border-collapse: collapse;}
th, td { border: solid 1px; padding: 0 }
td:first-child { width: 200px  }
td:first-child + td {  width: 150px }
td:first-child + td + td {  width: 120px }

          Primeira 200px
          Segunda 150px
          Terceira 120px

          texto
          texto
          texto

Note que usei o seletor first-child + td para aplicar um estilo diferente para cada td em sequencia da tabela.
Comment: Não que a w3schools seja uma excelente fonte. Mas nesse caso o problema acho que não foi a fonte, mas sim o entendimento do conteúdo da página. Lá fala *"All layout attributes are removed in HTML5."* removidos do HTML5 não do CSS.
Comment: Não deixa de ser uma verdade, que o `HTML5` descontinuou os atributos de format nas *tags*, mas por isso não gosto muito da referência do w3schools :)
O w3.org por sua vez é muito detalhado e difícil de ler às vezes, por isso prefiro o mozilla.org, e ainda tem muita coisa em português. Mas concordo com você, que a forma como foi escrito lá não é bem clara
Comment: Tb uso mais a referência da MDN do que W3C, mas o w3school tem alguns exemplos práticos que as vezes ajudam o entendimento. []´s
Comment: Desculpa aí pessoal, eu que não expressei direito. Minha questão é específica do estilo na tag. Já editei a pergunta !
Comment: Entendi @RBZ, nesse caso só usar a `style: width` na tag. O negócio do `HTML5` foi remover só os atributos de estilo, como `width` e `height` mas style é totalmente funcional

Definir largura de  ou  no HTML5


unable to make html table column fixed size (not auto expand according to Data)

Question:
I have above data table. Now the problem is when data coming from backend is very much it expand and make the table awkard.
I want to wrap whole data in particular fixed column size. colmn should not be expanded.
My html code is like:

      Subject

     <s:property value="subject" />

Plz help.
Thanks in Advance
Comment: You missed a closing tag of tr
Comment: no this is just copy paste mistake... tr is closed properly
Comment: Can you fix it on the question?
Comment: Btw "Work Item/Tasks" won't have a value like that in real life :) If you seperate that with a space it would be fixed.
Answer: To have fixed column widths, use table-layout: fixed; in your CSS.
Comment: @F.Müller Add `word-wrap: break-word;`, but it will also break other words ant random place (it will break where it needs to break)
Comment: @F.Müller It's `word-wrap`, not `text-wrap`
Comment: First I thought of this aswell but the problem lies in the "text-is-sticky-and-will-expand-cause-no-whitespace" problem (see his image). You could also just set the widths of each individual td. If you do this the text will draw over the rest of the table even when the sibling td's are as big as they should be. But the answer is good as such. :)
Comment: http://jsfiddle.net/5084duow/2/ word-wrap does not work when you have no whitespaces (which is rarely the case) I just mentioned this cause of his image. But you are right for the "standard" case.
Comment: I tried "table-layout:fixed" , now column size doesn't expand but data is overlapping all column next to Subject.
Comment: @AbhishekRajawat yes the problem is that if you have no whitespaces it will not break the text it will just expand to the right. See here: http://jsfiddle.net/5084duow/2/
Comment: @F.Muller, yes I got your point, I need to give white space. Its ok. But Actually this was test scenario made my tester, if user typed like this, table will badly messed.
Answer: use this CSS
      . padng10{

   width:70px;
   text-overflow:ellipsis;
     overflow: hidden;
    white-space: nowrap;
  }

Comment: for this-- class="padng10"  and also give some width to that div


Functions over $\mathbb C$ that are both additive and multiplicative

Question: If we have a function $f:\mathbb R\to\mathbb R$ so that, for all reals,
$$f(x)+f(y)=f(x+y)\text{ and }f(x)f(y)=f(xy),$$
we can conclude that it is either identically $0$ by the following argument:
We have $f(x)^2=f(x^2)$, so nonnegative $x$ are mapped to nonnegative $f(x)$. However, this means $f$ is monotonically nondecreasing, so, as $f(q)=cq$ for all rational $q$ and some fixed $c$, $f(x)=cx$ for all $x\in\mathbb R$, and then we can easily find $c\in\{0,1\}$.
However, this argument fails for $f:\mathbb C\to\mathbb C$. My question is thus as follows:

Does there exist a function $f:\mathbb C\to\mathbb C$ besides $f(x)\equiv 0$ and $f(x)\equiv x$ for which
  $$f(x)+f(y)=f(x+y)\text{ and }f(x)f(y)=f(xy)$$
  for all $x,y\in\mathbb C$?

I've been able to show a bit about algebraic numbers:
If $P(x)\in\mathbb Q[x]$, we know by additivity, multiplicativity, and the fact that $qf(x)=f(qx)$ for any $q\in\mathbb Q$ (by additivity), that $f(P(x))=P(f(x))$. (The same should hold for multivariate polynomials as well.) So, if $P(x)=0$, then $P(f(x))=0$. If we have a polynomial $P$ of degree $n$ and its roots $x_1,\dots,x_n$, we have that
$$\sum_{i=1}^n x_i^k=f\left(\sum_{i=1}^n x_i^k\right)=\sum_{i=1}^n f(x_i)^k,$$
where the first equality is because the sum is rational. Now, because $S=\{x_i\}$ and $T=\{f(x_i)\}$ are two (multi)sets for which
$$\sum_{s\in S}s^k=\sum_{t\in T}t^k$$
for all $k$, they must be in fact equal, and thus $f$ permutes the roots of any rational polynomial. However, I can't figure out how to generalize this at all to non-algebraic numbers, or whether anything should break.
Answer: $f(z)= \overline{z}$ comes to mind.
There are also "wild" automorphisms of $\mathbb C$, for which you need the Axiom of Choice: see e.g. this posting
Comment: Oops -- I can't believe i forgot about conjugation. And it's not too difficult to prove that conjugation is the only nontrivial continuous automorphism of $\mathbb C$. Are there any others particular automorphisms that enjoy other nice properties (i.e. ones that are nicer than an arbitrary "wild automorphism" as constructed in your linked answer)?
Comment: All except the identity and conjugation are wild (non-measurable).  See the Kestelman paper referred to in the link I gave.


Windows Server Clear on Logout Policy

Question: I was wondering is it possible to create a policy on Windows Server 2008 R2 or 2012 that will clear everything (all files from desktop, documents, etc) once the user has logged out of the system? It will basically seem like once they log back into the system it will look like a new PC.
I hope this makes sense.
Thanks in advance :)
Comment: Have a look into this [thread](http://superuser.com/questions/244849/wiping-an-accounts-setting-and-files-when-user-logs-off).
Comment: There is also mandatory profiles, here are some links but there's also some good YouTube videos on this as well.  `1.` https://msdn.microsoft.com/en-us/library/windows/desktop/bb776895(v=vs.85).aspx `2.` https://support.microsoft.com/en-us/kb/973289 `3.` http://www.jeroentielen.nl/howto-create-a-mandatory-profile-server-2012. I'd do some reading, watch some videos, and then test until you get it to work from the OS you need it.
Answer: Put the user connecting to it in the local group Guest.
That way the system create temporary profile for those users and they are deleted at logoff.
Answer: Assuming a domain based system with roaming profiles, there are a few GPO settings which could potentially achieve this effect:
Delete cached copies of roaming profiles
Prevent Roaming Profile changes from propagating to the server
As suggested in the comments, a mandatory profile could also work. The best thing to do would be to test based on your own circumstances and requirements.

Windows Server Clear on Logout Policy


HP Proliant ML350 G5 Windows Server 2012

Question: We have two types of servers we need to upgrade to Windows Server 2012 64bit

HP Proliant DL380 G6
HP Proliant ML350 G5

I think they both have licenses for Windows Server 2008 but they are currently running Windows Server 2003.
I have seen on their website that Windows Server 2012 should work on the DL380 server but I am not sure about the ML 350.
http://h17007.www1.hpe.com/us/en/enterprise/servers/supportmatrix/windows.aspx#.WWbHglElGUk
Can I install and run Windows Server 2012 on my HP Proliant ML350 G5?
Answer: Yes, Windows 2012 will run on your G5 ProLiant.
However, G5 servers date back to 2005. So installing a atop such an old platform may not be the best idea.


Matching values between two different fields, each of which have multiple values

Question: I have a content type with an imagefield and a link field. Each of those fields accepts four values; so the user uploads four images and types four URLs in each node.
I want to use Views to create a block based on that node that displays the first image linked to the first URL; the second image linked to the second URL; etc. I don't want to use CCK 3 with Multigroup (if possible) because it seems to sometimes cause weird behavior in Views, Contemplate, etc.
Given the existence of Delta fields, "Group multiple values", etc., it seems like this should be possible. But I can't make it work. Is it possible? Or should I bite the bullet, use CCK 3, and hope it's not confusing as all get-out?
Answer: You shouldn't use delta for such thing as data sometimes get reordered in the tables (ex: for node reference, the nid gets reordered regarding the title of the node referenced).
So I'll recommend you to create 4 fields for images and 4 for the URL and eventually put them in groupfields.
Also to make things prettier you can theme your form and put each group of field in a row using div or table.
Have a look at Theming Forms in Drupal 6 for information regaring form theming and the official documentation: The theme registry for special cases.
Another nice tutorial: http://www.akchauhan.com/theme-drupal-form/


Get de conteúdo em JavaScript

Question: Preciso fazer algumas alterações em uma página web.
Estou criando um formulário em HTML com JavaScript e preciso de ajuda no seguinte caso:
Meu formulário possui um campo onde o usuário digita o ID de um contest do SPOJ-WWW, depois de digitado o ID a página deve fazer um get de alguns dados do contest que está no SPOJ para completar outros campos do meu formulário.
Por exemplo, o usuário digita o ID de algum problema e a página automaticamente identifica qual é o problema e completa os campos, título, descrição, objetivos, etc.
Existe alguma função no JavaScript que faça isso de alguma forma, tipo dando get do conteúdo?
Comment: Se estiver aberto para usar Jquery, `ajax` pode ajudar
Answer: Não sei se eu entendi bem, pois não sei o que é SPOJ rsrsrs....
Porém acredito que o que você queira pode ser feito da seguinte maneira:
1 - Implemente uma função para manipular o preenchimento do ID. Essa função vai disparar quando o evento "onfocusout" acontecer no input.
2 - Ao disparar, a função faz um "fetch" para o endpoint que serve o conteúdo que você quer.
3 - Você pega o Response do GET Request realizado (pelo fetch()) e então coloca as informações recebidas nos campos que decidir.
handleIdSearch(event){
 let valor = event.target.value;
 fetch("http://urlDaApi.com.br?idProduto="+valor).then( function(resposta){
      // Veio um objeto do tipo Response, precisamos transformá-lo em JSON
      // Response.json() retorna outra Promise
      return resposta.json();
   }).then( function(json){
      // Pegue os valores do JSON
      document.getElementById("outroInput").value = json.valorOutroInput;
   }).catch( function(error){
      throw error;
   });
}

document.getElementById("campoIdProduto").addEventListener('focusout',
// Callback do evento
function(event){
    handleIdSearch(event);
})

Voi lá!
Answer: Fazendo uma requisição GET utilizando javascript puro:
var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML =
      this.responseText;
    }
  };
  xhttp.open("GET", "ajax_info.txt", true);
  xhttp.send();

Exemplo retirado de W3schools
Ainda pode utilizar a função fetch como mencionado pela resposta de Caio Saldanha.

Fazendo uma requisição com a biblioteca jQuery:
$.get( "ajax/test.html", function( data ) {
  $( ".result" ).html( data );
  alert( "Load was performed." );
});

Exemplo retirado da documentação do jQuery

Get de conteúdo em JavaScript


MATLAB newbie: error using "saveas" to save a plot as a pdf file

Question: I am a Mac (10.6.8) user.  I have written MATLAB code for plotting calculation results and then saving the plots as pdfs.  I use "saveas" (see example below).
I get this error:
??? Error using ==> print at 325
Problem converting PostScript. System returned error: -1.Failed to convert to output format; Ghostscript status: -100.**** Unable to open the initial device, quitting.

Error in ==> saveas at 155
        print( h, name, ['-d' dev{i}] )

Error in ==> Results_processor at 1219
saveas(gcf,saveFigTo1, 'pdf')

Here is the relevant piece of code:
calculationResultsPath    = '/Me/Projects/ThisProject';
calculationResultsDirectory          = strcat( calculationResultsPath,'MATLABProcessedResults' );
mkdir( calculationResultsDirectory );

% ...Code for importing results to be plotted from external files (works fine)...

% ...Code for plotting (works fine)... I get the figures I want.

% The problem is:
saveFigTo1    = strcat(resultsDirectory,'/majorsMgO.pdf')
saveas(gcf,saveFigTo1, 'pdf')
hold off
pause
clf;

Some further information...  This worked fine last week when I first wrote it!  Since then, I think I updated to Mac OS 10.6.8 from 10.6.7, but nothing else has changed in my code or in the version of Matlab I use (R2009a) (unless I have a very bad memory!).
Also, I came across some older suggestions on similar questions to use "print."  I tried using:
print(gcf,'filename').  I did get a pdf, but it would not open in any pdf viewing programme.  I assume (but don't know for sure) that this could be related to the fact that I use a Mac.  I have noticed that there are a few things (especially related to external file manipulation) that don't run on Mac.
If anyone could help, I would be very grateful.

Update:
I found a GhostScript for Mac and installed it as Chris suggested.  Unfortunately, that didn't work.  I read on a forum that many Mac users are having problems with MATLAB plots at present, possibly related to java.  There was an operating system update (to OS X 10.6.8) last week and that is when the problems began.  My code worked before then.
I still have not found a solution to this and I don't think the MATLAB people have either, so if anyone has suggestions about how to save plots WITHOUT using saveas, I would love to hear them.  The "print" command does not work for me either--it produces PDFs that I can't open.
Answer: I think the problem here is GhostScript dying and not so much Matlab. A Google for that GS error turns up many pages such as this. Is this at all applicable? If you use GS outside of Matlab does it work?
As an aside, you might take a look at this FEX submission export_fig. It has treated me well. Worst case you could output to png and convert to PDF later.
Comment: Thank you, Chris.  I had not even heard of GhostScript until you mentioned it.  I'll look into it!
Answer: One recommendation I can make is to use a different format that OS X understands and simply convert the result to pdf with a system call
See if the following works:
% Load a test image
im = imread('cameraman.tif');

imshow(im); % display the image

saveas(gcf,'test.tif','tif');

% convert to pdf using a syscall to cupsfilter
!cupsfilter test.tif > test.pdf 2> /dev/null

% open the file with your default pdf viewer
!open test.pdf

If the above is not working, yet another approach is to get the bitmap from the figure window and write it using imwrite.  Note, this method doesn't benefit from the nice font scaling features of the saveas and print. This approach assumes the im variable above still exists.
imagesc(im); colormap gray;

% Set the border color to white
set(h,'Color',[1 1 1]);

% Get the image in the figure
frame = getframe(gcf);
imout = frame.cdata;

% on OS X, the stretch window image
% appears in the bottom right corner
% of the image.  Remove it.
imout = imout(10:end-9,10:end-9,:);

% Write the image out to a lossless tif
imwrite(imout,'test.tif','tif','Compression','none')

You could then convert the tifs to pdf files as above.  The quality of the figure will depend on the figure size.  In most cases, I wouldn't use this second approach as saveas handles the fonts nicely.  Using getframe is meant only as a workaround to the true problem with saveas.
Comment: Thanks a lot for the suggestion, ephsmith.  The imshow(im) command produces the image, but the files "test.tif" and "test.pdf" are both empty.
Comment: I'm sorry to hear that.  I'm unable to test on your specific setup.  I'm running 2010a on OS X 10.6.8.
Comment: Thanks ephsmith.  Saving directly does work, but it is painful because I need to save so many figures!
Comment: I completely understand.  I have to generate loads of figures as well.
Comment: It is interesting that saving from the figure window works. In my version of Matlab, `saveas` is the callback function for saving from the figure window. I'll post another approach that uses `imwrite` instead.


Golden Rectangle into Golden Rectangles

Question: Can these golden rectangles be rearranged to exactly cover the underlying cyan  golden rectangle?

That's the entire question.  All that follows is related discussion. I want to make a more elegant proof without words. It comes from the series:
$$\sum_{n=1}^{\infty} \phi^{-n} = \phi$$
The golden rectangle has a well known dissection into squares to make the golden spiral. I'm wondering if the golden rectangle can be divided into smaller golden rectangles with areas $(\phi^{-1}, \phi^{-2},\phi^{-3}, \phi^{-4}, \phi^{-5})$, ... .
Half the rectangles have edges of the form $\phi^{-n}(\sqrt{\phi} \times \sqrt{1/\phi})$, the other half have edges of the form $\phi^{-n}(1 \times \phi)$. These two series make squares with areas $1/\phi$ and $1$, as shown in the opening graphic.
Note that the golden triangle can be divided into golden gnomons with those exact areas. Also, the golden gnomon can be divided into golden triangles with those exact areas, as shown below.

If we solve the following instead,
$$\sum_{n=2}^{\infty} x^{-n} = x$$
we get $x = 1.46557123187...$, the real root of $x^3-x^2-1=0$, which is the Narayana cow sequence constant.  In 1356, Narayana asked "A cow gives birth to a calf every year. In turn, the calf gives birth to another calf when it is three years old. What is the number of progeny produced during twenty years by one cow?".
It turns out I could make a proof without words with the infinite cow fractal. But it wasn't until today that I thought to  add the summation to the picture. So then I tried making the golden version, and found it had apparently never been done, and seemed to be hard to solve.

Is there a similar picture for the golden rectangles with a rearrangement of the rectangles in the first image above?
Basing the rectangle dissection on Ammann's Chair doesn't seem to help, but their are nice ideas there.
This is related to New Substitution Tilings Using 2, φ, ψ, χ, ρ.
Comment: @YuriyS I believe that "Can we divide the golden rectangle into this exact series of smaller golden rectangles?" intends to ask whether the arrangement of embedded rectangles used to derive the golden spiral is a fractal or not. Am I right?
Comment: Is the situation regarding this post and the dupe as it is now acceptable for you or do any problems persist?
Answer: Impossible w/ Rectangles Alone
I believe what you're asking for is impossible using golden rectangles alone. A walk-through of possible horizontal-vertical orientations of the inserted pieces (along w/ a little imagination showing that shifting the pieces doesn't help) ends in the following configurations, demonstrating that you can't manage to fit the five largest rectangles of the sequence into the "frame". (Symmetry about the dashed blue line allow us to condense the exploration of the #1-vertical sequence.)

Possible w/ Rectanges and Squares
A solution is possible however if you allow the use of squares for the $\phi^{-2n}$ areas, which avoids the $\sqrt{\phi}$ issue.
Comment: pretty convincing, I think I tried most of those.

Golden Rectangle into Golden Rectangles


How to use interface to communicate between activities after process death?

Question: I am building an SDK and need to implement callbacks between activities, without actually finish an activity. I previously used onActivityResult to provide results back to caller activity. However, this closes activity and I need to deliver callback, without finishing activity from SDK. My current implementation:
fun initializeSDK(){
    SDK.getInstance().initialize(resultsCallbackImpl)
}
val resultsCallbackImpl:ResultsCallback = object : ResultsCallback {
    override fun response1() {

    }

    override fun response2() {

    }
};

For example, the client calls initializeSDK() from his activity after the button click. Then the client passes interface as parameter, which is set as a property in SDK singleton. Then I use that interface to return results.
The problem occurs after process death. The interface becomes null, because it is not serialized and I can't return callback to client anymore. How should I edit my code to tackle this issue? Is it even possible?
I know that client can initialize SDK in the application class, then it will be re-set after process death. However, such an approach will result in difficulty for the client to communicate results back to activity from application class.
Comment: Could you use a foreground service for this?
Comment: Does my answer address your issue?
Comment: I just updated my answer. I hope it is useful.
Comment: I would suggest you to add module classes in to your app(main project), so you can access all of variables. It can be a little bit tedious, but it will work.
Answer: Update:
Do a right click on the project tree and add a new AIDL file called IMyAidlInterface.aidl:
package com.test.aidlsample;

import com.test.aidlsample.MyData;

interface IMyAidlInterface {
    List<MyData> getData(long id);
}

If you need to return objects to your client you need to declare and define them as parcelable and import them in aidl file too, here is the MyData.aidl that should be beside the other aidl file:
package com.test.aidlsample;

// Declare MyData so AIDL can find it and knows that it implements
// the parcelable protocol.
parcelable MyData;

and this is MyData.java in the java folder:
public class MyData implements Parcelable {
    private long productId;
    private String productName;
    private long productValue;

    public MyData(long productId, String productName, long productValue) {
        this.productId = productId;
        this.productName = productName;
        this.productValue = productValue;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeLong(this.productId);
        dest.writeString(this.productName);
        dest.writeLong(this.productValue);
    }

    protected MyData(Parcel in) {
        this.productId = in.readLong();
        this.productName = in.readString();
        this.productValue = in.readLong();
    }

    public static final Parcelable.Creator<MyData> CREATOR = new Parcelable.Creator<MyData>() {
        @Override
        public MyData createFromParcel(Parcel source) {
            return new MyData(source);
        }

        @Override
        public MyData[] newArray(int size) {
            return new MyData[size];
        }
    };
}

Now build the project so Stub class gets built. After a successful build continue with the service:
public class SdkService extends Service {

    private IMyAidlInterface.Stub binder = new IMyAidlInterface.Stub() {
        @Override
        public List<MyData> getData(long id) throws RemoteException {
            //TODO: get data from db by id;
            List<MyData> data = new ArrayList<>();
            MyData aData = new MyData(1L, "productName", 100L);
            data.add(aData);
            return data;
        }
    };

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }
}

and add the service to the sdk manifest. If you are adding sdk as a dependency to the client like: implementation project(':sdk') you don't need to add AIDL files to client. If not, you have to add them and build the client application. Now, only remains to implement the client activity:
public class MainActivity extends AppCompatActivity {

    IMyAidlInterface mService;

    /**
     * Class for interacting with the main interface of the service.
     */
    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className,
                                       IBinder service) {
            // This is called when the connection with the service has been
            // established, giving us the service object we can use to
            // interact with the service.  We are communicating with our
            // service through an IDL interface, so get a client-side
            // representation of that from the raw service object.
            mService = IMyAidlInterface.Stub.asInterface(service);

            try {
                List<MyData> data = mService.getData(1L);
                updateUi(data);
            } catch (RemoteException e) {
                // In this case the service has crashed before we could even
                // do anything with it; we can count on soon being
                // disconnected (and then reconnected if it can be restarted)
                // so there is no need to do anything here.
            }

        }

        public void onServiceDisconnected(ComponentName className) {
            // This is called when the connection with the service has been
            // unexpectedly disconnected -- that is, its process crashed.
            mService = null;
        }
    };

    private void updateUi(List<MyData> data) {
        //TODO: Update UI here
    }

    @Override
    protected void onResume() {
        if (mService == null) {
            Intent serviceIntent = new Intent();

            //CAREFUL: serviceIntent.setComponent(new ComponentName("your.client.package", "your.sdk.service.path"));
            serviceIntent.setComponent(new ComponentName("com.test.sampleclient", "com.test.aidlsample.SdkService"));
            bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
        } else {
            try {
                updateUi(mService.getData(1L));
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        super.onResume();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

every time your client activity gets visibility, it gets data from sdk service. Just build your logic over this template. In sdk activity save data to a database and in service query them from database. I've used simple parameters in this sample.
I assumed your sdk is a library in the client app. If not, you need to do some small modifications maybe. And as I mentioned before you can find more details here: Android Interface Definition Language (AIDL). There are lots of samples and even more Q/A here in the SO on the subject. Good luck.
Original: You need to get callbacks from an activity that is currently invisible since your SDK activity is in front, right? To do that you can create a database for your SDK, persist data to your database and get data via an AIDL in the starting activity:
SdkService sdkService;
CallbackData callbackData

private ServiceConnection mConnection = new ServiceConnection() {
    // Called when the connection with the service is established
    public void onServiceConnected(ComponentName className, IBinder service) {
        sdkService = SdkService.Stub.asInterface(service);
    }

    // Called when the connection with the service disconnects unexpectedly
    public void onServiceDisconnected(ComponentName className) {
        Log.e(TAG, "Service has unexpectedly disconnected");
        sdkService = null;
    }
};

in onCreate:
Intent i = new Intent()
i.setClassName("your.sdk.packageName", "your.sdk.service.path.and.name");
bindService(i, mConnection, Context.BIND_AUTO_CREATE);

and in whenever needed:
if(sdkService != null){
    callbackData = sdkService.getCallbacks();
    updateUI();
}

Just be careful getting a binder is an async job so if you call bindService and right after call sdkService.getCallbackData you get a NullPointerException. So you might want to move getCallbacks and updateUI inside the onServiceConnected and call bindService in onResume so every time activity becomes visible you would check if there is CallbackData so you can update your UI or whatever.
Comment: I know IPC via AIDL seems to be complicated, but it is quite simple, standard and easy to use. I try to update my answer with a complete sample.
Comment: Yes, I need exactly that, quote: "You need to get callbacks from an activity that is currently invisible since your SDK activity is in front, right". Thanks for your approach I haven't known this. Will this approach work even if process death occurs? Will my restored activity be able to communicate with client's activity after that?
Comment: Yes, because after you return to the client activity, it gets recreated again. It gets a binder to the SDKService and will get the data from sdk database. Using AIDLs is a standard solution for communication in developing sdks. BTW, what you are mentioning as the process death is probably a scenario that client activity is destroyed by system but process is not killed since your sdk activity is alive and showing.
Comment: Yes, this is the scenario what I call process death. You said that client's activity gets recreated after I return to it. However, I ned somehow to recreate client activity without returning to it. Because, after process death occurs activity from SDK is present and client's activity is destroyed by the system without using AIDL. So you are saying that if I implement AIDLs, then client's activity will also be recreated automatically, even though activity which is precent to user is actually the one from SDK?
Comment: No I mean if your client is not visible you should not really care about it. When sdk activity creates a data it saves it in the database. At a time, the client activity needs to become visible. Either it has been destroyed or not you call getBackupData and get the required data from the SDK database and make required changes in the client activity.
Comment: Thanks, just one more question, before accepting this answer. So by calling getBackupData I will reactivate the client ,without finish SDK's activity, and client will be able to get results even if it was previously destroyed yes?
Comment: Sure. It gets whatever you wish from SDK to the client activity. You bind to the sdk service and call getData, and in sdk service you get data from database and return it.
Comment: Have you been successful with the AIDL implementation?
Comment: I have looked at it and got confused if I should rather use Messenger for communication. I don't need concurrency benefits using AIDL. Also, I could not find a decent example for Messenger communication between two activities. All examples were structured in a way that the activity instantiates service and receive callbacks from it. The issue in my case is that there are two activities: client's and our SDK activity.
Comment: Thanks, I awarded bounty to you! I am still working on finishing it in our project, but so far it seems promising! I will keep you updated
Comment: I wish you good luck and looking forward to hearing form it.
Answer: You cannot use interfaces directly to communicate between activities.
As soon as you start a new activity and new activity becomes visible android OS can kill 1st activity anytime (you can try this with a flag inside developer option "Don't keep activities"). So user of your SDK will complain about certain random "null pointer exception".
So, Now if you want to share data between current and previous screen, you might have to rethought your solution using Fragments.
Exposing your UI using a fragment and communicating back your result to activity which then would update proper fragment which needs the data.
I faced similar issue in one existing app which I was asked to fix. I switched entire app to fragments and single activity, first to release a hot fix.
Comment: Thanks for good overview! Yes I know about process death aka "Don't keep activities" and I just wanted to reassure myself if I my thinking is correct. I fought about fragments, but that mean that our SDK would not have even a single activity at all. It would be all fragments. So client then could initialise our SDK and add fragment. Would that be work correctly with "Don't keep activities"? However, if process death occurs fragment will be restored automatically by the system, but interface would still be null
Comment: The problem statement is that you need to send some kind of events to parent continuously. That means Parent has to be alive. I can think of handling such situation with fragments only. Now if you want to handle death, then you need to properly save state of fragments and custom  ui components if you have any. Proper handling of lifecycle callbacks is important in your case.
Answer:
The problem occurs after process death. The interface becomes null, because it is not serialised and I can't return callback to client anymore. How should I edit my code to tackle this issue? Is it even possible?

This is not possible. If the client process dies, all of its executing code - including your SDK - gets wiped away.

I know that client can initialise SDK in the application class, then it will be re-set after process death. However, such approach will result in difficulty for client to communicate results back to activity from application class.

So what? If the client Activity is restarted, it should call the SDK again to set a new callback instance which you can use from that point forward.
Comment: The issue is that client has no way of determining if process death occurred and an activity from SDK has been restarted. How can client activity call SDK again and set a new callback after process death occurred? I can't find any way in which client can restart SDK initialisation, because it is not client activity, which becomes presented after process death it is the last visible activity, which is always the one from the SDK... :(
Comment: Oh, so it's your Activity that is on top? In that case, why do you need to communicate back to the client activity? There's no guarantee that activity will exist if yours is in the foreground. Please clarify what you're trying to achieve.
Comment: Yes, my activity is on top. I wanted to hear other people opinions about this question. I also was hesitant to use this approach and wanted to get feedback if it is even possible to communicate to the client activity after process death occurred. By looking at yours and other question I feel that it is not possible to do that. Thanks!
Answer: You can use a sharedviewmodel that is bound to both activities; have a mutablelivedata variable that you can observe from the two activities.
ideally on the first activity you can just put the value inside the mutablelivedata variable. Then on the second activity get the activity.
Follow the following link to give you a guideline.
ViewModel Overview


Using Eloquent to build relationship that stretches across four or more tables

Question: Here is a schema:
users: id

schools: id | district_id

school_users: id | school_id | user_id

districts: id

How would I build a relationship in Eloquent in order to return $district->users?
class District
{
    public function users()
    {
        //something that mirrors this functionality
        return $this->hasManyThroughThrough("User","SchoolUser","School");
    }
}

Answer: You should span accross 2 relationships:
class District
{
    public function users()
    {
        return $this->hasMany('School');
    }
}

class School
{
    public function users()
    {
        return $this->belongsToMany('User');
    }
}

class User
{
}

$books = District::with('schools.users')->get();


Is it a good idea to use a linear model (like logistic regression) to generate new features for a non linear model (like random forest)?

Question: The setting is a 2-class classification problem. We have too many features, some of them not very informative and with many zeros. We are thinking in ways of selecting the best features, and PCA (in the full dataset or maybe in groups of related features) is one of the alternatives. But I thought if there was another way of generating linear combinations of features that not only takes in consideration the intrinsic variance, but also the relationship with the target. Like a target-PCA, if that existed.
And an approximation of this idea could be what I ask in the main question: Could it be a good idea to use a linear classifier like logistic regression or SVM to generate linear combinations of features that, in a way, are optimizing the information gain with respect to the target? Because I think that if, given a subset of variables, a hyperplane can give a good separation of the classes, the equation of the hyperplane, considered as a feature, have more predictive power than any of the individual features, so maybe you could substitute the group of features with the new one and give all this generated features to the last model (the random forest) as the inputs.
EDIT: There is a very similar question to this one, that someone has suggested:
Non-perpendicular hyperplane decision trees
It's closely related to what I was thinking. Thanks everyone!!
Answer:
It looks like Partial Least Squares (PLS) is what you call "target-PCA" - originally this is for regression, but there are versions for classification.

One problem with what you propose here is that you will need to be careful when later using something like cross-validation for assessing the quality of your classifier, because if you use the whole dataset for feature generation, cross-validation of the later random forest will be misleading. (This can be dealt with cross-validating the whole process, but that's more difficult and computationally more cumbersome.)

I'd be surprised if information reduction before random forest is better than random forest on the full information - I don't know of any results that would suggest that such an operation in advance somehow helps the random forest, although the possibility that it does in your situation cannot be excluded (if you have enough data you could leave some aside and compare).

Another issue is that logistic regression or SVD generate features in order to optimise their own way of classifying - why should it be better to use these features with another method that was set up to do something else?


Reset all votes on a content type every week

Question: I am trying to build a website where people vote on individual nodes of a content type using the rate module. Is it possible to reset these votes say every 7 days or every 30 days, so that another round of voting can take place. How would I do this within drupal. I do not want to have to go through phpmyadmin to clear the voting api cache. I would prefer if this is done from within the website I'm building.
Is this possible?
Answer: There's many ways to accomplish this. The voting data for the Voting API module is stored in the votingapi_vote & votingapi_cache tables. Essentially, you need a way to target the vote data you wish to eliminate in these tables (e.g. via a DB query) and then build some process on which to regularly execute it (e.g. a cron run).
A crude example would be a custom module that evokes hook_cron() to check the last query execution and fire it if it hits its time threshold:
/**
 * Implements hook_cron().
 */
function MYMODULE_cron() {

  // Clear the vote every week.
  $vote_clear_timestamp = variable_get('MYMODULE_vote_clear_timestamp', 0);
  if ($vote_clear_timestamp <= strtotime('-1 week')) {

    // A more targeted process would use db_delete() to target criteria
    db_query("TRUNCATE {votingapi_vote}");
    db_query("TRUNCATE {votingapi_cache}");
    variable_set('MYMODULE_vote_clear_timestamp', time());
  }
}

Comment: I'm not very good with writing custom modules, please could you guide me
Comment: Drupal Answers isn't a tutorial site. Google for tutorials on creating a module in D7 or take a look at the [examples](https://www.drupal.org/project/examples) module. The code is pretty straight forward for D7; you need a ***mymodule.info*** & ***mymodule.module*** file with the cron function in the ***mymodule.module***
Comment: Ok, I think I understand what you're saying now. The question now is how to limit it per content type


Explode number string and change the format

Question: I have many strings such as:

"184.108.40.206.2"

and I would need to pull it apart and put it back together again like this:

"1.05.22.01.02"

The difference is that there are no leading zero for the first one.
This is a big, "copy, manipulate and paste" job because the strings are used as codes in one of out programs.
Comment: Have you tried using REGEX?
Comment: Sorry I have no experience with REGEX.
Comment: @morne, the first digit will be 1 or 01? Do you expect "01.05.22.01.02" as result?
Comment: The 1st digit will always be "1" or "2", the rest should all have a preceding 0 if bellow 10.
Answer: Perhaps a VBA UDF is simpler:
Function FormatThis(oCell As Range) As String
    Dim vValue As Variant
    Dim vSplit As Variant
    Dim lCt As Long
    vSplit = Split(oCell.Value, ".")
    For lCt = LBound(vSplit) + 1 To UBound(vSplit)
        vSplit(lCt) = Format(vSplit(lCt), "00")
    Next
    FormatThis = Join(vSplit, ".")
End Function

Call from your cell as =FormatThis(A2)
Answer: An unorthodox solution is to open a new worksheet and do the following:
1) Copy all the numbers (220.127.116.11.2) you want to change and paste it into the new worksheet.
2) Highlight the cells and go to the DATA tab and select "Text to Column"S
2a) Select Delimited and hit NEXT
2b) Select delimiters as Tab and Other with just a dot:

2c) Hit Finished.
Now each of the numbers should be in a new column, and you are going to use if conditions then concatenate them.

Then you can modify the columns as you wish:
for example I have:
for column 1: =D6
for column 2: =IF(E6<10, CONCATENATE(0,E6),E6)
for column 3: =L6
for column 4: =IF(G6<10, CONCATENATE(0,G6),G6)
for column 5: =IF(H6<10, CONCATENATE(0,H6),H6)
If this is the output you're after then we can squeeze back together by concatenation:

The end product is column P or (my column 6)
The formula for the concatenation is: =CONCATENATE(D6,".",E6,".",F6,".",G6,".",H6)
Comment: Yeah, the situation is actually complicated with textfiles etc. so this is the most appropriate answer. thanks
Comment: @morne you can add more conditions for each of the columns as you wish, before all columns are concatenated with a "`.`" inbetween each column.


is $\sin x/(k+\cos x)$ strictly monotonically increasing

Question: i want to find out if
$\sin x/(k+\cos x)$
is strictly monotonically increasing for $0<x< \pi$ and a constant $k>0$.
Plotting the function suggests this is true.
Comment: is $k$ assumed to be positive?
Answer: If $k < 1$ then there will be some value of $x$ such that $k + \cos x = 0$ and the function is undefined.
If $k > 1$ then as $x$ approaches $\pi$ then the numerator starts to approach 0 (while the denominator is greater than 0).  And since f(x) is clearly positive elsewhere this would go against the proposition of a monotonic function.
If $k = 1$ the $f(x)$ is not defined at $\pi$ but the domain is the open interval $(0,\pi)$ so this is not a problem.  And the the numerator and denominator are both going to $0.$
And in fact $\lim_\limits{x\to \pi^-} f(x) = \infty$
In this case the function is monotonic over the domain.
Comment: Thanks for the answers.


Decimal expansions and topological connectedness

Question: I'm a bit confused by the following footnote from Moschovakis's Notes on Set Theory, p. 135fn24 (in the note, $\mathcal{N}$ denotes the Baire space). The puzzling part is in bold:

One may think of $\mathcal{N}$ as a "discrete", "digital", or "combinatorial" version of the "continuous" or "analog" $\mathbb{R}$. A real number $x$ is completely determined by a decimal expansion $x(0), x(1), x(2), \dots$, where ($n \mapsto x(n)) \in \mathcal{N}$, but two distinct decimal expansions may compute to the same real number. This is a big "but", it is the key fact behind the so-called topological connectedness of the real line which is of interest in analysis, to be sure, but of little set theoretic consequence. We may view Baire space as a "digital version" of $\mathbb{R}$ because it does not make any such identifications, each point $x \in \mathcal{N}$ determines unambiguously its "digits" $x(0), x(1), \dots$.

I don't understand the bold part. What is the relation between the fact that some real numbers have two distinct decimal expansions and topological connectedness? Does anyone have any clue about the thought behind the quotation?
Answer: Consider the real number $1$. The fact that it is the limit of the sequence
$$\langle 1.1,1.01,1.001,1.0001,\ldots\rangle\;,$$
for instance, implies that it must be equal to $1.0000\ldots\;$. The fact that it is the limit of the sequence
$$\langle 0.9,0.99,0.999,0.9999,\ldots\rangle$$
shows that it must be equal to $0.9999\ldots\;$. If this were not the case, i.e., if $0.999\ldots$ were not equal to $1.000\ldots\;$, then
$$L=\{x\in\Bbb R:x\le0.999\ldots\}$$
and
$$R=\{x\in\Bbb R:x\ge1.000\}$$
would be a separation of $R$: $L$ and $R$ would be disjoint closed sets whose union was $\Bbb R$, showing that $\Bbb R$ was not connected.
Comment: Perfect! Thanks a lot for this.
Comment: @Nagase: You're very welcome.


Insert de uma tabela na outra com Auto-increment

Question: Olá, comecei recente com banco de dados e estou tentando resolver um pepino, um zebra mal feita no banco e no sistema, usamos atualmente Firebird.
Veja só:
Tenho tabela PRODUTOS e nela, temos coluna CLASSIFICACAO, esta coluna é uma FK com tabela CLASSIFICACAO, por alguma razão não existe uma validação entre as duas tabelas, para conferir um registro em CLASSIFICACAO(PRODUTOS) com tabela CLASSFICACAO, isso faz um bug no sistema, dai para corrigir tenho que identificar qual registro não esta em uma e na outra e fazer um insert.
Quando é pouco registro, vai na mão, agora quando é muito registro vira um Deus me livre.
Pensei em fazer seguinte comando:
delete from CLASSIFICACAO;

insert into CLASSIFICACAO (DESCRICAO) select CLASSIFICACAO from PRODUTOS

Minha ideia, seria passar CLASSIFICACAO que esta em produtos para tabela CLASSIFICACAO, copiando informação, problema que em CLASSIFICACAO temos coluna codigo que não esta como auto-increment e não pode ficar null logicamente.
Como eu poderia colocar ali para ele ir preenchendo campo codigo, na tabela CAMPO codigo, pertence ao produto, se eu pegar ele, dá bug.
Comment: Qual versão do Firebird você está utilizando? A partir da versão 3 você pode utilizar a função Row_Number para preencher o código, ou nas versões anteriores pode criar/utilizar uma Sequence ou Generator
Answer: Então amigo, obrigado pela ideia. Encontrei uma alternativa também, usei distinct para agrupar um select e por meio dele fazer o insert na tabela Classificacao, depois ajustei uma generator e uma trigger para tabela.
delete from CLASSIFICACAO;
insert into CLASSIFICACAO (DESCRICAO)
select distinct CLASSIFICACAO from PRODUTOS;

Mas obrigado, também foi de grande ajuda.
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).
Answer: eu tentaria algo assim,
verificaria apartir de produto quais estão usando um id de classificação que não existe e insert desses id como voce falou:
insert into classificacao (id_classificacao)
SELECT p.classificacao FROM produto p
left join classificacao c on p.classificacao = c.id_classificacao
where c.id_classificacao is null

voce pode decompor esta query e rodar so o select para analisar os dados retornados na query, troque o p.classificacao por * e veras os dados do left join
espero que ajude
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


GIT: projeto com 2 versoes em diferentes clientes e ramo principal

Question: estou com uma duvida em relacao a organizacao do GIT.
Tenho 1 projeto que irá se dividir em 2 versoes para clientes distintos, gostaria de manter um ramo principal e que as alteracoes genericas fossem feito nesse ramo e replicado para as 2 versoes, porem cada versao tera suas alteracoes unicas tb.
O ideal seria fazer com fork ou com branches?
Comment: Eu diria que o ideal seria ter uma configuração que iria seguir o caminho A ou o caminho B, ter dois códigos fontes separados pode lhe dar muita dor de cabeça (experiência própria)
Comment: Mas ai cada melhoria generica eu vou ter que ficar replicando para N projetos, nao acho que seja inteligente isso.

O produto é o mesmo, so temos 2 versoes levemente diferentes para clientes especificos.
Comment: Dependendo do número de arquivos do projeto que mudariam para cada cliente, se forem poucos acredito que usar branch pode ser a solução mais rápida e simples. Porém o fork é a cópia de um projeto base que pode ser alterado livremente que no seu contexto parece ser mais interessante, ainda mais se no futuro você use o projeto base para novos clientes.
Comment: André é esse meu pensamento, ai teria 1 produto base com 2 variantes para cada cliente, qlq alteracao generica é feita na base e replicadas para os demais.

Sera que é a melhor forma para solucionar esse problema?
Comment: @RBoschini, acho que a melhor forma seria o projeto base ser projetado para aceitar parametrizações assim como funciona o Wordpress e outros CMS. Outra forma de fazer é desenvolver o projeto base de maneira genérica e as variantes teriam o projeto base como dependência.
Comment: Não iria adiantar, é um ecommerce e a maior variacao sera de layout e nao de regras de negocio.

a api continuara a mesma, apenas o front seguirá um base que ira se ramificar em 2 versoes levemente semelhantes.

Parametrizar isso nao seria o melhor caminho nesse caso.
Comment: Acabei resolvendo criando fork e fazendo sync com o projeto base qd preciso.
Answer: Esse é o tipo de problema que um versionador de código não vai ajudar você a resolver, o que ele ajuda é na paralelização de um trabalho de desenvolvimento de software, mas o objetivo será sempre os ramos voltarem para o principal.
Eu recomendaria a você buscar uma solução na arquitetura, como fazer extensões ou plug-ins, existem frameworks para isso, em .Net existe o MEF, Managed Extensibility Framework e neste link você pode saber como ele funciona e procurar para algo parecido para a plataforma que você usa.
Answer: Você pode usar duas branches distintas no mesmo repositório. Assim vai ser mais prático manter as duas versões distintas quando precisar fazer alguma alteração que deseja aplicar em ambas as branches por meio de uma outra branch, cherry-pick, etc.
Contudo, não recomendo que faça isto com o seu projeto. Tente manter apenas uma única versão da sua aplicação. Se os clientes tem diferentes necessidades, controle isto com diferentes telas ou permissões. Se continuar com esta ideia, você terminará com duas aplicações distintas e o código que deseja aplicar em ambas não dará certo de tão diferente que as duas aplicações ficaram uma da outra. Isto virará um pesadelo para manter.
Comment: Eu sou testemunha desse inferno de manutenção. Tentou-se fazer isso de cada cliente ter seu branch específico. Na época, tínhamos uns 20 a 30 clientes nesse esquema; desses, 3 sobreviveram em 4 branches separados (sim, um cliente tem 2 branches) em que não há manutenção praticamente (e são infernais de manter, quando necessita), 2 voltaram para o ramo principal e o resto foi cancelado. Entre os motivos dos cancelamentos estava a instabilidade do software
Comment: @JeffersonQuesado, no começo sempre parece ser uma boa ideia. Inicialmente você evita o problema de gerenciar na mesma aplicação as features distintas, e tudo parece bom e as coisas fluem bem. Mas depois de um tempo o destino desta solução é sempre o caos, hehehe


How to output just a page's contents in page.tpl.php in Drupal 7?

Question: I am creating a page.tpl.php template in Drupal 7 in which I want to rearrange how certain elements of the page are laid out. Specifically I want the title of the page to appear before the tabs and messages section (which I have done) and have the content of the page appear after the tabs and messages section (this is where I run into issues). I can't find a way to just render the $page['contents'] without the title. Is there a way to achieve this in Drupal 7?
I know that the node.tpl.php template handles the node specific layout, but it doesn't allow me to layout the page like as described above.
Thanks.
Answer: Somethings can be done in page.tpl.php & some in node.tpl.php
Like you said, you need to make title of the node appear before tabs. You can do this in your page.tpl.php. Find $title variable as well as $tabs & arrange accordingly in your page.tpl.php. Like --
<?php if ($title) : ?>

    <?php print $title; ?>

<?php endif; ?>
<?php if ($tabs): ?>

    <?php print render($tabs); ?>

<?php endif; ?>

After this you will have print render($page['content']);, where node.tpl.php comes into the scene, so arranging other things like node content, comment, links you will have to go to your node.tpl.php & arrange accordingly. More modification such as in comment & other TPLs will come into the scene like comment.tpl.php etc..
Comment: This is what I ended up doing in the end where I do not print out the node's title in the node.tpl.php file to achieve the effect I am looking for. As a caveat to others who want to achieve the same thing, you will need to use a node type specific templates so as to not hide article titles when multiple articles are listed on a page.
Comment: You didn't specify the content type specific requirement, so I didn't mention anything of that regards in my answer. Anyway, node title is part of page.tpl.php not node.tpl.php..


Live Chat Servlet JSP application

Question: I was going through some Live Chat Plugin.
Actually, We already have Web Based application deployed on tomcat running fine.
Now need is to integrate Live Chat feature.
So was thinking and created some design that on FrontEnd I will use jQuery and on Server Side I will use BlockingQueue for incoming Chat Request and then process each request etc etc.
Later on I thought of like instead of doing it all from scratch I can go through some Plugin, There are many jQuery plugins but they all have their own Advertisement added to it. Also most of all are paid for commercial use.
So I came across XMPP Protocol.
I am not much clear on XMPP, does it can help me in developing such Application?
I tried with WebSocket but it requires HTML 5 which restricts me to dig into more.
can some one suggest me proper and right approach for it.
Answer: If can use Java EE 7 then Web Sockets are definitely a way. This technology was specifically designed to handle connection of multiple clients and their interaction on the web page. If you can't switch to Java EE 7, there are also other frameworks which can do the job like Atmosphere or others, just take a look at the list which can be found here.
Comment: I read regarding webSocket. Consider I can switch to Java 7 still can't afford that it works only with HTML 5. Need some solution with Java 6.
Comment: I already wrote that in my answer, give Atmosphere a try:)There are already plenty of chat examples - https://github.com/Atmosphere/atmosphere-samples/tree/master/samples

Live Chat Servlet JSP application


How to declare WCF subtype(knownTypes) without having to reference it

Question: We have a server that can return a "configuration", this configuration is a big and complex hierachy of classes.
Our application works by "packages", meaning that we have a "common" base, and then there is part of the application that will not be even installed.
It means that the configurations classes are not all in the same project, and we often have structure like:
public class SomeObject{
   public IEnumerable<ISomeObjectChild> Childs{get;set;}
}
public interface SomeObjectChild{
   //[...]
}

And in some other project, have some class that implement them:
public class SomeChildImplementation: ISomeObjectChild{
   //[...]
}

There is factory to instantiate those kind of childs and everything is working fine.
Now we have to transfer over the network this kind of configuration, using WCF.
My issue is that I know I should indicate what could be the types potentially implementing the ISomeObjectChild. I know that usually, we should declare them with [KnownType(typeof(SomeChildImplementation))], but it is not possible:

This class doesn't know all its possible childs
This class cannot even reference thoses childs

So how could I indicate what are the possible implementations?
(in this case it's with an interface, but I've some others cases with abstract classes).
Comment: Not a duplicate but a answer to your question: https://stackoverflow.com/a/41460207/6666799
Answer: KnownTypesAttribute has another constructor that can be used to specify a method that will return an array of KnownTypes, see here
The implementation of this method can depend on how dynamic you want to be. Either configure the types you want to support in some configuration file or use System.Reflection to scan for classes that implement ISomeObjectChild
Comment: This is interesting. I'm curious, performance wise, what would you recommend? How would you do this "configuration"?
Comment: @J4N Are you referring to the configuration file or reflection approach? In terms of performance the method you use will only be invoked once, at least for the `DataContractSerializer`.


Criar uma pasta em php em um repositorio especifico

Question: Eu crio uma pasta pra cada usuário, porem esta criando onde esta meu arquivo php, quero criar em uma pasta dentro desse repositório onde esta o arquivo, mas não esta indo, é simples mas sou novato.
<code>$parts = explode('/', $dir);
        $file = 'dados.json';
        $dir = $data;
        foreach($parts as $part)
            if(!is_dir($dir .= "/$part")) mkdir($dir);
        file_put_contents("$dir/$file", $json);
</code>
Tentei isso:
<code>$parts = explode('/', $dir);
        $file = 'dados.json';
        $dir = $data;
        $past = 'Users'
        foreach($parts as $part)
            if(!is_dir($dir .= "/$part")) mkdir($dir);
        file_put_contents("$past/$dir/$file", $json);
</code>
Answer: se o código está funcionando e apenas criando a pasta no lugar errado, tente isso:
<code>               $parts = explode('Users/', $dir);
                $file = 'dados.json';
                $dir = $data;
                foreach($parts as $part)
                if(!is_dir($dir .= "/$part")) mkdir("C:\Users\$dir");
                    file_put_contents("C:\Users\$dir\$file", $json);
</code>
onde "C:\Users\" seria o caminho completo de onde deseja criar a pasta
Answer: Resposta:
<code>                   $parts = explode('Users/', $dir);
                    $file = 'dados.json';
                    $dir = $data;
                    foreach($parts as $part)
                    if(!is_dir($dir .= "/$part")) mkdir("Users/$dir");
                        file_put_contents("Users/$dir/$file", $json);
</code>


Limit of expected value of supremum and infimum

Question: Let $(\Theta,d)$ be a metric space, $\mathcal{X}\subset\mathbb{R}^n$ and $f:\Theta\times \mathcal{X}\to\mathbb{R}$. Define $X$ as a random variable in $\mathcal{X}$. Suppose that the mapping $\theta\mapsto E[f(\theta,X)]$ is continuous.
For a fixed $\theta\in\Theta$ define the subsets $B_1(\theta),B_2(\theta),...$ as $B_j(\theta)=\{\theta':d(\theta,\theta')< 1/j\}$. Therefore, $B_1(\theta)\supset B_2(\theta)\supset\cdots $ and $B_j(\theta)\downarrow\{\theta\}$ as $j\to\infty$.
Is it true that
$$
\lim_{j\to\infty}E\left[\sup_{\theta'\in B_j(\theta)}f(\theta',X) - \inf_{\theta'\in B_j(\theta)}f(\theta',X)\right] =  E[f(\theta,X)]-E[f(\theta,X)]=0\quad ?
$$
My approach was by defining $\theta_j^U$ and $\theta_j^L$ such that
$$
f(\theta_j^U,X) = \sup_{\theta'\in B_j(\theta)}f(\theta',X),\quad f(\theta_j^L,X) = \inf_{\theta'\in B_j(\theta)}f(\theta',X).
$$
So by continuity, we have
$$
\lim_{j\to\infty}E\left[\sup_{\theta'\in B_j(\theta)}f(\theta',X)\right]=\lim_{j\to\infty}E[f(\theta_j^U,X)]=E[f(\lim_{j\to\infty}\theta_j^U,X)]=E[f(\theta,X)].
$$
The weak arguments are that $\theta_j^U$ might not be well defined and that $\theta_j^U$ not necessarily converges to $\theta$ a.s.
Can anybody provide some insights? Is the affirmation true? If not, under what conditions is it true?
Answer: I don't think this is true.  If we take $\Theta = [-1,1]$, $X = \pm 1$ with probability $\frac 12$, and define $$f(\theta, x) = \begin{cases} x & \theta \le 0 \\
-x & \theta > 0\end{cases}$$ then $\mathbb{E}[f(\theta,X)] = 0$ so in particular $\theta \mapsto \mathbb{E}[f(\theta,X)]$ is continuous.  However, if we fix $\theta = 0$ then $\sup_{\theta' \in B_j(0)} f(\theta',X) = 1$ and $\inf_{\theta' \in B_j(0)} f(\theta',X) = -1$ for every $j > 0$ so $$\lim_{j \rightarrow \infty} \mathbb{E}\left[\sup_{\theta' \in B_j(0)} f(\theta',X) - \inf_{\theta' \in B_j(0)} f(\theta',X)\right] = 2.$$
I'm not sure exactly what the conditions you need are, but I would guess that at the very least you need $f(\theta,x)$ to be continuous in $\theta$.
Edit: If you have $\Theta$ is locally compact, $\theta \mapsto f(\theta,x)$ is continuous, and $\mathbb{E}[\sup_{\theta \in \Theta} |f(\theta,X)|] < \infty$, then the dominated convergence theorem gives
$$\lim_{j \rightarrow \infty} \mathbb{E}\left[\sup_{\theta' \in B_j(\theta)} f(\theta',X) - \inf_{\theta' \in B_j(\theta)} f(\theta',X)\right] = \mathbb{E} \left[\lim_{j \rightarrow \infty}\left( \sup_{\theta' \in B_j(\theta)} f(\theta',X) \right)- \lim_{j \rightarrow \infty}\left( \inf_{\theta' \in B_j(\theta)} f(\theta',X)\right)\right] = \mathbb{E}[f(\theta,X) - f(\theta,X)] = 0$$
Comment: Thanks for the answer! I don't understand how did you use the continuity of $\theta\mapsto f(\theta,x)$. Is it sufficient that $\Theta$ is locally compact and $\theta\mapsto f(\theta,x)$ to conclude that $\lim_{j\to\infty}\sup_{\theta'\in B_j(\theta)}f(\theta',x)=f(\theta,x)$ ?
Comment: Yeah, the local compactness gives that the closure of $B_1(\theta)$ is compact (because it's a closed subset of a compact set) so $\theta \mapsto f(\theta,x)$ is uniformly continuous on the closure of $B_1(\theta)$.  This is slightly stronger than what we need because it actually means that $\lim_{j \rightarrow \infty} \sup_{\theta_1,\theta_2 \in B_j(\theta)} |f(\theta_1,x)-f(\theta_2,x)| = 0$.


how fast does the proportion of associative operations on $S$ decrease with |$S$|?

Question: as doubtless many have done before me, i recently fell into wondering how many of the binary operations on a finite set are associative. the stackexchange software fortunately pointed me to this discussion Is the Ratio of Associative Binary Operations to All Binary Operations on a Set of $n$ Elements Generally Small? before i could irritate people by submitting a duplicate question.
on that location André Nicolas provided a neat answer to Doug Spoonwood's enquiry concerning the limit as $n \to \infty$ of the proportion ($r_n$) of operations on a set of $n$ elements which are associative.
as André points out his estimate is sufficient to show $r_n \to 0$ but there is a lot of scope to use similar arguments to tighten it. in fact $r_n$ appears to drop very rapidly with $n$. suppose we define:
$$ \alpha_n = \sum_{j=1}^n r_j
$$
Q1 is $\alpha_n$ a convergent sequence? (easy?)
Q2 (harder?) if the answer to Q1 is positive, and $\alpha = \lim_{n \to \infty} \alpha_n$, is $\alpha$ a Liouville number, hence transcendental?
Answer: André arrives at a ratio $r_n=O(\frac1n)$ merely by checking if $1^2$ commutes with $1$. For "most" choices, we should be able to find $d$ elemends $k_1,\ldots, k_d$ that in most caes differe from their squares as soon as $n\gg 2d$. If for each of these we check if $k^2$ commutes with $k$, this should give us that $r_n=O(n^{-d})$.
So Q1 is alredy answered positively with $d=2$ (which may even be not too hard to handle explicitly with all special cases).