Simple xxx yyy { } CSS selector not working - why?

Question: I have a seemingly simple html construct:

Now I want to target the a (which unfortunately does not have its own class), so I use this CSS
.img-wrapper a {
  background-image:url(../images/bkgs/stripes_tiny_08.png);
  background-repeat:repeat;
}

but nothing happens to this a element! It's certainly not the background image itself, also tried a simple color. The weird thing is: there is another, similar construct further up on the page and there the selector works!
Firebug shows the following CSS paths (the target a is at the end)
working: html.js body.single div#page.wrap div#main-container.container div#primary.site-content div#content article#post-26.post-26 div.featured-image a.img-link
not wrk: html.js body.single div#page.wrap div#main-container.container div#primary.site-content div#content aside#yarpp_widget-2.widget div.bloglist article.post div.three div.featured-image a

I'm out of ideas. Haven't found any overriding CSS declarations. Any idea how I can target that a?
EDIT: the target a contains an img which has a :hover opacity set. That way I can see that the background color works, not the background image however
Comment: http://jsfiddle.net/r48ST/ It works. I'm assuming that your image isn't transparent and you can't see what's behind it, or that there's more in play with conflicting styles.
Comment: it's not .img-wrapper a img{ /* ... */ } ?
Comment: just opinion: add display:block; to .img-wrapper a
Comment: Sorry forgot one important detail: the a contains an img which has a :hover opacity set. That way I can see that the background color works, not the background image however. I edited the question to make it clear.
Comment: You mention the Firebug paths, but are you saying the selector is not even showing as ever applying to the element, or is it being crossed out (as shown when being overridden)?
Comment: @ScottS: it was not crossed out but showed as applied (at the top of the list).
Comment: Okay it works now.
Miljan Puzovic was spot on in this comment:

"just opinion: add display:block; to .img-wrapper a"
Comment: Odd, is the `img` positioned absolutely or floated, causing the `a` to collapse to zero dimensions?
Comment: "img" element is positioned static, but you always must give display:block to "a" element if "img" element is inside of him. just expirience :)
Comment: no, the only styles that apply to the image are   .img-wrapper img {
    display: block;
}
img.scale-with-grid {
    height: auto;
    max-width: 100%;
    width: auto;
}
Answer: remove img (if it's not transparent)
for conflicts:

put !important at the end of css instruction.
or try inline style.
Comment: I think his problem isn't that the style is being overridden, but rather that it's being applied behind the image element that is being wrapped.
Comment: img has a hover opacity of 0.5; also tried !important -> no change.
Answer: Are you trying to do this effect? http://jsfiddle.net/r48ST/1/
[EDIT]: This is that effect http://jsfiddle.net/r48ST/2/ , just added some opacity on image. Also, put some transition effect on opacity an you have full effect.
Comment: No, actually this effect: http://labs.sevenspark.com/ when you hover over th eimage you see the stripes of the background image.
Comment: Thanks,a ctually your comment above about the display:block did the trick. Can you explain to me why? Other than in your jsfiddle, there is no width specified for the wrapper div
Comment: display:block guarantees that '' element will be full over his children element in height an will have 100% width of parent element. Because of that, parent of '' element (in this case .img-wrapper) must have limited width. If not, then parent of .img-wrapper must have limited width, or display:block of '' element will cause that '' element extends over 100% of first parent which have some limit of width. And in there is no such parent, it will have 100% width of body.
Answer: Without specifying dimensions for your  tag, it will conform to the dimensions of the  tag that it contains. As such, any background image that you apply will be overlayed by the . Putting repeat on only repeats the background image as many times ans it will fit (cropped or whole) within the element. If you give the element a width and a height greater than that of the image that it wraps you should see the background.
I hope this was the issue that you were facing. Otherwise, if you can post a bit more of your code or a demo we will be able to better help you.

EDIT: I just noticed your edit about the :hover opacity. What I suggest is that you change the styling to be more like this: a > img:hover { visibility: hidden; }
Comment: sorry my first comment was misleading. It's not quite what I want; I would like to achieve the hover effect seen here http://labs.sevenspark.com/
Comment: okay here is your solution using jQuery: `$("a > img").mouseenter(function() { $(this).fadeTo(.65, 400); }).mouseleave(function() { $(this).fadeTo(1, 400); });` You will have to come up with an IE fix though, since fadeTo doesn't work in IE. I can help you with that if you have trouble


An interesting limit: $\lim_{n\rightarrow \infty}\frac{1}{n^{2}+1}+\frac{2}{n^{2}+2}+\cdots+\frac{n}{n^{2}+n}$

Question: $$\lim_{n\rightarrow \infty}\frac{1}{n^{2}+1}+\frac{2}{n^{2}+2}+…+\frac{n}{n^{2}+n}$$
Thanks in advance
Comment: There is no attempt by OP. Who voted up for this post?
Comment: @MithleshUpadhyay This question was in the network-wide hot questions list for some time (around 100 views IIRC). This usually change voting patterns a lot, since many users from others sites (which do not visit this site regularly) vote on such posts. You can probably find some discussion about this [on meta](http://meta.math.stackexchange.com/questions/tagged/hot-questions-list). This was also discussed [in this chat room](http://chat.stackexchange.com/transcript/51965/2017/1/17), which arose from a discussion in a comments to an answer on meta.
Comment: Have u studied riemann sum?
Comment: @Shobhit It's not a Riemann sum.
Comment: the limit comes out to be 1/2 or 0.50
Comment: @MartinSleziak, yes. Thanks. People must avoid voting up for such posts.
Answer: HINT:
$$\frac{1}{n^2+n}\sum_{k=1}^n(k)\le \sum_{k=1}^n\frac{k}{n^2+k}\le \frac{1}{n^2+1}\sum_{k=1}^n (k)$$
SPOILER ALERT:  Scroll over the highlighted area to reveal the solution

We can write the limit as$$\lim_{n\to\infty}\sum_{k=1}^n\frac{k}{n^2+k}$$Then, using $n^2+n\ge n^2+k\ge n^2+1$ we have $$\frac{1}{n^2+n}\sum_{k=1}^n(k)\le \sum_{k=1}^n\frac{k}{n^2+k}\le \frac{1}{n^2+1}\sum_{k=1}^n (k)\tag 1$$We can sum the  arithmetic progression to obtain $$\sum_{k=1}^n (k)=\frac{n(n+1)}{2}\tag 2$$Using $(2)$ in $(1)$ reveals $$\frac{n(n+1)}{2(n^2+n)}\le \sum_{k=1}^n\frac{k}{n^2+k}\le \frac{n(n+1)}{2(n^2+1)}\tag 3$$whereupon applying the squeeze theorem to $(3)$ yields the coveted limit $$\lim_{n\to\infty}\sum_{k=1}^n\frac{k}{n^2+k}=\frac12$$
Comment: Shouldn't $\sum_{k=1}^n=\frac{n^2+n}{2}=\frac{n(n+1)}{2}$?
Also, it seems like the squeeze theorem doesn't hold.  I must be missing something.
Comment: @MattGroff Matt, yes of course.  I've edited the typo.  The squeeze theorem absolutely applies.  $\lim_{n\to\infty}\frac{n(n+1)}{2(n^2+n)}=\lim_{n\to\infty}\frac{n(n+1)}{2(n^2+1)}=\frac12$
Comment: Oops, you're right...  I was still thinking of the sum as a finite value, and not considering the limit as it approaches infinity!  Many thanks, and +1!
Comment: @MattGroff You're quite welcome.  My pleasure.  -Mark
Answer: Added for your curiosity.
Sooner or later, you will learn about harmonic numbers and it will be clear to you that $$S_n=\sum_{i=1}^n\frac{i}{n^2+i}=n \left(n H_{n^2}-n H_{n^2+n}+1\right)\tag 1$$ For large values of $p$, the asymptotics is $$H_p=\gamma +\log \left({p}\right)+\frac{1}{2 p}-\frac{1}{12
   p^2}+O\left(\frac{1}{p^4}\right)\tag 2$$ Applying $(2)$ in $(1)$, you will get as an approximation $$S_n=\frac{1}{12} \left(-\frac{1}{n^2}+12 n+\frac{6 n+7}{(n+1)^2}\right)+n^2 \log \left(\frac{n^2}{n^2+n}\right)+\cdots$$ Using Taylor series for the logarithm and long division for the remaining term, you should end with $$S_n=\frac{1}{2}+\frac{1}{6 n}-\frac{1}{4 n^2}+\frac{2}{15
   n^3}+O\left(\frac{1}{n^4}\right)\tag 3$$ which, for sure, shows the limit and how it is approached. It also gives a very simple approximation of the result.
For example, using $n=10$, the exact result is $$S_{10}=\frac{3039003639041255}{5909102214621606}\approx 0.5142919396$$ while $(3)$ would give $\frac{5143}{10000}$.
Comment: Claude, this is really nice! (+1)
Comment: Your answer definitely helps a lot to satisfy our curiosity, the starting line is so relevant. +1
Comment: @Dr.MV. Thanks, my friend ! Have a nice day.
Comment: For me, it is night time - 11:55 p.m.  Time for sleep.  Bonne nuit, mon ami.


Why denominator is $^{15}\rm C_{10}$?

Question: Question: Fifteen telephones have just been received at an authorized service center. Five of these telephones are cellular, five are cordless, and the other five are corded phones. Suppose that these components are randomly allocated the numbers $1$, $2$, . . . , $15$ to establish the order in which they will be serviced. (Round your answers to four decimal places.) What is the probability that after servicing ten of these phones, phones of only two of the three types remain to be serviced?
Answer: $$\frac{3\cdot(^{5}\rm C_1\cdot ^{5}\rm C_4+^{5}\rm C_2\cdot^{5}\rm C_3+^{5}\rm C_3\cdot^{5}\rm C_2+^{5}\rm C_4\cdot^{5}\rm C_1)}{^{15}\rm C_{10}}$$
My question: Why isn't the denominator $^{15}\rm C_5$ when the numerator consists of certain groups of $5$ phones.
Comment: Because we are randomly choosing 10 phones out of 15 phones to be serviced.
Comment: First, the numerator does not consist of groups of phones, the numerator is just a number. Second, it doesn't matter if you write the denominator as $_{15}C_{10}$ or $_{15}C_5$, because $_{15}C_{10}=_{15}C_5$.
Answer:
Answer: $$\frac{3\cdot(_{5}\rm C_1\cdot_{5}\rm C_4+_{5}\rm C_2\cdot_{5}\rm C_3+_{5}\rm C_3\cdot_{5}\rm C_2+_{5}\rm C_4\cdot_{5}\rm C_1)}{_{15}\rm C_{10}}$$
My question: Why isn't the denominator $_{15}\rm C_5$ when the numerator consists of certain groups of $5$ phones.

You're correct, but note that
$$
{15\choose 5}={15!\over10!5!}={15\choose 10}.
$$
You can think of it like this: we could just as well count all the ways that the first ten phones got all five of one type, ${5\choose5}=1$, and then some each of the other two types, which would give us exactly the same denominator and numerator, so the two are actually interchangeable.
Answer: The denominator is 15C10 because the question says what is the probability "after servicing ten of these phones", which implies it's 15C10 instead of 15C5.

Why denominator is $^{15}\rm C_{10}$?


Launch Android SDK manager - Tools directory doesn't exist? Mac

Question: I'm on mac, I think I've done everything right so far. following these instructions:
http://developer.android.com/sdk/installing/adding-packages.html
it says to navigate to tools/ directory in terminal. Here are my steps.

Open terminal
cd Applications
result is: No such file or directory

path to my tools directory is as follows
Applications->adt-bundle-mac-x86_64-20130219  ->SDK -> tools

I tried putting my folder onto my desktop, both the tools folder, and my adt-bundle because I could change directory to my desktop, and when I enter ls to the terminal I see my tools folder, and my adt-bundle is there,
but the problem is when I try to enter
cd tools
or
cd adt-bundle(etc...)
it says that it is not a directory.
what do I do?
Comment: if your path is /Applications/adt-bundle-mac-x86_64-20130219 then launch `/Applications/adt-bundle-mac-x86_64-20130219/sdk/tools/android`
Comment: What do you mean "launch" Do I enter the command as follows? launch /Applications/adt-bundle-mac-x86_64-20130219/sdk/tools/android   ??? Or does launch mean "change directory?"
Comment: at the Terminal shell prompt ($), just type `/Applications/adt-bundle-mac-x86_64-20130219/sdk/tools/android` and press .
Answer: Go to this directory:
cd /adt-bundle-mac-x86_64-20131030/sdk/tools

and run:
./android

Comment: The android command is no longer available.For manual SDK and AVD management, please use Android Studio. For command-line tools, use tools/bin/sdkmanager and tools/bin/avdmanager
Comment: this is actually not wrong, just need clarification to make it more useful
Comment: worked fine for me. Obviously whoever reads this must set the right path in order for this to work.
Comment: This does work although the path is incorrect but the key difference here is prefixing ./

Thanks
Answer: I recently encountered this issue, and figured I'd post on this for clarification or for anyone still encountering it.
It seems you have to be at the root of the /adt-bundle-mac-VERSION/sdkdirectory in order to execute the "android" command.
I normally cd into the directory until I reach the location of the command, but in this case I encountered the same issue as the original poster.
You must use the tab key to the android command...
ie...
locate your installation /adt-bundle-mac-x86_64-20131030/sdk hit TAB key /tools hit TAB key /android
instead of cd adt-bundle-mac-x86_64-20131030/ cd/sdk cd/tools android
If done properly the SDK manager should launch for you.
Hope this helps anybody out there.
Comment: Think adding Android SDK to your path brings the same results as I understand you right - the benefit is that android and that other cli commands are available from every dir.
Answer: You can launch the SDK Manager by using the GUI:

Launch Android Studio
Create a new blank project
In the toolbar, look for the icon with tooltip "SDK Manager"
Answer: A lot of answers have been given here that you should go to /{path-to-your-android-sdk}/tools
and run ./android.
For me, this did not work. When I opened the android file located at my /{path-to-your-android-sdk}/tools directory with a text editor, it contained the following:
#!/bin/bash
echo The "android" command is no longer available.
echo For manual SDK and AVD management, please use Android Studio.
echo For command-line tools, use tools/bin/sdkmanager and tools/bin/avdmanager
exit 1

So the right approach now, is as stated by @Shijil in his comment.
In the directory for your android sdk, you should use:
For SDK Manager:
cd tools
cd bin
./sdkmanager

For AVD Manager:
cd tools
cd bin
./avdmanager

NB For the last command in each of the options above, you will have to supply additional args depending on the operation you want to perform. An example arg that works for both is --list. Running the commands without any args will only display the possible args you could have passed.
Personally, I think using the GUI in android studio is easier. Especially for linux beginners.
Answer: Use cd /users/user/...your path.../android-sdk/tools
and then :
./android
Answer: Here is your "tools" directory for Android Studio in OS X El Captain(Yosemite also has the same path hopefully):
Users/user-name/Library/Android/sdk/tools

In the terminal, just type: Library/Android/sdk/tools
and hit enter. And you are in the tools folder.
Please note that user-name refers to the mac user
Answer: Better open terminal and type which android.
It will tell you the path where you have the package installed.
Then yeah, you just have to execute that path on the terminal.
Your android package might have been installed with Homebrew or others, so the path can be different.
Edit: typo
Answer: For me the directory was cd /Users/your_user_name/Library/Android/sdk/tools/
and after that the command was ./android list targets
I hope this can help


Prediction evaluation metric for panel/longitudinal data

Question: I would like to evaluate several different models that provide
predictions of behavior at a monthly level. The data is balanced, and
$n=$100,000 and $T=$12. The outcome is attending a concert in a given
month, so it is zero for ~80% of the people in any month, but there's
a long right tail of heavy users. The predictions I have do not seem
to respect the count nature of the outcome: fractional concerts are
prevalent.
I don't know anything about the models. I only observe 6 different
black-box predictions $\hat y_1,...,\hat y_6$ for each person per month. I do
have an extra year of data that the model builders did not have for
the estimation (though the concert-goers remain the same), and I would
like to gauge where each performs well (in terms of accuracy and
precision). For instance, does some model predict well for frequent
concert-goers, but fail for the couch potatoes? Is the prediction for
January better than the prediction for December? Alternatively, it
would be nice to know that the predictions allow me to rank people
correctly in terms of the actuals, even if the exact magnitude cannot
be trusted.
My first thought was to run a fixed effects regressions of actual on
predicted and time dummies and look at the RMSEs or $R^2$ for each model. But
that does not answer the question about where each model does well or
if the differences are significant (unless I bootstrap the RMSE). The distribution of the outcome also worries me with this approach.
My second idea was to bin the outcome into 0, 1-3, and 3+, and
calculate the confusion matrix, but this ignores the time dimension,
unless I make 12 of these. It's also pretty coarse.
I am aware of Stata commands concord by T.J. Steichen and N.J. Cox--which has the by() option, but that would require collapsing the data to annual totals. This calculates Lin's Concordance Correlation Index with confidence intervals, among other useful stats. CCC ranges from -1 to 1, with perfect agreement at 1.
There's also Harrell's $c$ (calculated through
somersd by R. Newson), which has the cluster option, but I am not
sure that would allow me to deal with the panel data. This gives you confidence intervals. Harrell's c is the generalization of the area under a ROC curve (AUC) for a continuous outcome. It's the proportion of all pairs that can be ordered such that the subject with the higher prediction actually has the higher outcome. So $c=0.5$ for random predictions $c=1$ for a perfectly discriminating model. See Harrell's book, p.493
How would you tackle this problem? Would you suggest calculating statistics like MAPE that are common in forecasting?

Useful things found so far:

Slides on a repeated measure version of Lin's Concordance Correlation Coefficient
Comment: We'll need to know more about the behavior, is it ordinal/binary/continuous valued? Because this experiment is longitudinal, does your interest lie in forecasting or predicting outcomes in an individual? Mixed effects models are used for inference, not prediction. They don't work because, in order to *predict*, you need an estimate of the random effect.
Comment: Actual behavior is either counts or continuous. The predictions are all continuous. I would like to see how good the individual level monthly predictions are.
Comment: "Individual level monthly predictions" in persons whom you've observed previous data or persons at initial assessment? I.E. are you obtaining $\widehat{Y_{i=12}} = f(X_{i=12, 11, \cdots, 1}, Y_{i=11, 10, \cdots, 1}$ or $\widehat{Y_{i=I}} = f(X_{i=I, I-1, \cdots, 1}, Y_{i=I-1, I-2, \cdots, 1}$ or $\widehat{Y_{i}} = f(X_{i})$ or ... please clarify as prediction from longitudinal is not a hand-wavy matter.
Comment: This is a sample of people who were used for the estimation, but the prediction is for the year after the estimation window. The prediction for the first month is a function of lagged, observed behavior and observed covariates for person $i$: $\hat Y_{i,1}=f(Y_{i,t-1},X_{i,t}).$ I expect the first month to be pretty close. For the second month (and thereafter), it's a function of last month's prediction and that month's observed covariates: $\hat Y_{i,2}=f(\hat Y_{i,1},X_{i,2})$. I expect this prediction to diverge from the actuals more and more. I want to compare $Y_{i,t}$ and $\hat Y_{i,t}$.
Comment: estimation implies parameter estimation which may be a part of "training" for a predictive model, but I think you mean to say that your sample is used for training a predictive model. What you're stating here is a conditional semi-markov process and has unique applications in forecasting.
Answer: To evaluate a semi-Markov forecast's predictive ability, there are a number of methods available depending on sample size and other available information.
For evaluating any predictive/forecast model, you have the option of cross validation (specifically leave-one-out or iterative split sample cross validation), where a model is estimated in a "training" sample and model uncertainty assessed in a "validation" sample. Depending on the distribution of the outcome, a number of measures are available by which you can select a model among a panel of eligible models. For general non-parametric measures for model selection, people really like AIC and BIC, especially the latter.
CCC and c-statistics are used to evaluate binary cross-sectional predictions like from tests/assays, so you'll have to rule them out if you're predicting, say, BMI or IQ. They measure calibration (like the Hosmer Lemeshow test) and what's called risk stratification capacity. No intuitive connection to continuous outcomes there, at least not as far as I can tell.
RMSE on the other hand is used to evaluate continuous predictions (save the case of risk prediction in which RMSE is referred to as a Brier score, a pretty archaic and deprecated model evaluation tool). This is an excellent tool and probably is used to calibrate upwards of 80% of predictive models we encounter daily (weather forecasts, energy ratings, MPG on vehicles, etc.).
A caveat in split sample validation or resampling for evaluating forecast models is that you may only be interested in future outcomes when your sample leaves you predicting past outcomes. Don't do this! It doesn't reflect the models application and can vastly sway selection in a negative fashion. Roll forward all available information and predict future, unobserved outcomes in all available cases.
Pretty much any applied linear models book will cover prediction, RMSE, and the nuances of training and validating models. A good start would be Kutner, Nachtsheim, Neter, Li, also consider Diggle's "Time Series Analysis", Diggle Heagerty Zeger Li's, "Longitudinal Data Analysis", and potentially Harrell's "Regression Modeling Strategies".
Comment: CCC and Harrell's c can be used with continuous outcomes. CCC also has a repeated measures implementation. See the references/links I added in the question.
Comment: Doesn't matter. You're not classifying.


Synthetic control, exogeneity of treatment, parallel trends assumption?

Question: I am relatively new to methods for causal inference. So, please excuse my conceptual confusion. However, I have been looking into the synthetic control method first proposed by Abadie and Gardeazabal (2003) in this paper on the economic costs of conflict. One thing that is confusing to me is that in most of the papers I have read the treatment does not seem to be exogenous. I understand that the Basque region presents a unique opportunity to study the economic costs of conflict since the terrorism there unlike in some other places was not economically motivated. However, it still seems to me that the onset of terrorism was not random by any means and that in turn there could be some other confounding variable effecting both the onset of terrorism and GDP.
How do we know that there are not violations to the parallel trends assumption? Would anyone be able to explain this to me? My understanding is that like difference in differences designs synthetic control methods still rely on the parallel trends assumption for causal inference. However, if for difference in differences designs the treatment needs to be exogenous for the parallel trends assumption to be satisfied. Why do treatments often not seem exogenous when synthetic control methods are used and there is seldom an explanation of why the parallel trends assumption is satisfied?
Answer: Unlike the difference-in-differences, SCM does not assume parallel trends. It allows for the effects of observed and unobserved predictors to change over time while assuming that pre-intervention covariates maintain a linear relationship with outcomes post-treatment (see p. 399-400 in Abadie's JEL paper for a comparison of the two). This is a much weaker assumption than parallel trends.
This explains why economists don't spend any time worrying about this, except to show that it fails and they cannot use DiD (e.g., see p. 397 on the paper linked above).


How to DELETE in one batch, but different changeset?

Question: I am using sap.ui.model.odata.v2.ODataModel and trying to delete multiple object. Desire result is DELETE requests are in one batch, but different changeset. Because if I wrap them up in the same changeset, one request failed will cause others to rollback.
I've tried to use setDeferredGroups, but it results in two batches.
oModel.setDeferredGroups(["group1"]);
oModel.setDeferredGroups(["group2"]);

oModel.remove("/EquipmentSet('1')", {groupId: "group1"});
oModel.remove("/EquipmentSet('2')", {groupId: "group2"});

oModel.submitChanges({
    groupId: "group1",
    success: this.successCallback,
    error: this.errorCallback
});

oModel.submitChanges({
    groupId: "group2",
    success: this.successCallback,
    error: this.errorCallback
});

And also tried setChangeGroups, it still results in two batches. I did not quiet understand what's the difference between groupId and changeSetId. And what's the use of EntityTypeName?
oModel.setChangeGroups({
    "EntityTypeName": {
        groupId: "group1",
        changeSetId: "changeSet1",
        single: true
    }
});
oModel.setChangeGroups({
    "EntityTypeName": {
        groupId: "group2",
        changeSetId: "changeSet2",
        single: true
    }
});

oModel.remove("/EquipmentSet('1')", {groupId: "group1"});
oModel.remove("/EquipmentSet('2')", {groupId: "group2"});

oModel.submitChanges({
    success: this.successCallback,
    error: this.errorCallback
});

Comment: Have you tried the same groupId, and different changeSetId in your first approach? Same groupId would ensure one batch request.
Comment: @Allen, thx! Fixed this problem by `oModel.remove("/EquipmentSet('1')", {groupId: "group1", changeSetId: "changeSetId1"});`
Comment: I am glad to help!
Answer: Thanks Allen, problem fixed
oModel.setDeferredGroups(["group1"]);

oModel.remove("/EquipmentSet('1')", {
     groupId: "group1",
     changeSetId: "changeSetId1,
     success: this.successCallback,
     error: this.errorCallback
});

oModel.remove("/EquipmentSet('2')", {
     groupId: "group1",
     changeSetId: "changeSetId1,
     success: this.successCallback,
     error: this.errorCallback
});

oModel.submitChanges({
    groupId: "group1"
});

And callback will no longer be caught by submitChanges(), it is caught by each remove().
Ref: OData V2 Model remove()


Código não funciona como esperado

Question: Meu código deveria ler nome e peso usando uma lista auxiliar e jogando os dados para uma lista principal. No final, ele gera um resultado do maior e menor peso com o nome das pessoas que possuem esses pesos.
O problema é que ele está substituindo a variável menor por um peso maior, que deveria ir para o if que atribui a variável maior ao peso e não no if abaixo. Além disso, depois do terceiro resultado ele não usa mais os if's, o que é bem estranho.
Comentei algumas linhas que estava usando para debugar. Segue o código:
cadastro = []
dados = list()

while True:

    dados.append(input('Digite o nome: '))
    dados.append(input('Digite o peso: '))
    # print(dados[1])

    if len(cadastro) == 0:
        maior = menor = dados[1]

    else:

        if dados[1] > maior:
            maior = dados[1]
            # print(f'Função maior funcionando. {maior} {menor}')

        elif dados[1] < menor:
            menor = dados[1]
            # print(f'Função menor funcionando. {menor} {maior}')

    cadastro.append(dados.copy())
    dados.clear()
    resp = ' '

    while resp not in 'SN':
        resp = input('Você quer continuar? [S/N] ').strip().upper()[0]

    if resp == 'N':
        break

print(f'Ao todo você cadastrou {len(cadastro)} pessoas.')
print(f'O maior peso cadastrado foi {maior} de: ', end='')

for (nome, peso) in cadastro:
    if peso == maior:
        print(f'{nome}', end=' ')

print(f'O menor peso cadastrado foi {menor} de: ', end='')

for (nome, peso) in cadastro:
    if peso == menor:
        print(f'{nome}', end=' ')

Answer: Você não informou os dados que usou para testar, mas o problema provavelmente ocorre porque o peso deveria ser um número, mas no código você manipula-o como string (já que input retorna uma string).
O problema de comparar strings é que, mesmo se só tiverem dígitos, elas são comparadas lexicograficamente. Isso quer dizer que a string '2' é considerada "maior" que a string '10':
print('2' > '10') # imprime "True"

Eis o trecho relevante da documentação que explica esse comportamento:

Lexicographical ordering for strings uses the Unicode code point number to order individual characters

Ou seja, a ordem lexicográfica leva em conta os Unicode code points de cada caractere (para entender melhor o que é um code point, sugiro começar por aqui). Mas basicamente, cada caractere possui um código numérico associado (pense no Unicode como uma extensão da tabela ASCII - e que fique claro que essa é uma simplificação bem grosseira), e ao comparar strings, o valor desse código (que é o code point) é usado para determinar o que é "maior" ou "menor".
No caso, o code point do caractere '2' é maior que o do caractere '1', por isso a string '2' é considerada "maior" que a string '10'. Funciona da mesma forma que uma comparação entre as strings 'b' e 'ac'. Como o b é "maior" que o a (o code point do caractere b é maior que o do caractere a), então lexicograficamente 'b' > 'ac' - ou seja, em uma ordenação de strings, o 'b' viria depois de 'ac', assim como o '2' viria depois de '10':
lista = [ '2', '10' ]
print(sorted(lista)) # ['10', '2']

lista = [ 'b', 'ac' ]
print(sorted(lista)) # ['ac', 'b']

Veja aqui este código rodando
Enfim, ao comparar pesos desta maneira, como strings, pode ocorrer a situação que você descreveu: um peso com valor numérico menor (por exemplo, 2) é considerado maior que outro (como o 10) porque os dados estão como strings, e não como números.

Se quer levar em conta os valores numéricos (e não os code points dos caracteres da string) para fazer as comparações (e acredito que seja isso que você quer, já que estamos falando de pesos), você deve converter o peso para número, usando int() (caso só possa ter valores inteiros) ou float() (se puder ter casas decimais). Você também pode capturar o ValueError, que ocorre caso não seja digitado um número, e pedir que digite novamente. Ficaria assim:
while True:
    try:
        peso = int(input('Digite o peso: '))
        break
    except ValueError:
        print('Peso deve ser um número')

Inclusive, na documentação tem um exemplo igual a este.
Ou seja, enquanto não for digitado um número, continua pedindo que digite novamente. Assim você garante que o peso será um número e que as comparações sejam feitas corretamente, levando em conta o valor numérico.

Outro detalhe é que talvez você não precise guardar tudo em uma lista, se o objetivo é somente obter o maior e menor valor. Uma opção seria manter um contador de cadastros e atualizar o maior e menor valores diretamente, sem precisar guardar em uma lista:
cont = 0
while True:
    nome = input('Digite o nome: ')
    while True:
        try:
            peso = int(input('Digite o peso: '))
            break
        except ValueError:
            print('Peso deve ser um número')

    if cont == 0:
        maior_peso = menor_peso = peso
        nome_maior = nome_menor = nome
    else:
        if peso > maior_peso:
            maior_peso = peso
            nome_maior = nome
        elif peso < menor_peso:
            menor_peso = peso
            nome_menor = nome

    cont += 1
    resp = ' '
    while resp not in 'SN':
        resp = input('Você quer continuar? [S/N] ').strip().upper()[0]
    if resp == 'N':
        break

print(f'Ao todo você cadastrou {cont} pessoas.')
print(f'O maior peso cadastrado foi {maior_peso} de: {nome_maior}')
print(f'O menor peso cadastrado foi {menor_peso} de: {nome_menor}')

OBS: A diferença para o seu código é que este só imprime um dos nomes em caso de empate. Já o loop que você fez imprime todos os nomes, caso tenha mais de uma pessoa com o peso mínimo ou máximo. Neste caso, eu até entendo o motivo de ter que guardar tudo em uma lista.

Se quer guardar os cadastros em uma lista, não precisa de duas listas como você fez (e insere em uma para logo depois remover, é uma complicação à toa). Bastaria adicionar o cadastro dentro do loop, assim:
cadastros = [] # Obs: usar [] e list() dá no mesmo, ambos criam uma lista vazia
while True:
    nome = input('Digite o nome: ')
    while True:
        try:
            peso = int(input('Digite o peso: '))
            break
        except ValueError:
            print('Peso deve ser um número')

    if len(cadastros) == 0:
        maior_peso = menor_peso = peso
    else:
        if peso > maior_peso:
            maior_peso = peso
        elif peso < menor_peso:
            menor_peso = peso

    cadastros.append((nome, peso))
    resp = ' '
    while resp not in 'SN':
        resp = input('Você quer continuar? [S/N] ').strip().upper()[0]
    if resp == 'N':
        break

print(f'Ao todo você cadastrou {len(cadastros)} pessoas.')

print(f'O maior peso cadastrado foi {maior_peso} de: ', end='')
for (nome, peso) in cadastros:
    if peso == maior_peso:
        print(f'{nome}', end=' ')

print(f'O menor peso cadastrado foi {menor_peso} de: ', end='')
for (nome, peso) in cadastros:
    if peso == menor_peso:
        print(f'{nome}', end=' ')

Se bem que a parte final é meio repetitiva, daria para simplificar criando uma função:
def encontrar_nomes_por_peso(cadastros, peso_busca, descricao):
    print(f'O {descricao} peso cadastrado foi {peso_busca} de: ', end='')

    for (nome, peso) in cadastros:
        if peso == peso_busca:
            print(f'{nome}', end=' ')
    print()

encontrar_nomes_por_peso(cadastros, maior_peso, 'maior')
encontrar_nomes_por_peso(cadastros, menor_peso, 'menor')

Answer: O único erro que eu vi no código foi tratar o input do peso como String.
Demonstrado na linha dados.append(int(input('Digite o peso: ')))
cadastro = []
dados = list()

while True:

    dados.append(input('Digite o nome: '))
    **dados.append(int(input('Digite o peso: ')))**
    # print(dados[1])

    if len(cadastro) == 0:
        maior = menor = dados[1]

    else:

        if dados[1] > maior:
            maior = dados[1]
        # print(f'Função maior funcionando. {maior} {menor}')

        elif dados[1] < menor:
            menor = dados[1]
            # print(f'Função menor funcionando. {menor} {maior}')

    cadastro.append(dados.copy())
    dados.clear()
    resp = ' '

    while resp not in 'SN':
        resp = input('Você quer continuar? [S/N] ').strip().upper()[0]

    if resp == 'N':
        break

print(f'Ao todo você cadastrou {len(cadastro)} pessoas.')
print(f'O maior peso cadastrado foi {maior} de: ', end='')

for (nome, peso) in cadastro:
    if peso == maior:
        print(f'{nome}', end=' ')

print(f'O menor peso cadastrado foi {menor} de: ', end='')

for (nome, peso) in cadastro:
    if peso == menor:
        print(f'{nome}', end=' ')

Answer: cara , eu usei lista de dicionario..

cadastro = []
while True:
    nome = input('Digite o nome: ')
    peso = int(input('Digite o peso: '))
    cadastro.append({'nome':nome,'peso':peso})
    resp = input('Você quer continuar? [S/N] ')
    if resp.upper() == 'N':
        break
print(f'Ao todo você cadastrou {len(cadastro)} pessoas.')
lista_pesos = [x['peso'] for x in cadastro]
lista_pesos.sort()
peso_maior = lista_pesos[-1]
peso_menor = lista_pesos[0]
maior = [ x for x in cadastro if x['peso']== peso_maior][0]
menor = [ x for x in cadastro if x['peso']== peso_menor][0]
print(f'O maior peso cadastrado foi do {maior["nome"]} com {maior["peso"]}'   )
print(f'O menor peso cadastrado foi do {menor["nome"]} com {menor["peso"]}',  )

Código não funciona como esperado


BM01 2011/12 Question 6 Geometry Problem

Question:
Let $ABC$ be an acute-angled triangle. The feet of the altitudes from
$A,B$ and $C$ are $D, E$ and $F$ respectively. Prove that $DE +DF \le BC$
and determine the triangles for which equality holds.
The altitude from A is the line through A which is perpendicular to
BC. The foot of this altitude is the point D where it meets BC. The
other altitudes are similarly defined.

Thanks in advance for any contributions.
Comment: Did you mean $DE +DF \ge BC$?
Answer: $\Delta DEF$ is the orthic triangle of $\Delta ABC$, and it is well-known that $DF=b\cos B$ and $DE=c\cos C$. Also using the well-known projection formulae, $a=b\cos C+c\cos B$. So the inequality is equivalent to:
$$b\cos B + c\cos C \le b\cos C+c\cos B$$
$$(b-c)(\cos B - \cos C) \le 0$$
This inequality is easily proved because $b\le c \implies \sin B \le \sin C \implies \cos B \ge \cos C$. Similar procedure applies for the $b \ge c$ case.
The equality clearly holds in isosceles triangles. $A,B,C$ and $a,b,c$ have usual meaning.
For info on orthic triangle, click here
Comment: Many thanks. Do you think perhaps though there is another solution? I had made some progress in fashioning a cyclic quadrilateral with its base as the diameter of its circumcircle and the BMO1 does not tend to demand any theorems that are not taught at secondary school.
Comment: Can you tell me what all you know? I'll try to use only that
Comment: http://www.ukmt.org.uk/docs/BMO%20Preparation%20Sheet.pdf Here is what they state is satisfactory to know for the tests. As you can see the requirements for BMO1 are very basic, e.g. alternate angle theorem, opposite angle theorem. It does mention that you should know some properties of orthic circles for the BMO2 and it may well be the case that since this is the hardest question on the paper they require a bit extra knowledge. Thank you anyway though.
Comment: @MadChickenMan , So should I or should I not think of something else?
Comment: It's up to you, it seems unlikely that what you gave wouldn't be the solution, but I am curious as to whether there is another solution. If you think that your solution is probably the only one then don't bother.
Comment: @MadChickenMan well I thought of 2 more ways, but they just turned out to be longer ways to get to what I already had done. In the end of both, I obtained the same inequality that I wrote in the answer. I think any solution would most probably boil down to this.

And since you're new here, I should probably mention that it is customary here to click on the check mark next to an answer which satisfactorily answers your question.
Comment: Thanks for the heads up. So did these 2 solutions involve the orthic triangle properties used in your first answer, or were you able to find a solution without them, if so I'd love to see them.


When is the Blow-up of $\mathbb{P}^n$ dominant?

Question: Let $X\subset\mathbb{P}^n$ be some algebraic variety. Lets assume that there are some homogeneous polynomials $f_0,\ldots,f_n$, all of degree $d$, that generate the vanishing ideal of $X$. When is the rational map $\mathbb{P}^n\dashrightarrow\mathbb{P}^n, x\mapsto (f_0(x):\cdots:f_n)$ dominant? Are there some nice criteria? What are examples where it is not the case?
Answer: Here is an example. Let $A$ and $B$ be vector spaces of dimension 2 and 5. Let
$$
X = \mathbb{P}(A) \times \mathbb{P}(B) \subset \mathbb{P}(A \otimes B).
$$
The ideal of $X$ is generated by quadrics, which span the space
$$
\mathrm{Ker}(S^2(A \otimes B)^\vee \to S^2A^\vee \otimes S^2B^\vee) = \wedge^2A \otimes \wedge^2B \cong \wedge^2B.
$$
Note that $\dim(A \otimes B) = 10 = \dim(\wedge^2B)$.
But the image of the corresponding map
$$
f \colon \mathbb{P}(A \otimes B) \dashrightarrow \mathbb{P}(\wedge^2B)
$$
is the Grassmannian
$$
\mathrm{Gr}(2,B) \subset \mathbb{P}(\wedge^2B).
$$


Comparing 2 population proportions using significance tests

Question:
In a sample of 200 male drivers, 130 said they used seat belts. In a
  sample of 300 female drivers, 163 said they used seat belts. Test the
  claim that men are more safety conscious than women, at a significance
  level 0.01. What will be your conclusion if you test whether there is
  a gender difference for seat belt use at the same significance level?

So I've performed significance test and get z=4.32 => P-value<0.000317<0.01. Hence I can conclude that men are more safety conscious than women. I just don't understand the last question, say, 'What will be your conclusion if you test whether there is a gender difference for seat belt use at the same significance level?'. Any hint is appreciated, thanks!
Comment: This looks like homework.  I've tagged it as such so you can get appropriate answers.  If it's not then you can remove the tag.
Answer: The second part of the question is asking about any difference, commonly called a 2-tailed test.  It's asking what the answer would be if the value for men could be higher or lower than women. The first question is more specific and a one-tailed test, that men are more safety conscious.


Cache architecture in gem5 simulator

Question: How can I modify the cache architecture in the gem5 simulator? I want to be able to configure the cache so that it is used differently (either set-associative or fully associative) depending on a certain execution mode?
I am new to gem5 and still finding my way. Where can I change the modelling of the cache architecture and how it is used in the source files?
Thanks!
Comment: Welcome to SO, G. I have the following advice: try to keep the question as precise as possible, specially in the title. E.g., a good one would be "How to change between set-associative and fully associative caches in gem5?". Since a more general "cache architecture" question would likely not be answerable. Also send an email to the gem5 mailing list just in case. I don't know the answer to this one in particular.
Answer: You can change the modelling of the cache architecture by changing the Tags. The Tags are instantiated in src/mem/cache/cache.py.
This modification can be done either by:

Creating a config file. It is the correct approach and will give you more control over the simulation (check Jason's tutorial http://learning.gem5.org/book/part1/simple_config.html to learn how to create a config file).
Quick and dirty approach by modifying the default value of Tags between BaseSetAssoc and FullyAssoc within the cache.py file. This, however, will not work towards your final goal of changing the model according to the execution mode.

Cache architecture in gem5 simulator


Symfony2 RuntimeException: The autoloader expected class "Doctrine\DBAL\Driver\PDOMySql\Driver" to be defined

Question: I've deployed my site to my development server using Capifony and although it has been deployed correctly when I go the the site i.e dev.xyz.co.uk/app_dev.php I get the following error:

RuntimeException: The autoloader expected class "Doctrine\DBAL\Driver\PDOMySql\Driver" to be defined in file "/var/www/vhosts/dev.xyz.co.uk/shared/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOMySql/Driver.php". The file was found but the class was not in it, the class name or namespace probably has a typo.

Any idea what's causing it? It works fine when deploying to production.
Comment: Just guessing: Have you cleared your cache?
Answer: You may check the first line of the file "Driver.php" just to read <?php.
If you just read <? and tried to deploy on differents servers for dev and prod, just check if they have the same value for "short_open_tag" (in php.ini).
If it's "on" on your prod's server and "off" on your dev's server you may have this error.
Answer: It can be problem of accelerator (xcache, eaccelerator, apc). Restart PHP it can help.


problema ao logar em formulário com php

Question: desenvolvi um sistema de login em php nesse site sem banco de dados com uma senha fixa localhost tudo funciona normalmente mais quando upei os arquivos para o servidor e tento acessar ele chega a carregar a página porem retorna para o inicio e na url do navegador aparece que não é seguro tem como consertar isso segue as imagens e o código fonte.
na imagem acima aparece ao lado da URL não é seguro e isso não me deixa logar na pagina main.php lembrando que localhost funciona normalmente
Login:
<form action="login.php" method="post" name="login" id="login" class="login form-login" onsubmit="return validaCampo(); return false;">

Painel do cliente

Para ter acesso a todo o conteúdo do Fábio Rabin basta acessar o painel com o
                            usuário e senha enviados para o seu email.

                                <input type="text" name="user" id="user" class="form-control user" placeholder="Digite seu nome" />

                                <input type="password" name="pass" id="pass" class="form-control user" placeholder="Digite sua senha" />

                            <input type="submit" value="Entrar" class="btn btn-primary send">

            </form>

login.php:
<?php
error_reporting(0);
ini_set("display_errors", 0);
?>
<?php
$user = $_POST['user'];
$pass = $_POST['pass'];
include("bd.php");
if ($valida[$user] == $pass) {
    setcookie("logado", "1");
    echo "";
} else {
   /* echo "Usuário ou senha incorretos!";
    echo "
";
    echo "";
    echo "Clique aqui para tentar novamente.";
    echo "";*/
}
?>

Poxa vida!
 Seu usuário ou senha estão incorretos!
 - Clique aqui e tente novamente -

main.php:
    <?php
if (IsSet($_COOKIE["logado"])) {
} else {
        echo '<meta http-equiv="refresh" content="0;url=login">';
    exit;

}
?>

            X

E ai cara seja bem-vindo!
Aqui você vai encontrar todo o conteúdo necessário sobre o Fábio Rabin, basta
                    clicar no botão abaixo e efetuar o download.

                Baixar conteúdo

logout.php:
<?php
setcookie("logado", "");
?>

Você desconectou!

                Aguarde, você será redirecionado
para página inicial.

Se demorar muito clique aqui

bd.php(aqui é aonde eu coloco usuário e a senha fixa)
<?php
$valida[fabiorabin] = "download123";
?>

Comment: Perece como "não seguro" porque não tem HTTPS/TLS, isto é o que o Chrome analisa apenas, qualquer página de login sem HTTPS é inseguro, pela lógica do Chrome. *Mas, ironicamente o sistema também está bem inseguro, desde comparações com `==`, utilizando apenas um cookie para validar (qualquer um pode dar um `document.cookie = "logado=1";`) e armazenamento de senhas em texto plano.*
Answer: O "Não seguro" significa que o seu site não tem protocolo de segurança SSL. Você pode conseguir esse protocolo em alguns sites de hospedagem pagos e gratuitos, como foi sugerido pelo @Inkeliz. Mas não é por isso que você não consegue se logar. O que acontece é que você está liberando o ambiente (main.php) através de cookies. E se no seu navegador estiver desabilidada essa permissão, você não consegue inseri-lo, para fazer a verificação posterior.
Eu consegui me logar tranquilamente.

Minha sugestão. Trabalhe com $_SESSION do php que você não terá esse problema.
Comment: Nota: é possível ter de graça utilizando [Let's Encrypt](https://letsencrypt.org/). Inclusive utilizando o [Caddy](https://caddyserver.com/), ao invés de NGinx/Apache, ele já utiliza o Let's Encrypt.
Comment: @Inkeliz, boa. Vou editar.
Answer: O Google anunciou em seu blog com o seguinte artigo "Movendo-se para uma Web mais Segura", no qual explicou que em Janeiro 2017 houve uma atualização no Google Chrome 56, que marca páginas HTTP que coletam senhas ou cartões de crédito como NÃO SEGURO na barra de url e com cadeado de segurança vermelho.
Até então, apenas as páginas em HTTP que solicitam informações como senhas e cartões de crédito apareciam como páginas não segura. Porém, o plano do Google Chrome é a longo prazo, que pretende marcar todos os sites HTTP como não seguro ou não protegidos.
Veja o que a Google tem a dizer sobre o assunto:  HTTPS nos principais sites
Para desenvolvedores e webmasters:
Há um site de teste que possui duas páginas, uma HTTP  http://www.httpvshttps.com/  e outra HTTPS   https://www.httpvshttps.com/ , e alternando entre elas é mostrado na sessão atual do navegador a diferença no carregamento de ambas.
Tendo em vista o acima exposto e se você não tiver um site que seja seguro e não ranqueado no mecanismo de busca do Google, corra para contratar um selo de segurança SSL e faça a instalação HTTPS em seu site. :)

problema ao logar em formulário com php


How to interpret time-varying AUC for Survival Analysis?

Question: I have trained some models for survival forecast (only interested in ranking of observations). I obtained C-index values as well as dynamic AUC values for the three trained models (CPH, AFT -weibull- and a Random Survival Forest) implemented in scikit-survival.
I then calculated out-of-sample (test set) AUC for all three models. This is the output plot:

COX PH.
 AFT.
 RSF.
So the two questions are:

How should I interpret this upward trend in the model's predictive performance?

The AUC for the CPH and AFT looks almost the same. What situation could potentially explain this matching predictive performance for the two models?.

Thanks!

Edit for clarification:
The cumulative/dynamic AUC is defined by Lambert and Chevret as:
\begin{equation}
    AUC^{CD} (t)  = \dfrac{\sum_{i=1}^{n} \sum_{j=1}^{n} I(X_j > t) \, I(X_i \leq t) \, I(\hat{\lambda}_j \leq \hat{\lambda}_i) \, w_{i}}{(\sum_{i=1}^{n} I(X_i > t)) (\sum_{i=1}^{n} I(X_i \leq t) \, w_{i})} \nonumber
\end{equation}
It is a measure of how well a model can distinguish subjects who fail by a given time $t_r \leq t$ from those that fail in $t_r > t$.
Comment: For those of us not familiar with "Ishwaran's formulation" could you please explain what is plotted along the horizontal axis of these plots?
Comment: Hi, EdM. The phrase was wrongly formulated, thanks for pointing that out. My reference was to Ishwaran´s work on RSF (which is the bases for the models implemented in python's Scikit Surv an R's randomforestSRC libraries.
The X axis is the time.
Answer: The Weibull model is unique in that it satisfies both the accelerated failure time assumption (multiplicative survival curves) as well as the proportional hazards assumption (multiplicative hazard curves).  This should explain why the difference in performance between these models is essentially indiscernible.  Can you elaborate on the x-axis in each of your plots?  Is this the number of subjects or events in the model?  If so then it should not be surprising that a model based on more events fits better than a model based on fewer events.  If this is not the correct interpretation of the x-axis let me know.
Comment: Thanks! Regarding the X-axis, that's the time.
Comment: Does this mean that for an x-axis value of, say, 25 you are using all of the events up to time 25 to fit a model and investigate the out-of-sample fit?
Comment: The plots show the value of dynamic AUC for each time period. This AUC value is a ratio of correctly ordered pairs, given the output of the model (risk, CHF or S) and the real (observed) times. I added the formula used by the Python library I'm using and a link to the original paper.


Get user object within module

Question: I need the $user object within a module am creating. But am not able to get it. I have created a module that extends user object hold more data. Its working fine. I am also
able to use this values in theme files. But am not able to get it in any function within
a module.
The standard value $user->name; or my custom value $user->data['privacy']; nothing is available in module.
I tried using this
global $user;
$user = $user->name;

What is the mistake here? Is it that global is not the right way to get the user object?
Answer: You're currently referencing the global $user object, then in the very next line you're overwriting it with a string (the username). So your global $user object is destroyed, and you will probably be logged out of the site (as well as the code not working as expected).
You're referencing the global user object in the correct way, but by default it isn't fully loaded (i.e. with fields attached, etc). To get the extra data you should use the user_load() function like so:
global $user;

// Get the fully loaded user object
$account = user_load($user->uid);

// Get the username. Make sure you don't override the global $user object here!
$username = $account->user.

// Get a field value.
$field_items = field_get_items('user', $account, 'field_foo');

Comment: We used global because we were not able to get $user in module. How am i suppose to get user_id now? I am able to get all these in templates.
Comment: I'm really not sure what you mean, the global `$user` object is available everywhere...it's a global. From _anywhere_ in your code use: `global $user; $uid = $user->uid;`
Answer: I had the same problem, and I fixed it with the following code.
 module_load_include('pages.inc', 'user', 'user');
 global $user;

Comment: The `$user` global isn't declared in user.pages.inc, loading that file won't make any difference

Get user object within module


How to create footer links in drupal 6

Question: I am doing a site in Drupal 6, and I need to create footer links which needs to be displayed in the footer.
How can I create it?
Answer: Create secondary links in admin/menus/secondary links.
Once completed, go to blocks/list/, look for your secondary links, and place them in the footer block region.

How to create footer links in drupal 6


Make a dynamodb attribute as partition key of one index and as sort key of another index

Question: Is that possible to make an attribute as partition key of one index and as sort key of another index?
For example, I have a table named Events with attributes user, status, created_at.
Can I create both of below GSIs
GSI user_status [user as partition, status as sort]
GSI status_created_at [status as partition, created_at as sort]
Comment: What happens if you try it?
Answer: That is pretty much the idea with GSIs. In short: the answer is yes.
Be cautious, though, of creating GSIs where you have massive cardinality on a small set of partition keys, such as the second GSI example where you partition on status. Presumably there are only a handful of status values in total but for each status, the cardinality (number of items with the same status) might be very large. The reason this can be a problem is that GSIs, like tables, are subject to read and write capacity limits which apply per partition. As your table scales, having low distribution accross partitions with very high cardinality could result in poor performance.


Add new dependency to a Windows Service that already has dependencies

Question: I want to add via Batch script a new service-dependency to an existing service with old dependencies, without deleting these dependencies.
I know the command sc config ServiceA depend= ServiceB/ServiceC/ServiceD can add multiple dependencies, but I don't know how to use it to - for example - add ServiceD dependency to a service that depends on ServiceB and ServiceC, with the same result and without mentioning the old dependencies (since I don't know them).
What is the way to do that? And - how to revert the change (also via Batch)?
I have no much experience with Batch, by the way.
Answer: Find out the existing dependencies, add your new one and write the whole thing back, say you have a service called w3svc, you can use:
sc.exe  qc  w3svc

or in PowerShell:
(get-service w3svc | Select ServicesDependedOn).ServicesDependedOn

where you can loop through these and build a new sc.exe command to execute.
Example:
 $serviceName = "w3svc"
 $cmd = "config $serviceName depend= "
 (gsv $serviceName | Select ServicesDependedOn).ServicesDependedOn | % {$cmd += $_.Name + "/"}
 $cmd += "myMasterService"
 invoke-expression "sc.exe $cmd"

We are building a command string from the existing services and add your own.
To remove yours do the same thing, but in the loop exclude your service.
 $serviceName = "w3svc"
 $cmd = "config $serviceName depend= "
 (gsv $serviceName | Select ServicesDependedOn).ServicesDependedOn | % {
      if ($_.Name -ne "myMasterService")
      {
           $cmd += $_.Name + "/"
      }
 }
 # remove the last slash
 $cmd = $cmd -replace "/$", ""
 invoke-expression "sc.exe $cmd"

I haven't tested the actual sc.exe commands, but I assume you know what you are doing.
Comment: Sorry, it's 2015, not the 1980s. I haven't done batch files in a long time and doing this in a batch would be much more difficult anyway.
Comment: Thanks! Can you write the Batch commands to run if I don't want to use PowerShell? It will really really help!


Which pages affect text area CSS?

Question: I have a text area with CKEditor. The default font in this text area and my theme is 20 pixels and I cannot change its size with CSS, but if I change theme and use Garland, the font change to the normal size.
If I copy Garland styles and page.tpl.php in my theme, the text area is still using a 20 pixels font. Why?
Answer: CKEditor set its own CSS classes for text areas, but that would not explain why copying the CSS files from a theme to another doesn't change the visualized styles.
The problem here is that simply changing the files used by a theme doesn't change the used styles; you need to let Drupal know the theme has been changed, and this can be done in two ways:

you select a different theme as default one, disable the theme you modified, re-enable it, and select it again as default theme
you force Drupal to refresh the cache it is using, or you empty the cache tables

In the first case, you submit the theme selection form after each operations.
Comment: thank u for edit my question :) and your response.  i tried two resolution but it didnt work.
Comment: thank u. problem was with cache. and this code help me too .cke_show_borders {
background:white;
font-size:12px;
}

Which pages affect text area CSS?


Ubuntu: install only a signed verified deb package

Question: What the final goal is:
Install a given package securely for a series of servers.
We have servers running on different cloud data centers.
We install our app on them as deb file.
Currently we upload the updates as deb files via an ansible script.
This is slow as the "master" node needs to update all the machines.
We think it would be nicer if we could just issue sudo apt update <package> for every node.
But what about security?
The repo server would need to be on the internet.
Thus, we would need to make sure that the package installs securely.
deb files can be signed, but afaik dpkg-verify only verifies that the signature is correct. Thus a malicious but correctly signed package would pass the verify check.
So could we

Install from an https repo server
Install only signed packages signed with a specific key only (for our app deb only)

Another approach is acceptable as long as security is not compromised.
Answer: If you use apt install or the ansible apt module to install packages, then the repo metadata must be signed by a key known to your system, such as the Ubuntu distribution signing keys, or any keys you explicitly add with the apt_key ansible module. Anything signed by an unknown key, or not signed, would be rejected.
So you can just create an apt repository to hold your packages, sign its Release file with your own GPG key, and distribute that public key to your servers.
Comment: @transient_loop Creating and updating the repo can be automated easily enough, either via ansible or via whatever is deploying your software builds. But yes, if you put something in the repo then all you have to do is apt install (or upgrade if you're upgrading it).
Comment: This sounds like what I want, apart from being pretty simple. Are you saying hat, because the access to update the servers is secured via the ansible script and the ssh key used to connect, there is no actual need to do anything else other than sign the release and run `apt install`?
Comment: paranoid follow up question though (which had prompted me to ask the question in the first place): Assume the worst case that someone hacked the repo server - all servers would then silently install a compromised version, if the hacker signed the malicious package correctly with an own key. So would it be possible that the package (and only that package) would be installed from a specific signature only?
Comment: @transient_loop How would the hacker get a copy of your private key? You would not keep that on the repo server.
Comment: of course not...


How to show $\operatorname{GL}_2 (\mathbb Z_2)\cong D_3$

Question: I want to show that $\operatorname{GL}_2 (\mathbb Z_2)\cong D_3$ while $\operatorname{GL}_2(\mathbb Z_2)$ is the group of matrices $2\times 2$ above $\mathbb Z_2$.
I tried to show that maybe every $A\in \operatorname{GL}_2(\mathbb Z_2) $ is a rotation or reflection, but I failed to do that.
Comment: One silly way of doing it would be to find the order of $\operatorname{GL}_2(\mathbb{Z}_2)$, then to prove that it is not abelian. Can you see why this works?
Comment: @sha Exactly! I've given a (hopefully) more helpful answer now though.
Comment: You mean $GL_2(\mathbb{Z}_2)$ above?
Comment: I do. I've edited it.
Comment: Isomorphism does not mean equality. You can't show the elements of this matrix group are rotations or reflections. As an analogy, even though the exponential function is an isomorphism from $\mathbf R$ to $\mathbf R_{>0}$, it does not mean you will find elements of the second group that are negative just because some elements of the first group are negative. An isomorphism means the underlying groups have the same structure, but not that every *interpretation* of the meaning of an element in one group will carry over to an element of the second group.
Comment: @user1729 well both are of order 6 and non abelian. but i cant see it.. hint?  is there only one group of that sort up to isomorphism?
Answer: The group $\operatorname{GL}_2(\mathbb{Z})$ acts on the space $\mathbb{Z}_2\times\mathbb{Z}_2$, and it fixes the origin. The remaining 3 points are permuted, and every permutation is realised (prove it!). This means that $\operatorname{GL}_2(\mathbb{Z})$ has $S_3$ as a homomorphic image, but as both groups have order 6 we have that $\operatorname{GL}_2(\mathbb{Z})\cong S_3$.
Finally, label the points of your triangle with $\{1, 2, 3\}$ and use a similar argument to see that $D_3\cong S_3$. Hence, $\operatorname{GL}_2(\mathbb{Z})\cong D_3$.


Confidence % on a single point estimate

Question: I am working on a business case problem for my company (CPG) and was asked to come up with a way to predict Customer Order Fill Rate (CFR) based on the amount of inventory we hold.
Now I have come up with a formula to estimate CFR based on the cases of inventory we hold using regression, however I was asked about the probability that my estimated CFR will be correct.
So if my regression formula suggests in the future that having 100 cases of product XYZ will result in an estimated CFR of 98%, the business team asked me what is probability of actually achieving that CFR.
But I was wondering if there is a way to give such a probability on a single point estimate? I mean I am aware that I could use a prediction interval (I guess is more accurate for this case than confidence interval) to say the I am 95% confident that the future point estimate will be within a range. But I wanted to confirm if there is any such thing (a confidence %) for a single point estimate.
EDIT (Clarification):
So my observed data set for building the regression is  something like this:

My inventory data set is from 0-100 cases (not unique values, I can have duplicate inventory values with different CFR).
For regression I plot from 0-100 cases (taking the average CFR for each point) and build a curve for it. Here's is the regression formula I determined:

With this formula, the input is the inventory (number of cases) and the output is the projected CFR.
I want to know how I can determine (or if its even possible) to get a probability value of in the future actually achieving the CFR (point estimate).
My regression formula has an x (inventory (cases)) and y (CFR): the formula determines if x = 15 then y = 93.4%.
But what is the probability that my estimation of 93.4% CFR from x = 15 will be correct? Is there a way to give confidence % for the point estimate of 93.4% CFR?
Thank you.
Comment: It is assumed to be normally distributed.
Comment: What do you mean by "single point estimate"? Is it that you observed only a single value and treat it as your estimate?
Comment: The information is not enough; description of model is unclear.
Comment: Hi, I edited the question to try and make it more clear. Sorry if I seem to not be completely transparent with the data as it is confidential.
Comment: What is assumed distribution of y?
Answer: If these are means, the chance of doing better than them is going to be around 50%, on the proviso that the median is close to the mean. Probably you have a bit of negative skew, so the median might be a bit above the mean, giving you a bit better than 50%.
If you want more, it can be done but what you need is an explicit model of the order filling process.
The simplest way to do this is to let demand be random, and fill all orders where there is stock, and have excess demand lead to unfilled orders.
Your likely variables (some known and others not) will be the number of product lines, the distribution of the mean demand for each product, and the time variances of the individual product demands. In order to simplify the model, I would assume every product has an equal coefficient of variation for demand.
Now you can use Monte Carlo methods to generate estimated CFR from your model. Then you can adjust the parameters to match the real world CFR data. When the model is matching your data, you can then read off from it the variance of the CFR for each inventory level.
You will need to use nonlinear optimisation to do this - but in this case be sure to generate all your random numbers at the start - if you take a new set of random numbers each time a parameter changes, the GRG (generalised reduced gradient) optimisation problem  will never converge.
You can do all of this in Excel if you have to - using the 'solver' add in to do the GRG.
Comment: Hi, thank you for the answer. However I do not think I understand exactly what you said about the probability, because if the regression formula is giving an output I just was wondering if statistically we can get a probability of how accurate it will be. Are you suggesting that in reality the regression output will be correct 50% of the time? That seems strange.
Comment: I assumed you want SE of CFR, so you can say the CRF for I= 20 is 95 %, AND that there is a x% chance of achieving a CFR of larger than eg. 90%.

Now the probability of  CRF>95% (doing better than the mean) is going to be close to 50%, on the proviso that the mean of the CRF (for inventory=20) is close to the median.

If you have the data for each CFR event, you can directly estimate the SE of the CFR and the SE of the mean of the CFR by fitting a nonlinear model for CFR as a function of inventory.
Comment: Now if you want instead the SE of the means, but don't have the raw data, but know the number of observations is large, without any simulation you can say that the SE will be small. Indeed for the practical problem you are dealing with it might well be quite fine to assume the SE is zero.
Comment: Ah ok, I now understand from your second comment. Thank you.

Confidence % on a single point estimate


serialize default attributes using XmlSerializer

Question: Based on this post I tried to create a child class of XmlTextWriter that writes all attribute values, even the default ones. But I can't make it work. Can someone help?
Here is the class I want to serialize:
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlType(AnonymousType = true)]
[System.Xml.Serialization.XmlRoot(Namespace = "", IsNullable = false)]
public class Foo
{
    public string content { get; set; }

    [System.Xml.Serialization.XmlAttribute()]
    [System.ComponentModel.DefaultValue(true)]
    public bool isActive { get; set; }
}

Here is the code where I create an instance of Foo and serialize it to a string:
XmlSerializerNamespaces ns = new XmlSerializerNamespaces(
    new XmlQualifiedName[] { new XmlQualifiedName("", "") });
    // I need that for not writing a namespace during serialization
XmlSerializer serializer = new XmlSerializer(typeof(Foo));
Foo f = new Foo();
f.content = "hello";
f.isActive = false;

string fStr;
using (MemoryStream ms = new MemoryStream())
using (XmlWriter wr = new XmlTextWriter(ms, new UTF8Encoding(false)))
{
    serializer.Serialize(wr, f, ns);
    ms.Position = 0;
    using (StreamReader sr = new StreamReader(ms))
    {
        fStr = sr.ReadToEnd();
    }
}

This code will give me the following content for fStr:
<?xml version="1.0" encoding="utf-8"?><Foo><content>hello</content></Foo>

But I want to get the default value explicitly written as well, i.e.
<?xml version="1.0" encoding="utf-8"?><Foo isActive="true"><content>hello</content></Foo>

So I created a child class of XmlTextWriter and replaced the new XmlTextWriter(...) from above with new DefaultValueXmlTextWriter(...). Here is my DefaultValueXmlTextWriter class:
public class DefaultValueXmlTextWriter : XmlTextWriter
{

    public DefaultValueXmlTextWriter(Stream s, Encoding e) : base(s, e) { }
    public DefaultValueXmlTextWriter(string s, Encoding e) : base(s, e) { }
    public DefaultValueXmlTextWriter(TextWriter t) : base(t) { }

    public override void WriteAttributes(XmlReader reader, bool defattr)
    {
        base.WriteAttributes(reader, true);
    }
}

The mousover for base.WriteAttributes says:

When overridden in a derived class, writes out all the attributes
  found at the current position in the XmlReader.

So I assumed that always choosing true for defattr would do the trick, but it does not change anything in the output. I tried false as well, doesn't work either.
Any ideas?
Comment: `XmlSerializer` decides what to serialize, not `XmlWriter`.  `XmlWriter` and its deprecated subclass `XmlTextWriter` have no understanding of what is being serialized.  They write to XML whatever is requested.  To force `XmlSerializer` to serialize default-value properties, I found [Force XML serialization of XmlDefaultValue values](https://stackoverflow.com/q/28054335/3744182) and [How to tell XmlSerializer to serialize properties with `[DefautValue(…)]` always?](https://stackoverflow.com/q/15357589/3744182).    Do either of those adequately answer your question?
Comment: And, in any event, [`XmlWriter.WriteAttributes Method (XmlReader, Boolean)`](https://msdn.microsoft.com/en-us/library/system.xml.xmlwriter.writeattributes(v=vs.110).aspx) is for copying attributes from an `XmlReader` to an `XmlWriter` (e.g. it's used internally by [`XmlWriter.WriteNode Method (XmlReader, Boolean)`](https://msdn.microsoft.com/en-us/library/1wd6aw1b(v=vs.110).aspx)) so it doesn't come into play during serialization.
Answer: In your example you are mixing ComponentModel and Serialization annotations and they don't appear to work as expected. I ran through every permutation settings I could think of and the results I got were unexpected.
var foo = new Foo();
foo.content = "hello";
//foo.isActive is left undefined
Console.WriteLine($"foo.isActive is left undefined");
Console.WriteLine($"foo.isActive = {foo.isActive}");
XmlSerializer serializer = new XmlSerializer(typeof(Foo));
string file = "File.xml";
using (StreamWriter sw = new StreamWriter(file))
{
    serializer.Serialize(sw,foo);
}
bool attExists = File.ReadAllText(file).Contains("isActive");
Console.WriteLine($"It is {attExists} that isActive exists in {file}");
using (StreamReader sr = new StreamReader(file))
{
    Foo test = (Foo)serializer.Deserialize(sr);
    Console.WriteLine(test.isActive);
}

The results where the 3rd line of the code is changed and reflected in the output of the first line the test
foo.isActive is left undefined
foo.isActive = False
It is True that isActive exists in File.xml
False

foo.isActive = true;
foo.isActive = True
It is False that isActive exists in File.xml
False

foo.isActive = false;
foo.isActive = False
It is True that isActive exists in File.xml
False

If you are hydrating your results back into a different class your results here are not going to be so good. It would appear that all the annotation does is tell the serializer not output the value if it is the default value.
Personally, I would accomplish this by defaulting the value in a public constructor and ignoring the annotation all together. The intent is more explicit and re-engineering the Xmlserializer is way, way overkill and may come with other unintended consequences.
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlType(AnonymousType = true)]
[System.Xml.Serialization.XmlRoot(Namespace = "", IsNullable = false)]
public class Foo
{
    public string content { get; set; }
    [System.Xml.Serialization.XmlAttribute()]
    public bool isActive { get; set; }
    public Foo()
    {
        isActive = true;
    }
}

Running the same test results in much more predictable results.
foo.isActive is left undefined;
foo.isActive = True
It is True that isActive exists in File.xml
True

foo.isActive = true;
foo.isActive = True
It is True that isActive exists in File.xml
True

foo.isActive = false;
foo.isActive = False
It is True that isActive exists in File.xml
False

Good luck!


Where did the term backbeat come from?

Question: In most modern music in 4/4 beats 2 and 4 are where the snare hits are and are usually referred to as the backbeat. Normally in 4/4 the 2 and 4 beat would not be accented, but the snare hits do just that. Where did this idea originate and why is it so important to accent 2 and 4?
Comment: Wiki has some info on [backbeat](http://en.wikipedia.org/wiki/Beat_%28music%29#Backbeat) but another related term is for example, *four on the floor* which is also another working musician lingo. They mostly come from musician-to-musician slang.
Comment: To quote Chuck Berry, the importance of the back beat to rock and roll music is that you can't lose it.  :)
Comment: poss. duplication of 'Why is the backbeat called the rockbeat'.(Oct.'13)
Answer: Where did this idea originate? West Africa, then transplanted to the New World. It is a defining characteristic of African-American music, and all the styles of music that grew out of and were influenced by African-American music. It then spread to the rest of the world via the 20th-century music of the USA, Cuba, Brazil, Jamaica, and other nations with African descendants in the population who influenced the musical culture.
Comment: What I heard explained was the term became more widespread as the jazz age transitioned into rock and roll.  Drummers went from the swing style "ding-ding-a-ding" (on the cymbal) to "Boom [sha] Wack Boom [sha] Wack" (bass drum with hi-hat then snare) pattern we're familiar with today.
Comment: It might be oversimplification. Accenting weak parts of the bar can be found in traditional Irish music e.g. reels, and in turns Irish music influenced many other styles. Is it African or African-American music influence? On the other hand I would also think that African music influence is much broader than just accenting 2 and 4...
Answer: Several places I've seen suggest that the "backbeat (accenting beats 2 and 4)  originated in the strumming patterns in early country music (then called "hillbilly" to market to "Whites" as opposed to "race" which was marketed to "Blacks" in the 1920s.) Of course, any dance-like 4-beat music has a bit of a metric accent on beats 1 and 3, and syncopation has been around for centuries.
There was (and still is) a lot of cross-influences between genres of music. (Genres are often just marketing.)

Where did the term backbeat come from?


SQL Comparing columns and calculating the difference

Question: I'm using Oracle 11gR2
I have a table for example:
ProductName   |   Volume   |   Date
-------------------------------------------
ProdA         |   1000     |   11-Oct-2013
ProdA         |   2000     |   16-Oct-2013
ProdB         |   500      |   12-Oct-2013

ProdA         |   200      |   11-Nov-2013
ProdB         |   100      |   16-Nov-2013
ProdB         |   300      |   12-Nov-2013

What i want to do is total the volume for each product and then compare the volume across 2 months and have a calculated field working out the difference, so i would end up with:
ProductName   |   VolumeCurrentMonth   |   VolumePrevMonth   |   Difference
-------------------------------------------
ProdA         |   200                  |   3000              |    -2800
ProdB         |   400                  |   500               |    -100

My code is no where near the fulfilling the requirement but i'll post it anyway:
Select ProductName, sum(Volume), to_char(Date, 'Month') as Current_Month, to_char(run_date, 'Month') as PY_Month
from Sales
where Date is not null
group by ProductName, Date;

Comment: Yeah that returned what i needed pretty much, thanks!
Answer: I'd take a two-step appoarch - first, an inner query to group by products and months. Then, the outer query can handle the comparing with the previous month using the analytic LAG function:
SELECT productName, volume_sum AS curr_month_sum,
       LAG(volume_sum) OVER (PARTITION BY productName ORDER BY month)
FROM   (SELECT    productName, trunc(theDate, 'MM-YYYY') AS month, SUM(volume) as volume_sum
        FROM      some_table
        GROUP BY  productName, trunc(theDate, 'MM-YYYY')
       )


How do I create a Parameter class(es) to be passed to custom report classes?

Question: I am working with a custom report engine that uses XML and XSL to output the report data to the browser. Each report can have multiple parameters of different value types (integers, strings, dates).
Each report has its own class (inheriting from a base report class) and XSLT that gets the data from the DB based on the parameters, generates the xml, and styles it with the XSLT. However currently, the parameters are listed individually in each class. I think it is more efficient to create a Parameter class, have a generic list of all the parameters, add the parameters to the list when the report data is requested, then the base class can loop through the list of parameters and output the appropriate XML.
Here is what the code looks like now:
public class Report
{
    //Common functions used by all reports
}

public class OrderDetailReport : Report
{
    public long? Parameter1 { get; set; }
    public long? Parameter2 { get; set; }

    public XElement CreateXML()
    {
        var xml = new XElement();

        xml.Add(GetXMLParameters());

        //Get Data and generate XML

        return xml;
    }

    public XElement GetXMLParameters()
    {
        var parameters = new XElement("Parameters",
                            new XElement("Parameter",
                                    new XAttribute("Name", "Parameter1"),
                                    new XAttribute("Value", Parameter1)),
                            new XElement("Parameter",
                                    new XAttribute("Name", "Parameter2"),
                                    new Attribute("Value", Parameter2)));
        return parameters;
    }
}

What should the Parameter class look like so that it can handle all different value types and be able to format the value that is displayed on the screen?
EDIT:
I want to be able to move the GetXMLParameters() function to the base class and have a list something like List<Parameter> in the base that GetXMLParameters() will loop through and create the XML.
This will avoid having GetXMLParameters() in each CustomReport class.
Thanks. I hope this was clear.
Oran
Answer: take a look at serialization. There are many xml serializers in .net (wcf, xml etc) that will convert your objects for you. You can also shape the xml output by using attributes on the members you wish to serialise.
I offer up this solution because as long as your class can be serialized it will always work and allow for future growth.
AS REQUESTED:
public static class SerialiserHelper
{
        public static string Serialize(this object @object)
        {
            try
            {

               DataContractSerializer serializer = new DataContractSerializer(@object.GetType());

                using (MemoryStream memoryStream = new MemoryStream())
                {

                    serializer.WriteObject(memoryStream, @object);

                    var encoder = new System.Text.UTF8Encoding(false);

                    return encoder.GetString(memoryStream.GetBuffer(), 0, Convert.ToInt32(memoryStream.Length));
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        public static T DeSerialize<T>(this string serializedObject)
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(T));

            var encoder = new System.Text.UTF8Encoding(false);

            using (var memoryStream = new MemoryStream(encoder.GetBytes(serializedObject)))
            {
                return (T)serializer.ReadObject(memoryStream);
            }
        }

Comment: I don't understand how this will solve my problem. I clarified what I am trying to do in the question.
Comment: Avoid inheritance. Go for composition instead. The code will be less brittle. When dealing with object transformations which by the look of your code it is, use the visitor pattern.
Comment: look at the problem as if your passing in data into a function and getting a result out. If you think that way, you start seeing the bigger picture of what actually is happening. an Object goes in, XML comes out. If you use the serialization stuff, then all the problems with class hierarchy and inheritance go away to some extent, because your using the generic code that the kind people at Microsoft have designed for you.
Comment: I think I see what you are saying. Can you give me a code example of how it would look?
Comment: Hope the code helps, its just an Extension method, that is for all objects, BEWARE THERE BE MONSTERS HERE. If your object can not be serialized, or has not been designed to be serialized, then this extention will throw exceptions. Take a look at the DataContractSerializer for more info. This is just one of the XML serializers. I use it because it gives me more control over the output XML. http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx
Answer: Look about reflection :)
http://msdn.microsoft.com/fr-fr/library/system.reflection.aspx
Comment: Can you explain how that would help?
Comment: It allow you to browse easily object attributes


Model based on many variables

Question: Let's say I have a matrix of values for many different variables Y1..Y1000 at X=1,2,3..,10. Some of these variables are directly correlated with X, some follow different shapes (e.g. a normal distribution) and some are just random. I want to build a model to predict X based on given values of Y1..Y1000.
What would be the correct approach for this? I assume a simple linear regression would not be feasible because of the number of variables and the fact that not all variables are linearly dependent on X.
Comment: I'm having trouble following this. First, do you have 100 or 1000 variables labeled "Y"? Are you using "Y" for the predictor variables & "X" for the response variable? (That's OK, but it's the opposite of how it's usually done.) Is the main issue here that you have a multivariate situation (ie, multiple response variables)? Is this supposed to be a $p>>n$ problem? Re different shapes, note that the distribution of predictors is irrelevant, but if the issue is w/ response variables, can you say more about what the distributions are? (Eg, I think a random variable can be normally distributed.)
Comment: I'm sorry that I wasn't clear enough, my stats vocabulary is a bit rusty... The 100 was a typo, that should have been 1000 in both cases.

So just to reiterate, I have a set of data that tells me how Y1..Y1000 behave for different known values of X and I want to build a model "X ~ Y1, Y2, Y3, ...", to predict X based on values of Y. So I think X would be the dependent/response variable and Y the independent/predictor variable. Sorry if I mislabeled them.
Comment: So in general I think the problem is that I only have around 10 data points per variable but a lot of variables.
Answer: I would estimate a PCA on the Ys and regress X against the factors that explain the most significant amount of the variation of each of the Ys. Based on your comment, however, a classical PCA may be problematic since you have significantly more variables than observations. Asymptotic PCA a la Connor and Korajczyk (1986) might be a better choice. There are other variations on PCA that may be appropriate (like probabilistic PCA).
Comment: Because the principal components of the Y's have *nothing* to do with *X*, why does this help?  For an explicit example of the difficulty, please see [this comment](http://stats.stackexchange.com/questions/32471/how-can-you-handle-unstable-beta-estimates-in-linear-regression-with-high-mul/32577#comment63983_32577).
Comment: I have to admit I am not really sure how to go from a PCA on Y to a model. Is there a good tutorial somewhere out there that would explain this process step by step?

Model based on many variables


Import data using ECK and feeds module

Question: Is it possible to import data from CSV file and insert all in two different entities
for example I have created two different entities, cadidates and exams entities, once I import data to exam entity i would like to make candidat entity updated also referencing to some field, i have tried many solution possible but in vain
Answer: Why not make two importers that you run on the same CSV dataset? Run it first on the first imported setup and then again on the next. Each imported can be configured to create the needed content type.

Import data using ECK and feeds module


rational points and closed subvariety

Question: Please help me to solve this question or introduce references that help me.
Let $k$ is an algebraically closed field of characteristic zero. Assume that $Γ$ is a finite group, acting on an affine scheme $X = \mathrm{Spec}(A)$ by automorphisms (Where $A$ is commutative associative $k$-algebra). Let $X_{rat}$ denote the set of $k$-rational points of $X$ and $ \mathcal{O}(X)$ be the structure sheaf of $X$.
1) Given a finite subset $ \mathbf{x} ⊆ X_{rat}$ with this property that $y \notin Γ · x$ for distinct $x, y \in \mathbf{x}$. Let $Z = \cup_{x \in \mathbf{x}} \Gamma \cdot x$. Proof that $Z$ is a $Γ$-invariant closed subvariety and the $ \mathcal{O}(X) \rightarrow \mathcal{O}(Z)$ is surjective?
2) We say that $X$ is an affine variety if $A$ is finitely generated and reduced. Proof that $X_{rat}$ is $Γ$-invariant and that $X_{rat} = X$ if $X$ is an affine variety.
thank you.
Comment: In the question 2), your $X$ should be the set of maximal ideals of $A$. Otherwise $X_{rat}=X$ holds only when $\dim X=0$.
Comment: Please explain that how $ \Gamma $ induces an isomorphism on the residue fields. Thanks
Comment: Any $\gamma\in \Gamma$ induces an isomorphism of local rings $O_{X, x}\to O_{X, \gamma x}$, so it induces an isomorphism of residue fields.
Answer: 1) $\Gamma$ maps a rational point to a rational (hence closed) point because it induces an isomorphism on the residue fields of $x$ and $\gamma(x)$ for any $\gamma\in\Gamma$. So $Z$ is a finite subset consisting in closed points. This implies $Z$ itself is closed (finite union of closed subsets). As $X$ is affine, $\mathcal O(X)\to \mathcal O(Z)$ is thus surjective. Finally $Z$ is invariant by $\Gamma$ by construction (it is a union f orbits.
2) As said above, $\Gamma$ maps a rational point to a rational, so $\Gamma(X_{rat})=X_{rat}$. The equality $X=X_{rat}$ is just the weak form of Nullstellensatz for finitely generated $k$-algebras.

rational points and closed subvariety


Pré-vizualizacao de informações ao selecionar campo no input

Question: Tenho uma duvida, na verdade não sei se é possível, já que eu procurei na net e não achei nada.
Eu gostaria de saber se é possível fazer pre-visualização de um "perfil" ao selecionar o nome desse perfil em um <Option>
Tipo
<select id="selecao">
        <option value="perfil 1">Fulano</option>
        <option value="perfil 2">Fulanin</option>
        <option value="perfil 2">Ciclano</option>
</select>

Ai após selecionar um dos nomes citados na lista abrir uma especie de mini-card com mais informações daquele usuário
Comment: você quer fazer isso ao selecionar o *option* ou ao passar o mouse por cima?
Comment: ao selecionar..
Comment: Onde ficam armazenadas as informações dos perfis?
Answer: Sim é possível. Se a informação estiver do lado do servidor vai precisar de ajax e no select vai precisar de escutar o evento change.
O ajax é uma ferramenta/método para comunicar entre o browser e o servidor. Você pode passar informação para o servidor e o ajax fica à espera da resposta e corre uma função quando a receber.
Para despoletar o ajax precisa de um event handler. Um escutador que detecta quando o select muda, quando faz uma escolha. Aí, dentro dessa função pode fazer o pedido ajax.
Por exemplo:
$('#selecao').on('change', function(){
     var data = { opcao: $(this).val()};
     $.ajax({
        url: url,
        data: data,
        success: function(respostaServidor){
            $("#resposta").html(respostaServidor); // mero exemplo
        }
    });
});

Depois precisa do lado do servidor escutar este pedido com por exemplo (assumindo que PHP é a linguagem do lado do servidor):
$opcao = $_GET["opcao"]; // guardar os dados do ajax numa variável

// depois precisa de fazer uma query à base de dados,
// aqui varia conforme o que tem no servidor e precisa precisar melhor na pergunta
// Depois da query à base de dados (ou ficheiro) pode retornar o valor com por exemplo:

echo $dados; // enviar resposta de volta para o lado do cliente

Comment: @ErlonCharles, sorry :P Na próxima espero mais 10 segundos a ver se você está por perto :)
Comment: Droga, cancelei a resposta de novo. kkkkkkkkkkkkkkk. tome um `+1`
Comment: kkkkkkkkkkkkkkk


Middle div take the remaining height between a top div and a absolute positioned bottom div

Question: I have this kind of structure, where I am wrapping three divs (top, middle, bottom) inside a div (wrapper):

#wrapper {
  width: 60%;
  height: 200px;
  border: 2px solid red;
  margin: 0 auto;
  position: relative;
}

#top {
  height: 50px;
  background: green;
}

#middle {
  background: orange;
  overflow: auto;
}

#bottom {
  background: blue;
  position: absolute;
  width: 100%;
  bottom: 0;
  left: 0;
  padding: 10px 0;
}

      Top

Some content

Some content

Some content

Some content

Some content

Some content

Some content

Some content

Some content

      Bottom

As you can see the wrapper div has a fixed height, and the bottom div is positioned absolute in relation to the wrapper div. And the middle div has a list of contents, which is are out of the wrapper div. What I want to achieve is to make the middle div take only the remaining height is between the top div and the bottom div and still be able to scroll. How can I achieve this?
Answer: easiest way is to use flex :(actually seems to be a duplicate)

#wrapper {
  width: 60%;
  height: 200px;
  border: 2px solid red;
  margin: 0 auto;
  display: flex;
  flex-flow: column;
}
#top {
  height: 50px;
  background: green;
}
#middle {
  flex: 1;
  background: orange;
  overflow: auto;
}
#bottom {
  background: blue;
  padding: 10px 0;
}

      Top

Some content

Some content

Some content

Some content

Some content

Some content

Some content

Some content

Some content

      Bottom

the display:table property and absolute positionning can help for older browsers:

#wrapper {
  width: 60%;
  height: 200px;
  border: 2px solid red;
  margin: 0 auto;
  display: table;
  table-layout: fixed;
}
#top,
#bottom {
  color: white;
  display: table-cell;
  vertical-align: middle
}
#middle {
  display: table-row;
}
#top {
  height: 50px;
  background: green;
}
#middle {
  background: orange;
  position: relative;
  height: 100%;
}
#middle .buffer {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  overflow: auto;
}
#bottom {
  height: 1%;
  background: blue;
  padding: 10px 0;
}

    Top

Some content

Some content

Some content

Some content

Some content

Some content

Some content

Some content

Some content

Some content

Some content

Some content

Some content

Some content

Some content

Some content

Some content

Some content

    Bottom

Answer: You could do something like this with your css:
#wrapper {
  width: 60%;
  height: 200px;
  border: 2px solid red;
  margin: 0 auto;
  position: relative;
}

#top {
  height: 25%;
  background: green;
}

#middle {
  background: orange;
  overflow:scroll;
  height:50%;
}

#bottom {
  background: blue;
  position: absolute;
  width: 100%;
  bottom: 0;
  left: 0;
  padding: 10px 0;
  height:15%
}

Here is the jsfiddle. This will let you scroll if your content is too big to hold. I added some extra height parameters, but you can change them to fix your specific needs. The important thing is to set your overflow to scroll so that if there is extra content, the DOM will scroll so you can see all the content.
Comment: Yes, and I have changed removed `overflow:scroll` and added these properties `overflow-y:scroll; overflow-x: hidden;`. But there's still a thik white line between the #middle and #bottom div. That feels very odd. Is there anyway to remove that? [jsfiddle](https://jsfiddle.net/5L8x2cea/)
Comment: Yes, just update how big the middle is. I just added another 5%: https://jsfiddle.net/5L8x2cea/1/
Answer: simply give overflow:hidden to wrapper. To hide anything that overflows out of the container/wrapper div.
or     overflow: scroll; if you want to have access to the hidden content ( but this adds a nasty scrollbar on some areas).

#wrapper {
  width: 60%;
  height: 200px;
  border: 2px solid red;
  margin: 0 auto;
  position: relative;
  overflow:hidden;

}

#top {
  height: 50px;
  background: green;
}

#middle {
  background: orange;
  overflow: auto;
}

#bottom {
  background: blue;
  position: absolute;
  width: 100%;
  bottom: 0;
  left: 0;
  padding: 10px 0;
}

      Top

Some content

Some content

Some content

Some content

Some content

Some content

Some content

Some content

Some content

      Bottom

Comment: Yes.  But I need it to be scrollable.


Is there a finite generating set for the clone of all operations on a finite set with at least 3 elements?

Question: Let $S$ be a finite set with at least $3$ elements, and let $O(S)$ be the set of all finitary operations on $S$. That is, it is the set of all unary, all binary, all ternary, etc operations collected in one big set. Does there exist a finite set of operations such that the clone generated by that set is $O(S)$?
Answer: The answer is yes, and in fact $O(S)$ can be generated by a single binary function. For example, in 1936 Webb proved that the function $$(x,y)\mapsto [\min\{x,y\}+1]_{\mbox{mod } \vert S\vert}$$ generates the whole clone $O(S)$. See also Webb's thesis and this hsmse question, as well as Graham 1967.
More generally, there is a wealth of information about such topics in Lau's book Function algebras on finite sets, although it can be a bit tricky to navigate. Note that your $O(S)$ is Lau's $P_{\vert S\vert}$.

There is an important (if elementary) caveat here: since there are uncountably many clones on a finite set with $>2$ elements, it is not the case that "big = complicated" for clones: a subclone of a $1$-generated clone need not be finitely generated. Of course there is no reason to be surprised by this, but it's still worth mentioning.


This CSS works when col 2 is marked up before col 1 but not vice versa: what am I doing wrong?

Question: What am I doing wrong here? I want two columns, the left one (col 1) fluid, the right (col 2) with a fixed width of 300px. My code works fine, so long as I mark up col 2 before col 1 in the HTML. (The order of the id definitions in the CSS doesn't matter.) For readability of the markup I would like to mark up col 1 before col 2, but when I do I get a page in which the right-hand column, col 2, is missing.
CSS
#col1 {
        width:auto;
        padding: 10px;
        margin-right:300px;
        overflow:hidden;
      }
#col2 {
        float:right;
        padding:10px;
        width: 300px;
      }

HTML
This works:

Hello 2

Hello 1

This doesn't:

Hello 1

Hello 2

Comment: So, the trick is with `float:right`. If you don't need to support old browsers, you might look into [flexbox](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Using_CSS_flexible_boxes) or [column layouts](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Columns/Using_multi-column_layouts).
Answer: When you float an element right, you are saying that everything after it in the DOM will flow to the left of it. There are other available options for you. For example, you can display:inline-block for both DIVs and set vertical-align:top. You could also use display:table-cell.
Answer: The float: right is causing the issue.  It is taken out of the flow of the document and moved to the right.  Then the rest of the elements are rendered.  Since a div is a block element, the browser clears the line and displays the next div under it.
When you have them reversed, the div is floated to the right and the other column is placed in the proper location.
Answer: You're margin on the right of div 1 is screwing it up. You want to float div 1 on the left and div 2 to the right and get rid of your margins.

*, html, body{box-sizing: border-box;}
body, html{margin: 0;}
#col1 {
    float: left;
    width:calc(100% - 300px);
    padding: 10px;
    overflow:hidden;
    border: 1px solid black;
}
#col2 {
    float:right;
    padding:10px;
    width: 300px;
    border: 1px solid red;
}

Hello 1

Hello 2

Another way to do this is to use a container div with relative positioning and then place your divs inside of it with absolute positioning.