Smart PayPal Buttons in React, disable the button

Question: I have this implementation of the PayPal smart buttons in React:
function PayPalButtonComponent(props: PayPalButtonProps) {
  const [show, set_show] = useState(false);
  const [error, set_error] = useState<string>();

  const create_order = (_: any, actions: any) => {
    return actions.order.create({
      purchase_units: [
        {
          amount: {
            currency: props.currency || "EUR",
            value: props.total
          }
        }
      ]
    });
  };
  const handle_approve = (_: any, actions: any) => {
    return actions.order.capture().then((details: any) => {
      if (props.onSuccess) props.onSuccess(details);
    });
  };
  const handle_cancel = () => {
    if (props.onCancel) props.onCancel();
  };
  const handle_error = () => {
    if (props.onError) props.onError();
  };
  const render_button = () => {
    const Button = paypal.Buttons.driver("react", { React, ReactDOM });
    return (
      <Button
        style={{
          layout: "horizontal",
          size: "responsive",
          shape: "rect",
          color: "gold",
          tagline: false
        }}
        funding={{
          allowed: [paypal.FUNDING.CARD, paypal.FUNDING.PAYPAL],
          disallowed: [paypal.FUNDING.CREDIT]
        }}
        createOrder={create_order}
        onApprove={handle_approve}
        onError={handle_error}
        onCancel={handle_cancel}
      />
    );
  };

  useEffect(() => {
    if (props.isScriptLoaded) {
      if (props.isScriptLoadSucceed) set_show(true);
      else set_error("Unable to load the paypalscript");
    }
  }, [props.isScriptLoaded, props.isScriptLoadSucceed]);

  if (error) return
{error}
;
  if (!show) return <FakeButton />;

  return render_button();
}

I have struggled to implement these buttons in react since there is no documentation, I have found and copied some code from here and trying to guess other stuff. But I can't understand how to disable the button.
In this guide they state that one can call the disable() method on the actions object but can't figure out how I can accomplish that with my configuration.
Have you ever try something similar? Do you know any documentation one can follow?
edit
What I'm trying to accomplish is to set the button in a disable state during the payment. I know there is the paypal overlay, but when the transaction completes I change the app route and since it happen when onSuccess is called, due to the apparent async nature of actions.order.capture() this can't happen instantaneously, and so there is a moment when one can click again on the paypal button. If i can disable the button i have solve the problem.
The onInit implementation allows you to disable/enable the button before clicking on it, useful for some sort of validation before the checkout (like terms checked) but doesn't apply to my case. I have also tried to call actions.disable() in create_order but that breaks the button.
Comment: The documentation you linked to shows an `onInit` function that sets up a listener that calls `actions.disable()` based on events that happen. This seems straightforward enough. Have you tried implementing that? If not, why not? What would you like to do instead? Your question does not specify.
Answer: Have same situation here and the onInit example from documentation is not that straight forward as some think... You would need to create hidden imput and assign somsort of variable to it when payment made in order to achieve buttons to be disabled after payment. To bad no one solve this one.
Answer: For React, I would use the official PayPal NPM (@paypal/react-paypal-js) package. They have some good documentation on how to use it... in your case just use the  component and you can set if its disabled or not as an attribute.
Checkout their code example:
import { useEffect } from "react";
import {
    PayPalScriptProvider,
    PayPalButtons,
    usePayPalScriptReducer
} from "@paypal/react-paypal-js";

// This values are the props in the UI
const amount = "2";
const currency = "USD";
const style = {"layout":"vertical"};

// Custom component to wrap the PayPalButtons and handle currency changes
const ButtonWrapper = ({ currency, showSpinner }) => {
    // usePayPalScriptReducer can be use only inside children of PayPalScriptProviders
    // This is the main reason to wrap the PayPalButtons in a new component
    const [{ options, isPending }, dispatch] = usePayPalScriptReducer();

    useEffect(() => {
        dispatch({
            type: "resetOptions",
            value: {
                ...options,
                currency: currency,
            },
        });
    }, [currency, showSpinner]);

    return (<>
            { (showSpinner && isPending) &&
 }
            <PayPalButtons
                style={style}
                disabled={false}
                forceReRender={[amount, currency, style]}
                fundingSource={undefined}
                createOrder={(data, actions) => {
                    return actions.order
                        .create({
                            purchase_units: [
                                {
                                    amount: {
                                        currency_code: currency,
                                        value: amount,
                                    },
                                },
                            ],
                        })
                        .then((orderId) => {
                            // Your code here after create the order
                            return orderId;
                        });
                }}
                onApprove={function (data, actions) {
                    return actions.order.capture().then(function () {
                        // Your code here after capture the order
                    });
                }}
            />
        </>
    );
}

export default function App() {
    return (

            <PayPalScriptProvider
                options={{
                    "client-id": "test",
                    components: "buttons",
                    currency: "USD"
                }}
            >
                <ButtonWrapper
                    currency={currency}
                    showSpinner={false}
                />
            </PayPalScriptProvider>

    );
}


Breez Create Complex Entities

Question: I have Entity Like this
 public class Person
{
    public string FirstName { get; set; }
}

public class Employee
{
    public string EmployeePhoto { get; set; }
    public virtual Person Person { get; set; }
}

so when I try to create new entity on breezjs on client side
manager.createEntity('Employee');

it didnt create the person entity with it that unable to bind like this
<input type="text"  data-ng-model="vm.employee.person.firstName" placeholder="First Name" />

but it show me the following error

Cannot read property 'entityState' of undefined
Comment: Have you tried creating the person first and then creating the employee by passing an object that sets the person like this: http://stackoverflow.com/questions/17538542/breezejs-how-to-initiate-complex-type-properties-when-creating-a-new-entity
Comment: How can I do That? I donot understand the link you attach
Comment: Breeze isn't going to automatically create a person entity when you create an employee entity.  You'll need to create the person entity yourself.
Answer: What you are calling a complex entity, Breeze thinks of as two related entities: Employee and Person.  As Wayne and Jeremy noted, you need to create each of them.
But there is something else: Breeze manages the relationship between the entities using their foreign keys.  You need to have identifiers for each of your entities, and the foreign key relationships to them.  Then your entities would look something like this:
public class Person
{
    public int PersonId { get; set; }
    public string FirstName { get; set; }
}

public class Employee
{
    public int EmployeeId { get; set; }
    public string EmployeePhoto { get; set; }
    public virtual Person Person { get; set; }

    [ForeignKey("Person")]
    public virtual int PersonId { get; set; } // relates Employee to Person
}

The foreign keys are essential, because that is how Breeze can recognize the relationships between entities that are sent to and from the server.
And then you can do this:
var employee = manager.createEntity('Employee');
var person = manager.createEntity('Person');
employee.person = person;

OR you can do it this way, telling Breeze to assign the property in the initializer:
var person = manager.createEntity('Person');
var employee = manager.createEntity('Employee', { person: person });

OR you can relate the properties by personId in the initializer:
var person = manager.createEntity('Person');
var employee = manager.createEntity('Employee', { personId: person.personId });

Comment: the problem is when I try to bind like this

data-ng-model="vm.employee.person.firstName"

it show me the following error

'firstName' is required'
Answer: I found the problem, I was trying to create the entity after featch metadata,
like this
this.manager.fetchMetadata()
            .then(function () {

            });

when I take out... it fixes

Breez Create Complex Entities


Opening a ECSlidingViewController from a non ECSlidingViewController

Question: I have tried reaching a ECSlidingViewController on IBAction. However when I tried the below code:
<code>-(IBAction)openNewPage:(id)sender{ //IV

UIStoryboard *storyboard;
ECSlidingViewController *slidingViewController = (ECSlidingViewController *)[storyboard instantiateViewControllerWithIdentifier:@"IV"];
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
    storyboard = [UIStoryboard storyboardWithName:@"iPhone" bundle:nil];
} else if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
    storyboard = [UIStoryboard storyboardWithName:@"iPad" bundle:nil];
}

slidingViewController.topViewController = [storyboard instantiateViewControllerWithIdentifier:@"FirstTop"];

}
</code>
I get the following error:
<code> 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'
</code>
I tried a modal action on the button, the 'touchupinside' will land at the InitialViewController. Any suggestions on this?
Answer: You need to move the line where you define slidingViewController to below your if-else-if clause because storyboard will be nil where you currently do it.
<code>UIStoryboard *storyboard;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
    storyboard = [UIStoryboard storyboardWithName:@"iPhone" bundle:nil];
} else if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
    storyboard = [UIStoryboard storyboardWithName:@"iPad" bundle:nil];
}
ECSlidingViewController *slidingViewController = (ECSlidingViewController *)[storyboard instantiateViewControllerWithIdentifier:@"IV"];
slidingViewController.topViewController = [storyboard instantiateViewControllerWithIdentifier:@"FirstTop"];
</code>
Comment: In this case, I passed the modal action to the initial view controller which is blank. As a result I get a blank page. If I pass it to the top view controller I get the error again. Any idea on how to go about this? thanks for the help
Comment: @SiddharthanAsokan, I have no idea what you're talking about without seeing more code. What modal action? What is the initial view controller? If you log slidingViewController using the code I gave you , does it log correctly?


How to break URL's in java?

Question: If I have a string:
This is a sentence. It also has a url www.example.com.

how can i break it, and turn it into
This is a sentence. It also has a url www example com.

notice the url was broken, but the other dots weren't removed.
how do i do this with java?
Comment: First, `www.example.com` is not a URL, it's a domain. `http://www.example.com` is a URL. There's no way to know which dot should be removed and which one shouldn't unless you know the structure of the URL.
Answer: You can use a regular expresion like this
/^www\.([a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9])\.([a-zA-Z]{2,})$/

How to break URL's in java?


Strange behavior of MySQL IMPORT

Question: On Windows platform (Windows7)
I am trying to import a database form .sql file through command prompt by using following command

mysql -u username -p database-name < path-of-file\filename.sql

It runs successfully.
But If I use semicolon at the end of the command

mysql -u username -p database-name < path-of-file\filename.sql;

It is not showing any error/warning but printing mysql help document and import fails
On Linux Platform (Ubuntu)
Both import(With semi-colon & without semi-colon) work fine.
My MySQL Version : 5.5
Answer: Windows command line (cmd.exe) is not a POSIX-shell, as most likely your Linux shell is. This means ; are treated differently -- the ; is interpreted by your shell and not by your MySQL client.

Strange behavior of MySQL IMPORT


Como consumir menos memória em runtime C#?

Question: O que eu gostava de saber é quais são as formas mais eficientes para consumir menos memória em runtime.
Uso de variáveis "static" ?
Criar objeto com instancias ou uma static class?
Uso do Dispose() para libertar memória, etc.
Comment: O `Dispose` não libera memória, pelo menos não deveria, porque vai depender de quem o implementou. O `Dispose` deve servir para liberação de recursos externos e apenas isso. Sobre o _static_, realmente pode haver um ganho em alguns casos porque não há passagem de referência do `this` para o método, mas você precisa considerar que, se está tão preocupado com esse tipo de coisa, deveria estar usando uma linguagem mais apropriada para o problema que está tendo.
Comment: Apenas tentando adivinhar, suspeito que está a corrigir o problema errado. A maior parte das aplicações não tem problemas de memoria a menos que façam coisas que não devam.
Comment: Na verdade, só queria dicas de como programar de forma mais eficiente no que diz respeito ao uso de de variáveis e metodos
Answer: A pergunta começa um pouco ampla. Há muitas maneiras e o assunto me interessa, acho legal usar técnicas de economia de memória porque elas ajudam muito na performance. Menos memória usada (no heap) traz menos lixo gerado, menos coletas, menos pausas, menos overhead pra gerenciamento da memória.
Uso de variáveis estáticas tendem a gastar mais memória, ou pelo menos retê-la por mais tempo. Se a semântica que precisa é essa, ok usar, caso contrário não use.
Porém o seu uso pode ser muito útil, não para economizar, mas sim para evitar coletas desnecessárias. Se você sabe que não haverá acesso concorrente (em alguns casos é possível, só é preciso mais cuidado) e que o objeto muda algumas vezes, mas sempre mantém uma instância dele, pode ser mais interessante criar um objeto e reusá-lo, pode ser uma forma "de pobre" de fazer um pool de objetos. Mas é preciso entender o que está fazendo. Feito corretamente cria-se menos objetos e gera menos coletas dando menos pausas. Uma das dificuldades é quando o objeto não tem tamanho definido, como o caso de strings, outra é que pode perder localidade e o objeto ficar longe do seu container, oque pode fazer tudo ficar mais lento, aí começa criar o problema que linguagens que não possuem GC têm (ao contrário da crença popular, GC pode oferecer melhor performance em muitos cenários).
Não importa se a classe é estática ou não. Ela em si não define estado, a única coisa é que não pode ter estado em uma instância dela, mas pode ter instâncias de outros objetos dentro dela.
O Dispose() é interessante onde ele é necessário, e tem várias perguntas sobre isto (acho que existe mais sem a tag).
Pool de objetos é uma dica forte e .NET mais recente (2.1) já tem isto mais ou menos pronto para as situações triviais. E tem adicionais como o pool de streams, só pra ficar em um exemplo.
O uso do ref em structs pode trazer um ganho enorme, mas novamente, precisa saber usar certo. Veja também Para que serve esse 'in' em C#?.
As técnicas são muitas. Tem coisas mais específicas, tem coisas que dependem do que está fazendo, tem muitas coisas que são pequenos detalhes.
Coloquei no GitHub para referência futura.
Answer: Usar Static é a pior coisa que podes fazer em termos de memória. Ao usar Static estás a dizer ao servidor que esta variável está sempre disponível na memória pois é inicializada assim que o programa inicia.
O que é que recomendo?
Não cries variáveis para guardar valores que só vão ser utilizados uma vez.
Exemplo:
int result = num1 + num2;
if(result<0)
{}

Pode ser resumido em
if((num1+num2)<0) {}

Outra coisa que recomendo é utilizar o using () para que todas as variáveis utilizadas dentro desse bloco sejam recolhidas pelo garbage collector assim que o código sair desse bloco.
Comment: O último parágrafo não faz o menor sentido. O uso de `Dispose` não deve ter absolutamente nada a ver com coleta de lixo, ele deve ser usado para liberação de recursos externos. Se alguém implementa `Dispose` forçando a coleta, está fazendo isso completamente errado. Inclusive, forçar a coleta de lixo é uma das piores coisas que se pode fazer quando se quer cuidar da memória.
Comment: Usar `static` está longe de ser a pior coisa que pode fazer com memória, na verdade há casos que é a melhor. Servidor?!? Seu exemplo economiza zero em memória. Acho que não entendeu a funcionalidade do `using` e vide também comentário do @LINQ.


Determine where hazards starts to increase for a continuous variable

Question: I'm interested in a continuous variable, namely blood pressure.
The higher the blood pressure, the greater the risk of heart attack and stroke.
However, studies frequently report that also low blood pressure is associated adverse outcomes.
The question is: what is the optimal blood pressure? At what value of blood pressure does risk start to increase?
In other words, how can I model, and visualize graphically, what hazard ratio various levels of blood pressure is associated with. I suspect that some will suggest restricted cubic splines. Do you have any suggestions on suitable R packages that will help me visualize the effect of blood pressure on hazard. I'm fairly familiar with Cox regression and plan using the RMS package. Time-dependent variables are included.
Sample data (no time-dependent variables):
event <- c(1,0,1,0,0,0,0,1,0,0,0,1,1,0,1,0,0,1,0,1,1,1,1,0,1,1,1,0,0,1)
survival <- c(4,29,24,29,29,29,29,19,29,29,29,3,9,29,15,29,29,11,29,5,13,20,22,29,16,21,9,29,29,15)
statin <- c(0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0)
bloodpressure <- c(160,120,150,140,135,110,139,140,153,129,149,163,179,129,144,119,100,115,145,150,130,120,122,129,116,171,129,126,159,150)
data <- data.frame(event, survival, statin, bloodpressure)
View(data)

require(rms)
fit <- coxph(Surv(survival, event) ~ statin + rcs(bloodpressure, 3), data=data)

I had something like this in mind:
http://www.bmj.com/content/325/7372/1073/F1

http://www.nejm.org/doi/full/10.1056/NEJMoa1215740

Thanks
Answer: I think you are on the right track with rcs of the rms package. In fact, rms comes with its own version of Coxph, it is called cph.
You might wish to try the following
fit <- cph (Surv(survival, event) ~ statin + rcs(bloodpressure, 3), x=TRUE, y=TRUE, data=data)
# x, y for predict, validate and calibrate;
plot(Predict(fit), data=data)

You may read more about this in the lecture note of Professor Harrell (author of RMS package and a book of the same name) http://biostat.mc.vanderbilt.edu/wiki/pub/Main/RmS/rms.pdf Scroll to Section 18.4
Here is however another side to consider - have you included all the relevant variables in your model? It is not necessary to have only one variable in the model to visualize its effect. An under-specified model produces biased estimates because it does not control for all the potential confounding variables. (See for example: http://en.wikipedia.org/wiki/Omitted-variable_bias)
EDITED: For the plot.Predict method to work correctly, you would need the following two lines before the cph line. (I have to confess I don't know the exact meaning of this, but I see this in 18.1 of Harrell's notes, and it helps resolve the error message for me) Hope this helps~
dd <- datadist(data)
options(datadist = 'dd')

Comment: Thanks @Clark! I've tried that actually;
plot ( Predict ( fit ) , data=dataset )
and
plot(fit).
This is covered in the book RMS (p. 517), but I'm getting the errors: "variable age_inclusion does not have limits defined by datadist" and "'x' and 'y' lengths differ", respectively, when using those commands.
Comment: I edited my post to add in the datadist command which resolves the "does not have limits defined by datadist" error. However, I am not sure where does the variable age_inclusion come from. I suspect the above suggestion would resolve the 2nd error as well, but if it does not, you may wish to check out this post: http://stackoverflow.com/questions/18110691/x-and-y-lengths-differ-in-r
Comment: Thanks again Clark. I had the datadist in order, but found out that the problem was my choice of Cox model; I use the extended Cox model, that did not work. When I switched to the "usual" (without start and stop intervals for observations) it worked. Unfortunately I really want to use the extended Cox model, as the other one discards 90% of data...
Comment: You are welcome! I am a bit confused - from the sample you gave above, there is no time dependent variables, why would you need start and stop intervals for observations? Is the variable age_inclusion somehow related to this start-stop thing you are referring to?
Comment: Sorry for the confusion. I wrote in parentheses that i used time-dependent variables, many observations on the same individual (counting process format on data). So it worked out fine as long as I only use 1 observation per individual. If I find out how to fix it, I'll get back here! The age_inclusion was patient age at study entry (real data set, not included in sample data above).
Comment: I see. See if this (Section 4) might help:
http://cran.r-project.org/doc/contrib/Fox-Companion/appendix-cox-regression.pdf
It is for coxph, but might work for cph
Answer: Don't accept this answer, it's only for variety:
In oncology, there is a different approach more closely to proportional hazards. It would work as follows: One splits the blood pressure scale in small intervals and estimates the hazard ratios "locally". You'll get a plot of blood pressure vs. hazard ratio. It is called STEPP by Bonetti and Gelber (2004). There is also a R package. But you have to keep in mind the downsides of this apporach: It needs rather large sample sizes and the results depend on the (arbitrary) length of the intervals. After all, it is more useful for explanatory than confirmatoric analysis. Also, you will not get the optimal blood pressure but only an interval. The only pro is that you don't have to specify the shape of the hazard function.
(Which is also a downside because it's tempting you to think less in advance of your analysis)
Comment: Thanks Horst! Always nice with inputs from other fields. I've actually thought about splitting blood pressure into quantiles (e.g deciles) and obtain hazard ratios for these groups. The problem is that I then have to use one of these groups as a reference, which might not be a huge drawback but I think that it would be a bit better to model the variable as continuous. Have a look at: http://www.nejm.org/doi/full/10.1056/NEJMoa1215740
Answer: I would try the cox.ph family in the mgcv package, which is available for the generalized additive models implemented by the gam function. Generalized additive models (GAMs) are sort of the multiple linear regression analogue for spline models. If you have a large dataset, worry not, because mgcv is also quite fast. After fitting the flexible, semi-parametric GAM, you can eyeball the curve, and then start thinking about a parametric generalized non-linear model that captures its shape well.
Comment: Thanks @Brash, I'll definitely have a look at the mgcv package and GAMs, although I'm not familiar at all with these methods. My only skepticism is that I haven't seen GAM models being used for these tasks before. I'm enthusiastic about new methods anyways!
Answer: For a graphic display of relation between BP and events, you could following using ggplot2 and R. Here is an example using your own sample data:
library(ggplot2)
ggplot(data, aes(x=bloodpressure, y=event))+stat_smooth()

The shaded zones indicate 95% confidence intervals.
Two curves can be obtained based on statin use:
ggplot(data, aes(x=bloodpressure, y=event, group=factor(statin), color=factor(statin)))+stat_smooth()

Here the patients taking statins are very few, hence the curve is not complete.
Above code uses 'loess' as the method. Since you are expecting it to be a curve, the code can be changed as follows:
ggplot(data, aes(x=bloodpressure, y=event))+stat_smooth(method = "lm", formula = y ~ poly(x, 2), size = 1)

You can also show actual event rate in groups of bloodpressure. Say you divide all into 10 bloodpressure groups. For large sample size, the number of groups can be increased to get more accurate curve. The y axis in following curves give proportion of patients in that group who had events.
data$grp = cut(data$bloodpressure, 10)
aa = aggregate(event~grp, data=data, mean)
ggplot(aa, aes(x=grp, y=event))+geom_line(aes(group=1))

Errorbars can be added:
ddt = data.table(data)
aaa = ddt[,list(meanevent=mean(event), se_event=se(event)),by=grp]
ggplot(aaa, aes(x=grp, y=meanevent))+geom_line(aes(group=1)) + geom_errorbar(aes(ymin = meanevent-se_event, ymax = meanevent+se_event), width = 0.2)

Comment: Thanks @rnso, much appreciate Your answer. I believe, but I'm not sure, that these graphs/methods will present the univariate association between my predictor of main interest and the outcome. However, I need to present the effect of blood pressure after adjustments (most likely via Cox regression) for a list of covariates. Your graphs, however, will definitely come at handy sooner or later.
Comment: These graphs do show univariate association, which is also important. Multiple curves can be drawn based on other factors and I have added in answer above a graph comparing curves in patients on statins versus not on statins.
Comment: This completely ignored the follow up time and hence is definitly not a valid strategy to analyse this right-censored data
Answer: If you want to visualize the effect of a continuous predictor on a time-to-event outcome such as yours, you could use the contsurvplot package. For example you could pick a certain point in time and plot the survival probability at this point in time as a function of the covariate using the following code:
library(splines)
library(survival)
library(contsurvplot)

# your data
event <- c(1,0,1,0,0,0,0,1,0,0,0,1,1,0,1,0,0,1,0,1,1,1,1,0,1,1,1,0,0,1)
survival <- c(4,29,24,29,29,29,29,19,29,29,29,3,9,29,15,29,29,11,29,5,13,20,22,29,16,21,9,29,29,15)
statin <- c(0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0)
bloodpressure <- c(160,120,150,140,135,110,139,140,153,129,149,163,179,129,144,119,100,115,145,150,130,120,122,129,116,171,129,126,159,150)
data <- data.frame(event, survival, statin, bloodpressure)

# fit a cox model
fit <- coxph(Surv(survival, event) ~ statin + bs(bloodpressure, 3), data=data,
             x=TRUE)

# plot at t
plot_surv_at_t(time="survival",
               status="event",
               variable="bloodpressure",
               data=data,
               model=fit,
               t=c(10, 20, 25))

Instead of picking a few points in time directly, you can also visualize the association using a survival contour plot:
plot_surv_contour(time="survival",
                  status="event",
                  variable="bloodpressure",
                  data=data,
                  model=fit)

Or a survival heatmap:
plot_surv_matrix(time="survival",
                 status="event",
                 variable="bloodpressure",
                 data=data,
                 model=fit)

All of these plots, how the required estimates are calculated and more is described in detail in the associated publication: https://www.doi.org/10.1097/EDE.0000000000001630


Style being set but not changing

Question: UPDATE: I have read that in Angular, you cannot manipulate the DOM. What are you supposed to do then, what is best practice? I have tried using a timeout, NgZone, ChangeDetectionStrategy.OnPush, ChangeDetectorRef detectChanges() all with no success.
I have an html img element:

and some sccs:
img.selected {
    -webkit-filter: grayscale(100%); /* Chrome, Safari, Opera */
    filter: grayscale(100%);
}

When this loads, it applies the selected class, and makes the image grey as expected.
However, when I run the following typescrpt the image just stays grey:
let imgEl: HTMLElement = document.getElementById('icon-image-' + subCategoryModel.id);
imgEl.className = "";

When I log the className, it shows selected is there before, and has been removed after.
console.log(imgEl.classList);

Any ideas why, even though I remove a className, the style is not reflected?
When I look at the source code, it is not updating the DOM, but imgEl.classList is being changed. Do you know why?
Thanks
UPDATE:
Something strange, if I change the className in the DOM manually (in Firebug for example), it reflects the change. However, as soon as I click the image, it updates to what the original value was. It is as if the DOM is being refreshed.
If this is the case, then how is it possible to update the DOM dynamically? Because the DOM refresh just overwrites all changes.
Html
  <ion-row *ngFor="let trio of getTriples()">
    <ion-col *ngFor="let item of trio" (click)="itemTapped(item)">

    </ion-col>
  </ion-row>

Typescript
  itemTapped(subCategoryModel: SubCategoryModel) {
    let idx: number = this.isInArray(this.employeeModel.subCategories, subCategoryModel);
    let imgEl: HTMLElement = document.getElementById('icon-image-' + subCategoryModel.id);
    if (idx >= 0) {
      this.employeeModel.subCategories.splice(idx, 1);
      imgEl.setAttribute("class", "");
    } else {
      this.employeeModel.subCategories.push(subCategoryModel);
      imgEl.setAttribute("class", "selected");
    }
    console.log('icon-image-'+subCategoryModel.id+' ('+imgEl.id+'): ' + document.getElementById('icon-image-' + subCategoryModel.id).className);
  }

Comment: You'll need to create an [mcve]. Fundamentally, clearing `className` will remove all classes from an element, and thus remove any styling applied by those classes.
Comment: "When I look at the source code, it is not updating the DOM, but imgEl.classList is being changed. Do you know why?" If you view source code in Firefox, you get the initial state of the page, not the latest, so any changes through JS are not reflected. I think Chrome may give you the latest. At any rate, if you just open the developer tools, that would be a live view of what the effectively HTML is.
Comment: Thanks, I will try in Chrome.  I have added an UPDATE to the question I ask that says that the DOM seems to be reset. p.s. I am using Ionic 2.
Comment: Tried it in Chromes Developer Tools, and the DOM does not change when `imgEl.setAttribute("class", "");` is executed.
Comment: Is this a scope issue, am I updating the wrong document? What's the answer, I'm confused. Appreciate any help.  I do a simplified version in jsfiddle and it works, so I think this maybe has something to do with Ionic2?
Comment: How do you do `$scope.$apply()` in Ionic2 typescript?
Answer: This is a solution:
html

ts
  isItemShown(item: SubCategoryModel) {
    return this.itemShown === item;
  }

  toggleItem(item: SubCategoryModel) {
    if (this.isItemShown(item)) {
      this.itemShown = null;
    } else {
      this.itemShown = item;
    }
  }

Answer: Try assigning a deselected class to the element.
Add the required css to that.
Somewhat like this
let imgEl: HTMLElement = document.getElementById('icon-image-' subCategoryModel.id);
imgEl.className = "deselected";

css
img.deselected {
  /* your css here */
}

Comment: Hi vishak, thanks for your feedback. I tried that (adding `img.deselected`) with no success.
Comment: Can you share a fiddle?
Comment: Thanks vishak, I have posted a solution above.
Answer: You can try using ng-class.
Documentation here
A simple example

Style being set but not changing


Toggling not working properly in node--contenttype.tpl.php file

Question: I am theming a node of type "test".
I am using toggling in this "node--test.tpl.php" file.
Below is my code in "node--test.tpl.php":

Property

    MLS #:

    <?php echo $node->field_listing_id['und']['0']['value'];?>

code in javascript file is
 (function ($) {
        $('#block1 > a').click(function()
       {
        $("#block1_content").toggle("slow");

         });

  })(jQuery);

Loading the java script files in template.php
drupal_add_js("themes/bartik/custom.js", $type = 'file', $media = 'all', $preprocess = FALSE);
drupal_add_js("themes/bartik/jquery.min.js", $type = 'file', $media = 'all', $preprocess = FALSE);

jqueries and jquery plugins are enabled in modules.
but toggling is not working.
How to do toggling using jquery
Comment: your scripts are correct, ensure your scripts is loaded into site by checking source and no need to add jquery.min.js
Comment: @Anoop Joseph:scripts are loaded.
Comment: check if jquery working on the page by using an alert() in script
Comment: @Anoop Joseph: hm Jquery is not working on the page by using an alert.
Comment: the below one ans is right no need to add jquery.min.js, if you added already it is causing the above conflict because it already available in drupal.
Comment: @Anoop Joseph: I have removed jquery.min.js file. but still no use. cleared cache after removing jquery.min.js file also.
Comment: find out the reason what causing conflict on your page. when i run your script in firebug console its ok.
Answer: Try writing it when document get ready like this:
jQuery(document).ready(function ($) {
        $('#block1 a').click(function()
       {
        $("#block1_content").toggle("slow");

         });

  });

Answer: No need to add "jquery.min.js". Drupal has by default this file.
Comment: I have removed jquery.min.js file. but still no use. cleared cache after removing jquery.min.js file also.  Do I need to install any module. I have "jqueries" and "jquery plugins" are enabled in modules.
Comment: plz verify your page resource and check your custom file exist or not. also try $('#block1 a').click(function()
Comment: Checked everything. but still no use. Tried this but not working
Comment: RE: check if jquery working on the page by using an alert() in script
Comment: Just placed alert . Its working. But when I Am using alert on button click its not working.
Comment: try "jQuery update" module...
Comment: Yeah Used this module also. But no use


Web usb devices not displaying in chrome windows 10

Question: I am using chrome version 86.0.4240.193 in my windows 10 .I am trying to connect usb devices and  cant find any device in chrome://devicelog. The same devices are being detected in mac and even in ubuntu 18.04 installed chromes .I am really in a fix any help regarding this ? .Can anyone tell me why this issues occurs
.I have installed and reinstalled chrome many times ,but nothing works.
Thanks
Answer: The most common reason you will see a device available on other platforms but not on Windows is that Windows imposes additional restrictions on what devices can be controlled from a user-space application such as Chrome. Microsoft provides a special driver called WinUSB.sys which must be the selected driver for the device. If you are building your own device I have published a guide for designing a device to support WebUSB across all platforms. If you are working with a device you don't have the ability to change then Zadig provides a tool for replacing the driver for a USB device with the WinUSB.sys driver.
To see what driver has been selected for your device,

Open the Windows Device Manager control panel.
Find the device.
Right-click on it and select "Properties".
Open the "Driver" tab.
Click "Driver Details".


React - Material-UI Modal causing an error with the tabindex

Question: I am getting this error when I open a modal on my React app but I can't figure out what it means or how to fix it.
"Warning: Material-UI: the modal content node does not accept focus.
For the benefit of assistive technologies, the tabIndex of the node is being set to "-1"."
<SettingsModal event={this.state.eventDetails} id={this.state.eventDetails.id} delete={this.handleRemoveEvent}/>

returns:
return(
  <>
    <Paper className={classes.SettingsModal}>

{this.props.event.name}

{this.props.event.description}

{this.props.event.id}

        <Button onClick={(e) => this.props.delete(this.props.event)}>Delete Event</Button>
    </Paper>
  </>
);

Comment: You have to include your code in this type of question. But I think the answer is here https://github.com/mui-org/material-ui/issues/9775 , specifically `A tabIndex: -1 on PaperProps did the trick`
Comment: ok I added the code to the question. Where would I add a tabIndex in that?
Answer: I've found fix! To remove this error you should wrap your Modal content with DialogContent component like this
import DialogContent from '@material-ui/core/DialogContent';
// ...
render () {
    return (
       <Modal open={this.state.modalOpened} onClose={() => this.setState({ modalOpened: false, modalContent: null })}>
                <DialogContent>
                    {this.state.modalContent}
                </DialogContent>
            </Modal>
    );
}

Comment: DialogContent may add things you don't want, simply add tabIndex={-1} on the first component inside the modal is the right answer
Comment: In MUI 5.4.0, the import path is different:
`import DialogContent from '@mui/material/DialogContent';`
Answer: i had the same problem. apparently wrapping a div around SettingsModal should fix it.
Answer: All the credit goes to @Idos's comment above since he found the reference to the GitHub Issue. I found that this specific comment was  useful.
The wrapping element of the Modal Contents needs to have a prop of
tabIndex: {-1}
In your case looks like you need to do the following:
return(
  <Paper tabIndex:{-1} ...>
...
  </Paper>
);

Comment: this works to me
Answer: Following @Wolfman comment, I just used Fragment from React, because it doesn't add any DOM element:
render () {
    return (
       <Modal open={this.state.modalOpened} onClose={() => this.setState({ modalOpened: false, modalContent: null })}>
                <>
                    {this.state.modalContent}
                </>
            </Modal>
    );
}

Even though, I still don't understand that issue :/


Is the divertimento a freeform sonata?

Question: So, I once looked up divertimento and what it means and I was told that it can have anywhere from 2 to 10 movements. The fact that it mentioned movements made me think:

Okay, so it is a sonata without a defined form, right?

So here is the typical form of a sonata:

Sonata form
Ternary form or Sonata form
Optional but if present, a minuet or a scherzo
Rondo form, Sonata form, or Sonata Rondo form.

Forms that aren't usually in a sonata but can be in place of the typical second or third movement forms include fugue and Theme and Variations. Sometimes a fugue is added to the end of a Rondo movement as well for a dramatic ending.
However, the more I listen to divertimenti, the more I can hear form in it. For instance, this divertimento in D by Mozart has this form in it:

Sonata form, but with some odd harmony in the exposition(second theme isn't in the dominant)
Binary form, like a minuet, but slower than your typical minuet
Kleine Rondo(ABA form, but clearly not ternary form, must be a little rondo)

Basically your typical sonata - the typical slow movement form
And as another example, here is a later divertimento by Mozart, for a trio instead of a quartet:

and here is its form:

Sonata form, no odd harmonies in the exposition
Ternary form, typical for a slow movement
Minuet and trio, typical for a third movement
Theme and Variations?, a second slow movement
Minuet and trio, a second third movement, though the 1 measure pause for all instruments is a bit odd for Mozart. Also there is a second trio, which is unusual, even for Beethoven but especially for Mozart. Even further diversion from the typical form takes place because there is a coda at the end.
Sonata Rondo form, a typical form for a final movement

It seems to me, that a divertimento is your typical sonata +/- 1 or more movements, not so much a sonata without a defined form.
So is a divertimento a freeform sonata or is is a typical sonata with movements added to or subtracted from it?
Answer: I think you need to differentiate sonata as form from sonata used in the title of a work.
This is just using "sonata" in the title...

So here is the typical form of a sonata:
1 Sonata form
2 Ternary form or Sonata form
3 Optional but if present, a minuet or a scherzo
4 Rondo form, Sonata form, or Sonata Rondo form.

...that plan of movements might be seen with something title like "Piano Sonata in..."
There are some typical groupings of movements. Mozart's piano sonatas are mostly in three movements. But sometimes a work titled "sonata" may have only two movements. There is too much variety in the layout of movements to say there is a definite format. You can't really expect to know the number of movements just by the title.
Of course the sonata form are those individual movements with the recapitulation that defines the form.

So is a divertimento a freeform sonata or is is a typical sonata with movements added to or subtracted from it?

I wouldn't call it "freeform sonata." To me, that suggests a fantasia.
I would say it's a multi movement work that doesn't adhere to a conventional movement design as can be seen in quartets or symphonies.
I don't have a historical source to back this up, but because the divertimento - and the related serenade - was meant for entertainment, something to be played during a social event, I imagine the variation in number of movements may have been determined by the length needed for the event.
Answer: There is a false premise in the question, in assuming that the Classical composers (Haydn, Mozart, Beethoven, and their contemporaries) even had the concept of "sonata form". The term "sonata form" was invented by theorists in the 19th century, not the 18th. The standard recipe for sonata form that still persists today in elementary textbooks ("write two themes, the first sounding masculine, the second sounding feminine in a different key, then mix them up a bit, and finally repeat them both in the same key") bears little relationship to most sonata first movements that classical composers actually wrote.
The only composers who actually wrote sonatas in "textbook sonata form" are virtually never played, because the results were frankly boring and predictable. One exception was Schubert, who got away with it because he could write such good tunes that "form" didn't really matter. If Schubert had been using computer notation software, he could have written the recapitulation to some of his sonata form movements in 30 seconds - just "copy the exposition, paste, transpose the second subject, edit two or three bars to fix up the new key relationship between the two subjects, save, end".
By the middle of the 19th century, anything resembling the textbook recipe was dead and buried by Liszt and his successors, but textbook writers still copied it from one generation to the next.
I was first puzzled by all this when I started playing the Beethoven piano sonatas (as a 13 or 14 year old). I had already learned what "sonata form" was supposed to be like, but couldn't figure out how any of the Beethoven that I was playing corresponded to the standard recipe. It took me about another 30 years to be convinced that the fault was with the recipe, and not with either Beethoven or my ability to analyse a score!
Classical divertimenti were the equivalent of modern muzak - nothing more than a pleasant background noise. Anything requiring intellectual effort by the listeners would have been a waste of time, so the result was a string of relatively short movements each with a simple formal organization - binary, ternary, or rondo. There's not much more to be said, as a generalization.
Comment: A substantial number of Beethoven piano sonatas and piano sonata movements correspond to the standard recipe. As an example, his Piano Sonata No. 25 in G Major is in textbook 3-movement sonata form, and its 1st movement is in textbook sonata-allegro form. I don't think you've played enough Beethoven piano sonatas.
Answer: The divertimento

The Divertimento is a very famous instrumental form in the middle of the XVIII.  Century after the demise of the suite.  In particular, it was widely used by Haydn, Mozart and other Austrian composers of the time.
The term divertimento has been commonly used for certain pieces for keyboard instruments and often for solo instrumental ensembles.
Formerly this musical form was divided into a series of sentences ranging from five to nine.

The divertimento, the serenata and the cassazione are almost a transition between the suite and the symphony.
Mozart composed 12 serenades, 2 cassazioni and 17 divertimenti.  Some composers of the 20th century, including Bartók, Berkeley, have used the term in simple compositions for string or chamber orchestra.
Source:
http://www.melomanos.com/la-musica/formas-musicales/divertimento/

Is the divertimento a freeform sonata?


Show currently selected product variation

Question: I have this gravity forms code in my functions php file.
I would like to replace the word "BOOM" with the currently selected product variation name on my woocommerce product page.
This should then populate the Gravity form field with the current product variation name .
<code>add_filter( 'gform_field_value_your_parameter', 'my_custom_population_function' );
function my_custom_population_function($value) {
return 'BOOM';
}
</code>
Comment: Not possible as variation selection is a client side live event that comes after php server side…
Comment: @LoicTheAztec You could leave the field empty and populate it via an AJAX call, correct?
Comment: Yes javascript + Ajax is the only way…
Comment: I have tried this but then the gravity form will not update.
Comment: I have used java script to and the correct value is been updated in the gravity form but the form will not update on change of the value or when the field is first populated. Its killing me
Comment: Can you edit your question so it also contains the HTML structure of your form?
Answer: For those who are interested I used the following....
https://www.businessbloomer.com/woocommerce-get-currently-selected-variation-id/
together with this JS
Trigger a form update in Gravity Forms after jQuery change to hidden field
The result...
$(function() {
<code>$('input.variation_id').change(function() {
    var var_per = $('input.variation_id').val();
  $('#input_12_27').val(var_per).change();
});
</code>
});


Nesting multiple tab presenters

Question: If you consider the GWTP sample app with tabs at:
http://gwtp-sample-tab.appspot.com
Is it possible to have a 3rd level of tabs, lets say inside Home -> Info -> Tab1 and Tab2, and how would that be implemented?
Asked in a different way: it is possible to have nested TabContainerPresenters beyond two levels?
It is important that the 3rd level tabs act as places and that they have their own name tokens.
Comment: Nobody has any experience with this?
Answer: Yes, it is possible, but:

When you have 3 levels of nested tabs - managing the code base is like HELL
You need to create nav tokens for all combinations of you tabs, and will look like (#tab1lvlTab2lvlTab3lvl), for example if there is 3 tabs in 3 levels, we should create 27 nav tokens, so it's horrible to support

In my opinion - 2 level of nested tabs it's already too much. Maybe you should consider to redesign you navigation in your application.
Comment: Thank you for your input. I agree with you that the design might not be optimal. However, is it possible that you can provide a crude overview of how it would be implemented? I have been trying to extend the gwtp sample app with a 3rd level, but without any luck.

Nesting multiple tab presenters


Ao clicar em um link alterar dentro da tag vídeo o valor de ser para o link clicado

Question: Tenho uma lista de filmes em mp4 na página em uma lista li são 1000 links que abrem direto no navegador.
A questão é que criei um iframe que recebem os links vai target mais alguns links ele inicia um download do mp4.
Então eu queria usar ao invés do iframe a tag vídeo do html5 que dá certo e exibe o filme sem fazer o download.
Só que não quero criar 1000 tags vídeo e sim uma só que apenas troca o atributo src de acordo com o link clicado.
Answer: Em resumo você teria que fazer conforme demonstrado no código abaixo.
1º Definir os links todos com o mesmo class;
2º Colocar um id único para cada link, conforme mostrado no exemplo abaixo;
3º Inserir o case para cada link, definindo o endereço src de cada vídeo.

$('.linkvideo').click(function(){
   var link = $(this).attr('id');
   switch(link){
      case 'link1':
 $('#fonteVideo').attr('src', 'https://www.w3schools.com/tags/movie.mp4');
 $("#divVideo video")[0].load();
        break;
      case 'link2':
         $('#fonteVideo').attr('src', 'https://www.w3schools.com/html/mov_bbb.mp4');
  $("#divVideo video")[0].load();
         break;
    }

});

Link1

Link2

   <video width="320" height="240" controls>
    <source id="fonteVideo" src="">
   </video>


How do we pass from proportionality back to equality in a Bayesian derivation?

Question: Here's an answer from one of the questions in the newsletter.  I'm not trying to suggest that it's incorrect, I just don't understand why it's an acceptable practice.  I know that simplifying assumptions are made all the time, but why is this useful?
\begin{equation}
\begin{split}
p(\theta|y) &= \frac{p(y|\theta)p(\theta)}{p(y)} \\
&\propto\frac{\Gamma(\alpha)\Gamma(\beta)}{\Gamma(\alpha+\beta)}\theta^{\alpha-1}(1-\theta)^{\beta-1}*\binom{n}{y}\theta^y(1-\theta)^{n-y} \\
&\propto\theta^{\alpha-1}(1-\theta)^{\beta-1}*\theta^y(1-\theta)^{n-y} \\
&\propto\theta^{\alpha+y-1}(1-\theta)^{\beta+n-y-1} \\
&=\frac{\Gamma(\alpha+y-1)\Gamma(\beta+n-y-1)}{\Gamma(\alpha+\beta+n-1)}\theta^{\alpha+y-1}(1-\theta)^{\beta+n-y-1}
\end{split}
\end{equation}
My issue is that we go from "proportional-to" to "equals", which is fine, but what exactly is this saying?  As in, I understand how we go from each line to the line following it, but I don't understand what this tells us.  Sure, we eventually get back to a Beta distribution, but only after removing a ton of values.  Are these values not important?  Does it mean anything profound that a Beta prior with a binomial likelihood has the property of conjugacy?  It can make calculations simpler, sure, but is this useful in practice, if so why?
EDIT 1:
So are these constants actually thrown out, or accounted for later? I understand that constants don't matter with respect to proportionality and integration, but throwing them out completely just seems counter-intuitive to me. Sure, if you're multiplying/dividing a bunch of numbers by an expression with a constant, and all you care about is the relationship of those numbers to each other, then you can throw out constants and the relationship remains the same. Is that what's going on here?
EDIT 2:
From what I can tell, we get rid of constants, simplify, and then take the integral and normalize that integral. By virtue of the normalization, we're inherently accounting for the constants that we removed before. Is this correct? I think I understand now, for whatever reason, I kept thinking of the original equation as a scalar value rather than a probability distribution.
Comment: You can ignore all constants of proportionality in *any* probability density function because at the end you know it has to have unit total area. For instance, it suffices to know the PDF of the standard normal distribution is proportional to $\exp(-x^2/2)$; finding the constant (equal to $1/\sqrt{2\pi}$) is just an exercise in integration. That's all that's going on here. Answers to the rest of your questions are available here by searching on keywords like [conjugate prior](http://stats.stackexchange.com/search?q=conjugate+prior).
Comment: @whuber So are these constants actually thrown out, or accounted for later?  I understand that constants don't matter with respect to proportionality and integration, but throwing them out completely just seems counter-intuitive to me.  Sure, if you're multiplying/dividing a bunch of numbers by an expression with a constant, and all you care about is the relationship of those numbers to each other, then you can throw out constants and the relationship remains the same.  Is that what's going on here?
Comment: The constants can *always* be accounted for--just do the integral! Here it's been done for you: where do you think all the gammas came from in the last equation? :-)  Another way to read this derivation is to erase all the intermediate lines, leaving an *equality* for $p$.
Comment: @whuber I felt stupid for having asked the question, but since it can help other people, I un-deleted it.  If you or anyone else could provide a more detailed explanation, that would be wonderful.  I'm pretty sure that I follow what you're saying, but for me, at least, it's a lot more helpful to see a *full explanation*.
Comment: @whuber From what I can tell, we get rid of constants, simplify, and then take the integral and normalize that integral.  By virtue of the normalization, we're inherently accounting for the constants that we removed before.  Is this correct?  I think I understand now, for whatever reason, I kept thinking of the original equations as a scalar value rather than a probability distribution.
Answer: This seems to be a fairly common issue when beginning to work with these problems; I've had similar questions quite a few times in person.
As you suggest in comments, the normalizing constant is implied by the fact that you must be left with a density at the end.
Slightly less informally, at every step of the derivation, we're really dealing with something that integrates to 1, though stating this fact is (as here) usually omitted.
In some simpler cases where this kind dropping of constants is done it may be possible to keep the constants around and do the explicit integral (and the first times you tackle those problems, is worth doing explicitly), but there are times when the required integral is difficult or sometimes impossible to evaluate algebraically, even though we can show that it must have the required value -- in most cases we can't evaluate a term like $p(y)$ except by "the whole expression still integrates to 1, so that term must be..." (though of course, you must remain aware that the thing must be integrable and so on - one can only hand-wave away what can really be hand-waved; in some situations physicists might be able to cancel out infinities but we really can't).
If it would help, you could write "$= c\cdot$" for "$\propto$" at every intermediate line (or rather use $c_1$, $c_2$ etc anywhere the constant changes). It's still an equality at the end and there's only one possible value for the final constant (if you couldn't make the argument that there's only one possible value, you have to ponder whether it might not be the case).
I call this approach 'spot the density'. In fact, being able to spot (multiples of) densities (and probability functions in the discrete case) has given me shortcuts on a host of integrations (/summations) on non-probability problems. Knowing enough densities is like having a table of integrals for free.
What happens if we keep an equality all the way through?
\begin{split}
p(\theta|y) &= \frac{p(y|\theta)p(\theta)}{p(y)} \\
&=\frac{1}{p(y)}\frac{\Gamma(\alpha)\Gamma(\beta)}{\Gamma(\alpha+\beta)}\theta^{\alpha-1}(1-\theta)^{\beta-1} \cdot \binom{n}{y}\theta^y(1-\theta)^{n-y} \\
&=\left[\frac{\Gamma(\alpha)\Gamma(\beta)}{\Gamma(\alpha+\beta)p(y)}\binom{n}{y}\right]\theta^{\alpha-1}(1-\theta)^{\beta-1}\cdot\theta^y(1-\theta)^{n-y} \\
&=\left[\frac{\Gamma(\alpha)\Gamma(\beta)}{\Gamma(\alpha+\beta)p(y)}\binom{n}{y}\right]\theta^{\alpha+y-1}(1-\theta)^{\beta+n-y-1} \\
&=\left[\frac{\Gamma(\alpha)\Gamma(\beta)}{\Gamma(\alpha+\beta)p(y)}\binom{n}{y}\frac{\Gamma(\alpha+\beta+n-1)}{\Gamma(\alpha+y-1)\Gamma(\beta+n-y-1)}\right]\\&\quad\quad\cdot\frac{\Gamma(\alpha+y-1)\Gamma(\beta+n-y-1)}{\Gamma(\alpha+\beta+n-1)}\theta^{\alpha+y-1}(1-\theta)^{\beta+n-y-1} \end{split}
We're left to say "what is the term in the brackets $[]$?" Given the data, it's a constant. The value of the constant is immediately clear from integrating both sides w.r.t $\theta$. The value in doing it the way it was done before should be clear.
Comment: Thanks for responding.  I definitely understand what's going on now.  It's been a long time since I've done anything stats related, and tbh I'm pretty sure I learned it completely incorrectly the first time around-- or rather just memorized techniques instead of actually understanding what I was doing.  Again, thanks for your help.  Hopefully this time, now that I'm much more motivated and interested, I'll learn stats *correctly*.
Comment: Yes, while it was clear you already understood, it was a good question which deserved a fuller answer - indeed, I might come back and improve it later. On that deeper understanding and motivation - I know it can take a while. Some decades ago I was into my third year of doing stats subjects (and mostly doing pretty well in them) before I finally said "Oh, *now* I get it!"
Comment: Oh, I'm not complaing, I appreciated the additional explanation... I feel that my biggest issue was that I did not put enough effort into math when I was an undergrad.  Unfortunately, I was able to get good grades without truly understanding the material.  I thought this was awesome at the time (I was pre-med), now that I'm extremely interested in data analysis/machine learning, I feel incredibly stupid for not caring more when I was younger.  Nonetheless, I'm studying hard now, and can't wait for that moment that I feel *mathematically mature*.  I hope I get there soon, but it's a long road.
Comment: I'm still waiting for that feeling.


Voice crossings and voice leading measures

Question: In "The Geometry of Music", Dmitri Tymockzo discusses voice crossings in measures of voice leading sizes:

"I consider a measure of voice-leading size to be "reasonable" if it
  satisfies two basic requirements: first, it should depend only on how
  far the individual voices move, with larger motion leading to larger
  voice leadings; and second, it should judge voice leadings with voice
  crossings to be larger (or at the very least, no smaller) than their
  natural uncrossed alternatives."
"I propose that any method of measuring voice leading is acceptable, as
  long as it does not have the counterintuitive consequence that "voice
  crossings" make a voice leading smaller. It is actually quite easy to
  formulate this principle mathematically: if a metric is not to favor
  voice crossings, then it must treat the collection of distances {x1 +
  c, x2, …, xn} as being at least as large as {x1, x2 + c, …, xn},
  whenever x1 > x2 and c ≥ 0. Intuitively, this means that the metric
  should not prefer an uneven distribution of distances, such as {4, 0,
  0} over a more even distribution, such as {1, 1, 2}"

Why should voice leadings with voice crossings be judgded as larger than their uncrossed alternatives? And why does such metric does not prefer an uneven distribution of distances over a more even one?
Answer: Tymoczko is really discussing voice-leading efficiency here. In short he's saying that, given multiple progressions that have identical pitch content (but with the pitches divided among the voices differently), voice leading without voice crossing will be more efficient (that is, smoother and with less movement among the chords) than the progression(s) with voice crossing.
Consider the following examples:

In the above example, the voices move:

G to G in the soprano, or 0 half steps;
E to B in the alto, or 5 half steps;
C to D in the tenor, or 2 half steps;
and C to G in the bass, or 7 half steps.

This combines for a total motion of 14 half steps. Important to note is the voice crossing in the second chord due to the alto being lower than the tenor.
Contrast this with:

In this example without voice crossing, the voices move:

G to G in the soprano, or 0 half steps;
E to D in the alto, or 2 half steps;
C to B in the tenor, or 1 half step;
and C to G in the bass, or 7 half steps.

This combines for a total of 10 half steps, decidedly less than the 14 half steps in the voice-crossed example above.
As for the "uneven distribution of distances," let's look at the distances moved again: {0,5,2,7} in the first, and {0,2,1,7} in the second. Whenever we have a large leap, it can be viewed as a result of voice crossing; notice how the {5,2} in the voice-crossed example is smoothed out to {2,1} in the second example. As such, typical efficient voice leading will not have these uneven distributions, because they suggest possible voice crossing.
This uneven distribution becomes even more clear when we remove the bass voice: we have an uneven {0,5,2} in the voice-crossed example compared to an even {0,2,1} in the more efficient example.
(Note: for another recent answer where I discussed voice-leading distance, see Can one measure the "distance" between chords? If so, how?)


Does an invertible real matrix have a real cubic root

Question: $A$ is an invertible real matrix, is there a real matrix $B$ such that $A=B^3$?
For the complex case, it is not difficult. Over complex numbers, every invertible matrix has a cubic root.  In fact, over $\mathbb C$, since every invertible matrix has a logrithm, we can take a  family of matrices $e^{t\log A}$, and taking $t=1/3$ yields a square root of $A$.
The condition "invertible " is necessary for the real case. In fact,  here's a counterexample link.
How about general cases? $A$ is an invertible real matrix, is there a real matrix $B$ such that $A=B^n$, where integer $n\geq 2$?
Comment: Working with the real Jordan form of $A$ will be a good place to start.
Comment: I think you can assume it's upper-triangular, and then use the binomial formula, eg $(A+B)^{1/3}=A^{1/3}+\frac13A^{-2/3}B-\frac19 A^{-5/3}B^2+\frac{20}9A^{-8/3}B^3+\cdot$. Specifically, if $A$ is diagonal and $B$ is nilpotent.
Answer: Yes, every real matrix that is diagonalizable over the complex numbers has a real cube root. Suppose $A$ is such a matrix. Then there is a real invertible matrix $P$ such that $P^{-1}AP =D$ where $D$ is a matrix that is 'almost' diagonal-it has real numbers $\lambda_1,...,\lambda_m$ along the main diagonal and also (if it has one or more non-real eigenvalues) some 2x2 real blocks of the form $$\begin{bmatrix}a&-b\\b&a\end{bmatrix}=\begin{bmatrix}r\cos\theta&-r\sin\theta\\r\sin\theta&r\cos\theta\end{bmatrix}$$along the main diagonal and 0's elsewhere.Let $E$ be the matrix in which each $\lambda_i$ is replaced by $\lambda_i^{1/3}$ and each 2x2 block is replaced by $$r^{1/3}\begin{bmatrix}\cos(\theta/3)&-\sin(\theta/3)\\\sin(\theta/3)&\cos(\theta/3)\end{bmatrix}$$. Then $(PEP^{-1})^3=A$. Similarly the matrix $A$ has $\nu$-th roots if $\nu$ is any odd natural number.
Comment: What if it's not diagonalizable? For example $$A=\begin{bmatrix}1&1\\0&1\end{bmatrix}$$ does have a cube root $$\begin{bmatrix}1&1/3\\0&1\end{bmatrix}$$ but your method doesn't apply to it.
Comment: is there an $A$ which is an invertible real matrix, but there is no real matrix $B$ such that $A=B^3$?
Answer: Yes. It suffices to prove that $A$ is similar to a real matrix $C$ that can easily be seen to have a real cubic root $R$. So, if $P^{-1}CP=A$ and $R^3=C$, we may take $B=P^{-1}RP$.
Since all real matrices admit "real Jordan forms" (please consult Matrix Analysis by Horn and Johnson if you don't know what a real Jordan form is), it suffices to consider the case where $A$ is a real Jordan form with a single Jordan block. That is, we may assume that
$$
A=J_k(\lambda)=\pmatrix{\lambda&1\\ &\ddots&\ddots\\ &&\ddots&1\\ &&&\lambda}
\quad\text{or}\quad
A=J_k(rQ_\theta)=\pmatrix{rQ_\theta&I_2\\ &\ddots&\ddots\\ &&\ddots&I_2\\ &&&rQ_\theta}
$$
where $\lambda$ is a nonzero real number, $r>0$ and $Q_\theta\ne\pm I_2$ is the $2\times2$ rotation matrix for angle $\theta$.
If $A=J_k(\lambda)$, take $R=J_k(\lambda^{1/3})$. Then $C$ and $A$ are similar because both of them are non-derogatory matrices with the same minimal polynomial $(x-\lambda)^k$. (That $\lambda\ne0$ is essential here. If $\lambda=0$, the minimal polynomial of $C=R^3$ is no longer $(x-\lambda)^k$ unless $k=1$).
Similarly, if $A=J_k(rQ_\theta)$, take $R=J_k(r^{1/3}Q_{\theta/3})$. Note that $A$ and $R$ are similar over $\mathbb C$ to
$$
J_k(re^{i\theta})\oplus J_k(re^{-i\theta})
\quad\text{and}\quad
J_k(r^{1/3}e^{i\theta/3})\oplus J_k(r^{1/3}e^{-i\theta/3})
$$
respectively. Thus the minimal polynomials of $A$ and $C$ (as $r\ne0$) are both equal to $(x-re^{i\theta})^k(x-re^{-i\theta})^k=\left(x^2-2r\cos(\theta)x+r^2\right)^k$. So, the two matrices are again similar because they are non-derogatory matrices with the same minimal polynomial.
Answer: For square roots of real $A$ to exist, it is enough that all of the real eingenvalues of $A$ are $>0$.
Cubic roots, and more generally roots of odd order, exist for every real invertible $A$. The proof can be done like in the solution of @user1551.  A similar approach is using polynomials that do Hermite interpolation of the function $t\mapsto\sqrt[3]{t}$ on the spectrum of $A$ ( considered with multiplicities).
I tested an approach for cubic roots using the Newton method. That is, start with some $x_0$ ( perhaps $I$ if not a problem), and use the recurrence
$$x_{n+1} = x_n - \frac{x_n^3-a}{3 x_n^2}$$
(the quotient since all of the $x_n$ commute with $a$).  It seems that the convergence is quite good.
This could work with other polynomial equations $P(B)= A$.
Another approach works if $A$ is not too far from $I$ , that is $A= I+\delta$, with $\delta$ small ( the spectral radius $\rho(\delta)<1$). Then we can take
$$\sqrt[n]{A} = \sqrt[n]{1+\delta}= (1+\delta)^{\frac{1}{n}} = \sum_{k\ge 0}\binom{\frac{1}{n}}{k} \delta^k$$


Get current directory in erlang

Question: I'm using chicagoboss for web development. To test some test modules I would like to change my current directory to something else. I know I can change directory by specifying full path to to cd("full path").
Suppose I'm in a directory "/home/user/workspace/myproject/myapp/" where I'm running myproject project.But now I want to check  my current location using erlang shell.
Is there any function/command in erlang to get current working directory? In python I was using os.getcwd().
Comment: You may have better success in the long run if you look up `priv_dirs`. Each application in Erlang has a private directory for static data. Highly useful in some cases, though it is not directly what you are asking for.
Answer: Try:
{ok, CurrentDirectory} = file:get_cwd().
Also check out erldocs.com to quickly look up functions in the Erlang documentation.
Answer: Use the command:
pwd().

More text to get to the Stackoverflow minimum
Comment: Note that this prints out the directory and returns `ok`

Get current directory in erlang


Qt moving from LGPL to commercial halfway through

Question: I've never understood this bit about licensing on the Qt website.

Qt Commercial Developer License The Qt
  Commercial Developer License is the
  correct license to use for the
  development of proprietary and/or
  commercial software with Qt where you
  do not want to share any source code.
You must purchase a Qt Commercial
  Developer License from us or from one
  of our authorized resellers before you
  start developing commercial software.
  The Qt Commercial Developer License
  does not allow the incorporation of
  code developed with the Qt GNU LGPL v.
  2.1 or GNU GPL v. 3.0 license versions into a commercial product.

If you are starting to develop an app while you're not sure if you'll ever want to sell it (using LGPL), how would they prevent you from moving to the commercial license at some point? As long as the API is the same you simply recompile / link, no?
What am I missing?
Comment: I'm voting to close this question as off-topic because it is about licensing or legal issues, not programming or software development. [See here](http://meta.stackoverflow.com/questions/274963/questions-about-licensing/274964#274964) and [here](http://meta.stackexchange.com/questions/139804/can-licensing-questions-ever-be-on-topic) for details, and the [help] for more.
Comment: Simply consult firstname.lastname@example.com Qt support and a lawyer.
Answer: I believe that the text only refers to code that has already been distributed under LGPL, and therefore cannot be closed-sourced by switching Qt license.
I think you have nothing to worry about: nobody know/cares where the undistributed code you wrote came from (Commercial Qt or LGPL Qt). As long as it hasn't been released under a LGPL license, nothing can happpen.
Comment: How? The text says :"The Qt Commercial Developer License does not allow the incorporation of code developed with the Qt GNU LGPL v. 2.1 or GNU GPL v. 3.0 license versions into a commercial product." I don't see where it mentions license of developed product. It only talks about license of Qt. If you didn't distribute the product, they can't know if you developed it using LGPL version of Qt.
Comment: Yes that's what I expected. There's no way they can tell. I think the clause is quite confusing. I understand about the difference between LGPL and commercial in terms of linkage and code modifications, but the text implies that you have to start the development of a potentially commercial product with a commercial license. So in reality that is bullshit. You can postpone the decision about what license to use until the actual release point.

Thanks for verifying.
Comment: That's what I was trying to say, there's no way they could know.
Answer: It is the Commercial licence that adds the restriction. When they sell their software under their own commercial licence, they are free to add restrictions within the limits of the law. They are allowed to stipulate that you cannot licence software under their commercial licence that was developed using the LGPL version of the software. It is difficult for them to police, certainly, but they may just be relying on most people to do the right thing (and the fact that their Commercial licence isn't too expensive anyway).
There is nothing stopping you from selling software developed with the LGPL version, and you don't have to publish your source code. The only real consequence of using the LGPL is that you cannot technically link to the QT libraries statically. That isn't common with Qt so it's not much to worry about. And of course you don't get the same support.
To release using the commercial version, you need to purchase the commercial version from Qt (which gets you a licence code). The source is the same, but you are not using the commercial 'form' of Qt unless you buy it or steal it.
Answer: If you didn't do any modifications to the Qt Sources, yes you can go ahead and sell it.
From Qt Licensing documentation, Can create proprietary applications in accordance with the LGPL v. 2.1 terms ..
Also from the Documentation,
<code>Qt GNU LGPL v. 2.1 Version
</code>
This version is available for development of proprietary and commercial applications in accordance with the terms and conditions of the GNU Lesser General Public License version 2.1.
Support services are available separately for purchase.
Comment: You can sell it if you make modifications to the Qt source code. You must publish (or make available to anyone who asks) the changes you make to the Qt source code, that's all.
Comment: Well, I guess that's what I mean in my answer... :)
Comment: Then what is the meaning of the first sentence?
Answer: Formerly Qt was available on GPL and the Commercial License. This used to mean that a Commercial License was need to do closed source. After the Nokia acquisition Qt was also licensed under the LGPL - after this fact, the only difference between Qt Commercial and LGPL are about shipping modified versions of Qt or Qt Solutions and the support contract.
Comment: And whether you can bind statically to the Qt libraries.
Answer: The license text is probably legally not binding. It effectively adds an extra restriction to the GPL, namely "you cannot use your GPL code later in combination with the Qt commercial license". From clause 6 of the GPL: "You may not impose any further restrictions on the recipients' exercise of the rights granted herein."
Comment: That is incorrect. It adds a restriction to the Commercial licence, not the LGPL/GPL one.
Comment: I know that the wording is technically put into the Commercial License. However, this is an action by the same legal entity that is also distributing the same software under GPL terms. Their actions must be considered not just in isolation but also in combination. You can't add extra restrictions to the GPL by putting them in a separate license text.
Answer: As you can sell your software using the Qt LGPL version (it's not only GPL anymore), this point should be moot for most users.


Why do Sylvester numbers, when reduced modulo $864$, form an arithmetic progression $7, 43, 79, 115, 151, 187, 223, \ldots$?

Question: The following observation has been made:
Numbers in Sylvester's sequence,when reduced modulo 864, form an arithmetic progression.
This has been checked for the first ten members of the sequence:
$
7\equiv 7 \pmod{864}\\
43\equiv 43 \pmod{864}\\
1807\equiv 79 \pmod{864}\\
3263443\equiv 115 \pmod{864}\\
10650056950807\equiv 151 \pmod{864}\\
113423713055421844361000443 \equiv 187 \pmod{864}\\
12864938683278671740537145998360961546653259485195807\equiv 223 \pmod{864}
$
I have been unable to check other numbers in this sequence, due to the rapid growth of the sequence, the numbers become too large to handle.
Here is an attempted proof that ALL Sylvester numbers, when divided by $864$ ($864 = 4 \times 6^3$), leave a remainder which is either $7$ or $43$ or $79$ or $115$ or $151$ or $187$ or $\ldots$ or $799$ or $835$. There  are only 24 possibilities. There are infinitely many Sylvester numbers, but when you divide them by $864$, the remainder of that division, can only be one of 24  numbers . These 24 numbers form an arithmetic progression: $7$, $43$, $79, $\ldots$, $763$, $799$, $835$. There are only 24 possibilities for the remainder of that division.
We note that all Sylvester numbers can be written as polynomials in powers of $6$.  This is a direct  consequence of the way the sequence has been defined,  and the fact that the first two members of the sequence are $2$ and $3$. One may define the sequence by the recurrence relation:
$s_i=s_{i-1}(s_{i-1}-1)+1$
Sylvester's sequence can also be defined by the formula:
$s_{n}=1+\prod_{i=0}^{n-1}s_{i}$
We write the first few Sylvester numbers as polynomials in powers of $6$, and then divide them by $864$, and look at the remainder of that division. We shall also try to spot a pattern, and then prove that the pattern applies not just in the specific case we are looking at, but rather it is true in general.
Note that
$7 = (2\times 3) + 1 =  6 + 1\\43 = 6 \times 7 + 1 = 6 \times (6 +1) +1 = 6^2 + 6 + 1$
(Note that the last three terms of this polynomial add up to $43$).
$1807 = 42 \times 43 + 1 = ( 6^2 + 6 ) ( 6^2 + 6 +1 ) +1\\1807 = 6^4 + 2\times 6^3 + 2\times 6^2 + 6 + 1$
(Note that the last three terms of this polynomial add up to $79$. The other two terms of this polynomial, when added together, are divisible by $864$).
$3263443 = 1806\times 1807 + 1  = ( 6^4 + 2\times 6^3 + 2\times 6^2 + 6 )*( 6^4 + 2\times 6^3 + 2\times 6^2 + 6 + 1 ) + 1\\3263443 = 6^8 + 4\times 6^7 + 8\times 6^6 + 10\times 6^5 + 10\times 6^4 + 3\times 6^2 + 6 + 1$
(Note that the last three terms of this polynomial add up to 115.  All the other terms of this polynomial, are each individually, divisible by 864, each term leaving a remainder of zero).
$10650056950807 = 3263442\times 3263443 + 1 = (\ldots + 8\times 6^6 + 10\times 6^5 + 10\times 6^4 + 3\times 6^2 + 6)\times (\ldots + 8\times 6^6 + 10\times 6^5 + 10\times 6^4 + 3\times 6^2 + 6 + 1 ) + 1 = \ldots + 88\times 6^6 + 30\times 6^5 + 20\times 6^4 + 4\times 6^2 + 6 + 1 = 10650056950807$
(Note that the last three terms of this polynomial add up to 151. All the other terms of this polynomial, are each individually, divisible by 864, each term leaving a remainder of zero).
We have spotted a pattern. When you write a Sylvester number as a polynomial in powers of six, all the terms of the polynomial greater than or equal to power 5 ($6^5$ or higher powers ) are divisible by $864\; (=\; 4\times 6^3)$.
In fact,
$6^5/864 = 9\\6^6 / 864 = 54\\6^7 / 864 = 324$
and all higher powers of 6 are divisible by 864. Therefore, the only terms in the polynomial which may not be divisible by 864 are the fourth and the third powers of 6, and the lower powers.
Therefore we have:  $A\times 6^4 + B\times 6^3 + n\times 6^2 + 6 + 1$
Specifically, we have to show, that the integer coefficient of $6^4$, which we have called A, is always even (a multiple of 2 ). We must also prove that the integer coefficient of $6^3$, which we have called B, is always a multiple of 4 or it is zero.  This will ensure that $A\times 6^4 + B\times 6^3$ will always be divisible by 864.
But what about the last 3 terms of the polynomial?
Recall that we wrote 43 as a polynomial in powers of 6.
$43= 6^2 + 6 + 1 = x^2 + x + 1$
We can also write 7 as a polynomial in powers of 6.
$7 = 0\times 6^2 + 6 + 1$
We can also write 1807 as a polynomial in powers of 6.
$1807 = 6^4 + 2\times 6^3 + 2\times 6^2 + 6 + 1$
We also wrote 3263443 as a polynomial in powers of 6.
3263443 = 6^8 + 4*6^7 + 8*6^6 + 10*6^5 + 10*6^4 + 3*6^2 + 6 + 1
We also wrote 10650056950807 as a polynomial in powers of 6.
$10650056950807 = \ldots + 88\times 6^6 + 30\times 6^5 + 20\times 6^4 + 4\times 6^2 + 6 + 1$
If we now compare the last three terms of all these polynomial expansions, we have:
$4\times 6^2 + 6 + 1 = 151\\3\times 6^2 + 6 + 1 = 115\\2\times 6^2 + 6 + 1 = 79\\1\times 6^2 + 6 + 1 = 43\\0\times 6^2 + 6 + 1 = 7$
Note that the last three terms of this polynomial expansion give the remainder of division by 864!!
We can use mathematical induction to prove that all Sylvester numbers, when expressed as a polynomial in powers of 6, their last three terms  will be of the form:  $n\times 6^2 + 6 + 1$,  with  $n= 0, 1, 2, 3, 4, 5, \ldots$
Because $24\times 36= 864$, we have: $24\times 6^2 + 6 + 1 = 864 + 6 + 1 = 871 \equiv 7 \pmod{864}$
Thus the pattern of remainders of  dividing Sylvester numbers by 864 is cyclical,  repeating itself over and over again, with a cycle length of 24.
Let us use mathematical induction to prove that the last three terms  of the polynomial expansion will be of the form:  n*6^2 + 6 + 1, {n=0,1,2,3,4,$\ldots$}
When n=3, we have: $s_n = 3263443 = 6^8 + 4\times 6^7 + 8\times 6^6 + 10\times 6^5 + 10\times 6^4 + 3\times 6^2 + 6 + 1$  and the last three terms  are of the required form. Now assume that the result is true for n=k.
When n=k, we have $s_{k+3} = \ldots +A\times 6^4 +B\times 6^3 + k\times 6^2 + 6 + 1$ (A, B, k are all integers ).
Use the recurrence relation for Sylvester's sequence.
$s_{k+4} = [\ldots+A\times 6^4 +B\times 6^3 + k\times 6^2 + 6 + 1 ]\times [\ldots+A\times 6^4 +B\times 6^3 + k\times 6^2 + 6 ] + 1$
Multiply out the two brackets to get: $s_{k+4} =  A^2\times 6^8 + A\times B\times  6^7 + \ldots+k\times 6^2 + 6^2 + 1 * 6 + 1 = A^2\times 6^8 + A\times B\times  6^7 +\ldots+ (k+1)\times 6^2 + 6 + 1$
We see that the last three terms are of the required form and by induction we have proven the result.
The only thing left to prove now is that the integer coefficient of 6^4 in polynomial expansion, which we have called A, is always even (a multiple of 2). We must also prove that the integer coefficient of $6^3$ in polynomial expansion, which we have called B, is always a multiple of 4 or it is zero.
If anyone has any helpful suggestions please let me know. If you can fill the gaps in this proof, then by all means  do so. Your help is appreciated.
I am waiting for your suggestions and help.
Comment: Have you tried modular arithmetic on _the Sylvester numbers themselves_ at all?
Comment: Please use MathJax: https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Comment: This is quite lomng-winded, but it seems t be that what you're trying to prove is that Sylvester numbers are $\equiv 7\pmod{36}$ (and I suppose that can be done easier), that's not enough to form an aritmetic progression, they also have to come in the right order for that.
Answer: What exactly do you want to prove?
That the remainders repeat cyclically?
This can be proven much easier:
Step 1)
If the elements in a sequence $a_1, a_2, a_3 ...$ can be defined as $a_n=f(a_{n-1})$ and two elements in the sequence are equal ($a_n = a_{n+m}$) then the elements in the sequence will repeat cyclically (*):
$a_{n+m} = a_n \Rightarrow\\a_{n+m+1} = f(a_{n+m}) = f(a_n) = a_{n+1} \Rightarrow\\a_{n+m+2} = a_{n+2}\Rightarrow\\\vdots\\a_{n+2m} = a_{n+m} = a_n\Rightarrow\\\vdots\\\\a_{n+km+i} = a_{n+i}$
Step 2)
If $a \equiv b$ then $a^2 - a \equiv b^2 -b$.
Let $r_m(n)$ be the division reminder of the number $n$ when being divided by some other number $m$.
The $n^{th}$ Sylvester number can be defined as $s_n=s_{n-1}^2-s_{n-1}+1$ so the reminder can be calculated as:
$r_m(s_n)=r_m(s_{n-1}^2-s_{n-1}+1)=r_m(r_m(s_{n-1})^2-r_m(s_{n-1})+1)$
Or:
$r_m(s_n)=f(r_m(s_{n-1}))$ with $f(k)=k^2-k+1$
Because we know that $r_m(s_n)$ are integers in the range $0\leq r_m(s_n) < m$ we know that within the first $m+1$ elements of the sequence $r_m(s_1),r_m(s_2),r_m(s_3),\ldots$ at least one element must occur twice.
Now we can apply "Step 1" to the sequence $r_m(s_1),r_m(s_2),r_m(s_3),\ldots$ and prove that this sequence must repeat cyclically for any value of $m$.
For some values of $m$ (like $r_{864}(s_1) < r_{864}(s_2) < r_{864}(s_3) < \ldots$) the values of the elements will increase until one element "repeats" and a new "cycle" begins.
For other values of $m$ (like $r_{29}(s_1) < r_{29}(s_2) < r_{29}(s_3) < r_{29}(s_4) \not\leq r_{29}(s_5) < r_{29}(s_6) \not\leq r_{29}(s_7) \ldots$) this will not be the case (however the sequence will repeat cyclically anyway).
I doubt that there is another possibility to find out if the the values of the elements are increasing for a given value of $m$ but by calculating the first elements of the corresponding sequence until one element is "repeating".
(*) As English is not my native language I don't know if I am always using the correct terms. Sorry.
Comment: According to https://en.wikipedia.org/wiki/Sylvester%27s_sequence#Formal_definitions, the recurrence relation is $s_n=s_{n-1}^2-s_{n-1} + 1$, not $s_n=s_{n-1}^2-s_{n-1}$.
Comment: @MartinR Thanks. I edited the answer and corrected that.


Xcode 6 simulator not deleting sandbox

Question: Without going on a bizarre snipe hunt into the bowels of ~/Library/Developer/CoreSimulator, I can't seem to remove an app completely from Xcode 6's simulator.
If I run the app the first time, all is good - The app believes it is the first time launched.
(no NSUserDefaults, etc)
If I then tap/hold to delete the app in the simulator, then re-run, all the data is there again-
Ergo it's NOT a clean install launch at this point.
Anyone figure out how to really remove the app from the simulator, as it is not removed as cleanly as it is on the device..
Comment: Do u rerun it with a different sdk version?
Comment: Definitely sounds like a bug. Try the Xcode 6.1 betas: judging from what's being posted to devforums.apple.com, the 6.0 Simulator is mega-busted.
Answer: Unfortunately it seems like a bug in the latest simulator. Currently I've only been successful with the "Reset Content and Settings..." item from the "iOS Simulator" drop down menu.
Comment: Unfortunately, that also nukes all photos added to the simulator, along with all contacts. **HIGHLY** undesirable. I just want the app's data gone.

Xcode 6 simulator not deleting sandbox


Sheet music terminology

Question: I am writing software for managing sheet music. Now I want to translate the software to English and need some common English words for sheet music related terms (single words preferred):

a single music piece for one or more instruments (e.g., a jazz piece with sheets for for 15 different instruments)

a "sheet music book" containing many single music pieces (e.g., Chopin Nocturnes, Jazz Real Book, Tchaikovsky Piano Concerto No 1)

as part of (1): sheet music for a single piece and a single instrument (e.g., Tchaikovsky Piano Concerto No 1 - Clarinet part only

what it is called when a musician makes music (including rehearsals and performances)?

a group of musicians playing together

Since the software should be applicable to any kind of music style (jazz, classical, ...) and any kinds of instruments and groups of musicians (single piano player, complete orchestra, marching band,...), what are the best terms for 1. to 5.?
With my little English knowledge, I came up with these terms:
for 1.: song
for 2.: songbook
for 3.: voice
for 4.: performance
for 5.: band
Are there better (more popular) English terms?
EDIT:
My first language is German. My German terms are:
for 1.: Heft
for 2.: Stück
for 3.: Stimme
for 4.: Spielereignis
for 5.: Band
I am not fully happy with that terms, but in German we don't have common words that cover all kinds of music.
Comment: From Wikipedia https://en.wikipedia.org/wiki/Sheet_music:
1. "book"
2. "piece"/"song"/"score"
3. "part"
Answer: For goodness sake, why don't you tell us what language you are translating from, and the terms you would use in that language. The chances that no-one here speaks the same language are close to zero.
1.: song: No. "piece" (or possibly "composition") Calling Beethoven's fifth symphony a "song" is not generally regarded as educated.
2.: songbook: No. (same reason as above). Usually an "album" (which works for just about any genre, I think)
3.: voice: No. Usually "voice" refers to either "a human voice" (i.e. sung), or any of the constituent parts of a polyphonic composition. Probably "part" is best.
4.: performance: Yes.
5.: band: No, since this could not include an orchestra or a group of choral singers (etc etc). Not clear what would be best, since it depends on the context.
You could also look at (for example) the terms used by software such as Musescore, which will be available in "your language" and also English.
Comment: For #5,  "ensemble"
Comment: Yes, sure "ensemble" might work in some cases, but it critically depends on how the word is being used in the context of the software system.
Comment: I added the german words where I started. Please see the EDIT secion in the question.
Comment: The Musescore-Website led me to (http://www.robertcarney.net/musical-terms-definitions.htm). But both glossaries do not provide substantial help for my question. E.g. "Piece" is used heavily the the second glossary but "piece" is not refered to as single glossray term. Very strange!

Sheet music terminology


Issues with "force user" on Samba 4.7 + Active Directory authentication

Question: We have a environment with a Samba 4.7 with couple shares that uses Active Directory as authentication mode and a Oracle application drop some files so users get it through those shares.
We have a specific share that needs to keep permisions from everything created there as a unix user (oracle - ID 1001), so I set the "force user" on the share, and it dont allow access for any user on the folder.
The folder permissions are 0700, user oracle, ID 1001.
I set the folder 777 to try out, and it works, created a file, then i check the IDs owner to the files created through Samba, looks like Samba is forcing user "oracle" from Active Directory (there is also a user with this name there) instead of forcing the local unix user.
Any idea how to fix it?
Found some ideas like set order on nsswitch.conf like "files winbind" but seems like Samba is ignoring this.
<code>[test_acess]
comment = test
path = /shares/test_acess
public = yes
writable = yes
browseable = yes
force user = oracle
create mask = 0700
directory mask = 0700
valid users = Domains\\Users
</code>
Answer: Found the issue
"winbind use default domain = true"
Need to turn it off or


Where is php.ini-development on Ubuntu LAMP?

Question: On my development machine I run Ubuntu 10.04.1 LTS. Following the official documentation, I used the following command to install Apache, MySQL and PHP in one go:
sudo tasksel install lamp-server

Now that I'm testing my PHP scripts, I want to enable "developer mode", if there is one, to enable error reporting and logging. I have read reference to files php.ini-production and php.ini-development that apparently come with some versions of PHP 5, but not the one I have installed.
All I have is /etc/php5/apache2/php.ini. This configuration does not echo errors or warnings, which makes my scripts hard to debug. I guess I can edit the configuration by hand, but I'd rather just be able to drop in a replacement if that's possible.
So what I'm looking for is an easy way to switch between development and production environments for PHP!
Answer: php.ini-development and php.ini-production, which come with the PHP 5.3 package, are really just examples of recommended settings. You should review the settings and make sure that they apply to your use and copy them to the regular php.ini file location. On my Ubuntu 10.04.1 LTS (lucid) server, here's where I find mine:
# locate php.ini-development
/usr/share/doc/php5-common/examples/php.ini-development

The alternative example, php.ini-production, is in the same directory.
Answer: php.ini-development file for php7 on ubuntu 16.04 is located in
/usr/lib/php/7.0/php.ini-development

So you can do the following: make backup copy of your current php.ini:
$ sudo mv /etc/php/7.0/apache2/php.ini /etc/php/7.0/apache2/php.ini.back

then copy production ini file:
$ sudo cp /usr/lib/php/7.0/php.ini-development /etc/php/7.0/apache2/php.ini

and restart the server:
$ sudo service apache2 restart

Comment: This was the right place to look in php 8 as well. `/usr/lib/php/8.0/`


How do I calculate the mean of this quantity?

Question: Let's say I have an array of numbers that have a specific order, say:
$$x_1, x_2, x_3, \cdots x_n$$
Problem: How do I calculate the mean of $\Delta x$, where
$\Delta x = x_{n+1}-x_n$
?
At first glance it might seem trivial:
$$\langle \Delta x \rangle = \frac1{n-1}\sum_{i=0}^n (x_{i+1}-x_i)$$
But let's look at an example. Suppose that I have the following four numbers:
$$1,5,8,11$$
Using the equation above would mean:
$$\langle \Delta x \rangle = \frac13\big[(5-1)+(8-5)+(11-8)\big] = \frac1310 \approx 3.33$$
But I could also sum the terms:
$$\frac{11-5}{2} \quad ; \frac{8-1}{2}$$
Which would mean:
$$\frac15\bigg[(5-1)+(8-5)+(11-8)+3+\frac72\bigg]=\frac{33}{10} = 3.3$$
Which is a different result. For me it seems that the first result is correct, because it agrees with the definition of mean.
Question: Which one is correct, and why does taking the two extra terms I proposed gives an incorrect result?
Comment: $(11-5)/2$ is the average of $(11-8)$ and $(8-5)$. Similarly, $(8-1)/2$ is the average of $(8-5)$ and $(5-1)$. Note that $(8-5)$ appears in both of these averages. So, your second approach is weighting $(8-5)$ more than the other differences.
Comment: I don't even understand the second approach.  Why would that calculate something called a mean?
Comment: Note that $\sum_{i=1}^n(x_{i+1}-x_i)$ is just $x_n-x_1$. Are you sure this is what you want?
Answer: Your first attempt is correct.
Note that you can simplify the process by telescoping your sum $$ \sum _{i=0}^{n-1} (x_{i+1}-x_i) = x_n-x_0$$ Thus your mean is simply $$ \frac {x_n-x_0}{n-1}$$


Manter valor de variável entre camadas de um função

Question: Queria fazer um site em que quando clicar na imagem ela dobre de tamanho e largura, mas podendo fazer isso no limite de somente uma vez, e se fizer mais, apareça um aviso a impedindo. Da mesma forma, se ela estiver no tamanho padrão, você não poderá diminuí-la, e aparecerá um aviso, mas se você aumentá-la e tentar diminuir, isso será possível.
Eu parei no código por aqui:
function passar(img){
        var d = 0;
        if (d == 0){
        var x = confirm("tem certeza que deseja aumentar a imagem?");
        if(x == true && d ==0){
        d=d+1;
        img.height=img.height*2;
        img.width=img.width*2;
        }
        else if (x== true && d==1)
        window.alert("Não é possivel aumentar mais");
        else{
        var y = confirm("tem certeza que deseja diminuir a imagem?");
        if ( y==true && d==1){
        d=d-1;
        img.height=img.height/2;
        img.width=img.width/2;
        }
        else if(y == true && d==0)
        window.alert("Não é possivel");
        }}}

Meu maior problema está sendo que quando um if-else fecha a chave, o d não possui o novo valor que eu o dei d=d+1 ou d=d-1, já tentei de outras formas mas não acho uma solução.
Comment: Tente usar `d += 1` e `d -= 1`
Comment: não pegou, continuou do mesmo jeito, quando fecha a chave do IF-ELSE o d(contador) perde o valor, ficando limitado ao proprio if e else.
Answer: Organizar o código sempre ajuda, está muito fácil se enganar onde cada if fecha, é um pesadelo dar manutenção em código assim, perdi vários minutos para entender o que realmente está fazendo e tenho minhas dúvidas se acertei. O nome das variáveis deveriam ser mais significativos. Não verifiquei se a lógica está correta.
Neste caso é necessário fazer a variável ser considerada de instância da função para seu valor mantido entre as execuções. Além disso só deve inicializar se ela não foi inicializada, por isso usamos um operador relacional

function passar(img) {
    passar.contador = passar.contador || 0;
    if (passar.contador == 0) {
        var confirma = confirm("Tem certeza que deseja aumentar a imagem?");
        if (confirma && passar.contador == 0) {
            passar.contador++;
            img.height *= 2;
            img.width *= 2;
       } else if (confirma && passar.contador == 1) {
            window.alert("Não é possível aumentar mais");
        }
    } else {
        var confirma = confirm("Tem certeza que deseja diminuir a imagem?");
        if (confirma && passar.contador == 1) {
            passar.contador--;
            img.height /= 2;
            img.width /= 2;
        } else if (confirma && passar.contador == 0) {
            window.alert("Não é possível diminuir mais");
        }
    }
}
var img = {height : 10, width : 10};
passar(img);
passar(img);

Coloquei no GitHub para referência futura.
Deixei como contador porque pode no futuro querer permitir novas escalas, na forma atual, nem precisa ser um contador numérico, já que só tem dois estados possíveis.
Claro que existem outras soluções.
Comment: Então, eu usei seu método(dei ctrl ctrl v hehe) e não deu certo. Desculpe pela má organização, é que para mim assim fica mais fácil. Eu peguei algumas coisas como o "img.height *= 2;", mas ele não funcionou, todo o javascript parou de pegar.
Aqui o site organizado:
http://pastebin.com/brpgW2zi
( não pode mais que 600 caracteres, então mandei em forma de link )
de qualquer forma, obrigado pela ajuda ^^
Comment: Por força do hábito eu coloquei um `var` onde não devia. Agora botei um teste


What does StoreGeneratedPattern mean?

Question: I'm doing EF design, who could tell me what does StoreGeneratedPattern mean?
I can't find a easy straight answer online.
Comment: Try [StoreGeneratedPattern Enumeration](http://msdn.microsoft.com/en-us/library/system.data.metadata.edm.storegeneratedpattern.aspx). Also, [StoreGeneratedPattern = Identity and Getter/Setter](http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/ea27ee63-14d0-4939-bc57-32493434df0d/) might be useful.
Answer: If you look at the samed called enumeration it tells what should be done if you insert or update rows:

None: No auto generated value is generated
Identity: A new value is generated on insert, but not changed on update
Computed: A new value is generated on insert and update
Answer: These answers are also not an easy straight answer and just point to or repeat the same arcane documentation that the OP is referring to.
This attribute is used when the column is computed by the database. So on inserts and updates, the value will not be written.
The value will be read back from the database after inserts and updates, though I would guess that if set to Identity, EF may not read the value after an update since it won't have changed. Whether it really makes that tiny optimisation I don't know.
An example might be an identity column or a last updated time-stamp.

What does StoreGeneratedPattern mean?