What are reference qualifiers for functions?

Question: According to this webpage, a non-static member function can have a trailing & or && in its declaration. They have the following example
struct S {
    virtual int f(char) const, g(int) &&; // declares two non-static member functions
    };

1) Does the signature of the second function include the virtual?
virtual int g(int) &&

2) What is the meaning of the trailing &&?
Comment: Please create two different questions for the two different questions in your text.
Comment: `&&` is for the r-value reference for '`*this`'.
Answer: struct S {
  virtual int f(char) const, g(int) &&;
};

struct D : S {
  virtual int f(char) const override;
  virtual int g(int) && override;
};

the above code compiles in both g++ and clang.  This indicates, at least in practice, that g is virtual in S.
See What is "rvalue reference for *this"? for your other question.
Comment: Good use of `override` there! I was going to confirm by testing if a pointer-to-base would call the correct `g`, but this is much better!


How can I center a logo image in an Omega theme?

Question: I'm using Omega (a subtheme obviously) and am having trouble centering my logo image. I tried adding a .logo-img CSS class to my global.css file but it isn't doing anything. I added the following, but results are weird:
margin-left: auto;
margin-right: auto;
border: 4px solid;

I added the border to see the image field because when I save these settings, the image stays on the left, but the border extends all the way to the right.
So those settings end up in the logo image resulting like this: https://i.stack.imgur.com/eMIsW.jpg (sorry I can't post images)
If I comment out the margin lines in the css file, the image stays the same.
I honestly don't know how to fix this. Is there a way to do this within my theme's settings? I can't find anything online or in the documentation.
Comment: Try Matt Galman's advice. Set Float none plus margin-left & right auto
Answer: By default the Omega theme CSS floats the image within branding left. You'll have to set it to float none.
Answer: You have to check the region your logo is in. normally it comes in the branding region.
You have to set the position of region from the theme settings. you can set your region to appear in center. For that you have to change prefix columns in the branding region configuration.
For more info on weight, position, columns of regions : https://drupal.org/node/1416128


tweepy streaming track filter results

Question: It seems not all the tweets I get using filter contain the item ("health" in this case). How could I get only tweets contain this specific item? Anyone can help me?
Thanks so much in advance!!
This is the line when I use filter:
sapi.filter(locations=[-79.55, 37.883, -75.067, 39.717],track = ["health"])
Answer: Unfortunately, the Streaming API does not allow filtering by both location and terms. From the docs:

Bounding boxes do not act as filters for other filter parameters. For example track=twitter&locations=-122.75,36.8,-121.75,37.8 would match any tweets containing the term Twitter (even non-geo tweets) OR coming from the San Francisco area.

So essentially the reason you are seeing some tweets that do not contain the word "health" is because you are receiving tweets containing the word "health", OR located within your bounding box (in this case, locations=[-79.55, 37.883, -75.067, 39.717]).
You can, however, try to filter by your term(s) then parse through the tweet data for the location, or alternately filter by location then search the tweet text for your term(s). I would probably suggest the latter if location is necessary to limit the scope of your tweet consumption.
Comment: Thanks so much, @dbernard! It reasonable to me now why got these results. Many thanks!!!
Answer: It is very easy you just need to add this line in your code.

twitterStream.filter(track=["health"])

tweepy streaming track filter results


Qt c++ strange behavior

Question: This code is not working in our constructor method, it is only working in a slot method. If we try to compile this code in constructor we get null pointer exception in Qt. But the same piece of code is working fine if we put it in other method (same class):
for(int l=0; l<sizeof(evo_ws); l++){

  printf("%d\n", evo_ws[l].generationen);
  printf("hulla");

}

Comment: You don't even say what is `evo_ws`. Have you checked it's not actually null ?
Comment: we defined a slot für a pushbutton with exactly the sae piece of code, there it is working fine
Comment: extern EVO_WS_TYPE   *evo_ws;     is extern var
Comment: EVO_WS_TYPE is typedef struct
Comment: @Nildse And where is this `extern` variable actually pointing to a valid instance?  I believe you have just mismanaged or misused your pointer, and the programs where it "works" is just undefined behavior kicking in.  The answer below already shows that your usage of `sizeof` is totally wrong, so it won't be surprising if you have done other things wrong in your program.
Comment: if we try to debug we get SIGSEGV Segmentation fault....
Comment: You didn't answer the basic question: *Where does the pointer evo_ws get initialized?*  You don't need a debugger for that -- it's your code and you must have had it initialized somewhere.  Right now, being `extern` means that the pointer is NULL.
Comment: this var is initialized in other header file extern EVO_WS_TYPE   *evo_ws;
Comment: we include this header file in our class
Comment: even this code is not working for(int l=0; l<3; l++){

  printf("%d\n", evo_ws[0].generationen);

}
Comment: is this the right way to access the integer var of this struct pointer ?
Comment: @Nildse Please show *how* this variable is initialized -- don't describe it.  Show the code.  Also, do you know what I mean by "initialized"?  You have a pointer, *but what does it point to?*  Just declaring a pointer isn't enough -- you have to point it somewhere before you use it.  That's what is missing from you -- where/when/how do you point this pointer to a *valid* instance of your struct?
Answer: sizeof returns size in bytes. I expect that evo_ws is declared such as Type evo_ws[20];. In that case sizeof(evo_ws) can be more than 20. You should use sizeof(evo_ws)/sizeof(*evo_ws).
Comment: we also tried                                             for(int l=0;l<3;l++){

        printf("%d\n",evo_ws[l].generationen);
        printf("hulla");

    }
Comment: this code is workig fine in oter methode, only not working in contructor method
Comment: `printf` is working fine in Qt. Is `evo_ws` really declared as a fixed-size array? Or is it a pointer? Or something else?
Comment: @Nildse Have you determined it is a `printf` problem?  How about just a simple `printf("abc\n");` and remove that line that uses the mysterious `evo_ws`?
Comment: In that case, the pointer seems to be `nullptr` in the constructor and is initialized later. Also if it is a pointer, `sizeof` does not return size of the pointed array but size of the pointer itself (4 bytes for 32-bit, 8 bytes for 64-bit systems).

Qt c++ strange behavior


Prove $0\le a_n \le a_{n+1} \le 1\ $ for all $n$, if $ a_{n+1}=\sqrt[3]{\frac{1+a_n}{2}}$ and $0\le a_1\le 1$

Question: I know that $0\le a_1\le 1$ and $ a_{n+1}=\sqrt[3]{\frac{1+a_n}{2}}$ for all $ n\ge 1$
Prove that $0\le a_n\le 1\ $ for all $n$, and $a_{n+1}\ge a_n$ for all $n$.
I think I shall assume the opposite and show that this leads to a false conclusion.
I don't know where to start and would appreciate any help I can get.
Comment: Are you sure you copied this right ? $a_{n+1}$ does not depend on $a_n$ ...
Comment: Have you tried using induction?
Comment: Wow! Thanks for all the comments. I will now try them, I'll be back.
Answer: Hints

I'd strongly suggest you try mathematical induction.

You'll probably find the following facts useful:
i. If $\ 0\le x\le1\ $ then $\ 0\le\frac{1+x}{2}\le1 $.
ii. If $\ 0\le y\le 1\ $ then $\ 0\le\sqrt[3]{y}\le1\ $.
Answer: Hint: $f(x) = \sqrt[3]{\frac{1+x}{2}}$ is an increasing function.
Answer: Maybe you should try to prove it by induction ! You have $0\le a_1\le1$ and you can prove that $a_1\le a_2$. Now that you have the base case, you can assume $0\le a_n\le1$ and $a_{n-1}\le a_{n}$ and prove that $0\le a_{n+1}\le1$ and $a_n\le a_{n+1}$. (Use the hint given by one of the answers above)
Answer: The recurrence is $$a_{n+1}=\sqrt[3]{\frac{1+a_n}{2}}$$
Let's go step by step. First, we'll prove that $$0\leq a_n\leq 1$$ for all $n$.
We are given that $0\leq a_1\leq 1$. Now suppose $0\leq a_k\leq 1$ for some $k\in\mathbb{N}$. This gives $$ \left(\frac{1}{2}\right)^{\frac{1}{3}} \leq a_{k+1} = \left( \frac{a_{k} + 1}{2} \right)^{\frac{1}{3}} \leq 1$$ which means $0\leq a_{k+1} \leq 1$. By the principle of weak induction, we have $0\leq a_n\leq 1$ for all $n$.
To show $a_{n+1} \geq a_n$ for all $n\in\mathbb{N}$, we outline a proof by contradiction. Suppose $a_{n+1} < a_n$ for some $n\in\mathbb{N}$. Using the recurrence in the problem, this would mean $$2a_n^3 - a_n - 1 > 0 \implies (a_n - 1)\left(2\left(a_n + \frac{1}{2}\right)^2 + \frac{1}{2} \right) > 0 \implies a_n > 1$$ which is a contradiction, since we have already shown that $0\leq a_n\leq 1$ for all $n\in\mathbb{N}$.
So we have $a_{n+1} \geq a_n$ for all $n\in\mathbb{N}$ as desired.
Comment: I'm sorry if this is a stupid question. Where did $2a_{n}^{3}-a_n-1>0$ came from? EDIT: Nevermind. Understood it now.
Comment: Yeah, just used the recurrence!
Answer: $a_n \ge 0$ is trivial.
$2a_{n+1}^3-2=a_n-1 \implies 2(1-a_{n+1})(a_{n+1}^2+a_{n+1}+1)=1-a_n$
Therefore $a_n \le 1 \implies a_{n+1}\le 1$
Finally $1-a_n \ge 2(1-a_{n+1})\cdot 1 \ge 1-a_{n+1} \implies a_{n+1} \ge a_n$.


Bluetooth Beacon Device Suggestions

Question: Hi new to the form always use it but never needed to ask anything, i just need advice on the following. thanks in advance!
Is it possible to connect a Bluetooth beacon to a visual studio c# application and use a android phone to send a message to the beacon where the application updates a database? many devices will be sending messages to the same beacon (my project idea). I know the android and messaging part will work but not sure if i can connect the beacon to the VS desktop c# app.
And this is the beacon i have been looking at, need something with a good range. (contacted manufacture about connecting it as they just show an app to configure. no reply lol)
https://accent-systems.com/product/ibks-105/
Open to suggestions.
Answer: Sorry, what you are describing won't work.  Bluetooth beacons are essentially transmit-only devices.  You can't send messages to them.  All beacons do is transmit a unique identifier.
It's unclear what your project is trying to accomplish here, but you can use web services as an intermediary for mobile devices to communicate with a C# Desktop app.  You can trigger this communication to happen when the mobile devices detect the bluetooth beacons.
Comment: Thank you for answering. I was thinking it would work the same way as two phones communicating. Instead of
Comment: The above method could i still connect the beacon to a visual studio c# desktop app to control what tags are being broadcast to the phones. Then ill just have to make the android app connect to the server to update a db. Project idea is a beacon attendance app
Comment: Or instead of that could i use the same app to control what tag the beacon broadcasts, signal360 beacon shows i can but asking to be safe. Sorry for all the comments.

Bluetooth Beacon Device Suggestions


Multiple imputation for outcome variables

Question: I've got a dataset on agricultural trials.  My response variable is a response ratio: log(treatment/control).  I'm interested in what mediates the difference, so I'm running RE meta-regressions (unweighted, because is seems pretty clear that effect size is uncorrelated with variance of estimates).
Each study reports grain yield, biomass yield, or both.  I can't impute grain yield from studies that report biomass yield alone, because not all of the plants studied were useful for grain (sugar cane is included, for instance).  But each plant that produced grain also had biomass.
For missing covariates, I've been using iterative regression imputation (following Andrew Gelman's textbook chapter).  It seems to give reasonable results, and the whole process is generally intuitive.  Basically I predict missing values, and use those predicted values to predict missing values, and loop through each variable until each variable approximately converges (in distribution).
Is there any reason why I can't use the same process to impute missing outcome data?  I can probably form a relatively informative imputation model for biomass response ratio given grain response ratio, crop type, and other covariates that I have.  I'd then average the coefficients and VCV's, and add the MI correction as per standard practice.
But what do these coefficients measure when the outcomes themselves are imputed?  Is the interpretation of the coefficients any different than standard MI for covariates?  Thinking about it, I can't convince myself that this doesn't work, but I'm not really sure.  Thoughts and suggestions for reading material are welcome.
Comment: I haven't got the answer, but one question and two notes: 1) log of a ratio is, of course, the difference of logs. So your DV is equivalent to log(treatment) - log(control). 2) Which textbook of Gelman's were you looking at?
Comment: Yes, the DV is equivalent to log(treatment)-log(control).  I'm basing the iterative regression imputation on the (nontechnical) chapter on missing data that Gelman has posted online: http://www.stat.columbia.edu/~gelman/arm/missing.pdf
Comment: I have been told that imputing the outcome leads to Monte Carlo error. Will try to find a link later. Don't forget that you need to make sure to include the outcome in the imputation models for the covariates.
Answer: As you suspected, it is valid to use multiple imputation for the outcome measure. There are cases where this is useful, but it can also be risky. I consider the situation where all covariates are complete, and the outcome is incomplete.
If the imputation model is correct, we will obtain valid inferences on the parameter estimates from the imputed data. The inferences obtained from just the complete cases may actually be wrong if the missingness is related to the outcome after conditioning on the predictor, i.e. under MNAR. So imputation is useful if we know (or suspect) that the data are MNAR.
Under MAR, there are generally no benefits to impute the outcome, and for a low number of imputations the results may even be somewhat more variable because of simulation error. There is an important exception to this. If we have access to an auxiliary complete variable that is not part of the model and that is highly correlated with the outcome, imputation can be considerably more efficient than complete case analysis, resulting in more precise estimates and shorter confidence intervals. A common scenario where this occurs is if we have a cheap outcome measure for everyone, and an expensive measure for a subset.
In many data sets, missing data also occur in the independent variables. In these cases, we need to impute the outcome variable since its imputed version is needed to impute the independent variables.
Comment: It has been widely practiced for ANOVA to get balanced designs. See the introduction of RJA Little, Regression with missing X's, JASA 1992. I suppose that you know that increasing the sample size in this way does not help you to get more precise estimates. For the case of auxiliary variables, read the section on super-efficiency in DB Rubin, Multiple Imputation after 18+ Years, JASA 1996.
Comment: **"Under MAR, there are generally no benefits to impute the outcome"** - I have seen this mentioned before, but I don't have any reference for it - can you provide one please ?
Comment: @StefvanBuuren - helpful answer for the most part, but my understanding is that "if we know (or suspect) that the data are MNAR" then imputation cannot solve our problems any more than complete case analysis can.  This seems to be fall in the "no free lunch" category.
Comment: Thanks, this is consistent with my intuition, but could you perhaps share a link to a well-done published study that imputes dependent variables?

One of the main reasons that I want to impute the outcome measures is to increase sample size (from about 250 to about 450), in order to facilitate semi-parametric tensor product interaction terms in GAM's that have very high df requirements (before they get penalized, lowering edf).

MAR is reasonable in my case.
Comment: I think you can quote Little 1992 http://www.tandfonline.com/doi/abs/10.1080/01621459.1992.10476282 for that, but please note the exceptions.
Answer: Imputing outcome data is very common and leads to correct inference when accounting for the random error.
It sounds like what you're doing is single imputation, by imputing the missing values with a conditional mean under a complete case analysis. What you should be doing is multiple imputation which, for continuous covariates, accounts for the random error you would have observed had you retroactively measured these missing values. The EM algorithm works in a similar way by averaging over a range of possible observed outcomes.
Single imputation gives correct estimation of model parameters when there is no mean-variance relationship, but it gives standard error estimates which are biased toward zero, inflating type I error rates. This is because you've been "optimistic" about the extent of error you would have observed had you measured these factors.
Multiple imputation is a process of iteratively generating additive error for conditional mean imputation, so that through 7 or 8 simulated imputations, you can combine models and their errors to get correct estimates of model parameters and their standard errors. If you have jointly missing covariates and outcomes, then there is software in SAS, STATA, and R called multiple imputation via chained equations where "completed" datasets (datasets with imputed values which are treated as fixed and non-random) are generated, model parameters estimated from each complete dataset, and their parameter estimates and standard errors combined using a correct mathematical formation (details in the Van Buuren paper).
The slight difference between the process in MI and the process you described is that you haven't accounted for the fact that estimating the conditional distribution of the outcome using imputed data will depend on which order you impute certain factors. You should have estimated the conditional distribution of the missing covariates conditioning on the outcome in MI, otherwise you'll get biased parameter estimates.
Comment: Thanks.  First off, I'm programming everything from scratch in R, not using MICE or MI.  Second off, I am imputing with draws of a (modeled) predictive distribution, not just conditional expectations.  Is that what you are talking about in the second paragraph?  If not, I'd appreciate clarification.  Also, which Royston paper are you referring to?  For your last point -- are you saying anything more complicated than "you should put your dependent variable in the imputation model."?  If so, I'd greatly appreciate clarification.
Comment: Lastly -- I'm not doing single imputation.  I'm fitting 30 models with filled in data and using the V_b = W + (1+1/m)B formula from Rubin.
Comment: Royston paper was hyperlinked. I actually meant to link the Van Buuren one who implemented the program in R and includes computational details: http://doc.utwente.nl/78938/

MICE/MI is a process. If you're imputing based on home-grown code, you ought to better elaborate on the details. Conditional means = predicted values if the model is correct (or approximately so, a necessary assumption). It is more complicated than "add the outcome", it's that you're imputing over several missing patterns (at least 3, missing covariate / outcome / jointly missing).
Comment: If you're singly imputing the predicted value 30 times, you should be getting the same results 30 times. How are you estimating the error?
Comment: Its a pretty simple algorithm -- say I observe a, b, c and d with some missingness.  I fill in all four with random draws (with replacement) from observed values.  Then I model imp = lm(a~b*+c*+d*) where * indicates filled in, and then x = predict(imp,se.fit=TRUE),
y = rnorm(N,imp$fit,imp$se.fit).  I then do a* = y, and then do imp = lm(b~a*+c*+d*), predict the same way, and so on.  I loop through the whole set of variables 50 times.  This is all from that Andrew Gelman textbook chapter that I linked above, and it is also why i don't get the same result each time.
Comment: The code there probably isn't clear and I can no longer edit.  Basically each prediction gets noise, as a draw from a normal with the variance of the imputation model's error term.  For four variables with missingness, I predict once per loop, and loop 50 times, to make 200 regressions per to-be-completed dataset.  This is probably overkill, as I get approximate convergence in distribution of imputed values within maybe 15 loops.
Comment: lots of x, a, b, c, ys floating around there... I don't think this tells the story. What do you do when a, b is missing jointly? Why can't you edit your post?
Comment: Can't edit after 5 minutes, apparently?  Anyway, I'll give that MICE paper a good read, but a brief skim indicates that MICE is in fact what I'm doing.  I just learned it from Gelman, who calls it iterative regression imputation.  Different statistical camps call things by different names sometimes.  Anyway, when a and b are missing jointly, I predict them as best I can with c and d.  I start with completely random imputations, and let both the original and the filled-in data predict the missing variables, one by one, incrementally changing the distribution from which I predict.
Comment: Just noticed this comment.  In fact, I am drawing from the posterior parameter distribution.  Thanks for thinking of this so far afterwards and making sure!
Comment: It is close to MICE, but not quite. You also have to account for the fact that the regression weights are estimated from the data. You can do this by drawing from the posterior parameter distribution, or alternatively, by taking a bootstrap sample before fitting the model. If you do not do this, confidence intervals will be too short, especially for small samples.


JNB after comparison with 0 (x86)

Question: I have this x86 assembly code:
mov     [ebp+var_8], 0

mov     eax, Str_len

cmp     [ebp+var_8], eax

jnb     short loc_4018C4

If Str_len is always different from 0, what does this JNB perform ? My reasoning is that if Str_len variable is never below than 0, the jump is never perform, right ?
Btw, how can a register have values below than zero in binary representation of x86 ?
Answer: jnb instruction jumps when the carry flag is zero. The cmp instruction updates the flags according to the result of the subtraction of src operand from the dst operand. The dst operand is the first operand in the Intel notation, thus, the flags will be updated according to the result of [ebp+var_8]-eax. As [ebp+var_8] equals to zero the carry flag will be cleared when when eax is zero and set otherwise. To summarize, the branch will happen when eax is equal to zero.
Answer: jnb (really an alias for jnc) uses one of the "unsigned predicates", so with respect to jnb, a value is never below zero.
But the thing that is zero is the first argument to the comparison, so it's really computing  0 - eax (and then it keeps only the flags, not the result), and then it jumps if there is no carry. So it comes down to: jump if Str_len is zero.

JNB after comparison with 0 (x86)


Reinstalling Linux: how to avoid downtime?

Question: My website runs on a dedicated Debian LAMP server . I would like to update the system (let's say I have a pretty old Debian version and I want to reinstall everything from scratch)
What strategy can I use to not have my website down while I am reinstalling everything?
Addendum
Of course I know I can buy another server in the meanwhile and change the DNS whenever it's done. But this doubles my work.
Aren't some service that maybe can act as a proxy-cacher for a limited amount of time? Maybe what does CloudFlare but caching everything not just images.
Comment: If you aren't asking how to do this yourself, and instead looking for a service to do this for you, then your question probably is either a shopping question, or more appropriate for site like webapps.se.
Answer: If you don't want any downtime, then really the only option is to build your new install on separate hardware and when you're happy that it's all working correctly, alter your DNS settings to point to the new server.
If you don't have another physical server, you might consider running your app on a cloud server while you do the upgrade of your physical server.
Comment: I already knew of course to buy another server just for the swap. I wanted to know if there were simpler alternative... (because If I have to buy another server just for the excanghe I will have to doulbe the work)
Comment: I added some infos from the question.
Answer: Have a second server take the load, using a load-balancer or just by re-pointing the IP for the duration of the update. In fact, if you use a load-balancer, you can then leave both servers up afterwards.
This is assuming the site isn't database-dependent. So, given the limited set of facts you gave us, this is my simple answer.
Answer:
Aren't some service that maybe can act as a proxy-cacher for a limited amount of time?

If your site is purely static, or at least is somewhat useful when setup read-only.  Then you temporarily pay for some web-hosting, and then use something like wget, or similar tools to spider the static portion of your web site.
You could setup a proxy in the cloud, setup squid as a proxy to your site, adjust DNS temporarily so all access goes through the proxy, then configure Squid to operate in offline mode, after you have everything cached.  You would probably want to script something that would have a browser visit all the important pages via the proxy, so everything gets into the cache.
Comment: The cloud offers you base OS images where you can install any application you want to install.  This blog post shows how to setup squid on Amazon EC2.  http://www.kiragiannis.com/cloud-computing/configuring-squid-in-the-amazon-ec2-cloud/  it is a bit out of date though.  Also see https://forums.aws.amazon.com/message.jspa?messageID=75229
Comment: AWS is a great plan. Pay a couple cents to have Amazon host your site for a couple hours.
Comment: A proxy in the cloud? Does cloud offer this? I don't think
Comment: awesome link... i guess this is the way to do it
Answer: If on a real crusade against new hardware (reasonable if you really, really don't have the budget) I would do this:

Install a virtualization system. This can be Xen if the Debian install is old, but not old enough not to have Xen. Use VirtualBox or even QEMU if necessary.
Install a virtualized Debian Squeeze system on a real system partition or logical volume. This will make it possible to "upgrade" this VM to primary OS later on. If you're using VirtualBox or QEMU your easiest choice will be to install to a separate hard disk. dedicating it fully to this VM.
Install all services on the VM and test everything accordingly.
When the time comes to switch, edit your grub.conf and boot into the new system. The VM (now physical server) will probably have to reconfigure itself because of the change of "hardware", but Linux is good at this. Remember to install grub on the new hardisk if there is one.

Have you considered upgrading Debian up to the latest version, though? Debian upgrades are remarkably good most of the time. If your current distribution is old enough not to be widely available on mirrors you can always use archive.debian.org until you reach a semi-current one.
Comment: Thanks for this answer. I am myself looking into this possibility; using virtualization for the only purpose to be able to upgrade OS / MySQL / etc without having to use new hardware.
Answer: I would start with a Virtual Machine.  Build up a system and then move over your current website.  That should let you know what is going to give you trouble in porting your app to a new version.  If you don't have another server machine at some point you are going to have to take it down to do the upgrade but knowing ahead of time where your problems are is a big step towards minimizing downtime.
Comment: That sounds like doing dev and QA work, not planning for an actual cutover. Those are important steps, but it's not what he asked for. As a sysadmin, I'd assume that the dev team had tested their stuff on the updated platform. And if they hadn't but were requesting it anyway, I'd know who's heads would roll.


Is it ok to use a random intercept model without testing for random slopes?

Question: In university we calculated a random intercept model for two-level nested data. We compared the random intercept model with all level-1 variable with the random intercept model with all level-1 and all level-2 variables. Like this we got main effects for level-1 and also main effects for level-2 variables. But we did not run a model to see if there are random slopes too. (In another step we even included an interaction term between a level-1 and a level-2 variable in the model, which was significant. But this was still without testing for random slopes before).
Now I am wondering if one shouldn`t always test for random slopes too? What happens if actually the random slope model would better fit the data than the random intercept model? Would that mean that the coefficients in the random intercept model are not estimated right?
Answer: Models with mixed effects have 2 stochastic ingredients:

Residual errors
Random effects

If you use a random slope and notice that the model performs better, it means that there is variability that was not properly captured by the residual errors, the random intercept, and fixed effects. Another direction that you can take is to be flexible on the residual errors (e.g. by using a Student-t instead of a normal distribution for the residual errors). Now the question is: which model performs better? The one with normal errors or with Student-t errors? The one with random slope and normal errors? The one with random slope and Student-t errors? ... And so on. If you can implement all of them and compare them, you can gain understanding on the features of the data. For example, if your model selection favours the model with Student-t errors and no random slope, it tells you that a single slope fits the data better (no variability among subjects in terms of the slope) but there might be some outliers that require a distribution with heavier tails than normal.
Answer: I would echo @East's advocacy for model exploration, but it was already stated very well.  Per Barr et all (2013; full citation below), a failure to fit random slopes when present could result in an inflated Type-I error rate (incorrect rejections of the null hypothesis when the null hypothesis actually is true).  So, (as I understand it) if the random slope model would better fit the data than the random intercept model, there will be a tendency for the fixed effect error to be under estimated.  In practice (again, as I understand it), the fixed effects coefficients will be estimated reasonably well, but the errors will be estimated incorrectly (with bias towards lower magnitude).
Barr, D. J., Levy, R., Scheepers, C., & Tily, H. J. (2013). Random effects structure for confirmatory hypothesis testing: Keep it maximal. Journal of Memory and Language, 68(3), 255-278.


performance em uma consulta do tipo select

Question: Para o SGBD o que é mais rápido receber os campos todos explicitados ou usar o caractere * que representa todos os campos. Caso haja diferença qual a razão?
Select coluna1,coluna2,coluna3, .....,colunaN from

Ou
Select * from

A pergunta é bastante clara, explicitar TODAS as colunas ou usar * e, não obstante, gostaria de uma resposta objetiva focada somente nessa condição.
Não é desejável que as respostas a esta pergunta sejam baseadas em opiniões mas sim em fatos, referências ou experiência específica.
Comment: Possível duplicata de [Número de colunas influencia em performance?](https://pt.stackoverflow.com/q/94825/3635) e [Por que usar "SELECT * FROM tabela" é ruim?](https://pt.stackoverflow.com/q/21583/3635)
Comment: A pergunta foi bastante clara, "explicitar todas as colunas ou usar *" e não usar o que for necessario
Comment: Para o SGBD é mais rápido receber o comando com todos os campos explicitados. O uso do * obriga o servidor a consultar quais são os campos antes de efetuar a busca dos dados, criando mais um passo no processo.  Fonte http://www.devmedia.com.br/sql-select-guia-para-iniciantes/29530
Comment: Creio que quanto menos campos você solicitar, mais rápida fica a consulta. Mas vamos esperar os mais experientes falarem.
Comment: Quando comecei a usar MySQL fui instruído a selecionar os campos que vou usar, ainda mais quando há muitos na tabela, ou quando vou fazer JOIN.
Comment: @LeoCaracciolo Isto não é totalmente verdade (ou seja é verdade mas não para todos os casos), cada motor tem um comportamento, pode ser que uma consulta com `*` seja otimizada para um tipo de motor mysql especifico, não dá pra afirmar nada, fora que de qualquer forma geralmente isso é **micro**-otimização e sendo assim dificilmente é este tipo de coisa que irá prejudicar o banco de dados, claro que depende muito do servidor, motor e/ou configurações.
Comment: @qualcuno leia as respostas desta pergunta, veja se lhe atende: https://pt.stackoverflow.com/q/21583/3635
Answer: Existem algumas pesquisas que sugerem que deixar o campo explicito em uma consulta torna a consulta mais rápida, já que o uso do * o banco de dados deve procurar por tabelas existentes e só depois exibir o conteúdo delas. Depende muito do montante de dados que você possuí, mas o melhor é especificar quais colunas são. Se você utilizar o MySQL com PHP, e houver uma alteração na estrutura da tabela como adicionar uma nova coluna, pode resultar em danos significativos em seu sistema se a consulta for feita com o *, ou pode até mesmo fazer com que dados não importantes trafeguem pela rede utilizando processamento e banda larga desnecessária.
http://weblogs.asp.net/jgalloway/archive/2007/07/18/the-real-reason-select-queries-are-bad-index-coverage.aspx


Getting unique objects based on nested object property

Question: I have an object array as follows. I need the unique objects based the _id field of the application object inside the group.

const myObjArray:any = [
    {
        "group": {
            "name": "SAM-admin",
            "active": true,
            "application": {
                "_id": "g4fac238hma10kjo3mv473vbs",
                "name": "Prism",
                "owners": "",
                "url": "",
                "description": "",
                "active": "",
                "created_by": "",
                "updated_by": ""
            },
            "created_by": "",
            "updated_by": "",
        },
        "user": "g4fac238hma10kjo3mv473vbs",
        "role": "g4fac238hma10kjo3mv473vbs",
        "isAdmin": true,
        "active": true,
        "created_by": "email@example.com",
        "updated_by": "",
    },
        {
        "group": {
            "name": "SAM-super-admin",
            "active": true,
            "application": {
                "_id": "g4fac238hma10kjo3mv473asc",
                "name": "Utopia",
                "owners": "",
                "url": "",
                "description": "",
                "active": "",
                "created_by": "",
                "updated_by": ""
            },
            "created_by": "",
            "updated_by": "",
        },
        "user": "g4fac238hma10kjo3mv473asc",
        "role": "g4fac238hma10kjo3mv473asc",
        "isAdmin": true,
        "active": true,
        "created_by": "firstname.lastname@example.com",
        "updated_by": "",
    }
    ,
        {
        "group": {
            "name": "SAM-guest",
            "active": true,
            "application": {
                "_id": "g4fac238hma10kjo3mv473asc",
                "name": "Utopia",
                "owners": "",
                "url": "",
                "description": "",
                "active": "",
                "created_by": "",
                "updated_by": ""
            },
            "created_by": "",
            "updated_by": "",
        },
        "user": "g4fac238hma10kjo3mv473asc",
        "role": "g4fac238hma10kjo3mv473asc",
        "isAdmin": true,
        "active": true,
        "created_by": "firstname.lastname@example.com",
        "updated_by": "",
    }
];

Here in myObjArray the second and third elements are having group object with same application _id
Hence i need to remove the third object.
How to do this at the easiest way in typescript.
Answer: As always, Array.reduce is perfect to grouping array of objects by property. Just pass along as the acc parameter an object that will collect all the items as you iterate. Finally, getting the Object.values of the result since we don't need the grouping keys.

var data = [{ "group": { "name": "SAM-admin", "active": true, "application": { "_id": "g4fac238hma10kjo3mv473vbs", "name": "Prism", "owners": "", "url": "", "description": "", "active": "", "created_by": "", "updated_by": "" }, "created_by": "", "updated_by": "", }, "user": "g4fac238hma10kjo3mv473vbs", "role": "g4fac238hma10kjo3mv473vbs", "isAdmin": true, "active": true, "created_by": "email@example.com", "updated_by": "", }, { "group": { "name": "SAM-super-admin", "active": true, "application": { "_id": "g4fac238hma10kjo3mv473asc", "name": "Utopia", "owners": "", "url": "", "description": "", "active": "", "created_by": "", "updated_by": "" }, "created_by": "", "updated_by": "", }, "user": "g4fac238hma10kjo3mv473asc", "role": "g4fac238hma10kjo3mv473asc", "isAdmin": true, "active": true, "created_by": "firstname.lastname@example.com", "updated_by": "", }, { "group": { "name": "SAM-guest", "active": true, "application": { "_id": "g4fac238hma10kjo3mv473asc", "name": "Utopia", "owners": "", "url": "", "description": "", "active": "", "created_by": "", "updated_by": "" }, "created_by": "", "updated_by": "", }, "user": "g4fac238hma10kjo3mv473asc", "role": "g4fac238hma10kjo3mv473asc", "isAdmin": true, "active": true, "created_by": "email@example.com", "updated_by": "", } ];

var result = (Object.values(data.reduce(function(acc, item) {
  if (!acc[item.group.application._id]) {
    acc[item.group.application._id] = item;
  }
  return acc;
}, {})));

console.log(result);
.as-console-wrapper {
  max-height: 100% !important;
}


Oracle Apex - can't customize plug-in

Question: I am currently working in the Sample Charts application in Oracle APEX version 5.1.2. I would like to edit the code for the Gantt Chart plug-in, but for some reason it won't let me type in the PL/SQL code box or erase anything in the box. I read somewhere online that only the master copy of the plug-in can be customized and that the Reference Master Plug-in From box has to be blank. However, it does say that "This is the "master" copy of this plug-in" and I can't erase or choose a blank value for the Reference Master Plug-in From box. In addition, on the screen that shows the list of all the plug-ins for the application, it says that this plug in was subscribed from a "Nonexistent Master".
This is what I am seeing on my screen:

Has anyone seen this before and/or know how to fix this problem?
Thank you in advance.
Answer: Open the Popup LOV for "Reference Master Plug-in From" and pick "- no plug-in -" to break the subscription, after clicking "Apply Changes" you will be able to make the necessary modifications.

Oracle Apex - can't customize plug-in


Swift ios check if remote push notifications are enabled in ios9 and ios10

Question: How can I check if the user has enabled remote notifications on ios 9 or ios 10?
If the user has not allowed or clicked No I want to toggle a message asking if they want to enable notifications.
Answer: Apple recommends to use UserNotifications framework instead of shared instances. So, do not forget to import UserNotifications framework. As this framework is new in iOS 10 it's really only safe to use this code in apps building for iOS10+
let current = UNUserNotificationCenter.current()

current.getNotificationSettings(completionHandler: { (settings) in
    if settings.authorizationStatus == .notDetermined {
        // Notification permission has not been asked yet, go for it!
    } else if settings.authorizationStatus == .denied {
        // Notification permission was previously denied, go to settings & privacy to re-enable
    } else if settings.authorizationStatus == .authorized {
        // Notification permission was already granted
    }
})

You may check official documentation for further information: https://developer.apple.com/documentation/usernotifications
Comment: Yeah, I personally would choose to use a switch statement.
Comment: It's amazing how they guys at apple always achieve to make something so simple as accessing two booleans to become a mess of async request. I am really curious to know the reasons behind such choices.
Comment: Seems to me this is the right answer as of July 2017.
Comment: why isn't this `if` `if else` and `if else`?
Comment: @OgulcanOrhan yeah I know it works - I used your code and upvoted your answer just so you know :) - I just wanted to know why all three conditionals need to be called? I'm being a little pedantic I suppose
Comment: Apart from using `else if` use `switch statements`  for avoiding any confusion
Comment: This only works with iOS 10+. If you need to support both iOS 9 and iOS 10+ you will need to use a combination of the methods found in this post.
Comment: what if notifications was enabled and then switched out in the phone settings?
Comment: @jalone but it's not a bool, it's potentially one of many states (currently 5). Also, even if you had a helper that turned it into a bool, it probably wouldn't be too useful as your product would most likely have different behavior depending on if it's .notDetermined or .denied anyways.
Comment: @Vadoff it was an hyperbole, I meant more in general why don't they provide a callback for the changed values forcing to create wrappers and handle states internally, why (at least at time this was written) documentation was very lacking, too many cases to handle (especially as of today with approximate location, temporary permission), behaviours changing depending on app state, etc.
Answer: Updated answer after iOS 10 is using UNUserNotificationCenter .
First you need to import UserNotifications then
let current = UNUserNotificationCenter.current()
current.getNotificationSettings(completionHandler: { permission in
    switch permission.authorizationStatus  {
    case .authorized:
        print("User granted permission for notification")
    case .denied:
        print("User denied notification permission")
    case .notDetermined:
        print("Notification permission haven't been asked yet")
    case .provisional:
        // @available(iOS 12.0, *)
        print("The application is authorized to post non-interruptive user notifications.")
    case .ephemeral:
        // @available(iOS 14.0, *)
        print("The application is temporarily authorized to post notifications. Only available to app clips.")
    @unknown default:
        print("Unknow Status")
    }
})

this code will work till iOS 9, for iOS 10 use the above code snippet.
let isRegisteredForRemoteNotifications = UIApplication.shared.isRegisteredForRemoteNotifications
if isRegisteredForRemoteNotifications {
     // User is registered for notification
} else {
     // Show alert user is not registered for notification
}

Comment: It tells you only if the token was ever generated (the device was registered), not if the notifications were blocked.
Comment: This doesn't appear to work for iOS 10. In the simulator I clicked "Don't Allow" and this code still said user is registered for remote notifications.
Comment: This is not the correct way of determining this. When notifications are disabled by the user this property continues to return true even across application restarts. This is odd as it goes against the documentation that states, "The value returned by this method takes into account the user's preferences for receiving remote notifications." You need to check if notifications are allowed by the user as well.
Comment: Remote Notifications are not supported in the iOS simulator. Only local notifications
Comment: Works for me on iOS 10. Try using an actual device instead of the simulator.
Comment: `isRegisteredForRemoteNotifications` works agin on iOS 12, not iOS 10-11.
Comment: I noticed that you did not add break statements in the switch statement. Are these not required?
Comment: @AbdullahUmer yeah, `break` statement is not required here. The reason is if a switch case has any statement in it, it will automatically end the execution at the end, it will not go to another case.
Answer: I tried Rajat's solution, but it didn't work for me on iOS 10 (Swift 3). It always said that push notifications were enabled. Below is how I solved the problem. This says "not enabled" if the user has tapped "Don't Allow" or if you have not asked the user yet.
let notificationType = UIApplication.shared.currentUserNotificationSettings!.types
    if notificationType == [] {
        print("notifications are NOT enabled")
    } else {
        print("notifications are enabled")
    }

PS: The method currentUserNotificationSettings was deprecated in iOS 10.0 but it's still working.
Comment: 'currentUserNotificationSettings' was deprecated in iOS 10.0: Use UserNotifications Framework's -[UNUserNotificationCenter getNotificationSettingsWithCompletionHandler:] and -[UNUserNotificationCenter getNotificationCategoriesWithCompletionHandler:]
Comment: Cam, I just tested this code on 10.2 (on a phone) and on 9.3 (on the simulator) and it worked on both.  tylerSF, thanks for the solution.
Comment: This solution is better since it also managed the case where user goes in settings, able / disable notifications and goes back in application
Comment: Will this work on iOS 9,8,7,etc...or do I need separate code?
Comment: I'm not sure, I've only checked it on iOS 10.
Comment: Thanks , what about if i need to change the status for notification from the application , could you please help me in this situation?
Comment: Not sure what you mean @wod... what are you trying to change?
Comment: @wod its not possible yet.
Answer: If your app supports iOS 10 and iOS 8, 9 use below code
// At the top, import UserNotifications
// to use UNUserNotificationCenter
import UserNotifications

Then,
if #available(iOS 10.0, *) {
    let current = UNUserNotificationCenter.current()
    current.getNotificationSettings(completionHandler: { settings in

        switch settings.authorizationStatus {

        case .notDetermined:
            // Authorization request has not been made yet
        case .denied:
            // User has denied authorization.
            // You could tell them to change this in Settings
        case .authorized:
            // User has given authorization.
        }
    })
 } else {
     // Fallback on earlier versions
     if UIApplication.shared.isRegisteredForRemoteNotifications {
         print("APNS-YES")
     } else {
         print("APNS-NO")
     }
 }

Answer: in iOS11, Swift 4...
 UNUserNotificationCenter.current().getNotificationSettings { (settings) in
        if settings.authorizationStatus == .authorized {
            // Already authorized
        }
        else {
            // Either denied or notDetermined
            UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
                (granted, error) in
                  // add your own
                UNUserNotificationCenter.current().delegate = self
                let alertController = UIAlertController(title: "Notification Alert", message: "please enable notifications", preferredStyle: .alert)
                let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
                    guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else {
                        return
                    }
                    if UIApplication.shared.canOpenURL(settingsUrl) {
                        UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
                        })
                    }
                }
                let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
                alertController.addAction(cancelAction)
                alertController.addAction(settingsAction)
                DispatchQueue.main.async {
                    self.window?.rootViewController?.present(alertController, animated: true, completion: nil)

                }
            }
        }
    }

Comment: @ChrisO you have to import UserNotifications
Comment: I'm getting an error with this `Use of unresolved identifier 'UNUserNotificationCenter'; did you mean 'NSNotificationCenter'?`
Answer: @Rajat's answer is not enough.

isRegisteredForRemoteNotifications is that your app has connected to APNS and get device token, this can be for silent push notification
currentUserNotificationSettings is for user permissions, without this, there is no alert, banner or sound push notification delivered to the app

Here is the check
static var isPushNotificationEnabled: Bool {
  guard let settings = UIApplication.shared.currentUserNotificationSettings
    else {
      return false
  }

  return UIApplication.shared.isRegisteredForRemoteNotifications
    && !settings.types.isEmpty
}

For iOS 10, instead of checking for currentUserNotificationSettings, you should use UserNotifications framework
center.getNotificationSettings(completionHandler: { settings in
  switch settings.authorizationStatus {
  case .authorized, .provisional:
    print("authorized")
  case .denied:
    print("denied")
  case .notDetermined:
    print("not determined, ask user for permission now")
  }
})

Push notification can be delivered to our apps in many ways, and we can ask for that
UNUserNotificationCenter.current()
  .requestAuthorization(options: [.alert, .sound, .badge])

User can go to Settings app and turn off any of those at any time, so it's best to check for that in the settings object
open class UNNotificationSettings : NSObject, NSCopying, NSSecureCoding {

    open var authorizationStatus: UNAuthorizationStatus { get }

    open var soundSetting: UNNotificationSetting { get }

    open var badgeSetting: UNNotificationSetting { get }

    open var alertSetting: UNNotificationSetting { get }

    open var notificationCenterSetting: UNNotificationSetting { get }
}

Comment: Notice that this is deprecated starting iOS 10
Answer: for iOS12 and Swift 4 also support iOS13 and Swift5
I also created a git for this you can check here
just add this singleton file in your XCode Project
import Foundation
import UserNotifications
import UIKit

class NotificaionStatusCheck {

    var window: UIWindow?

    private var currentViewController : UIViewController? = nil

     static let shared = NotificaionStatusCheck()

    public func currentViewController(_ vc: UIViewController?) {
        self.currentViewController = vc
        checkNotificationsAuthorizationStatus()
    }

    private func checkNotificationsAuthorizationStatus() {
        let userNotificationCenter = UNUserNotificationCenter.current()
        userNotificationCenter.getNotificationSettings { (notificationSettings) in
            switch notificationSettings.authorizationStatus {
            case .authorized:
                print("The app is authorized to schedule or receive notifications.")

            case .denied:
                print("The app isn't authorized to schedule or receive notifications.")
                self.NotificationPopup()
            case .notDetermined:
                print("The user hasn't yet made a choice about whether the app is allowed to schedule notifications.")
                self.NotificationPopup()
            case .provisional:
                print("The application is provisionally authorized to post noninterruptive user notifications.")
                self.NotificationPopup()
            }
        }

    }

    private func NotificationPopup(){
        let alertController = UIAlertController(title: "Notification Alert", message: "Please Turn on the Notification to get update every time the Show Starts", preferredStyle: .alert)
        let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
            guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else {
                return
            }
            if UIApplication.shared.canOpenURL(settingsUrl) {
                UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
                })
            }
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
        alertController.addAction(cancelAction)
        alertController.addAction(settingsAction)
        DispatchQueue.main.async {
            self.currentViewController?.present(alertController, animated: true, completion: nil)

        }

    }

}

to access this code on ViewController user this on viewDidLoad
NotificaionStatusCheck.shared.currentViewController(self)

Comment: for case `notDetermined` the permission wasn't requested yet, so whats the point of send the user to settings? It should ask for the permission is this case.
Comment: "import UIKit" must be added to use all the UI components in the code.
Answer: Here's a solution for getting a string describing the current permission that works with iOS 9 trough iOS 11, with Swift 4. This implementation uses When for promises.
import UserNotifications

private static func getNotificationPermissionString() -> Promise<String> {
    let promise = Promise<String>()

    if #available(iOS 10.0, *) {
        let notificationCenter = UNUserNotificationCenter.current()
        notificationCenter.getNotificationSettings { (settings) in
            switch settings.authorizationStatus {
            case .notDetermined: promise.resolve("not_determined")
            case .denied: promise.resolve("denied")
            case .authorized: promise.resolve("authorized")
            }
        }
    } else {
        let status = UIApplication.shared.isRegisteredForRemoteNotifications ? "authorized" : "not_determined"
        promise.resolve(status)
    }

    return promise
}

Answer: Even though user doesn't allow the push notifications, the device token is available. So it would be also a good idea to check if it's allowed to receive the push notifications.
private func checkPushNotificationAllowed(completionHandler: @escaping (Bool) -> Void) {
    if #available(iOS 10.0, *) {
        UNUserNotificationCenter.current().getNotificationSettings { (settings) in
            if settings.authorizationStatus == .notDetermined || settings.authorizationStatus == .denied {
                completionHandler(false)
            }
            else {
                completionHandler(true)
            }
        }
    }
    else {
        if let settings = UIApplication.shared.currentUserNotificationSettings {
            if settings.types.isEmpty {
                completionHandler(false)
            }
            else {
                completionHandler(true)
            }
        }
        else {
            completionHandler(false)
        }
    }
}

Answer: class func isRegisteredForRemoteNotifications() -> Bool {
    if #available(iOS 10.0, *) {
        var isRegistered = false
        let semaphore = DispatchSemaphore(value: 0)
        let current = UNUserNotificationCenter.current()
        current.getNotificationSettings(completionHandler: { settings in
            if settings.authorizationStatus != .authorized {
                isRegistered = false
            } else {
                isRegistered = true
            }
            semaphore.signal()
        })
        _ = semaphore.wait(timeout: .now() + 5)
        return isRegistered
    } else {
        return UIApplication.shared.isRegisteredForRemoteNotifications
    }
}

Comment: please don't do this to make a async operation appear sync ->    _ = semaphore.wait(timeout: .now() + 5)
Comment: @Augie Is there any specific reason except that async operation might take more than 5 seconds in some rare cases?
Answer: All answers above are almost correct BUT if you have push notifications enabled and all options disabled (alertSetting, lockScreenSetting etc.), authorizationStatus will be authorized and you won't receive any push notifications.
The most appropriate way to find out if you user can receive remote notifications is to check all these setting values. You can achieve it using extensions.
Note: This solution works for iOS 10+. If you support older versions, please read previous answers.
extension UNNotificationSettings {

    func isAuthorized() -> Bool {
        guard authorizationStatus == .authorized else {
            return false
        }

        return alertSetting == .enabled ||
            soundSetting == .enabled ||
            badgeSetting == .enabled ||
            notificationCenterSetting == .enabled ||
            lockScreenSetting == .enabled
    }
}

extension UNUserNotificationCenter {

    func checkPushNotificationStatus(onAuthorized: @escaping () -> Void, onDenied: @escaping () -> Void) {
        getNotificationSettings { settings in
            DispatchQueue.main.async {
                guard settings.isAuthorized() {
                    onDenied()
                    return
                }

                onAuthorized()
            }
        }
    }
}

Comment: In second snippet there is no else in guard.
Answer: The new style with async await
 static func getPermissionState() async throws  {
        let current = UNUserNotificationCenter.current()

            let result = await current.notificationSettings()
            switch result.authorizationStatus {
            case .notDetermined:
                //
            case .denied:
                //
            case .authorized:
                //
            case .provisional:
                //
            case .ephemeral:
                //
            @unknown default:
                //
            }

    }

Answer: My short asynchronously extension:
// UNUserNotificationCenter+Helper.swift

extension UNUserNotificationCenter {
    static func notificationsAllowed() async -> Bool {
        let settings = await UNUserNotificationCenter.current().notificationSettings()

        return !(settings.authorizationStatus == .notDetermined || settings.authorizationStatus == .denied)
    }
}

SwiftUI Example:
 @State private var notificationsAllowed = false

 @MainActor
 private func refresh() {
     Task {
         let notificationsAllowed = await UNUserNotificationCenter.notificationsAllowed()

         withAnimation {
             self.notificationsAllowed = notificationsAllowed
         }
     }
 }


Publishing Azure functions

Question: I work with several azure functions on a project that I didn't setup on my own, and when I try to publish the project which includes those azure functions to update them, the publishing failed with the following error :

Web deployment task failed. (Connected to the remote computer
  ("demo.scm.azurewebsites.net") using the Web Management Service,
  but could not authorize. Make sure that you are using the correct user
  name and password, that the site you are connecting to exists, and
  that the credentials represent a user who has permissions to access
  the site.

Where do I provide credentials ?
Comment: Are you deploying them from Visual Studio?
Comment: Yes, this is where I get the error
Answer: Here are the steps to publish an Azure Function from Visual Studio.

Go to the Azure Portal
Go to your Function App.
Then, select Overview and click Get publish profile and save the file.

Next, go to your Visual Studio project.
Right-click on your Azure Function project.
Select Publish and then Import Profile.
Finally, hit publish.

All the information needed, including your missing credentials, is in  that the profile.
Comment: Naturally this has changed in late 2022, but the essence is the same. We are deploying in Gov cloud. At your step 3, do this: Under Deployment/Deployment Center click the "Manage publish profile" tab up top. From the slide-out pane click, "Download publish profile".
Answer: I have the exact same issue. Tried to publish and get the exact same error. I did as kzrystof suggested and downloaded the publish profile from the Azure portal and imported it into VS2017. As soon as I pick the publish profile file and click the open button I get the "Publish failed" error message. I checked the output window to find out what the error was, but there is nothing new added to the output. I cleared the output window and clicked the Publish button and immediately receive the "Publish failed" error popup with no further details in the output window.
Update: I was able to successfully publish the Azure Function App by creating a new profile in VS2017 to a new instance up on Azure. I then removed the old instance from the Azure Portal. Successive attempts to publish from VS2017 then worked successfully.
Just as a test, I downloaded the publish profile from the Azure Portal for this new AF app and imported it into VS2017 and still this produces the same "Publish failed" error popup. MS still seems to need to do some work on that scenario.
Also, there still seems to be problems with ZipDeploy so avoid it for now. I keep having timeouts when trying to publish using ZipDeploy. Standard WebDeploy publishes the files individually and thus doesn't have timeout issues.

Publishing Azure functions


Expected value of random vector-constant matrix-random vector product

Question: I was reading through this post on the expected dot product of two random vectors. The answers there are quite interesting but not very conclusive. I was wondering if someone knows if the question is any more clear cut with a few restrictions.
Let $C \in \mathbb R^{n \times n}$ be a PSD correlation matrix (with $-1 \leq C_{ij} \leq 1 \ \ \forall \ i,j$ and $C_{ii} = 1 \ \ \forall \ i$) and $\vec x \in \mathbb \{0,1\}^n$ a binary random vector with $k < n$ ones. Is there anything one can say (upper/lower bounds or even an exact expression) about the expected value of the product?
$$
\mathbb E (\vec x^T  C \ \vec x)
$$
Comment: The straightforward bounds are $-k^2 \le \vec x^T  C \ \vec x \le k^2$ for all $\vec x \in \mathbb \{0,1\}^n$ with $k<n$ ones, and thereby these bounds also hold for the expected value.
Answer: Since $C$ is positive semi-definite, it has a Cholesky decomposition $C=LL^T$ with $L=(l_{ij})$. Thus
$$\newcommand{Var}{\operatorname{Var}}
E(x^TCx)=E((x^TL)(x^TL)^T)=\sum_{j=1}^nE(y_j^2)$$
where the $y_j=\sum_{i=1}^nl_{ij}x_i$ are also random variables. Now, denoting $D=\sum_{i=1}^nl_{ij}^2$ and $T=\sum_{1\le i<k\le n}l_{ij}l_{kj}$ so that $D+2T=\left(\sum_{i=1}^nl_{ij}\right)^2$,
$$E(y_j^2)=E(y_j)^2+\Var(y_j)$$
$$=\left(\frac kn\sum_{i=1}^nl_{ij}\right)^2+\sum_{i=1}^nl_{ij}^2\Var(x_i)+2\sum_{1\le i<k\le n}l_{ij}l_{kj}\operatorname{cov}(x_i,x_k)$$
$$=\frac{k^2}{n^2}(D+2T)+\frac{k(n-k)}{n^2}D-\frac kn\cdot\frac{2(n-k)}{n(n-1)}T$$
$$=\frac kn\left(\frac kn(D+2T)+\frac{n-k} nD-\frac{2(n-k)}{n(n-1)}T\right)$$
$$=\frac kn\left(D+2\frac{k-1}{n-1}T\right)$$
Since only $l_{jj}$ and below can be non-zero,
$$E(y_j^2)=\frac kn\left(\sum_{i=j}^nl_{ij}^2+2\frac{k-1}{n-1}\sum_{j\le i<k\le n}l_{ij}l_{kj}\right)$$
$$E(x^TCx)=\frac kn\sum_{j=1}^n\left(\sum_{i=j}^nl_{ij}^2+2\frac{k-1}{n-1}\sum_{j\le i<k\le n}l_{ij}l_{kj}\right)$$
Comment: Wow, this is really cool! Thanks a lot!


Using buttonIndex with multiple alert views

Question: I have about 4 alert views with different criteria when they appear. In all 4 views, the right button should always do the same thing.
I use the code below to try and say IF the buttonIndex == 1, do something.
Currently, It only works in one of my alert views. The others just end up closing the alert view and never running the code for IF buttonIndex == 1.
Any ideas would be appreciated.
if (a==1) {
            NSString *message = [[NSString alloc] initWithFormat:
                             @"Only $%@!",dollas.text];

            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:
                              @"Really?!"

                                                        message:message
                                                       delegate:self
                                              cancelButtonTitle:@"Close"
                                              otherButtonTitles:@"Facebook",nil];
        [alert show];
        [alert release];
        [message release];

        }

else if (a==2) {
            NSString *message = [[NSString alloc] initWithFormat:
                                 @"Somone just paid you $%@", dollas.text];

            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:
                                  @"Swish!"

                                                            message:message
                                                           delegate:nil
                                                  cancelButtonTitle:@"Close"
                                                  otherButtonTitles:@"Facebook",nil];
            [alert show];
            [alert release];
            [message release];

        }

And the delegate:
- (void)alertView:(UIAlertView *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex {

    if (buttonIndex == 1)
    {
       do.stuff;
    }

Comment: Don't use `buttonIndex == 1`. Instead, use `buttonIndex == alertView.firstOtherButtonIndex` or `buttonIndex == alertView.cancelButtonIndex`.
Comment: Oh nice. Didnt know I could do that. Thanks
Comment: If the only difference between each alert is the title and message then use variables for those and then have one set of code that creates and displays the alert view. No sense repeating the same code over and over.
Answer: You should be setting the delegate to self so that method gets called.
IE -
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:
                      @"Really?!"

                                                message:message
                                               delegate:self //SELF
                                      cancelButtonTitle:@"Close"
                                      otherButtonTitles:@"Facebook",nil];

Answer: Set the tags on each alertview and inside -didDismissWithButtonIndex check first for the alerts tag
eg:
    if (a==1) {
        NSString *message = [[NSString alloc] initWithFormat:
                         @"Only $%@!",dollas.text];

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:
                          @"Really?!"

                                                    message:message
                                                   delegate:self
                                          cancelButtonTitle:@"Close"
                                          otherButtonTitles:@"Facebook",nil];
    alert.tag = 1;
    [alert show];
    [alert release];
    [message release];

    }
    else if (a==2) {
        NSString *message = [[NSString alloc] initWithFormat:
                             @"Somone just paid you $%@", dollas.text];

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:
                              @"Swish!"

                                                        message:message
                                                       delegate:nil
                                              cancelButtonTitle:@"Close"
                                              otherButtonTitles:@"Facebook",nil];
        alert.tag = 2;
        [alert show];
        [alert release];
        [message release];

    }

then in -didDismissWithButtonIndex
- (void)alertView:(UIAlertView *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex {

    if (buttonIndex == 1 && actionSheet.tag == 1)
    {
       do.stuff;
    }
    else if (buttonIndex == 1 && actionSheet.tag == 2)
    {
       do.otherStuff;
    }

Comment: Thanks for the great answer. I actually needed to change the delegate:nil to delegate:self in the UIAlertViews
Answer: For the case (a == 2) you set the UIAlertView delegate to nil, so - (void)alertView:(UIAlertView *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex shouldn't even be getting called for this case. Change it to set the delegate to self.


Is $\mathbb{Z}_{p^\infty}$ a divisible group?

Question: Let $$\mathbb{Z}_{p^\infty}=\{x\in \mathbb{Q}/\mathbb{Z}: \ \exists n\in \mathbb{N} ,\ \ p^nx=0\}.  $$
Is $\mathbb{Z}_{p^\infty}$ a divisible group ?
Comment: Welcome to MSE. Please read this text about [how to ask a good question](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question).
Comment: What have you tried ?
Answer: Yes, $\mathbb Z_{p^\infty}$ is a divisible group. To prove it, let us pick any positive integer $n$ and any element $x\in \mathbb Z_{p^\infty}$. We have to prove that there exists some $y\in \mathbb Z_{p^\infty}$ such that $x = ny$.
First, let us write $n=p^k m$, where $k$ is a non-negative integer and $m$ is an integer coprime to $p$, and represent $x$ by a rational number $\frac a{p^\ell}$, where $a$ is an integer coprime to $p$ and $\ell$ is a non-negative integer.
Now, $m$ is invertible in $\mathbb Z / p^\ell \mathbb Z$, that is, there exists an integer $m'$ such that $mm' \equiv 1$ modulo $p^\ell$. Set $b=am'$. The rational number $\frac b{p^\ell}$ represents an element $z$ of $\mathbb Z_{p^\infty}$ and one has $m\frac b{p^\ell} \equiv \frac a{p^\ell}$ modulo $1$, hence $mz=x$ in $\mathbb Z_{p^\infty}$. Finally, take the element $y\in \mathbb Z_{p^\infty}$ represented by $\frac b{p^{k+\ell}}$. We get $p^k y = z$, hence
$$
 ny = mp^k y = mz = x \, .
$$
QED
EDIT (complement following comment by the author of the question): settting $Z:=\{[\frac a{p^n}]\in \mathbb Q /\mathbb Z \, : \ a,n \in \mathbb Z \text{ and } n\geq 0\}$, let us prove that $Z = \mathbb Z_{p^\infty}$. First, the inclusion $Z \subseteq \mathbb Z_{p^\infty}$ comes from the fact that $p^n [\frac a{p^n}] = 0$ in $\mathbb Q /\mathbb Z$ for all $a \in \mathbb Z$ and all $n \in \mathbb Z$ such that $n\geq 0$. Conversely, given $x\in \mathbb Z_{p^\infty}$,there exists $n\geq 0$ such that $p^n x = 0$ in $\mathbb Q /\mathbb Z$. Representing $x$ by a rational $\tilde x \in \mathbb Q$, this means that $p^n \tilde x$ is an integer. Hence, $\tilde x = \frac a{p^n}$ for some $a\in\mathbb Z$, which means that $x$ lies in $Z$. This proves the inclusion $Z \supseteq \mathbb Z_{p^\infty}$.
Comment: Thanks for your answer.


Approximate F-test of the intercept with pbkrtest

Question: I'm currently trying out the pbkrtest package. The test of the fixed effect (f1, in the example below) doesn't pose any problem.
## Not run:
library(lme4)
library(pbkrtest)

# large model:
m1 <- lmer(x ~ f1 + (1|ID) + (0 + f1|ID), data)

When I want to obtain an approximate F-test based on the Kenward-Roger approach for f1, I specify this model:
# small model
m2 <- lmer(x ~ 1 + (1|ID) + (0 + f1|ID), data)

and then:
KRmodcomp(m1, m2)

However, what kind of model should I specify if I would like to get an approximate F-test of the intercept?
Answer: To test a intercept less model (but including f1) you need to simply specify it (both ways are equivalent):
m3 <- lmer(x ~ 0 + f1 + (1|ID) + (0 + f1|ID), data)

or
m3 <- lmer(x ~ f1 + (1|ID) + (0 + f1|ID) - 1, data)

and then compare those:
KRmodcomp(m1, m3)

You can also get a test of all effects in (including the intercept) using function mixed in package afex, which does exactly this.

Example taken from ?KRmodcomp
require(pbkrtest)
fmLarge <- lmer(Reaction ~ Days + (Days|Subject), sleepstudy)
## removing Days
fmSmall <- lmer(Reaction ~ 1 + (Days|Subject), sleepstudy)
KRmodcomp(fmLarge,fmSmall)

#removing intercept:
fmNoIntercept <- lmer(Reaction ~ 0 + Days + (Days|Subject), sleepstudy)
KRmodcomp(fmLarge,fmNoIntercept)

Comment: It makes perfect sense, however, when I'm comparing m1 and m2 `KRmodcomp` runs smoothly, whereas when I'm comparing m1 and m3 I get this error message: "Error in KRmodcomp.mer(m1, m3): Models have either equal fixed mean stucture or are not nested". Any idea?
Comment: @vikkor Hmm, sounds strange. If yours does not work you need to post the data. I added a **working** example.
Comment: Curiously, if I use the `mixed` function from `afex` (as you suggested) with method set to "KR" I do not get that error. And, I don't get the error if I use `PBmodcomp` instead of `KRmodcomp`. I'll have to dig into this to understand where the problem is. Thanks anyway.
Comment: Note that if `f1` is a factor, then removing the intercept makes no sense, and all you'll get is a different dummy coding. This could cause the models not nested error.


Select an image from a list to an image field

Question: I'd like to achieve the following:
When the user creates new content, instead of uploading an image to an image field every time, I would like to make an opportunity for the user to select from 8 pre-uploaded images and if none of those are appropriate, allow her/him to upload a custom image as well.
Is there any way I can achieve this with contrib modules?
Thank you.
Answer: You can try "IMCE for File Field" module for this: https://www.drupal.org/project/imce_filefield
It depends on IMCE module. Gives the option to select a file from the predefined location instead of uploading.
Answer: Have you tried Avatar Selection module?

When a user edits their account details they can choose to upload an
  image or photo of themselves, also known as an avatar.

Another Hint:
Using the Media module you can allow users to select images from a library or upload there own which sounds like what you want.
Answer: A very simple approach would be to use the "List" option for selecting text as a field, and in the "allowed options" put in the image tags you want.  These may or may not appear as images in the drop-down or button selector, but you can fix that in the help file or in a side block.


Finding powers of prime ideals from its generators and understanding generator notation

Question: I am trying to understand ideal notation with pointed brackets and how to use it.
For instance, if I had an ideal $\mathfrak{a}=\left<2,1+\sqrt{-5}\right>$, where $2$ and $1+\sqrt{-5}$ are its generators, what does this mean for the format of the ideal?
And how would I find powers of this, i.e. $\mathfrak{a}^2$ or $\mathfrak{ab}$ for $\mathfrak{b}$ an ideal of the same form, (e.g. $\mathfrak{b}=\left<3,1+\sqrt{-5}\right>$)?
Answer: We have $\mathfrak{a}^2=(2^2, 2(1+\sqrt{-5}), 1+2\sqrt{-5}-5)=(2)$ by definition of the ideal product $IJ$ for two ideals in the ring $R=\mathbb{Z}[\sqrt{-5}]$. For discussions on the ideal product see here and here.
Comment: Thank you, I now understand that multiplying the generators will find the generators of the things in the product. I am still confused, however, as to why $(2^2,2(1+\sqrt{-5}),1+2\sqrt{-5}-5)=(2)$?
Comment: Wait, I think I have it;  $2^2, 2(1+\sqrt{-5}),2\sqrt{-5}-4$ are all made by multiplying the elements of $\mathbb Z \left[\sqrt{-5} \right]$ by multiples of $2$ and combining them? Is this right?
Comment: Yes, you are right.


Including non-TypeScript JS files in TypeScript-generated Require define

Question: Let's say I have the following TypeScript file:
import module1 = require( 'module1' );
import module2 = require( 'module2' );

...some code...

This would generate the following JavaScript on compilation:
define( [ 'require', 'exports', 'module1', 'module2' ], function ( require, exports, module1, module2 ) {
...
}

However, what if I want to include a file that's NOT a TypeScript module? I want it to be loaded by RequireJS, as it has dependencies that are also loaded by RequireJS. If I try to add e.g. this:
import someJsFile = require ( 'someJsFile' );

I just get a "Module cannot be aliased to a non-module type" error on compilation. If I skip the import part and just do require( 'someJsFile' ), it compiles, but the JavaScript it generates is a non-functional nested define instead:
define( [ 'require', 'exports', 'module1', 'module2' ], function ( require, exports, module1, module2 ) {
    define( [ 'someJsFile' ], function ( someJsFile ) {
    ...
    }
}

Is there any way of including JavaScript files in the outer, "correct" RequireJS define without having to convert the JS files to TS modules myself? Or do I have to manually create a RequireJS define and drop the import x = require( 'x' ) statements altogether?
Answer: Use amd-dependency. In your case :
/// <amd-dependency path="someJsFile" />
declare var someVarFromJsFile: any;

Comment: Oh, wow. I had tried that before, but I always put it _after_ the `import` statements, which didn't have any effect, so I assumed that approach was fruitless. Tried putting it at the top of the file now - works like a charm. Thanks!


Where to download MariaDB 10.3 over IPv6?

Question: CentOS 7 server with only IPv6.
When I try to use,
<code>[mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/10.3/centos7-amd64
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1
</code>
It tries to connect via IPv4 and fails, is there a IPv6 compatible repo somewhere that has MariaDB 10.3?
Answer: http://archive.mariadb.org/ is IPv4 however it lists the following as a mirror contain a Yum repository of a specific version that has an IPv6 address:
http://ftp.hosteurope.de/mirror/archive.mariadb.org/mariadb-10.3.9/yum//centos73-amd64/
Comment: Thank you, how would I add that repo to my centos 7 server?
Comment: @user1155594 Use a text editor to change the baseurl.


Adding and removing events handlers to html elemts

Question: My page consist of menu and body and both of them has div. When page opens I add to div elements event handler using "on" method and everything works fine. But body can be reloaded using ajax. I understand that div at body doesn't work and I want to add event handler to it.
I trying several thing but main problem is that when I add event handler to div it also added to div element at my menu. and when I click at menus div event fires two times. I trying use such construction
$('.div-element').off().on('click', function(){///});

but this has not any effect.
Please advice something.
Comment: Better would be to use delegation
Comment: ^^ what he said -> `$(document).on('click', '.div-element', function(){///});`
Answer: $(document).on('click','.div-element', function(){///});

Give a shot
Answer: Since the body is reloaded using ajax to make sure you retain the events you attached to div's inside body, you should use jQuery's delegated events. For example :
$('body').on('click', 'div', function(event){
//code for event handler
})

This will make sure that events added to div's are retained even after body reload.
Answer: Try this:
$('body').on('click','.div-element', function(){///});


Learn piano one hand at a time or simultaneously?

Question: I've started to teach myself how to play the piano, and one of the difficulties I've found is trying to get both hands to do things at once. I either forget one hand entirely, or have one hand trying to mimic the other.
This reminded me of many years ago when I was taught to play the viola. For many weeks, we did not use the bow, instead focusing on getting the left hand to do the things it was supposed to, and learning to read music. In hindsight, this makes sense to me, as it's often important to get used to some fundamentals before attempting to do everything at once.
So I was wondering, when learning the piano, is it better to learn each hand on their own, or muddle through the difficulties of synchronizing them from the beginning? Or, if there are arguments for both methods, what are the pros/cons of each? What problems may develop, or what difficulties might be avoided? Or is there perhaps a happy medium that has proven the most successful?
For my personal musical background, I have about nine years' experience with the viola, though I haven't played it in about five years (stopped after high school). I also play the guitar, but never learned to read music for it.
Comment: Whether or not you practice the hands separately, you must slow down to the point where you can play correctly when playing together.  Never practice a muddled confused mishmash, as doing so only makes you get better at getting it wrong.
Answer: When I was taking piano lessons I learned each piece three times: Once with the right hand, once with the left hand, and the third time putting both together. After a while, the third "learning" came a lot more quickly, and after a few years I would start to slowly sight read both parts together.
Today I will still practice the hard pieces one handed from time to time, especially when the timing is really disconnected between the two hands and I need at least one to go on automatic pilot. There are some pieces (Leyenda by Albeniz comes to mind) where the two parts are so intertwined it never makes sense to try to learn them alone. Usually that's clear from the beginning when it's the case.
Answer: There are actually two "schools of thought" about this. One (not so common these days, I think) that does not recommend practising one hand at a time, and the other uses "hands separate" a lot for learning purposes.
Personally, I have found hands-separate practice essential for learning pieces that I find difficult, although, as Todd rightly explains, there are some pieces where it doesn't work well because the piece doesn't really make much sense when playing only one hand.
I have a great belief in the teaching value of many of Bach's keyboard music, and read somewhere that in the first 2-part invention that he wrote (can be found on IMSLP) the fact that the individual hands take turns in playing the main theme is a sort of endorsement by Bach of the value of playing hands separately; almost as if he is suggesting that really is the best way to practice the piece.
Answer: The mantra in learning piano is: "start slowly." How slow is slow? So slow you are unable to make mistakes, and then a little slower than that.
Invariably when I have to choose a speed at which I think I can't make a mistake, at first I think: "come on, this is ridiculous!, of course I can't make a mistake"... and then I make a mistake.
As for the specific problem of hand coördination:
In the very beginning it helped me to practice away from the piano at first with my hands on my knees. For every note in my left hand I slapped my hand on my left knee and vice versa. When I could do that, I played the right hand on the piano and simultaneously moved my left hand in the air (or slapped it on my knee). After that I switched roles. The next step was playing with both hands at the same time, slowly.
After several weeks this kind of exercise wasn't needed anymore, but in the beginning I found it helpful to 'rewire my brain' so to speak.
Concerning hands separate versus hands together:
For any piece 'at your level' beginning with practising hands separate is needed. It's being used to tackle problems of reading, fingering, dynamics,..., before adding the extra complexity of having two hands to control.
But what I experience is that playing hands together after having practiced hands separate can feel as starting completely over. What I mean is that passages that were comfortable hands separate, are feeling clumsy again when starting hands together. Sometimes it is like having to learn the piece all over again. So the need to start slowly (and even slower than that) is there again but now hands together.
Because of that in my experience it is not efficient to practice towards 'perfection' hands separate before beginning hands together.
Of course the process of practicing hands together is greatly shortened (or even possible), because of the knowledge you gained from the practice hands separate, and that's what I use it for: orientation, experimentation and planning. But really learning the piece only starts with hands together.
Answer: It's very normal to have issues playing with both hands at first, but if you're finding yourself completely unable to do so at all, then maybe you're attempting to play music that's too hard for you.  This is a common problem for people that have significant experience on one instrument and then start another.  It feels embarrassing to go all the way back to basics and play stuff that you feel like is meant for 5-year-olds, but it really has to be done.  You're gonna play some Mary Had A Little Lamb, with the melody in the right hand, and single whole notes in the left.  There are some method books out there that have slightly more dignified music, if that helps.
Some struggle is good (it's the only way to grow), but hitting a wall isn't productive.
Answer: When I first started learning piano I also used to practice one hand at a time. I think it is important because then in the end it's all about coordination and if you want your hands to be well coordinated you first need each hand to know what it has to do.
Putting it all together is then a completely different story, you'll have to focus on the coordination and not on the single hand anymore plus you'll have to read 2 staff at a time (which might be tricky for someone which is not used to that), but indeed the practice that you gained playing with separate hands will help.
With experience and practice you'll do that more quickly and start putting it all together soon, however I still give a shot at each hand separately, I think it helps a lot. Of course with increasing difficulty of the piece you want to play you'll spend much more time practicing with two hands together. At times you'll have to focus on a small amount of bars when you'll have some difficult phrase (and then there are many ways which might help studying a single piece depending on the technique involved), which is also recommended when there are some particularly difficult parts in the piece (but I think this applies to the viola as well).
Answer: From my experience, beginning players (who start from not knowing how to read music at all) will play hands separately and then put them together. After you've gotten over some of the initial difficulty of just reading the music, I believe it's encouraged universally to learn/practice both at once. Of course, you can play separately to suss out some details, but on the whole, both hands should be played together. The faster you get used to playing and reading both lines-- difficult at first-- the better you will be equipped to handle more pieces that come your way. There is only a very tiny amount of piano works that are written for one hand, so really, it's in your best interest to just dive in.
The happy medium, in my opinion, is a 90-10 split. You start out playing with both hands (and pedal, don't forget those feet!). Then from playing, you figure out what you need to work on and separate as needed. This should mostly be from the technical standpoint, because to work on the overall interpretation, you really need all the parts together and playing each part individually isn't really going to help you much in the long run. I suppose, if you were working on a piece that was in the outer reaches of your technique, the split might become more even, but even then I don't think it should reach more than 60-40.
I'm originally a pianist, and then I got to the carillon, where similar to the organ, your feet move around a lot. It was hard for me learning an extra "line" (my feet), and it was always tempting to just practice the feet separately because it was so difficult for me and it slowed down my playing greatly. However, you move differently depending on what your hands AND feet are doing, so I became resigned to the fact that yes, no matter how excruciating, I need to play everything at once (and I do, so I'm intermediate sight-reader now). It's okay to play one at first to figure out what the melody is doing and what things you should emphasize, and just figure out the overall placement, but again, the piece is most improved when you play the entire piece, no matter how slowly at first, with all its parts and trappings.
Answer: I have never heard of one-handed practice actually being harmful for any piece of music, nor that it might teach you something you would later have to unlearn.
Slow practice and one-handed practice have both been essential to me on the piano, (although separating the limbs doesn't seem to help me on drums, interestingly), and one thing that helps very much in combination with them is dividing a bar up into a larger number of sub-beats, to understand it.
Imagine trying to tap out 2 beats per bar evenly on one hand, and 3 beats per bar evenly on your other hand.
If you subdivide the bar into 6 then one hand takes beats 1 and 4 while the other takes beats 1, 3 and 5. Many rhythms can be understood more easily that way, and practiced more slowly, on pretty much any instrument.
Large books full of short, graded exercises will not only strengthen your little fingers but prepare you for all sorts of confusingly counterpointed melodies.
Answer: I cannot gauge your piano level very well, but if you are having difficulties playing both hands at the same time, then the piece is may be too difficult for your level.
For piano players that are beyond the elementary level, I believe most players usually start learning the song both hands at the same time. This does help you get to learn the timing of the right and left hand right from the get go, instead of having to piece them together later on. Learning each separately and then piecing together later may actually be slower (depends on the piece) because of complex interweaving melodies, etc...
However, the practice is often done separately as needed. My piano teacher used to say if you cannot play the one hand alone, you definitely cannot play it properly with two hands. When practicing one-handedly, it will often reveal mistakes that you don't really notice while playing with two hands.
For elementary players, (at least from my experience), usually the learning process is just:

right handed songs;
primarily right handed songs with some added notes on the bass clef
more difficult songs with a more involved bass line for the left hand

That's why as I said earlier, perhaps if you are having difficulties of left and right handed songs, then maybe you are playing songs with a bass line that is too difficult at the moment for you.
One thing you can do to improve independent motor control with your hands is practice your left and right brain. The left brain controls the right hand and right brain for left hand. One exercise I was taught is to try rubbing your right hand on your thigh in a forward and backward motion (relative to a sitting position), and with your left hand do a upward and downward motion in a fist. Switch it up to have right hand as a fist, and left hand doing the rubbing. I know it sounds and looks retarded, but some people actually have difficulty because it involves independent directional motion.
Answer: I generally only practice certain passages one hand at a time, typically when I'm having trouble with something in one of the hands.  The more general rule is to isolate technical difficulties and work on them, which sometimes means working only one hand.  I especially do this when I'm working out what fingering to use on a passage.
I also find that, as I'm right-handed, I have to put more time into the left hand.  So, I often work with just the left hand.  Chopin Nocturnes are  a good example, because there are lots of leaps in the left hand that I tend to get sloppy with if I'm paying attention to the melody.
I wouldn't recommend going over just one hand in a really long passage all at once, though.  It's easy to lose your sense of the music, which can make the final result sound mechanical.
Answer: There are some beginning piano books that help one get the hang of integrating the two hands.  Here's what a piece in such a book might look like:
A melody is presented that straddles middle C.  (The hands are in the basic position where both thumbs play middle C.)  As the melody goes above middle C, the right hand becomes active, but the left hand stays in position, at the ready.  Within a couple of bars, the melody passes to the left hand, while the right hand rests.
There are other ways for the two hands to take turns, that was just an example.
As you progress with this approach, things will get gradually more complex.
I don't think you need to confine yourself to working with a book of this type, but it can be helpful to work with such a book alongside whatever other material you're working with.  It's a relatively painless way to get both hands working together towards a common cause.
You can find books that take this approach by browsing through the beginning piano books in a music shop.
Answer: That depends on the piece sometimes. My old teacher used to say practice one separately until you've got it down then "see" them together. Honestly, I'd recommend practicing one measure at a time by repeating one until you've got it and then move on. Lastly, play from the beginning after a few measures to smooth over any rough spots :)
Answer: Independence of both hands can be practiced by exercises of kinesiology e.g. cross-crawl.
There are many helpful links:
https://www.holistic-reflexology.co.uk/cross-crawl.html
A good exercise will also be to tap with one hand on your head while drawing circles with the other hand on your breast.
Every rhythm practice on your knees will also be beneficial.
Start two hands Piano playing with prelude no. 1 by Bach.


A union is connected, connected functions

Question: If A and B are connected subsets of a topological space X and $\bar{A}\cap B \neq \emptyset$, then $A\cup B$ is connected.
The picture is my teachers solution. I gave up a little to understand solution 1 (I looked at a question here and compared the solutions but still didnt get it) so I decided to at least understand solution 2. The thing I dont understand is the main steps in the proof, she shows that the restictions are connected, that the function is equal to zero (constant) but I dont get how this makes sense.
Answer: There is only one solution here (step 1 is just preparatory stuff). I'll attempt to add details, hopefully enough that you can grok it, along with some re-ordering to make things clearer.

We need to show that there is no combination of open subsets $U$ and $V$ of $A \cup B$ such that $A \cup B = U \cup V$ and $U \cap V = \emptyset$.
Firstly, note that $A \cup B$ not being connected is equivalent to there being a non-constant continuous map $f: A\cup B \to \{0,1\}$. We're going to assume that such an $f$ exists, and try to derive a contradiction.
What we know to start with is that $\bar{A} \cap B$ is non-empty, so we know that there is something in it: let $p$ be one such point. Without loss of generality, assume $f(p) = 0$ (else compose $f$ with the map swapping $1$ and $0$).
Now, since $B$ is connected, $f|_B$ must be constant, and since $f(p) = 0$, we must have $f(x) = 0$ for all $x \in B$.
And $f^{-1}(0)$ is a pre-image of an open set under a continuous map, so is open, and contains $p$, so is an open neighbourhood of $p$. B
ut since $p \in \bar{A}$, by definition of the closure, $f^{-1}(0)$ must intersect $A$, so there is some point $a \in A$ with $f(a) = 0$.
But $A$ is connected, so $f|_A$ is constant, so $f(x) = 0$ for all $x \in B$.
Combining this with the result three lines up, we have that $f(x) = 0$ for all $x \in A \cup B$, contradicting our assumption that $f$ is non-constant.
Thus, $A \cup B$ must be connected.
Comment: Thank you so much, so much clearer!
Comment: I dont really get why we need to say that we want to prove that there are no such sets U and V? Is it just not like saying that $A \cap B= \emptyset$?
Comment: Sure, you could word it that way (minus the typo). "For all open $A$ and $B$ such that $A \cup B = X$, we do not have $A \cap B =\emptyset$" is equivalent to $There do not exist open $A$ and $B$ such that $A \cup B = X$ and $A \cap B = \emptyset$. I don't see a particular reason to prefer the former over the latter.


On a quandle cocycle

Question: A quandle is a nonempty set $X$ on which there is defined a binary operation $(x,y) \rightarrow x*y$
satisfying the following properties.
(Q1) $x*x=x$, $\forall x \in X$.
(Q2) For any $x,y \in X$, there is a unique element $z \in X$ such that $x=z*y$.
(Q3) For any $x,y,z \in X, x*(y*z)=(x*y)*(x*z)$
Let $X$ be a finite quandle, and $G$ be
an abelian group written multiplicatively. A map $\theta:X \times X \times X \rightarrow G$ is called a
$3$-cocycle of $X$ with the coefficient group $G$ if it satisfies the following two conditions:
(i) $\theta(x,x,y)=\theta(x,y,y)=1_G$, for any $x,y \in X$.
(ii) For any $x,y,z,w \in X$
$\theta(x,z,w)-\theta(x,y,w)+\theta(x,y,z)=\theta(x*y,z,w)-\theta(x*z,y*z,w)+\theta(x*w,y*w,z*w)$
My question is the following:
Suppose $x*z_1=x*z_2=x$ and $y*z_1=y*z_2=y$, where $x,y,z_1,z_2$ are distinct elements in the quandle $X$. Then is the following equation true
$\theta(x,y,z_1)=\theta(x,y,z_2)$?
Any help is highly appreciated
Comment: Are you sure you have Q3 going in the correct direction? Not $(x*y)*z=(x*z)*(y*z)$?
Comment: yes, sorry for this confusing notation.
Answer: It seems to me that the answer is no. Take the trivial quandle $ x*y=x \,\,\,\,\forall x,y$, then the (second) cocycle condition is trivial, you should get a counter example with the trivial quandle on 3 elements

On a quandle cocycle