How to disable EDIT tab for webform?

Question: It would be great if anyone tell me how to disable EDIT Tab. I'm using Drupal 7.
I try with role permission, I successfully disable it for other submitter but failed to do the same for some submitter.
At the same time, I want that the submitter be able to change the workflow state, this is why i check all that permissions.
Thanks for the help.
Comment: Go to people >> permissions
Comment: What role is this? Everything is checked off.
Comment: A manager role with permissions to change workflow state of webform submissions without having access to edit the submission, i'm working with webform module
Comment: You may need to clear the cache after you changed the role permission,
Answer: For the roles in question, remove their ability to edit webform content types and make sure they don't have something like administer nodes checked off. It sounds like they may have too many permissions assigned to the role(s) that would cause the edit tab to appear. Also uncheck permissions pertaining to 'submissions' other than administrative roles.
Comment: I uncheck all role permissions pertaining to 'submissions' but nothing change, can the problem  be overcome from view access permissions ?
Answer: I had installed module tabtamer and it worked exactly like i want.

Tab Tamer is an administration utility that provides easy re-ordering, hiding, and deactivation of tabs and subtabs. You can also rename tab labels.

How to disable EDIT tab for webform?


Changing the delay timer? (c#)

Question: Short Question.
This is my Code.
var t = Task.Run(async delegate
{
    await Task.Delay(10);
    return 42;
});
t.Wait();

Thats what I will work with in General. But later in my Code I Need the delay to vary. I tried something like this already but I that does not seem right:
t.Wait(page*11);

(Whenever I click a button the variable "page" would Change. So Pretty much a new value everytime)
Comment: If all you're using the task for is the `Delay` method, and then using a blocking `Wait` on that task you might as well scrap the whole thing and just use `Thread.Sleep()`
Comment: `await Task.Delay(page*11);`?
Comment: I think he is misunderstanding the `Wait` parameters. It is for timeout but he seems to be understanding it as the amount of time to wait for?
Answer: You could declare a variable and pass it's value to the delegate you pass in Task.Run as below:
// define here the delayParam
int delayParam = 10;

var t = Task.Run(() =>
{
    await Task.Delay(delayParam);
    return 42;
});
t.Wait();

The return type of Task.Run is a Task<T> or just a Task if nothing it's returned. You can block on waiting the result of a Task, like you already do, by calling the Wait method. You can't pass arguments to the result...
Comment: You may as well just do `Task.Delay(delayParam).Wait();` instead of creating and waiting for `t`. Though I don't think `Wait()` should be used at all. Either `When()` in an async method or just use `Thread.Sleep()`
Comment: @p3tch of course you can do...just wanted to answer in the OP contex, in which he has used a block...Indeed your one liner in this specific case is fine.

Changing the delay timer? (c#)


Solving a partition function in polar coordinates

Question: The Hamiltonian for a particle is given by:
$$H_1 = \frac{P^2}{2m} + \frac{p^2_\theta}{2I} + \frac{p^2_\phi}{2Isin^2 \theta}$$
$I$ is the moment of inertia
$$I = \frac{mR^2}{4}$$
To get the partition function for one particle $Z_1(P, Q)$ the following integral has to be solved:
$$Z_1(P, Q, p_ \theta, \theta, p_\phi, \phi) = \int_ {-\infty}^{+\infty}\frac{dPdQ}{\lambda^3} dp_\theta d\theta dp_\phi d\phi e^{-\beta H_1}$$
Where $\lambda$ is  the thermal wavelength:
$$\lambda = h \sqrt{\frac{\beta}{2 \pi m}}$$
My issue here is that I do not know how to solve this 6 dimensional integral.
I am asked for the average energy < E >
$$\langle E \rangle = -\frac{ \partial \log(Z_1)}{\partial \beta}$$
Answer:
$$\langle E \rangle = \frac{5}{2\beta}$$
Comment: Z factorizes into 5 one dimensional Gaussian integral, the ensemble average over E becomes a sum of the 5 contributions, each one contributes $\dfrac{1}{2} k T$
Answer: With
$$H = \frac{P^2}{2m} + \frac{P_{\theta}^{2}}{2 m r} + \frac{P_{\phi}^{2}}{2 m r \sin^2\theta}$$
then
$$I = \int e^{- \beta H} \, dP \, dP_{\theta} \, dP_{\phi} \, dr \, d\theta \, d\phi$$
becomes:
\begin{align}
I &= \int d^{3}q \, \int e^{-\beta P^{2}/2m} \, dP \cdot \int e^{- \beta P_{\theta}^{2}/(2 m r)} \, dP_{\theta} \, \cdot \int e^{- \beta P_{\phi}^{2}/(2 m r \sin \theta)} \, dP_{\phi} \\
&= \int d^{3}q \, \left(\frac{2 m \pi}{\beta}\right)^{1/2} \, \left(\frac{2 m \pi r}{\beta}\right)^{1/2} \, \left(\frac{2 m \pi r \sin^2\theta}{\beta}\right)^{1/2} \\
&= \left( \frac{2 \pi m}{\beta}\right)^{3/2}  \, \int r^2 \sin\theta \, dr \, d\theta \, d\phi \\
&= 4 \pi \left( \frac{2 \pi m}{\beta}\right)^{3/2}.
\end{align}
This is how the integral is computed. The remainder is to add in the various constants and compute the average energy.
Comment: What I do not see is why you changed $R$ by $r$ with this equation: $R = 2 r$. Did you do it just for convenience (make the integral easier)? Note that without any change you get $\frac{2 p^2_\theta}{mR^2}$  in the second term (for instance)
Comment: The result of this integral $\int r^2 \sin\theta \, dr \, d\theta \, d\phi$ would not be $\frac{4\pi}{3}$ ?
Comment: More details if you are interested: http://physics.qandaexchange.com/?qa=3122/average-of-the-internal-energy-of-a-system


Regressing regression coefficients

Question: I'm looking for advice/opinion on whether the co-efficient(s) resulting from a geographically weighted regression analysis can subsequently be entered into an OLS regression as the dependent variable (i.e. to test for factors influencing the observed spatial variation). Are any major assumptions violated in doing so and, if so, are there any acceptable work-around?
Comment: I don't really understand your scenario but you could look at mixed-effects (multilevel, hierarchical) models. I've heard they're sometimes known as slopes-as-outcomes models.
Comment: I cannot understand:  "a geographically weighted regression analysis" means one model in the first step. Then you get estimates of one intercept and several slops. Just one observation, how to do regression again?
Comment: See  http://andrewgelman.com/2005/03/07/the_secret_weap/
Comment: Thanks for the responses. To clarify, the geographically weighted regression produces local coefficients for each IV for each case (1673 in total). In order to explore the causes of the variation I'm considering using a standard OLS regression with the co-efficients from the first step (the GWR) as the DV (n = 1673). I get meaningful estimates as a result but I'm unsure whether results from a geographically weighted model are suitable for subsequent inclusion in a linear model.
Answer: Regressing on OLS estimates runs against the (classical) assumptions of the model, which hold that the estimates are unknown constants that are estimated with data (which are random). So, if I understand the regression you are suggesting running, you would get some estimates but they would not have a formal interpretation. (Bayesians have the opposite view, that our estimates are random variables given the data.) Depending on the type of patterns you wish to test for, you may wish to look at spatial autocorrelation models (http://stats.idre.ucla.edu/other/mult-pkg/faq/general/faq-how-can-i-detectaddress-spatial-autocorrelation-in-my-data/) or hierarchical models (https://www.r-bloggers.com/hierarchical-linear-models-and-lmer/).

Regressing regression coefficients


Showing a collection of half open intervals generate a borel sigma algebra

Question: Let $\mathcal{H} = \{ (a, \infty) : a \in \mathbb{R} \} $. Let $\mathcal{B}$ be borel sigma algebra generated by the family of open sets. I have already shown that $\mathcal{B}$ is also generated by open intervals. Now I want to show that $\sigma( \mathcal{H} ) = \mathcal{B} $.
TRY:
We know intervals of the form $(a, \infty) $ are open sets. Hence, $\mathcal{H} \subseteq \mathcal{B} $ and so $\sigma( \mathcal{H} ) \subseteq \mathcal{B} $
If $\mathcal{I}$ is the collection of all intervals of the form $(a,b]$, we have shown in my class that $\sigma( \mathcal{I} ) = \mathcal{B} $. Consequently, if we can show that $\sigma( \mathcal{I} ) \subset \sigma( \mathcal{H} ) $, then we are done, and to do this it is enough to show that $\mathcal{I} \subset \sigma( \mathcal{H} )$. But this follows since we know
$$(a,b] =  (a, \infty) \cap (b, \infty)^c$$
Is this a correct solution?
Answer: Yes, that is a correct solution. However, I recommend writing it up in the other direction and in an assertive manner. Maybe like so:
Since for all $a < b$ we have $(a,b] = (a,+\infty) \cap (b,+\infty)^c \in \sigma(\mathcal{H})$. It follows that $\mathcal{I} \subset \sigma(\mathcal{H})$, and hence $\sigma(\mathcal{I}) \subset \sigma(\mathcal{H})$. By [cite lecture] we know that $\mathcal{B} = \sigma(\mathcal{I})$, thus $\mathcal{B}\subset \sigma(\mathcal{H}) \subset \mathcal{B}$, q.e.d.


Understanding Elasticsearch deployment in 2 server load balanced setup

Question: We have a two server load balanced ASP.NET MVC application that we're look to add search to - we like the look of Elasticsearch!
I'd like to build a bit of resiliency in so am considering installing ES on both servers and have them work like a cluster (which seems straightforward enough according the docs).
But I really want my MVC app to talk to "the cluster" not to each specific ES node, so if an ES node fails, or a server fails the application is unaffected:

Do I need to refer to the cluster in a special way from my application or setup some kind of internal domain for it?
I don't want to refer to "localhost:9200" or a server specific IP in my application I presume?
Answer: You should consider using the Elasticsearch .NET Client NEST. This client has built in support for failover connections when accessing an Elasticsearch Cluster.

If you want a failover client instead of passing a Uri pass an IConnectionPool see the Elasticsearch.Net documentation on cluster failover all of its implementations can also be used with NEST.
Comment: Never even considered there might be this capability - thanks Paige!


Find the number of non negative intagral solutions of $x+2y+z = 100 $. Given that $x, y, z \geq1$.

Question: I have taken the following approach using combinations.
I am considering $2y$ to be one object say $k$.
So now I will have the equation : $x+k+z = 100$
and the conditions : $x,z \geq1 $  and $k \geq2$.
Then in order to use the formula for distributing
  $n$ alike objects I convert this equation into
$X+K+Z =96$
where $X = x-1, K = k-2, Z = z-1$
and $X, Y, Z \geq0$
Now applying the formula for distribution of $n$ alike objects which is :
$\frac{(n+r-1)!} {n!(r-1)!} $
$\frac{(96+3-1)! }{96!(3-1)!}   = 4753$
But the answer is supposed to be $2401$
Why is this method wrong and what is the right way for solving this problem?
Comment: Your question says 'non-negative' then specifies $\ge1$, so you should be asking for 'positive integer solutions'
Answer: The problem with your solution is that you assumed k can be anything but in fact k must be even. Here is my solution:
Consider the parity of $x$ and $z$.
if $x$ and $z$ are both odd: then let $x=2m+1, z=2n+1.$ Then $m+n\le48.$ There are $$49(m=0)+48(m=1)...+1(m=48)=1225$$ ways to choose $m+n$.
if $x$ and $z$ are both even: then let $x=2m, z=2n.$ Then $m+n\le49.$ There are $$ 48(m=1)+48(m=2)+...+1(m=48)=1176$$
Therefore the answer is $1225+1176=2401$
Answer: Modifying abc...'s answer:
Case $1$ ($x$ and $z$ odd), letting $x=2m-1$ and $z=2n-1$:
$$2m+2y+2n=102\to m+y+n=51\to\binom{50}{2}=1225$$
Case $2$ ($x$ and $z$ even), letting $x=2m$ and $z=2n$:
$$2m+2y+2n=100\to m+y+n=50\to\binom{49}{2}=1176$$
Total positive integer solutions:$$1225+1176=2401$$
Answer: Alternatively, when $y=1,2,3,...,49$, it is the sum:
$$\sum_{y=1}^{49} {100-2y-1\choose 2-1}=\sum_{y=1}^{49} (99-2y)=99\cdot 49-2\cdot \frac{1+49}{2}\cdot 49=2401.$$


ionic build produces wrong apk filename

Question: using ionic (v 1.0.0.-beta.13), cordova 4.0.0.  When I build for android, the name of the apk produced is "CordovaApp.apk", rather than ".apk", which it was "previously" (before some updates to ionic, cordova, and a delete/add of the android platform in my project).  The project name in my config.xml (in the project top level directory) is correct.
I can see the build.xml in my android platform directory specifies this, but this file is overwritten by the "ionic build" each time, so changing it there doesnt fix anything...
Answer: check following link, its the problem with Cordova version- 4
http://forum.ionicframework.com/t/android-buid-apk-file-with-name-is-cordovaapp-apk-instead-of-widget-name/12255
Answer: build.xml should contain apk name, to change that you should do:
<code>android update project --name your_name --path
</code>

ionic build produces wrong apk filename


Fitting response surface using rsm package in R - Lack of fit test is missing

Question: I am trying to fit an rsm model to a data set with three factors, to try to find optimum parameters of a simple empirical environmental model for disease risk prediction, or influence of a change in each predictor. I am not really sure how to make a reproducible example so I will try to describe what I am doing.
My data looks like:
    rh_thresh temp_thres hours       auc
           93         11    11 0.6198718
           87          5    15 0.6256410

And is stored:
    Data are stored in coded form using these coding formulas ...
t ~ (temp_thres - 10)
rh ~ (rh_thresh - 90)
h ~ (hours - 12)

My independent variable is area under the curve of empirical ROC. Values are ranging from 0.6 to 0.82.
I have fitted second order model using SO function from rsm package.
Problem is that I dont get lack of fit test. Summary of the model fit:
Call:
rsm(formula = auc ~ SO(t, rh, h), data = cd_data)

               Estimate  Std. Error  t value  Pr(>|t|)
(Intercept)  0.73647659  0.00219900 334.9145 < 2.2e-16 ***
t            0.00465510  0.00059000   7.8900 1.127e-14 ***
rh          -0.01554212  0.00059000 -26.3424 < 2.2e-16 ***
h           -0.01402361  0.00059000 -23.7687 < 2.2e-16 ***
t:rh        -0.00144076  0.00015847  -9.0917 < 2.2e-16 ***
t:h         -0.00152461  0.00015847  -9.6208 < 2.2e-16 ***
rh:h        -0.00150469  0.00015847  -9.4950 < 2.2e-16 ***
t^2          0.00046880  0.00018059   2.5958  0.009628 **
rh^2        -0.00167358  0.00018059  -9.2671 < 2.2e-16 ***
h^2         -0.00190715  0.00018059 -10.5604 < 2.2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Multiple R-squared:  0.6838,    Adjusted R-squared:  0.6799
F-statistic: 172.8 on 9 and 719 DF,  p-value: < 2.2e-16

Analysis of Variance Table

Response: auc
               Df  Sum Sq  Mean Sq F value    Pr(>F)
FO(t, rh, h)    3 0.88339 0.294462 361.896 < 2.2e-16
TWI(t, rh, h)   3 0.21592 0.071975  88.458 < 2.2e-16
PQ(t, rh, h)    3 0.16610 0.055367  68.046 < 2.2e-16
Residuals     719 0.58502 0.000814
Lack of fit   719 0.58502 0.000814
Pure error      0 0.00000

Stationary point of response surface:
         t         rh          h
-7.3837482 -1.3846032 -0.1790263

Stationary point in original units:
temp_thres  rh_thresh      hours
  2.616252  88.615397  11.820974

Eigenanalysis:
eigen() decomposition
$`values`
[1]  0.0007978626 -0.0010301864 -0.0028796105

$vectors
         [,1]        [,2]       [,3]
t   0.9540713 -0.02300125 -0.2986952
rh -0.2143994 -0.74880338 -0.6271574
h  -0.2092386  0.66239296 -0.7193433

I guess the problem is over-saturation, but how do I report this? I do not have replicates.
Answer: I don't see a terrible problem here. You don't have replications, and that is why there is no estimate of pure error or test of lack of fit. But a response-surface model is just a regression model, and people fit regression equations to unreplicated data all the time. They just use the residual error as the denominator of tests (as is done in the output that is shown).
A separate issue is whether it is a good model. You should do a lot of residual plots (see any regression textbook) to explore this. You might also try a third-order model to see if it makes a significant improvement to the fit. Something like:
mod3 = lm(auc ~ poly(r, rh, h, degree = 3), data = cd_data)
anova(mod3, mod2)

where mod2 is the model you summarize here. If significant, that'd be a similar finding to having a significant LOF test.


Where can be stored MySQL data directory?

Question: So, where can be stored the MySQL data directory?
I mean the type of destination location: is outside BASEDIR ok? should be same partition? same disk? maybe a temporary RAM partition is also fine? NFS partition? symlinked to one of these? etc.
Answer: Anywhere that the mysql user can access it is fine. It's just a directory with files, that are read and written normally - there is nothing special about them. It can be a different partition, or even a different disk (e.g. SSD is a good idea). NFS will work, but make sure it's quick (for obvious reasons, really). Symlinks are also perfectly acceptable.
I have run MySQL from a ramdisk before, and it worked perfectly.
Comment: ..with the caveat that selinux or apparmor rules may need to be modified to allow mysql to read/write to the new location.
Comment: @Jay: There are different pieces of software or APIs that have some restrictions (to be same partition, etc.) and probably the reasons are subtile. Well, if MySQL has no such restriction, this is a good news, thanks. BTW, is this subject described somewhere in the official docs?
Comment: That may well be true, but just answering the question with "no" would not have been very useful, so I elaborated. You can probably start here: http://dev.mysql.com/doc/refman/5.0/en/multiple-data-directories.html


what is the difference between a flat 5 and a sharp 11

Question: I was looking at the chords from Blue in Green and Misterioso and in one there is a B flat major 7 sharp 11 which can be played b flat, D,E,A (those are notes)
And in the other there is a B flat 7 flat 5 which can be played B flat, D,E,A flat.
So what if we had B flat major 7 flat 5 instead of the second chord. Would the two be the same? Or does sharp 11 mean we shouldn't necessarily omit the 5 and play B flat, D,E,F,A?
Answer: Chord symbols are meant to primarily tell us what the sound should be a given place, and so a Jazz musician would have different interpretations of a (for example) C7#11 compared to a C7b5. Yes notes can be and often are omitted in voicings but remember, first, that chords are built from the root up through its extensions. This means that the basic triad sound of a Bbmaj7#11 versus a Bbmaj7b5 is already different, as the basic triad of a Bbmaj7#11 chord is Bb-D-F, and of a Bbmaj7b5 is Bb-D-Fb, leaving out a stable sounding fifth in the chord entirely (if you sit down and play these on piano, you'll also notice that maj7b5 chords sound very dark in comparison to maj7#11 chords; the natural fifth does indeed make a difference). Now they both might imply a Lydian-ish sound, but in the second chord (Bbmaj7b5) the flatted fifth has entirely displaced the natural fifth also meaning that if I play a natural fifth over the chord's flatted fifth, it will destroy the chord's actual quality, and will probably clash too. Conversely, playing the fifth in a Bbmaj7#11 will not destroy or alter the basic sound of the chord. As far as interpreting the chord symbols, going back to the C chords from earlier, I might interpret the chord scale of a C7#11 as C Lydian Dominant as the Lydian dominant scale has a natural fifth, a flat seven, and a sharp eleven, and over a C7b5 I might play the C whole tone scale as the whole tone scale has a flat fifth and seventh, but no natural fifth whatsoever. The Lydian dominant scale and the whole tone scale are very different sounds, so even though two chords might have "similar" constructions and similar voicings, they can imply very different overall sounds.
Comment: Yes, the flat-5 would suggest to me to omit the (unflatted) 5, and also put the note lower in the voicing... in contrast to sharp-11 which suggests to me to put that note higher in the voicing, and maybe include the (unflatted...) 5.
Answer: Above a root of B♭ an 11th will be E♭.
Above a root of B♭ an 5th will be F.
The alteration of those intervals should use the appropriate letters E for any quality 11th or F for an quality 5th.
Above a root of B♭ an ♯11th will be E♮.
Above a root of B♭ an ♭5th will be F♭.
Now you can spell the three chords:

B♭Δ7♯11 : B♭ D E♮ A♮
B♭7♭5 : B♭ D F♭ A♭
B♭Δ7♭5 : B♭ D F♭ A♮
Answer: To belatedly answer OP's questions:
-yes b5 and #11 refer to the same note (they are enharmonically equivalent);
-yes a #11 implies the 5th will not be altered.


Passing a Variable as a Type WITHOUT using Reflection: 'myvar' is a variable but is used like a type

Question: I've got a simple method that deserializes an xml string to a type that is specified.
public static class TextUtility
{
    public static T Deserialize<T>(string xml)
    {
        ...
    }
}

That's all good.  Where I'm having trouble is in calling this method.  The process looks like this:
public interface IMessageReceived
{
    string MessageBodyAsXML { get; set; }
    string MessageType { get; set; }
}

public class MessageReceived : IMessageReceived
{...}

List<MessageReceived> messageList = new List<MessageReceived>();

Then, in the worker class that is processing the messages, we loop over all the messages received.  Inside that loop, we loop over a list of potential message types.
foreach (MessageReceived message in messageList)
{
    foreach (var processor in processors)
    {
        if (processor.TypeToProcess.Name == message.MessageType)
        {
             // Now Create an instance of 'processor' from message.MessageBodyAsXML
        }
    }
}

I tries this:
object messageObject = TextUtility.DeserializeMessage<object>(message.MessageBodyAsXML);

And it kinda works, but the generic 'object' causes problems down stream.  I need to be more tightly coupled. I can do this:
Type type = processor.GetType();

And that does populate 'type' with the correct type. But then obviously I can't do this:
type messageObject = TextUtility.DeserializeMessage<type>(message.MessageBodyAsXML);

I am trying hard to avoid a long if/then for each type. Open to ideas.  Thanks!
Comment: Possible duplicate of [How do I use reflection to call a generic method?](http://stackoverflow.com/questions/232535/how-do-i-use-reflection-to-call-a-generic-method)
Comment: There *are* ways to switch from reflection (type-based) code into static (generic-based) code, but it is rarely worth it; the most obvious solution here would be: don't use generics at this point. Do you need that?
Comment: Avoiding generics is exactly what I'm trying to figure out how to do!
Answer: Obviously for such dynamic purposes where you don't know the type at compile-time you will need to provide an overload of your Deserialize method:
public static object Deserialize(Type targetType, string xml)
{
    ...
}

Comment: Wow, isn't passing a type as a normal parameter kind of defeating the purpose of Type Parameters? But this is probably Microsoft's fault, not yours.
Comment: ok, this is making sense.  I may start a new thread on how to write the overloaded method, if I need help with that. Thanks!
Comment: Sure, the implementation would depend on the specific XML serializer you are using but if you are using the standard `XmlSerializer` you could specify the target type when instantiating it: `var serializer = new XmlSerializer(targetType)`.


RecyclerView items clicking while scrolling

Question: I have a RecyclerView. Inside its adapter's onBindViewHolder() I set the OnClickListener to the ViewHolder's root layout.
However, I've recently noticed that I can't click on the RecyclerView's items while it's being scrolled. Only after it's stopped. If I click somewhere on the RecyclerView while I'm scrolling it, the RecyclerView only stops at that position, no items are clicked.
You can see what I mean inside the Gmail app. You can't open any email while you are scrolling its RecyclerView.
However, the Google Play app behaves differently. You can open app pages while scrolling the lists of apps. You can even scroll inner RecyclerViews horizontally while the parent RecyclerView is being scrolled.
Also I've noticed the same behaviour for a ScrollView. For example, if you put a lot of buttons inside it and begin to scroll it, the button listeners are not triggered. They can be triggered only after the ScrollView is stopped completely.
Do you have any idea how it's possible to achieve the behaviour like in the Google Play app? Thank you!
Comment: check [this](https://stackoverflow.com/questions/43435622/disable-touch-events-on-recyclerview-while-using-using-smoothscrolltoposition) may be helpful
Comment: @VikasTiwari Hi, Thank you for editing the post!
Answer: Here's a code written by Kimi Chiu in a related question:
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
    boolean requestCancelDisallowInterceptTouchEvent = getScrollState() == SCROLL_STATE_SETTLING;
    boolean consumed = super.onInterceptTouchEvent(event);
    final int action = event.getActionMasked();

    switch (action) {
        case MotionEvent.ACTION_DOWN:
            if( requestCancelDisallowInterceptTouchEvent ){
                getParent().requestDisallowInterceptTouchEvent(false);
                // stop scroll to enable child view get the touch event
                stopScroll();
                // not consume the event
                return false;
            }
            break;
    }

    return consumed;
}

If you subclass the RecyclerView class and override this method, it will behave as in the question.
Answer: You need to enable the "nested scrolling" flags inside of your scrolling parent. This is typically what you'd do if you want a horizontal scrolling recycler view inside of a vertical scrolling parent recycler view. You can do this for any scrolling view in general.
Answer: Don't do this. Think about the user experience. You want to be able to allow users to scroll without them accidentally clicking to open new windows or details. Android users expect scrolling to prevent clicking. Once you stop, then you expect clicking to show details. You can certainly accomplish this if you want by overriding the onTouch and deciding how to handle the touch event if it is supplied to the recycler view or the row items, but I think you are creating a bad user experience. I tried the app store, it stops when you touch it as well Not sure what you meant by scrolling while open click or horizontal scroll because if I scroll vertically and then swipe left it just changes the page viewer.
So maybe not the answer you want, but I think User Experience is more important than "cool effect of touch while scrolling" management. If Android wanted that to be their OS experience it would be built in. Now this isn't the case for everything like swipable row items, but default master detail list handling is pretty standardized.
Comment: Hi Sam, thank you very much for your suggestion! You are right about the User Experience. I had some similar thoughts. However, in fact I need something similar to the Google Play app's viewpager. I didn't try to explain that in my original question, because it would complecate it. I have kinda 2-3 pages with RecyclerViews and I can't swipe between them freely when I'm stuck during some RecyclerView's scrolling process (it's possible to swipe to the next page only when the scrolling is completely stopped). So, I thought maybe someone has a prepared workaround for this case.
Comment: Oh gotcha, ok that makes more sense. Although, I have many apps that have pageviewers with nested recyclerviews and none of them prevent my from swiping between pages while flinging the list. So I'm not sure why yours would behave that way. So you are saying if you fling the list and then swipe it will ignore your swipe?
Comment: Hm, that's strange. Maybe I've done something wrong. Yes, you are right, in my case I have to wait before I can swipe to the next page... Also I have another part of the app where there is a ViewPager and each page is simply a ScrollView with several TextViews (like a tutorial). It also behaves that way. If I fling one page and try to swipe to the next page, I can't. I've tried the same on another phone with Android 4.1.2 (the first one has Android 7.0). It behaves the same way...
Comment: ok so that is different then. Are you dealing with scrollviews per pageview or recycler views? Does it work fine for recycler view pages, just not scrollview pages?
Comment: Well, there are two different Activities. One has a ViewPager with Fragments based on a RecyclerView. And another Activity has a ViewPager with Fragments based on a ScrollView. Both variants behave the same. If you start scrolling on a page and immediately try to swipe to the next page (like the initial scrolling is still in process), it can't swipe.
Comment: That is strange. I have never seen that behavior. I'm afraid I don't know how to help you as I wouldn't know how to repeat it without investing many hours trying lol. But best of luck and if you find out what it was, post your own answer so we can learn from it in case we ever hit that. I still think something is off though as I don't have this issue on any of my apps. So seems weird.
Comment: I've tried a couple of apps. It looks like most of them behave the same way... Other than Google Play, only Aliexpress can swipe freely, and only from the second page to the first one. So I guess there should be some workaround to achieve this free swiping :)
Comment: Okay Sam, I understand you. Thank you very much for trying to help me!
Comment: If anyone is reading this thread and is interested, you can subclass the ViewPager and override its `requestDisallowInterceptTouchEvent` method to make it empty.
Answer: Only make the recyclerView react to click events when it is not scrolling:
if (recyclerView.scrollState == SCROLL_STATE_IDLE) {
    onItemClicked()
}


Solving $x([\frac{x}{2\pi}]+1)=100$ algebraically

Question: I wonder how to solve this equation  $x([\frac{x}{2\pi}]+1)=100$ with algebra. Here $[ ]$ is the integral function. I can use trial and error to find out integral solution say $x=25$ but it seems I can't easily show with algebra that there is only one solution existing.
Comment: Note that $\lfloor \frac{2\pi}{x}\rfloor+1$ is nondecreasing and $\frac{100}{x}$ is strictly decreasing. As $x=0$ is not a solution, if the system has a solution(in which 25 is one), then it must have just one positive solution and at most one negative solution. It seems that there is no negative solution by graph, though.
Comment: well, floor(x/2pi) + 1 must be integer, so x must be a factor of 100 also. you only need to check factors of 100
Comment: @qwr Not really, a rational number times integer can also be an integer, what if $a$ is a rational number say $\frac{100}{21}$ and $[x/2\pi]+1]=21$. I knew this is not a solution but $a$ can definitely be some non-integral values sometimes
Comment: ok what about putting bounds on floor(x/2pi). then you should see only a small range of numbers could work
Comment: What's the integral function?
Answer: Your question resembles a lot like: find the zeroes $y=x \cdot (\frac{x}{2 \pi} + 1) - 100$. You might expect a parabola-like graph, and indeed, this is what the graph looks like:

So, your question comes down to the question: are there one or two zeroes?
Answer: We denote $\left[ \frac{x}{2\pi} \right]$ by $\left\lfloor \frac{x}{2\pi} \right \rfloor$. Let $n = \left\lfloor \frac{x}{2 \pi} \right \rfloor$. We have $n \neq 0$. Also note that $2\pi(n-1) \le x < 2\pi n$ and $x= \frac{100}{n}$. Therefore, for each integer satisfying $\pi n - \pi \le \frac{50}{n} < \pi n$, there corresponds a unique solution. This inequality is equivalent to
$$
-5 \sqrt{\frac{2}{\pi }}<n\leq \frac{1}{2}-\frac{1}{2} \sqrt{\frac{200+\pi }{\pi }}\lor 5
   \sqrt{\frac{2}{\pi }}<n\leq \frac{1}{2}+\frac{1}{2} \sqrt{\frac{200+\pi }{\pi }}
$$
which reduces to, approximately,
$$
-3.98942<n\leq -3.52063\lor 3.98942<n\leq 4.52063
$$
Therefore, the solution of the equation $ x\left( \left\lfloor \frac{x}{2π} \right\rfloor +1 \right)=100 $ is unique.
Remark 1: The value of the unique solution is $x=25$.
Remark 2: One can argue by dividing the cases $n<0$ and $n>0$ separately and using monotonicity of the function; $n \le -1$, the function is apparently decreasing and $n \ge 1$, the functionn if apparently increasing. Sketching the graph for $-4 \le n  \le 4$ should be enough.
Answer: For all real $w$,
$$\lfloor w \rfloor \le w <\lfloor w \rfloor + 1. \tag{2}$$
So
$$w < \lfloor w \rfloor + 1 \le w + 1. \tag{3}$$
This gives rise to two cases of interest:
$$\begin{cases}w^2 < f(w) \le w(w+1), & w > 0 \\ w(w+1) \le f(w) < w^2, & w < 0, \end{cases} \tag{4}$$
where
$$f(w) = w(\lfloor w \rfloor + 1). \tag{5}$$
The given equation corresponds to solving $f(w) = \frac{50}{\pi}$, where $w = \frac{x}{2\pi}$.  Hence we have the bounds
$$\begin{cases}w^2 < \frac{50}{\pi} \le w(w+1), & w > 0 \\
w(w+1) < \frac{50}{\pi} \le w^2, & w < 0, \end{cases} \tag{6}$$
which in turn implies
$$\begin{cases} \frac{-1 + \sqrt{\frac{200}{\pi} + 1}}{2} \le w < \sqrt{\frac{50}{\pi}}, & w > 0 \\
\frac{-1 - \sqrt{\frac{200}{\pi} + 1}}{2} < w \le -\sqrt{\frac{50}{\pi}}, & w < 0,\end{cases} \tag{7}$$
hence
$$ \lfloor w \rfloor  \in \{-5, -4, 3\}. \tag{8}$$
We now address each case individually:
$$\begin{cases}
x \in (-\pi - \sqrt{\pi(\pi+200)}, -8\pi), & \lfloor w \rfloor = -5, \\
x \in [-8\pi, -10\sqrt{2\pi}], & \lfloor w \rfloor = -4, \\
x \in [6\pi, 10\sqrt{2\pi}), & \lfloor w \rfloor = 3. \end{cases} \\ \tag{9}$$
All that remains is to now evaluate $$\frac{100}{\lfloor w \rfloor + 1}$$ for each case and determine which intervals contain this value, hence admits a solution.
The first case requires $x = -25$, but $-8\pi < -25$, so no solution exists in this interval.
The second case requires $x = -\frac{100}{3}$, but $-\frac{100}{3} < -8\pi$, so again, no solution in this interval.
The last case requires $x = 25$, which is just barely inside the interval, as $25 < 10 \sqrt{2\pi}$.  Therefore, $x = 25$ is the unique solution to the equation.


Unexpected token: operator (>) | update or replace uglify-js to handle ES6?

Question: This is my first time building an a-frame app with react and when running npm run-script build in my cmd prompt I come across this error.
Failed to compile.

static/js/main.9516bce8.js from UglifyJs
Unexpected token: operator (>) [./~/aframe/dist/aframe-master.js:57303,0][static/js/main.9516bce8.js:80512,32]

"aframe": "^1.0.4"
"webpack": {
  "version": "2.6.1",
  "resolved": "https://registry.npmjs.org/webpack/-/webpack-2.6.1.tgz",
  "integrity": "sha1-LgRX8KuxrF3zqxBsacZy8jZ4Xwc=",
  "requires": {
    "acorn": "^5.0.0",
    "acorn-dynamic-import": "^2.0.0",
    "ajv": "^4.7.0",
    "ajv-keywords": "^1.1.1",
    "async": "^2.1.2",
    "enhanced-resolve": "^3.0.0",
    "interpret": "^1.0.0",
    "json-loader": "^0.5.4",
    "json5": "^0.5.1",
    "loader-runner": "^2.3.0",
    "loader-utils": "^0.2.16",
    "memory-fs": "~0.4.1",
    "mkdirp": "~0.5.0",
    "node-libs-browser": "^2.0.0",
    "source-map": "^0.5.3",
    "supports-color": "^3.1.0",
    "tapable": "~0.2.5",
    "uglify-js": "^2.8.27",
    "watchpack": "^1.3.1",
    "webpack-sources": "^0.2.3",
    "yargs": "^6.0.0"
  },

based on my research i'm guessing the version of uglify that i'm using doesn't support ES6
but I can't find anything online that can help me update or replace uglify-js to handle ES6
Answer: You can update it with
npm update uglify-js
which updates the package to the latest version that satisfies it version tag.
If this new version does not work, you can update it to a specific version
npm update email@example.com
or just update it to the latest one
npm update uglify-js@latest
Be careful because updates might break some existing code
Comment: This change did nothing, doesn't work.
Answer: terser-webpack-plugin works for me using webpack v4. it does support ES6+
Comment: Hey, so I tried installing terser-webpack-plugin but i'm still getting the same uglify error?

I did the following steps - (1) npm uninstall webpack (2) Deleted the node-modules folder and the package-lock.json file from your project's folder. (3)  npm install terser-webpack-plugin --save-dev (4) npm install (5) npm install firstname.lastname@example.com (6) npm uninstall uglify-js.
Comment: not sure if it is something do with webpack version, i am using webpack v4 and it works. hope some more experienced people will help, good luck


Android - VerifyError

Question: this is an error I am getting in Android Developer Console from hundreds of my users.
I've spend entire day trying to fix the issue in code and it took 9 releases and I am still getting these error reports. My application has about 5 thousand downloads a day and on about 10% of the devices it's crashing. Rating of my application went down from 4.7 to 3.0 in just one day because of this.
I literally can't figure this out.
I am at the point of letting someone actually remote connect to my machine and pay to look at it.
Anyhow, long story short. I've done an update in code last night and I've uninstalled google ads from my app. Added little bit of code and released app to android market. This morning I had 200 error reports. App is crashing on many devices.
I went to error reports and this is what most people are getting:
java.lang.VerifyError: a.xml.a$Searching
at a.xml.a.startTalkingActivity(a.java:849)
at a.xml.a.onActivityResult(a.java:1053)
at android.app.Activity.dispatchActivityResult(Activity.java:3890)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3511)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3557)
at android.app.ActivityThread.access$2800(ActivityThread.java:125)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2063)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
at dalvik.system.NativeStart.main(Native Method)

I've put ads back in, but error keep coming. I've removed code I've added, error still there and getting more angry reviews complaining of crashing on a button press.
I am going crazy here, I'd appreciate any help with this. I can't figure out what this error means.
Comment: Basically, class `a.xml.a$Searching` could not be "verified".  Something about the class is wrong, though you don't get much of a clue as what it might be.  (Almost as frustrating as "NoClassDefFoundError".)  Most likely there is a mismatch between your class and another class in a jar file on the device, in terms of types on a method call, etc.  This happens when the jar version changes in a non-compatible fashion (which unfortunately is not uncommon).  You may get some clue if you categorize the failures by phone brand, type, and Android version -- may be a brand or version that fails.
Comment: Are you using ProGuard obfuscate your source? try build application without obfuscate your code.
Comment: Sorry, how do I do that? And do I really want to release code of my app unobfuscated?
Comment: I didn't ask you publish it, if you are using ProGuard/obfuscating, try build without obfuscating and test it, to see if it is actually caused by obfuscating.
Comment: Ok sorry, maybe I didn't explain, that I can't reproduce this on my own Android devices, crashing comes from a small group of my users. About 10% of them, and I have a feeling it's 2.2 Android and below, but I can't be sure, because Google won't give me those stats.
Comment: It seems that only Android 2.2.x are having the problems, any way to find out why it would be only happening on those devices?
Comment: To yorkw: in my case, the VerifyError appear when obfuscating code and running it in 1.6 (real machine and emulator). it disappear whitout obfuscating.
Answer: You appear to have a Searching inner class of the a.xml.a class. That Searching inner class is referring to something that does not exist on the users' devices, even though it existed in your build target.
You might temporarily drop your build target to be the same as your minSdkVersion (if it isn't there already) and see if anything turns up in this class.
Beyond that, try to find common characteristics of the devices on which the app is failing (e.g., OS version).
Comment: It is so extremely frustrating,... I've spent entire day and still have no clue what it could be, nor exactly how to approach this issue.
Comment: @jjj: You could start by following the instructions in the second paragraph of my answer. Or, try running your application in older emulators to see if you can reproduce the problem (should occur the first time you try referring to `a.xml.a`). Or, paste the source code to `Searching` into your answer so others can review it.
Comment: Searching source code has about 2000 lines. But could this have something to do with my own machine? I can't see anything I've done in code. Java update? Some Eclipse update or change?
Comment: @jjj: "But could this have something to do with my own machine?" -- no. "I can't see anything I've done in code." -- then use your version control system to roll back to a known good version of the code.
Comment: I found that issue is somehow related to prior vs. 2.3 of Android. I've released my app with this limit and I get no more errors. Not a solution, but hey...
Comment: I've fixed the issue, had to cut the class to smaller chunks, it was too long.
Answer: I just wanted to give my solution to this problem, since I haven't really found this anywhere else.
I was able to solve the issue by double-checking the build path of the project. I always get the error when I forget to export external libraries. Hope this helps someone :-)
Answer: I've fixed the issue, had to cut the class to smaller chunks, it was too long.
Comment: Then you should mark this post as the right answer (green checkmark). Maybe you could give some details on your solution also.
Answer: I had the same problem after doing the Android ADT and Java updates. Try these steps:

Remove links to your external libraries in your Android project.
Move all your external libraries (including Google Ad libraries) to \libs folder inside your Android project.
Re-link your libraries, that now exist in the Project\libs directory.

Android - VerifyError


Find the asymptotic distribution of ${\theta}_{MLE} =\frac{-n}{\sum _{i=1}^{\infty}\ln(X_i)}-1$

Question:
We are given $f(x|\theta) = (\theta  + 1)x^{\theta} , \hspace{7mm} 0<x<1, \theta > -1.$
By considering the asymptotic distribution  of $\frac{1}{\theta_{MLE}+1}$,  find the asymptotic distribution of $\theta_{MLE}$.

My attempt:
I have worked out that the MLE to this question is $$\theta _{MLE} = \frac{-n}{\sum _{i=1}^{\infty}\ln(X_i)}-1$$
and I also worked out that $-\ln(X_i)$ $\sim \exp(\frac{1}{\theta + 1})$
Now, $$\frac{1}{\theta_{MLE}+1} = \frac{\sum _{i=1}^{\infty} -\ln(X_i)}{n}$$
I don't know how to proceed from here as the question asks for asymptotic distribution for $\theta_{MLE}$ yet what can I extract from  $\frac{1}{\theta_{MLE}+1}$ ?
How do I compute the asymptotic distribution for a question like this?
Comment: Use central limit theorem on $-\ln X_i$ (the sum you have written should be a finite sum, so $i$ runs from $1$ to $n$ assuming you have a sample of size $n$). That would give you asymptotic distribution of $1/(\theta_{MLE}+1)$. From there, you would need to apply the 'delta method' to get the limiting distribution of $\theta_{MLE}$.
Answer: Note that you know the exact distribution of the MLE, $\hat{\theta}$. Namely, as $-\ln X_i = Y_i$ has an exponential distribution with $\theta+1$, that is
$$
f_Y(y)=(\theta+1)\exp\{ - y(\theta+1)\}, \quad y>0,
$$
thus $ \sum Y_i $ distributed Gamma with $n$ and $\theta + 1$. So $(\sum Y_i)^{-1}$ has an inverse  Gamma distribution with the same parameters. As such,
$$
\hat{\theta}_n = n/\sum Y_i - 1 \equiv n\times \mathrm{InvGamma(n,\theta+1) -1}.
$$
For the asymptotic properties define $g(x) = 1/x -1$, thus the MLE is
$$
\hat{\theta}_n = g(\bar{Y}_n) = 1/\bar{Y}_n-1,
$$
by the continuous mapping theorem
$$
g(\bar{Y}_n) \xrightarrow{P}g(\mathbb{E}Y)=(1/(\theta + 1))^{-1} - 1= \theta,
$$
hence by the CLT
$$
\sqrt{n}( g(\bar{Y}_n) - \theta)\xrightarrow{D} N(0, (g'(\theta))^2/(\theta+1)^2),
$$
where $(g'(\theta))^2 = 1 / \theta ^ 2$.


A sequence converging uniformly to 0 so that Fatou's Lemma is a strict inequality

Question: I have to find a sequence of measurable functions such that it converges uniformly to zero but Fatou's Lemma is a strict inequality.
I can find a sequence of functions that converges pointwise to $0$ so that Fatou's Lemma is strict. However, when I want it converges uniformly to zero, I got stuck.
Please help me. Any advice is highly appreciated.
Comment: What have you tried? I'd recommend trying to find characteristic functions which do the job.
Comment: @FactorY That example stretches the function vertically--what if you stretch it horizontally?
Comment: A sequence of functions that converges pointwise to 0 so that Fatou's lemma is strict is $f_n = n \chi_{(0,1/n]}$ on $[0,1]$. But you know, it doesn't converge uniformly to 0.
Comment: $f_n=n\chi_{(n,n+1)}$.
Answer: For $f_n=\frac1n\chi_{(0,n)}$ we have $f_n\rightarrow0$ uniformly since $$\left|f_n-f_m\right|<\frac1n+\frac1m<\frac2N$$for $n,m>N$.
Then $$0=\int_{\mathbb{R}}\liminf_{n\rightarrow\infty}f_{n}dm<\liminf_{n\rightarrow\infty}\int_{\mathbb{R}}f_{n}dm=1$$and we get strict inequality in Fatou's lemma.
Comment: Your example is the same as Nick F's idea above. I try and it works. However, I don't know why do you prove a sequence converging to $0$ like this. I just simply prove $|f_n - 0| < 1/n \le 1/N < \varepsilon$, for all $n \ge N$ on the set.
Comment: You're right. I used Cauchy criterion for no particular reason. It gives the same proof in this case. It can be more useful if we don't know the limit of $f_n$.


Lazy Learning given Submission Files in Competitions

Question: In machine learning settings where you get the "real data" beforehand (e.g. a submission file in competitions like Kaggle), models can be "build around the data" that actually has to be predicted.
Isn't this a huge advantage in applied lazy learning? - The drawback of having computational time during classification and not training does not matter.
Still, I've only seen algorithms like knn at best being part of ensembles (for some diversity, not primarily because of performance in itself).
Answer: You are right, lazy learning is feasible for competitions like kaggle. However their issue comes from the fact that they are based on distances which actually incorporate some part of knowledge. Simple distance functions require complex data transformation, complex distance functions require less data transformation. As such to have in the end proper distances you have to put your learning bias either in distance function complexity either in feature transformation. Either way it is a knowledge introduced by designer not learned automatically. This is the hard part. Because most of the observations are not measured in a way aligned with true structure of the data to answer the learning question.
Imagine for example that your true model is $E=mc^2$. You have measured m, c and E. You want to regress E on the other features. If you use a regression technique which can find interaction terms automatically you have a chance to fit a model which approximates well, otherwise you would have to introduce it yourself. In the case of knn either in distance either in feature engineering.


Parser question, How can I get my int value from list

Question: Using BeautifulSoup
I do
games = html.findAll(class_ = "kv")

and got list of different values. How can I get my int value "Матчі"?
This is example what I have
[
All PickНайбільш популярний режим
,
Рейтинговий пошук матчівНайбільш популярне лоббі
,
Центральна лініяНайчастіша лінія
,
Роль ГоловнаНайбільш поширені ролі
,
10,598Матчі
,
36:25Тривалість матчу
,
53.09%Відсоток перемог
,
3.6Співвідношення УСП
,]

I need to get my 10,598 value from all this list
Answer: Use a regular expression to search for the DIV containing Матчі, and then extract the number at the beginning.
import re

games = html.find(class_ = 'kv', text = re.compile('Матчі'))
if games:
    game_count = re.match(r'^[\d,]+', games.string).group(0)

Answer: You can find  tag with text="Матчі" and then get previous node:
from bs4 import BeautifulSoup

html_doc = """

All PickНайбільш популярний режим

Рейтинговий пошук матчівНайбільш популярне лоббі

Центральна лініяНайчастіша лінія

Роль ГоловнаНайбільш поширені ролі

10,598Матчі

36:25Тривалість матчу

53.09%Відсоток перемог

3.6Співвідношення УСП

"""

soup = BeautifulSoup(html_doc, "html.parser")

value = soup.find("small", text="Матчі").previous
print(value)

Prints:
10,598

EDIT: To get value from title=:
html_doc = """

"""

soup = BeautifulSoup(html_doc, "html.parser")
print(soup.find(class_="rank-tier-wrapper")["title"])

Prints:
Ранг: ВартовийIV

Comment: yo, thanks. But I have another question. How from class get constant value?

I want to find ` tittle = ` in


Selecting range by finding start/end row number based on value in Sheets Script?

Question: tl;dr is there an easy method to select a range by finding starting and ending row numbers of the range by looking for a value in a column?
Not very familiar with java but i know this can be done very easy in other languages but i can't find anything to help me out at the moment (e.g. which() in R - finding row number of "Personal" and adding 2 to the row number to get the right one for the starting row and finding "Work" and subtracting one to get the ending row for the first section of the example provided)
I'm currently having a script automatically sorting smaller sections/tables of my worksheet based on whether or not a value in the section is checked(yes/no) (unchecked ones at the top). Right now i have manually specified the ranges in the script, but it's a hassle if i remove or add rows section (all the ranges below break). The columns do not change, i only need to find rows. So i was wondering if there's an easy method to choose the range automatically which can take into account rows being added or removed. Below is an example of a similar setup (i have a lot more sections in the actual one).
I want to select range A3:B5 for personal and A8:B10 for work. This is how it's currently coded (incl. the sorting), where i specify it manually (note that i have a Yes/no checkbox in C1 to toggle sorting based on status or due date):
date):
function onEdit() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("To do list")
var prange = sheet.getRange("A3:C5"); //manually edit if rows are added/deleted
var wrange = sheet.getRange("A8:C10"); //manually edit if rows are added/deleted

if(sheet.getRange("C1").getValue() == "Yes"){ //toggle checkbox in C1
prange.sort([
{column: 2, ascending: true},
{column: 3, ascending: true}]);
wrange.sort([
{column: 2, ascending: true},
{column: 3, ascending: true}])
}else {
prange.sort(
{column: 3, ascending: true});
wrange.sort(
{column: 3, ascending: true})
}
}

This is a similar worksheet and matches the code above:

Personal

Yes

Task
Completed
Due

Task 1
No
6/10/2021

Task 2
Yes
6/15/2021

Task 3
No
06/22/2021

Work

Task
Completed
Due

Task 1
Yes
6/10/2021

Task 2
Yes
6/14/2021

Task 3
No
6/19/2021

End

Edit:
Somewhat of a solution using excel commands instead:
Add a new sheet called "Ranges" and paste the following to cell A1 and A2:
A1 cell:=CONCATENATE("A",MATCH("Personal",'To do list'!A:A,0)+2,":C",MATCH("Work",'To do list'!A:A,0)-1)
A2 cell:=CONCATENATE("A",MATCH("Work",'To do list'!A:A,0)+2,":C",MATCH("End",'To do list'!A:A,0)-1)

and edit the code above to:
var sheet2 = ss.getSheetByName("Ranges");
var prange = sheet.getRange(sheet2.getRange("A1").getValue());
var wrange = sheet.getRange(sheet2.getRange("A2").getValue());

Comment: My initial thoughts suggest that it would be easier to separate personal tasks and work tasks on separate pages and handle in separate section of the onEdit function.
Answer: To start with, Java and JavaScript are different languages. I know, confusing. Since you seem to be new with it, I would strongly recommend to take a look at the tutorials on the JavaScript tag's about page.
Like Cooper said, you should probably use different pages, or, at least, different columns. This would greatly reduce the complexity of the problem.
That being said, this is how you would do it:
function onEdit(e) {
  // [...]

  const colA = sheet.getRange('A1:A')            // get the entire A column
  const colAValues = colA.getValues().flat()     // Read the values and make an simple array
  const workRow = colAValues.indexOf('Work') + 1 // Get the number of the row with "Work"

  const pRange = sheet.getRange(`A3:C${workRow-1}`)
  const wRange = sheet.getRange(`A${workRow+2}:C`)

  // [...]
}

You need to remove the last "End" so the wRange doesn't include it. You could also search for it and use its position.
Note that for workRow we need a +1 because JavaScript starts counting from 0 and Sheets starts from 1.
References

Range: getValues() (Apps Script reference)
Array: flat() (MDN)
Array: indexOf(searchElement) (MDN)
JavaScript template literals (``) (MDN)
Comment: Thanks, that's brillliant! Just what i was looking for. The actual spreadsheet has like 30 sections that i'm sorting section-by-section, so not really viable to split it up in different sheets. The sorting is reasonably quick as well even though it's a large spreadsheet, so I prefer to do it like you proposed. Thanks for the references as well


Provide a complete and accurate $\epsilon−N$ proof that the sequence $\{2+(−1)^n\}$

Question: Provide a complete and accurate $\epsilon−N$ proof that the sequence $\{2+(−1)^n\}$
diverges.
My attempt:
Suppose that it converges, then there exists a real number L that it converges too
$\exists L \in \mathbb R, \forall \epsilon > 0, \exists N > 0$, such that for all $n \in \mathbb N$, if $n > N$, then $|a_n - L| < \epsilon$
Let $\epsilon = 1$
Case when n is odd. If $n > N$, then $|1-L| < 1 \leftrightarrow 0 < L < 2$
Case when n is even. If $n > N$, then $|3 - L| < 1 \leftrightarrow 2 < L < 4$
Since the limit is not unique a contradiction. This series diverges.
Does this count as a complete $\epsilon - N$ proof?
Comment: No, the contradiction is that $L<2$ and $L>2$, which can't happen at the same time. This is essentially what you are trying to say. The way you said it is awkward is all.
Comment: "Since the limit is not unique a contradiction." You arrive at a contradiction, but this is an awkward way of saying it and not quite what the contradiction is
Comment: Since $L \in (0,2) \cap L \in (2,4)$ the limit is not unique as the definition states. Isn't that the contradiction?
Comment: Oh okay I see thank you
Comment: The proof is good.  But stylistically, it's generally considered better to use words rather than symbols.  You need to properly introduce the variable $N$: "Let $\epsilon = 1$.  Then by the definition of limit, there exists $N$ such that...."
Comment: The demonstration of the divergence (in this case, oscillating succession) is correct.
Answer: Let $a_n=2+(-1)^n$.
Assume $\displaystyle\lim_{n\to\infty}a_n=L$.
Then for any $\epsilon>0$ there is an $N>0$ such that if $n\ge N$ then $\vert a_n-L\vert<\epsilon$.
Let $\epsilon=\min\left\{\left\vert\dfrac{1-L}{2}\right\vert,\left\vert\dfrac{3-L}{2}\right\vert\right\}$.
Then for any $N>0$ if $n>N$ either $\vert a_n-L\vert=\vert1-L\vert$ or $\vert a_n-L\vert=\vert3-L\vert$.
Thus, for $n>0$, $\vert a_n-L\vert>\epsilon$, which is a contradiction.
Thus the sequence $a_n$ diverges.


How do I secure an ASP.NET MVC Web Api using OWIN/Katana?

Question: I'm attempting to secure an ASP.NET web API using the OWIN providers for Windows Azure Active Directory. I've configured the web api to use Windows Azure JWT bearer tokens as per below:
<code>public void Configuration(IAppBuilder app)
{
   app.UseWindowsAzureBearerToken(new WindowsAzureJwtBearerAuthenticationOptions()
     {
       Audience = "http://mywebsitename.azurewebsites.net",
       Tenant = "mydefaultdirectory.onmicrosoft.com"
     });
}
</code>
I then created a client application belonging to the same directory as the web api tenant. I specified the permissions to grant the client application access to the web api. The problem occurred when I tried to create a client application and authenticate against the API.
The client is just a simple windows store app with a button click method to authenticate against windows azure, and the code for the click even is below:
<code> private async void myButton_Click(object sender, RoutedEventArgs e)
    {

        AuthenticationContext ac = new AuthenticationContext("https://login.windows.net/nameofazureactivedirectorytenant");
        AuthenticationResult ar =
         await ac.AcquireTokenAsync("api/pathtoresource",
          "xxxxxxxx-xxxx-xxxxx-xxxx-xxxxxxxxxxxx");
        // Call Web API
        string authHeader = ar.CreateAuthorizationHeader();
        HttpClient client = new HttpClient();
        HttpRequestMessage request = new HttpRequestMessage(
          HttpMethod.Get, "http://mywebsitename.azurewebsites.net/api/pathtoresource");
        request.Headers.TryAddWithoutValidation("Authorization", authHeader);
        HttpResponseMessage response = await client.SendAsync(request);
        string responseString = await response.Content.ReadAsStringAsync();
    }
</code>
The app is failing to correctly create the authentication context, so I believe I am passing it the wrong parameter. I have been through a number of blog posts and SO answers, but nothing has worked thus far, any help would be appreciated!
Answer: Have a look at the samples available at https://github.com/AzureADSamples.  I think there are some examples there that should be applicable.


About an inequality between the real part and absolute value of an operator

Question: When dealing with operators on a Hilbert Space, one can define for $A\in\mathcal{B} (\mathcal{H})$ two natural notions imitating the real part and absolute value of a complex number
$$ Re(A) = \frac{A+A^*}{2}, \; \vert A \vert = \sqrt{A^* A}$$
We also have an order relation on self adjoint operators. Some natural inequalities of these objects (say $\vert A \vert \leq \Vert A \Vert I$) hold, but one that I find particularly tempting is:
$$ Re(A) \leq \vert A \vert $$
or even better
$$ \vert Re(A) \vert \leq \vert A \vert $$
My question is whether the last two inequlities are true in general
For example, this would easily give the fact that any trace class operator decomposes into 4 positive trace class operators. The proof of this fact I saw is somewhat tricky and relies on different methods.
Answer: As stated in PStheman's answer, the inequalities from the OP do not hold in general. However, something slightly weaker is true: For every $x\in B(H)$ there exists an isometry $v\in B(H)$ such that $\operatorname{Re}(x)_+\leq v|x|v^\ast$. This is Proposition 2.1 in Akeman, Anderson, Pedersen. Triangle inequalities in operator algebras.
For many applications such as the one stated in the OP, this is sufficient. It is also a key step in the proof of the triangle inequality for operators, which takes the form
$$
|x+y|\leq v|x|v^\ast+w|y|w^\ast
$$
with isometries $v, w$.
Comment: Thank you for the positive answer, and the reference.
Answer: Neither of these are true in general. Consider
$$A = \begin{pmatrix} 0 & 1 \\ 0 & 0 \end{pmatrix}. $$
The real part is
$$B = \begin{pmatrix} 0 & \frac{1}{2} \\ \frac{1}{2} & 0\end{pmatrix}, $$
And
$$ |A| = \begin{pmatrix} 0 & 0 \\ 0 & 1 \end{pmatrix}. $$
Then $|A| - B$ has a negative eigenvalue (one can see this from plugging this into wolframalpha; $\frac{1}{2}(1 - \sqrt{2})$ is an eigenvalue), so it is not positive. Thus Re$A$ is not bounded by $|A|$ in general. Also notice that $B = |B|$, so that neither of your proposed inequalities hold.
However, one might ask if this is true in the case that $A$ is self-adjoint or normal. When $A$ is self-adjoint, we have that $|A| - A$ is positive (indeed, one can think of $A$ as the identity function $f(x) = x$ on its spectrum; and it isn't hard to convince onself that $|f| - f \geq 0$ for any real-valued function). Also clearly $|A| - |\text{Re}A| = |A| - |A| = 0 \geq 0$, so both the inequalities hold.
So what about the normal case? I honestly don't know, but I hope the above sufficiently answers your question. I might give an edit later once I give the normal case some thought.
Comment: Great example! Thank you for the answer, I added the normal case in an edit.


\unfoldRepeats and \repeat with midi output in lilypond

Question: I have a piece of lilypond code here:
trebleNotesOne = {
    \unfoldRepeats {
        \repeat volta 2 {
            r8 a'16 b'16 c''8 b'16 c''16 d''2 |
            r8 b'16 a'16 b'8 a'16 g'16 f'2 |
        }
    }
}

bassNotesOne = {
    \clef bass
    \unfoldRepeats {
        \repeat volta 2 {
            a8 b8 c8 d8 a8 b8 c8 d8 |
            a8 b8 c8 d8 a8 b8 c8 d8 |
        }
    }
}

\score {
    \new GrandStaff
    <<
        \new Staff << \trebleNotesOne >>
        \new Staff << \bassNotesOne >>
    >>

    \layout {
        ragged-right = ##t
    }
    \midi {}
}

I want both the repetition notation (\repeat volta 2) printed in the sheet music pdf, and for the midi file generated to contain repeated plays.
The above code prints:

But I want in pdf:

with midi repetition.
Answer: To get repeats to display in proper notation in the PDF, but to also unfold in the MIDI, you will actually need to make two score blocks.
One score block with a \layout{}, and one with a \midi{}.
Put the \unfoldRepeats command in the midi score block.
(see 3.5.6 Using repeats with MIDI)
Something like this:
trebleNotesOne = {
    \new Staff
        \repeat volta 2 {
            r8 a'16 b'16 c''8 b'16 c''16 d''2 |
            r8 b'16 a'16 b'8 a'16 g'16 f'2 |
        }
}

bassNotesOne = {
    \new Staff
        \clef bass
        \repeat volta 2 {
            a8 b8 c8 d8 a8 b8 c8 d8 |
            a8 b8 c8 d8 a8 b8 c8 d8 |
        }
}

theMusic = {
    \new GrandStaff
        <<
            \trebleNotesOne
            \bassNotesOne
        >>
}

%% PDF SCORE
\score {
    \theMusic

    \layout {
        ragged-right = ##t
    }
}

%% MIDI SCORE
\score {
    \unfoldRepeats {
        \theMusic
    }
    \midi { }
}


antecedent and consequent phrase in minor scale

Question: MY question is what are the rules for melodic phrasing in minor scales.  For example, I know that in a major scale the vii wants to go up to the I and the V can go where ever etc.
what are the rules for a minor scales (aeolian, dorian etc.) are they different?  Where does the i want to pull up or down to and what would be the stable and unstable notes?
Comment: The **i** in any minor key/mode - Aeolian, Dorian, Phrygian etc., won't pull anywhere. It's already arrived! It's the root. It is the most stable in that key.
Comment: there are rules for melodic phrasing? I never knew. I always just listened and tried to make stuff sound melodic. On the basis that if it sounds like it, it probably is, and if it doesn't it doesn't really matter what the rules say.
Comment: Yea but I want to get the basics down before I start coming up with my own personal rules and confuse myself.  To me it matters because of that.
Answer: Melodic phrasing is different than tonal characteristics.
The guidelines for melodic phrasing are the same regardless of tonality. I encourage you to research parallel answers and contrasting answers.
Antecedents can be thought of like questions. Consequents can be thought of as one of the two types of answers above. How long they are / their shape / character is unique to each piece.

Regarding your question concerning tonal characteristics: between the major and natural minor scales, only 3 notes change: 3, 6, and 7. Musica ficta was a technique developed to provide extra pull to the tonic. The harmonic minor scale ended up being the result. The melodic minor scale was developed to alleviate the augmented 2nd created by the harmonic minor scale, which at the time was considered not only difficult to sing, but harsh on the ear.
Besides the 7th, the question of where notes "pull" is largely dependant on context. If you set a drone of a fifth, then raise it to a minor-6th, to the listener, it's going to want to pull downward due to aural memory.
Context influenced by emphasis and aural memory shape which tones "pull" in which directions. This is true regardless of tonality.
Comment: To clarify I guess what I'm asking is about the degrees in a key or scale.  Does the rules change? (chord progression also.)  Like how V-I, or VII-I in a progression gives resolve.  How does it work for the minor key since the diminsished is no longer the 7th and is now the ii.   I know people say just play what I feel but everytime I do that I get stuck composing something that sounds like it's missing something and I want to fix it.
Comment: No. Rules don't change. Use common progressions if you need them. ii for example can still be used as a predominant / substitute for iv.
Answer:
...antecedent and consequent phrase in minor scale?

I think you are asking about minor key music, so let's skip over modal music (Dorian, etc.)
Antecedent and consequent phrases are essentially defined by cadence types. The typical thing is an antecedent phrase ending with a half cadence on the dominant chord and a consequent phrase ending on the tonic. That model applies to minor key music too.

EDIT it seems part of your question is more generally about minor key harmony and how to handle the dominant chord, the antecedent aspect of harmony.
At the heart of dominant harmony in minor keys is raising the seventh scale degree to form dominant chords.
In C minor - with a key signature of three flats - the seventh degree is Bb. When you build a triad on the dominant the unaltered chord would be G Bb D. But the conventional thing to do is raise the seventh to make the chord G B D.
In technical terms the lowered seventh Bb one whole step below the tonic is called the subtonic, but the raised seventh B natural is a half step below the tonic and called the leading tone. The leading tone distinguished the dominant chord.
The leading tone triad is a diminished triad built on the leading tone. In C minor the leading tone triad is B D F. The leading tone triad is often considered an incomplete dominant seventh chord and can effectively function as a dominant chord. So, in minor key harmony there are two diminished chords: viio and iio.
Comment: Thank you.  Only thing is how exactly does it apply to minor music?  I'm getting confused as to if the dominant chord in a major key is the V and the Tonic the 1, is it the same in minor keys? the i is the tonic and the v is the dominant.  Or is it different.
Comment: In _common practice_ - basically Baroque and Classical eras - the dominant chord is _always_ a major triad with an optional dominant seventh. You could write it like `V(7) I` or for minor `V(7) i`, putting the 7 in parenthesis to show it is optional. Also, upper case `V` means a major triad whereas lower case `v` means a minor triad. Again a true dominant in either major or minor will be a major chord `V`.


Mean and Mean Absolute Deviation inferential statistics

Question: Consider the following data of runners in a race. The first data is from a certain year the second one is from the year after.
$Last\space year \space|\space Mean: 525s \space|\space MAD: 25s$
$This \space year \space|\space Mean: 613s \space|\space MAD: 21s$
The question asks to make inference from the measures of variability.
My answer:

The MAD this year is lower than last year, this means that more
students were closer to the mean time taken to finish the race. Since
the mean this year is greater than the mean last year, more students
were slower this year.

I feel like this should be right, but I am not quite sure if it is the right inference from the data given.
Comment: @Tim Isn't MAD = mean absolute deviation
Comment: Both definitions are used, although Median AD is probably more correct. Which definition is used in your problem?
Comment: @user2974951 is most likely Mean AD.
Answer: It seems to be a self-study question so let me just give you some hints to figure it out by yourself.

Mean is sensitive to outliers.
MAD is an acronym generally used for median of deviations from median. MAD is a robust measure of variability, so it is insensitive to outliers (see also other questions tagged as mad). You may want to use it if you have clear outliers in your data.
The MAD acronym is sometimes is also used for mean absolute deviation, you'd need to consult your materials for which one is it. If that is the case, if it is defined as an average absolute deviation from the mean, your reasoning is correct.
Comment: It's confusing that it is used as an acronym for both of these things. In my case, MAD was used as an acronym for mean absolute deviation. Thank you, Tim!


Diminuir a precisão do float em Javascript?

Question: Como diminuir as casas decimais de um número float no javascript?
Por exemplo, quero que 3.3333333333 se torne em 3.34.
Qual é a maneira mais simples de se fazer isso no javascript?
Tentei funções como Math.ceil, porém ela me retorna o valor inteiro.
float_value = 3.333333;
Math.ceil(float_value); // 4

Comment: Também dá para usar o `.toPrecision()` http://jsfiddle.net/cks2mvr9/
Comment: @qmechanik, você deveria postar como resposta, pra ganhar +1, rsrsrsrsrsrs
Answer: Use a função Math.round() que retorna o valor do número inteiro mais próximo.
Math.round(num * 100) / 100
Você também pode usar a função toFixed():
parseFloat("123.456").toFixed(2); // Se for uma string, converta pra numéro

Comment: Fino, amigo. Mas eu gostaria de saber se no `Javascript` tem alguma forma de fazer nativamente?
Comment: Acredito que uma função nativa pra isso não tenha, acho que só na mão mesmo, :)
Comment: Você também pode usar o toFixed...
Comment: Não me acostumei com isso ainda: No javascript puro, muita coisa é na mão ;)
Answer: Você pode usar o toFixed() pra fazer isso, mas ele retorna uma String, e não um float. Do próprio site:
var num = 5.56789;
var n = num.toFixed(2);

resulta em
5.57

Tem uma discussão sobre isso no SO gringo.
Comment: Logo temos: http://jsfiddle.net/mqzbsgxf/
Comment: Obrigado, Caio. Eu tinha pensando no `.toFixed`, porém ele retorna uma string. Mas, nesse caso, eu apenas teria que utilizar `parseFloat(num.toFixed(2))`
Comment: É uma volta, mas funciona!


Obter o AbsolutePath do input type="file"

Question: estou tentando obter o caminho completo do diretório através do input do tipo file, porém até agora só conseguir pegar uma pasta anterior, por exemplo, tenho a pasta no caminho C:/user/Documents/Images/Ontem então eu gostaria de pegar esse caminho todo, mas só consigo pegar a pasta Ontem, o codigo que estou fazendo é
$('#pasta').change(
    function absolutepath(e){
    var aqrs;
    var theFiles = e.target.files;
    alert(theFiles[0].webkitRelativePath);
});

Com esse código acima ele pegar o primeiro arquivo com a pasta com o input abaixo:
<input type="file" id="pasta"  multiple webkitdirectory />

Como faço para pegar o caminho todo?
Answer: Nao é possível.
Por medida de segurança os navegadores não permitem que você saiba o Path Absoluto do arquivo do usuário.
E você só consegue visualizar o nome da pasta anterior porque a propriedade webkitdirectory retorna a path relativo da sua pasta.

Dê acordo com a especificação do HTML5, um controle de upload não
  deve revelar o caminho real do arquivo selecionado. 1

1 THE MYSTERY OF C:\FAKEPATH UNVEILED
Comment: Na verdade, estou passando por algo semelhante. Estou fazendo um upload com redimensionamento de imagens, preciso jogar o caminho desta imagem num input, e estou sofrendo para fazer isso. Existe outro caminho? Algo que possa a ser feito? @Laerte, qual sua sugestão?
Comment: Cara infelizmente isso é uma limitação imposta pela especificação e implementada pelos navegadores, é uma medida de segurança não há nada que possamos fazer, mas no seu caso você quer replicar a imagem enviado pelo usuário pra outro input?
Comment: As imagens vão para uma pasta do servidor, o nome do arquivo é um md5. Eu preciso do caminho para salvar no banco. Esse caminho, eu lanço no input. No outro sistema que eu usava, a imagem aparecia, eu clicava com o botão direito e pegava o caminho da imagem. Mas não quero quer seja assim, prefiro automático, o usuário acaba se perdendo em coisas simples...


Data DatePicker - Processamento

Question: Senhores:
A data que eu tenho no datepicker é no formato dd/mm/yy, porém, a data no banco de dados é yy-mm-dd (campo date). Como eu faço para que no datepicker apresente a data padrão BR e quando vier via POST, entrar como formato EN?
Answer: Se quiser tratar no envio:
var dataQuebrada = $("#datepicker").val().split("/");
var novaData = new Date("20" + dataQuebrada[2], dataQuebrada[1] - 1, dataQuebrada[0]);
// new Date(year, month, day);
// -1 no mês porque ele começa do 0
// "20", pois você só tem os 2 últimos digitos

Se quiser tratar no recebimento:
var $datepicker = $("#datepicker");
var dataQuebrada = $("#datepicker").val().split("-");
var novaData = new Date("20" + dataQuebrada[0], dataQuebrada[1] - 1, dataQuebrada[2]);
$datepicker.datepicker();
$datepicker.datepicker('setDate', novaData);

Comment: Não entendi... O Post vem no php.
Comment: @AndréBaill Atualizei a resposta
Answer: Eu costumo tratar esses dados no lado do servidor, e usando PHP faço assim:
<input type="text" name="minha_data"
 id="minha_data" class="form-control data datepicker"
 value="<?php data_us_to_br($geral->dt_atendimento); ?>"
 placeholder="dd/mm/aaaa" maxlength="10" minlength="10" />

e no lado do servidor, quando vou receber o POST assim:
$valorMinhaData = data_br_to_us($_POST['dt_verificacao']);

e as funções que estou usando no caso são essas :
function data_us_to_br($dateUSA)
{
    if($dateUSA) {
         $ano = substr($dateUSA, 0, 4);
         $mes = substr($dateUSA, 5, 2);
         $dia = substr($dateUSA, 8, 2);
         $dateBR = $dia .'/'. $mes .'/'. $ano;

         return $dateBR;
    }

    return NULL;
}

function data_br_to_us($dateBR)
{
    if($dateBR) {
         $ano = substr($dateBR, 6, 4);
         $mes = substr($dateBR, 3, 2);
         $dia = substr($dateBR, 0, 2);
         $dateUSA = $ano .'-'. $mes .'-'. $dia;

         return $dateUSA;
    }

    return NULL;
}

Answer: Da p/ fazer assim com uma única linha de comando:
var d = $.datepicker.formatDate( "yy-mm-dd", $('#calendario').datepicker('getDate') );

Onde a variável d fica no formato mysql
E o $('#calendario').datepicker('getDate') Pega no formato que estiver

https://api.jqueryui.com/datepicker/
Comment: Mas e como eu recupero ela no php? Grato
Comment: nesse caso você pode usar o javascript para preencher algum campo do seu formulario e enviar pelo submit, ou fazer um ajax, tanto faz

Data DatePicker - Processamento


Avoid the escape key in VsVim

Question: Vim has the shortcut CTRL+[ that can be used instead of the escape key ESC. This shortcut is used by Visual Studio to open the Team Explorer. How can I replace this shortcut in order to use it like Vim?
Answer: To make this work you just need to switch control of CTRL+[ to VsVim via the options page:

Tools -> Options -> VsVim
Keyboard
Change the combo box to VsVim for CTRL+[
Comment: This option does not exists in that menu.
Comment: @jgarciad Can you see what key the Ctrl+[ is bound to on your solution?  Tools -> Options -> Environment -> Keyboard.  Go to the input box, hit Ctrl+[ and see what commands it is bound to.

Avoid the escape key in VsVim


How do I set the expiration value for tempstore.private service?

Question: I am using the tempstore.private service, which uses an expiration time of one week. I need to change this; changing it globally is fine.
There is an $expire property, but I've no idea how I'm supposed to set it.
Answer: The expiration time is a parameter set in the service container. If you look at core/core.services.yml you will see the tempstore.expire parameter is set with a default value of 604800 seconds. This value is set when the container is compiled, and will be the same for all private tempstores.
There doesn't seem to be a way to set this in code or to override the parameter with a configuration setting, although I do see some issues in the core issue queue for adding that ability.
So apart from editing core.services.yml, you can override the tempstore.private service in your own module in order to customize the behavior.
Comment: @thiokol, don't edit core.services.yml. Site-specific you can add the parameter to services.yml parallel to settings.php. Modules can add the parameter to mymodule.services.yml. Then it will be compiled into the container when you clear the cache.
Comment: Thank you, its not ideal but setting it in core.services.yml will be sufficient for me.
Comment: Yes, services.yml is the right way to go. I didn't know about that.


How can I 'translate' elements from a 'list' to those in another 'list' in Python?

Question: Alright, I did a bit of researching before I came here, and I didn't find anything that catered especially to what I wanted to find.
The problem is a little difficult, (at least, for me) so I'll do my best to explain it here.
Ok: So I've got a list of letters, that are taken from a string a user enters.
(They enter a string, then it's all broken down into individual letters and added to a list, where each letter is its own 'element')
Now I wanted to do this because I wanted to have all the letters inside this list to be translated into something else, depending on what I had 'set' each letter to be translated to.
I'm a bit confused as to how to do this, I could have a whole while loop that did the following:
Takes the first element, then runs the whole alphabet and numbers 1-9 by it. If it matched anything, it adds it to a new list.
The trouble is, it seems really inefficient to do this, and I am thinking their must surely be a better way to do this, I'll post what I am talking about below:
I can't get the code formatting to work correctly, and I'm just frustrated with it. Here's the code:
print("\t\t\tThe fun encryptor")
print("\n\n Please Enter the following string to be encrypted")
STRING = input("Entry: ")
STRINGCOPY = [STRING]
DIRECTORY = []
#The string is to be encyrypted.
STRINGLEN = len(STRING)
OPPLIMIT = 0
REPEAT = False
DIRECTORYT = []

while OPPLIMIT < STRINGLEN:
    DIRECTORY = DIRECTORY + str.split(STRING[OPPLIMIT])
    OPPLIMIT += 1

# String Added to the Directory necessary
if "a" in DIRECTORY[0]:
    DIRECTORYT += [0.01]
elif "b" in DIRECTORY[0]:
    DIRECTORYT += [0.11]
elif "c" in DIRECTORY:
    DIRECTORYT += [1.11]

    #and so on and so forth

a="0.01"
b="0.11"
c="1.11"
d="0.02"
e="0.22"
f="2.22"
g="0.03"
h="0.33"
i="3.33"
j="0.04"
k="0.44"
l="4.44"
m="0.05"
n="0.55"
o="5.55"
p="0.06"
q="0.66"
r="6.66"
s="0.07"
t="0.77"
u="7.77"
v="0.08"
w="0.88"
x="8.88"
y="0.09"
z="0.99"

As you can see, it seems almost pointless to go through this all, is there an easier way to do it?
Perhaps using the for function thing?
Comment: UGH, it doesn't show the screenshot: Here is the link: http://i1267.photobucket.com/albums/jj554/owatch/Photobucket_zps4438dfaf.png
Comment: It's much more helpful to post code as text (e.g., a pastebin.com) than as a screenshot. We can't copy and paste a screenshot and try to run it ourselves.
Comment: @user1883304 You can convert the string to a list by doing `DIRECTORY=list(STRING)`.
Comment: Also, you really shouldn't give your variables all-caps names like this; it makes it very hard to read your code. See [PEP 8](http://www.python.org/dev/peps/pep-0008/) for more details.
Comment: @Mike: What part of his code makes you think he needs a `list` of the characters?
Comment: @abarnert The OP probably doesn't need to, but they are doing the conversion in their code. I was just informing him/her that there is an alternative way to do it.
Comment: @Mike: Once you've explained that `str.split(STRING[OPPLIMIT])` is the same as `STRING[OPPLIMIT].split()`, and that `STRING[OPPLIMIT].split()` is the same as `STRING[OPPLIMIT]` because a one-character string always splits into a list of itself, and that this convoluted `while` loop is equivalent to just `for OPPLIMIT in range(len(STRING))`, and that the result `for` loop can be replaced by `for char in STRING`, then you can do that last simplification. But I don't think jumping all the intermediate steps helps the OP see why those are equivalent.
Comment: `list(STRING)` <- this is kind of useless in Python.
Comment: I've now got a new problem..
Answer: First, instead of creating 26 separate variables named a, b, etc., just create a dict:
values = {'a': 0.01,
          'b': 0.11',
          #...
}

Now, you can just do this:
for letter in DIRECTORY[0]:
    DIRECTORYT += [values[letter]]

Or, alternatively:
for letter in values:
    if letter in DIRECTORY[0]:
        DIRECTORYT += [values[letter]]

The difference between the two lies in how they handle duplicates. And I'm not sure which one you want (or, if you never have any dups, so it doesn't matter). Try executing both with different sample data until you get the idea.
As a side note, it's generally better to do:
DIRECTORYT.append(values[letter])

than:
DIRECTORYT += [values[letter]]

In other words, don't create a list if you don't need one.
But in this case, you may be able to replace the whole loop with a list comprehension or generator expression:
DIRECTORYT += [values[letter] for letter in DIRECTORY[0]]
DIRECTORYT += [values[letter] for letter in values if letter in DIRECTORY[0]]

or:
DIRECTORYT.extend(values[letter] for letter in DIRECTORY[0])
DIRECTORYT.extend(values[letter] for letter in values if letter in DIRECTORY[0])

The advantage of the extend/generator expression versions is, again, that they don't build temporary lists.
Comment: It does not work, I keep getting a blank result when I have it print the Directory
Comment: @Owatch: Please show the code (somewhere like pastebin.com) and explain where you're "print[ing] the Directory". Multiple people have bent over backward trying to read your mind here, but apparently none of use are Professor X.
Answer: Not really sure what you are trying to do, but here are two approaches.
You could set up a dictionary with the letters and their translations, then do a lookup on this dictionary when your user enters a word.
codes = {}
codes['a'] = 9
codes['b'] = 133
# and so on
codes['z'] = 1

user_input = raw_input('Please enter a string: ')

translated_stuff = []

for letter in user_input:
   if letter in codes:
       translated_stuff.append(codes[letter])

# a shorter way to do the above loop is
# translated_stuff = [codes[i] for i in user_input if i in codes]

print "Your translated stuff is : {}".format(''.join(translated_stuff))

Or, if you want that simply check if an input matches a set:
import string

match_list = string.letters + string.digits

user_input = raw_input('Please enter a string: ')
matched_stuff = [i for i in user_input if i in match_list]

Comment: why are you doing it that way?
Comment: Hey, I've tried using your way, but instead of using translated_stuff.append(codes[letter])   I am using COUNTLIMIT = len(User_input)

while x != COUNTLIMIT:
    for letter in User_input[x]:
        if letter in TRvalues:
            Tdirectory += TRvalues[User_input[x]]
    x = x + 1                                                                        but I keep getting the error:  'float' object is not iterable
Comment: I'm sorry, there is no way that I can get this code to work properly. So annoying
Comment: @Owatch: If you tried completely different code and your completely different code didn't work, why not try Burhan Khalid's _actual_ code? If you want to know why you're getting that `TypeError`, you'll have to show us the full traceback, and tell us where those other variables came from. (My guess is that `User_input` is a float or a list of floats, but I have no idea why, because you haven't shown the code that creates it. Maybe you're using Python 2.x and changed his `raw_input` to `input` anyway?)
Answer: It's unclear to me everything you were trying to accomplish in your code, but here how to translate each the characters of the string entered into the values shown in your code. There's no need to convert to first convert it to a list because a string is already a sequence of letters, which can be treated just like items in a list in most cases (the main difference being that they can't be changed).
It uses a Python dictionary (or dict) to hold the translation because that allows it to be used to lookup each letter and find the value associated with it very quickly, usually much faster than searching for it by checking every entry in a regular table or list.
It also makes sure only alphabetic characters (letters) are translated and converts uppercase ones to lowercase for the look-up operation since the dictionary only has entries for them in it.
import string

translate = {
    'a': "0.01", 'b': "0.11", 'c': "1.11", 'd': "0.02", 'e': "0.22", 'f': "2.22",
    'g': "0.03", 'h': "0.33", 'i': "3.33", 'j': "0.04", 'k': "0.44", 'l': "4.44",
    'm': "0.05", 'n': "0.55", 'o': "5.55", 'p': "0.06", 'q': "0.66", 'r': "6.66",
    's': "0.07", 't': "0.77", 'u': "7.77", 'v': "0.08", 'w': "0.88", 'x': "8.88",
    'y': "0.09", 'z': "0.99",
}

print("\t\t\tThe fun encryptor")
print("\n\nPlease type in a string to be encrypted and press the Enter key")
entry = input("Entry: ")

directory = [translate[ch.lower()] for ch in entry if ch in string.ascii_letters]

print('directory:', directory)

Comment: @martineau: Also, the OP _has_ responded to the other two answers, basically saying "I tried some different code from the code you gave, and it doesn't work in some unspecified way", followed by adding "I've now got a new problem..." to his question. Maybe the "new problem" is that wolverines are eating his router, and that's why he hasn't answered again since then?
Comment: `input()` if you are using Python 3.x, otherwise `raw_input()`
Comment: @BurhanKhalid: The OP is using `input` in his original code, and `print` as a function, etc., so hopefully he's using 3.x. But, considering his other comments, it's conceivable that he's using 2.x but following a 3.x tutorial, so that may be a useful comment after all…
Comment: @abarnert: I got the impression the OP was using 3.x, so tailored my answer accordingly -- never thought about the possibility you mentioned of them mixed-up. Oh, well, with no response so far, they don't seem concerned one way or the other.
Comment: @martineau: Yeah, I got the same impression, which is why I started off by saying the "otherwise `raw_input()`" comment wasn't necessary… but then I realized he had a `float` where he expected a `str` in some unseen code that appears to call `input`…


Printing to stdout with encoding in Python 3

Question: I have a Python 3 program that reads some strings from a Windows-1252 encoded file:
with open(file, 'r', encoding="cp1252") as file_with_strings:
    # save some strings

Which I later want to write to stdout. I've tried to do:
print(some_string)
# => UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 180: ordinal not in range(128)

print(some_string.decode("utf-8"))
# => AttributeError: 'str' object has no attribute 'decode'

sys.stdout.buffer.write(some_str)
# => TypeError: 'str' does not support the buffer interface

print(some_string.encode("cp1252").decode("utf-8"))
# => UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 180: invalid continuation byte

print(some_string.encode("cp1252"))
# => has the unfortunate result of printing b'<my string>' instead of just the string

I'm scratching my head here. I'd like to print the string I got from the file just as it appears there, in cp1252. (In my terminal, when I do more $file, these characters appear as question marks, so my terminal is probably ascii.)
Would love some clarification! Thanks!
Comment: What does `string_to_print = some_string.decode('utf-8'); print(string_to_print)` do?
Comment: It's just a str, so I get `AttributeError: 'str' object has no attribute 'decode'`
Comment: "(In my terminal, when I do more $file, these characters appear as question marks, so my terminal is probably ascii.)"  <- no, seeing as though in your answer you're writing cp1252, then your terminal encoding probably doesn't match your locale.
Comment: I'm voting to close this question as off-topic because the actual problem is too localised - it's caused by an incorrectly configured environment and/or by usage but is not properly described.
Answer: Since Python 3.7, you can change the encoding of all text written to sys.stdout with the reconfigure method:
import sys

sys.stdout.reconfigure(encoding="cp1252")

That could be helpful if you need to change the encoding for all output from your program.
Answer: To anybody out there with the same problem, I ended up doing:
to_print = (some_string + "\n").encode("cp1252")
sys.stdout.buffer.write(to_print)
sys.stdout.flush() # I write a ton of these strings, and segfaulted without flushing

Answer:
When you encode with cp1252, you have to decode with the same.

Eg:
import sys
txt = ("hi hello\n").encode("cp1252")
#print((txt).decode("cp1252"))
sys.stdout.buffer.write(txt)
sys.stdout.flush()

This will print "hi hello\n" (which was encoded in cp1252) after decoding it.
Comment: Printing after `decode` just tries to print a Unicode string, which leads you right back where you started. Your example only works because it only contains ASCII characters.
Comment: Yeah, agreed. Buffer writer has to be used.
Comment: This helped me a lot. I was reading from a STDIN, and writing to a file worked, as you can set the encoding in open(), but printing was a nightmare.
Comment: If different codecs are used for encoding and decoding (e.g. print(txt.encode("utf-8").decode("cp1252")) ) the result is not identical and may be printable. The translation errors can actually be helpful to find the offending characters.
Answer: You're either piping to your script or your locale is broken. You should fix your environment, rather than fixing your script to your environment, as this will make your script very brittle.
If you're piping, Python assumes the output should be "ASCII" and sets the encoding of stdout to "ASCII".
Under normal conditions, Python uses the locale to work out what encoding to apply to stdout. If your locale is broken (Not installed or corrupt), Python will default to "ASCII". A locale of "C", will also give you an encoding of "ASCII".
Check your locale by typing locale and ensure no errors are returned. E.g.
$ locale
LANG="en_GB.UTF-8"
LC_COLLATE="en_GB.UTF-8"
LC_CTYPE="en_GB.UTF-8"
LC_MESSAGES="en_GB.UTF-8"
LC_MONETARY="en_GB.UTF-8"
LC_NUMERIC="en_GB.UTF-8"
LC_TIME="en_GB.UTF-8"
LC_ALL=

If all else fails or you're piping, you can override Python's locale detection by setting the PYTHONIOENCODING environment variable. E.g.
$ PYTHONIOENCODING=utf-8 ./my_python.sh

Remember that your shell has a locale and your terminal has an encoding - they both need to be set correctly
Comment: Not piping, but it's also not my environment - it's a program that I have to run on school servers, which have ascii terminals. I could change my personal environment or use a different terminal, but I can't guarantee that the graders will.
Comment: It's Debian, I'm handing in a .py file that will be run with python3 by someone on a different computer, but reading from the same files, and always trying to write to ascii stdout
Comment: If your terminals really are ASCII (they probably aren't), why is your answer encoding to "cp1252"?
Comment: I have to encode to cp1252 to maintain the accent marks that were in the original data. This script's output will be redirected to a file, and I want that file to have those accent marks. My locale has nothing set for LANG/LANGUAGE or ALL, and everything else is "POSIX", fwiw
Comment: 1) Your terminals are not ASCII if they're displaying cp1252. 2) Your environment is not setup correctly if you don't have a LANG defined. That is why "more" is failing. You may find your students have correctly configured environments or a different encoding setup, meaning your brittle code will break


Ruby: Trying to get two classes to interact with each other

Question: I'm scratching my head a little bit on how to solve this problem I was presented:
I need to make two classes, Horse and Hay. Horse has initialize methods (colour/type). The Hay class has a method (size) for the hay's stack.
The Horse class must have a give method that takes hay and adds it to an array hay_stack for the Horse. The Horse can take a maximum of 3 Hay eaten and if he does it will print a "Too full!" message.
Finally, the Horse class needs a Eat method where when called will remove one of the Hays from the hay_stack.
Questions:

I'm confused on how to model this by using 2 classes. How does the Horse class interact with the Hay class's object? We need to pass information between the two.
If we do use 2 classes where should hay_stack be and how do we write the proper info to it?

I've done lots of googling to find my answer but to no avail. Thanks for your help!
Answer: You will need 2 classes, Horse and Hay.
The Horse class will have an array hay_stack of object Hay.
The give method will simply add a Hay object to the Horse's hay_stack with the maximum check ofcourse.
The eat method will remove a Hay object from the Horse's hay_stack.


compare weighted coins

Question: I have n (much larger than 2) coins that can give Head or Tail in a toss. For each coin, I have one sequence of trials which may have different lengths. For example, a conceptualized dataset could look like:
Coin 1: HHT
Coin 2: HHTTHHTHTTHHHTTHTHHHHH
Coin 3: THHHTTHHTTTTTTT
I would like to test whether all coins are identical, i.e., whether they have the same probability of giving Head or Tail. How would you approach this problem? Thank you.
Comment: Could you indicate why the trial lengths vary?  If the length of a sequence depends in any way on its outcomes, that ought to affect the analysis.
Comment: This is not the real data. There is no reason for the sequence lengths to be different, let's simply assume that the experimenters performed different number of coin tosses for each coin.
Comment: Assuming this is the real data I do not think that there is enough evidence to say with any confidence that any of the three coins are biased.  The larger the sample size the greater the confidence.
Answer: You could perform a $C$ likelihood ratio tests, where $C$ is the number of coins.
Let $L(\theta|y) = \prod_{c\neq c_j} \operatorname{Binomial}(y_c; n_c,\theta_c)\cdot\operatorname{Binomial}(y_{c_j}; n_{c_j},\theta_{c_j})$. We can test $H_0: \mbox{all $c_i$ are equal}$ vs. $H_j:c_i=c_{i'},\; \forall i,i' \neq j$, by finding the tail probability of the test statistic
$$T_j(y) = -2(\log L(\hat{\theta}_0|y) - \log L(\hat{\theta}_j|y)) $$
assuming that it follows a $\chi^2_1$ distribution. Here $\hat{\theta}_0$ maximizes $L(\theta|y)$ with the constraint of $H_0$ and $\hat{\theta}_j$ maximizes over the constraint of $H_j$. Since there are possibly a lot of p-values, you'll want to adjust them for multiple comparisons, e.g. using Bonferroni.
Intuitively, this is a way to see if one coin is behaving differently than the rest.
Comment: This approach is problematic because a Bonferroni correction is far too severe due to the correlations among the results.
Comment: @whuber What sort p-value adjustment would you use?
Answer: I think the Tukey–Kramer method is appropriate here. Implemented in R as TukeyHSD. Although it does make a normality assumption, it should be fine as long as your samples are larger than about 20 or so for each coin. If the means are reasonably close together, the homogeneity of variance assumption will roughly hold as well.
Quoting wikipedia:

When doing all pairwise comparisons, this method is considered the best available when confidence intervals are needed or sample sizes are not equal

More details here
Comment: This is a good answer that includes the appropriate caveats.  Just want to make sure that it is clear to the original poster that the example provided by the OP, with a sequence of only 3 tosses, is not amenable to this method.  If the dataset has **any** sequences this short, this method can fail spectacularly.
Answer: Especially if some of the coin sequences are relatively short (so it is important to model the number of heads from a binomial rather than normal distribution), one option is to fit a random-effects binomial model to the data (i.e. with a random effect of coin), and to compare it to a model without the random effect using a likelihood ratio test.
Edited to add:  If the likelihood ratio test supports the random effects model, then it is appropriate to conclude that the coins are not identical.

compare weighted coins