How can I restore a directory I accidentally deleted in git (command line)?

Question: I locally saved some files in my git directory on my computer yesterday. I must have played around with some git commands so that some text I wrote for my thesis that was is that directory is now gone along with its whole directory. Also some code I wrote..
I think it was never to be seen in the GitLab online website, telling me that it was never really saved in the git. But it isn't in my computer's local trash bin.
I have tried using git log but it does not show the directory I must have deleted. I also googled some options I have, including git reset and such. Nothing that gets me any further.
C:\Users\kanin\git_dir\Studis\Studis>git log
commit a6dedf6f4d79c6a7d476e7f8f19c6ab8e4e774b6 (HEAD -> Name, origin/Name)
Merge: 9cdad27 2b3e617
Author: Name Name <firstname.lastname@example.com>
Date:   Wed May 8 08:12:11 2019 +0200

    Merge branch 'hotfix_Names_branch' into 'Name'

    Wichtige <C3><84>nderung, da angrenzende R<C3><A4>ume nicht mehr auf optimierten Werten,...

    See merge request Name.Name/Studis!2

commit 9cdad275e74ce993f5e924a66ea776438415672b
Author: Name Name Name Name <email@example.com>
Date:   Tue May 7 15:50:32 2019 +0200

    Update send_emails.py

commit 420f7b8690edfbc5e1b7a29199a7e4992a836fa3
Author: Name Name Name Name <firstname.lastname@example.com>
Date:   Tue May 7 15:37:14 2019 +0200

    Update send_emails.py

commit 2b3e61780b4adb17e4a206d24c96e78161952b1d (origin/master, origin/HEAD)
Author: Name Name <firstname.lastname@example.com>
Date:   Tue May 7 15:35:59 2019 +0200

    Wichtige <C3><84>nderung, da angrenzende R<C3><A4>ume nicht mehr auf optimierten Werten, sondern jetzt gleich den Au<C3><9F>enwerten gesetzt werden

commit 503f140ba996e1c5f0dd7f948fec5ff9310dbcee
Author: Name Name Name Name <email@example.com>
Date:   Tue May 7 15:35:12 2019 +0200

    Upload New File

commit bf9ff0da6e9c63cccaaa9a407d77a1392ca16c10
Author: Name Name Name Name <email@example.com>
Date:   Tue May 7 15:23:03 2019 +0200

    Upload New File

commit f33f5f127ddd013c072081b57425bcf62446af07
Author: Name Name Name Name <firstname.lastname@example.com>
Date:   Tue May 7 15:21:06 2019 +0200

    Update room_skript.py

commit 8d04e1d93813e09b26ca25e1cbbf0f332c6111f5
Author: Name Name Name Name <email@example.com>
Date:   Tue May 7 14:55:59 2019 +0200

    Update views.py

commit 8550167a1fdf495b9b489a65eeb32461b1e30d21
Author: Name Name Name Name <email@example.com>
Date:   Tue May 7 14:42:23 2019 +0200

    Update settings.py

commit adcc29061fd25268a6697c18818ec958e0a9fc6b
Author: Name Name Name Name <firstname.lastname@example.com>
Date:   Tue May 7 14:25:01 2019 +0200

    Update settings.py

commit c4ff682b7b5c02f267a404761a7859b962e05f47
Author: Name Name Name Name <email@example.com>
Date:   Tue May 7 14:17:31 2019 +0200

    Update settings.py

commit bc726c0a4dfd57f2268a4e57200152745db4b936
Author: Name Name Name Name <firstname.lastname@example.com>
Date:   Tue May 7 14:04:48 2019 +0200

    Update admin.py

commit 0952e0cc232c34d516af4d9ae8014ca7304552cb
Author: Name Name Name Name <firstname.lastname@example.com>
Date:   Tue May 7 13:55:33 2019 +0200

    Update models.py

commit 1f27c822a03fb6db878d8affb0efc287273e94c1
Author: Name Name Name Name <email@example.com>
Date:   Tue May 7 12:36:52 2019 +0200

    Update settings.py

commit 3ad75b7c87c5631a22333fb0c917154c1764ca9e
Author: Name Name Name Name <firstname.lastname@example.com>
Date:   Tue May 7 12:28:12 2019 +0200

    Update settings.py

commit 2db94184e3391816c5834cfdd895006df7085bbe
Author: Name Name Name Name <firstname.lastname@example.com>
Date:   Tue May 7 12:17:15 2019 +0200

    Update settings.py

commit 147c600599291653a1128421e805f67f8c7eb710
Author: Name Name Name Name <firstname.lastname@example.com>
Date:   Tue May 7 12:16:32 2019 +0200

    Update settings.py

commit 4a0415d68830cf3cc80456605321abf7c925e96f
Author: Name Name Name Name <firstname.lastname@example.com>
Date:   Tue May 7 12:09:20 2019 +0200

    Update settings.py

commit d5613870826d7bcc58b0b9b0a6ffe981c999ed51
Author: Name Name <email@example.com>
Date:   Tue May 7 10:51:01 2019 +0200

    no message

commit 415729575f78b901dac5bfcf49fd0bd24b9ff5d1
Author: Name Name Name Name <email@example.com>
Date:   Tue May 7 09:06:00 2019 +0200

    Delete activate.bat

commit fc549dfc6ba69afac0e7f48efbbbca88e37c3fc3
Author: Name Name Name Name <email@example.com>
Date:   Fri May 3 15:18:52 2019 +0200

    Upload New File

commit 8f0995a8a3d3af8908c567c728bf63c2e3934503
Author: Name Name Name Name <email@example.com>
Date:   Fri May 3 15:18:28 2019 +0200

    Delete activate.bat

commit 1e992cad9dff9a5f5e222324202de9ca8b5ed931
Author: Name Name Name Name <email@example.com>
Date:   Fri May 3 15:17:55 2019 +0200

    Upload New File

commit aae3ebdc9f351cac1105a11a66577368209ce247
Author: Name Name <email@example.com>
Date:   Fri May 3 11:42:41 2019 +0200

    Added Jiaos Code

commit 49a893979d0351dd77369f96b11ee8793577b68c
Author: Name Name <firstname.lastname@example.com>
Date:   Thu May 2 15:39:16 2019 +0200

    Summe musste hinzugef<C3><BC>gt werden, um Programm laufen lassen zu k<C3><B6>nnen

commit aa9d44bc77a24b75c897dd8f4581f1aeb6f0b29e
Author: Name Name <email@example.com>
Date:   Thu May 2 15:19:47 2019 +0200

    Adjusted the folder names

commit 6b27c49966ffe38a5da525f20d1b1622049d8713
Author: Name Name <firstname.lastname@example.com>
Date:   Thu May 2 15:12:36 2019 +0200

    optCO2 added

commit 77cee5adae628cc1f3ab61070c77ea22d0dc20e9
Author: Name Name <email@example.com>
Date:   Thu May 2 14:48:57 2019 +0200

    results-Dateien angepasst

commit ecb3e0a8af3a1a027aa09bf606155ff408b8783d
Author: Name Name <firstname.lastname@example.com>
Date:   Tue Apr 9 09:03:33 2019 +0200

    Added the user profile generator

commit 80821cd5f6548598cb80de3d998b0e1dd3f8b2fd
Author: Name Name <firstname.lastname@example.com>
Date:   Wed Apr 3 11:29:57 2019 +0200

    PA and Paper added

commit a3cd71d31cd2276b2328e931f1bd2949ef8de50a
Author: Name Name <firstname.lastname@example.com>
Date:   Tue Apr 2 08:38:43 2019 +0200

    Names n<C3><B6>tige Skripte

commit c749b4d8aa9f915d7870cfa5e297832c3cab21c3
Author: fni <firstname.lastname@example.com>
Date:   Thu Oct 4 15:29:41 2018 +0200

    EBC Data API added

commit 6aca36443fe61429601315496a51c324c185c041
Author: Name Name <firstname.lastname@example.com>
Date:   Thu Oct 4 10:59:59 2018 +0200

    EBC Data API added

commit 278a4f5c7cd2769ae475b386afb7a5330ef76da3
Author: Name Name <firstname.lastname@example.com>
Date:   Tue Oct 2 16:53:39 2018 +0200

    EBC Data API added

commit 104f402dce48ab4595f4547c038546d1d99e047a
Author: Name Name <email@example.com>
Date:   Tue Oct 2 16:21:33 2018 +0200

    EBC Data API added

commit 1c668dff152ec5a9eab3bf7b0327c3855039f284
Author: Name Name <firstname.lastname@example.com>
Date:   Tue Oct 2 14:35:00 2018 +0200

    all files added

commit f846a116fe34f51c6d6612bdd318e6c75e614a71
Author: Name Name <firstname.lastname@example.com>
Date:   Tue Oct 2 14:23:08 2018 +0200

    Initial commit
(END)

I hope to get my files back :)
Answer: Did you track your directory with git? if so, you can try:
git reflog

And for your code, depending on the IDE you are using, you could get it back via the local history.


How to load all remaining content of a view after clicking a "load more" link?

Question: I have a view block that list contents.
What I want to do is to show only 5 items in this view and a load more link at the bottom of the view and if this link clicked, then show all remaining content of the view.
I tried the Views Load More module and the Views Infinite Scroll module. The Views Load More module didn't work, the Views Infinite Scroll module works good but I couldn't do what I want. It has an option to show X items per "show more" link clicked but it doesn't have an option to show all the remaining content of the view.
How to load all remaining content of a view after clicking a "load more" link?
Comment: I hesitate to post this as an answer (I might, if it makes sense ...): (1) clone that views block in a new views block that shows all content (2) adapt your views block to only show 5 items, and in its footer add a link with title "show more", which links to the same path, but with (say) "show_more" added to it. Then use block visibility settings to only show either block on relevant paths (pages). Makes sense? Or not at all?
Comment: It's a "*comment*" only (not an "*answer*") ... Ping me about it if you ever want me to convert it to an answer anyway. I'm also curious for "other" answers ... Have a nice day!
Comment: Thanks @Pierre.Vriens for your answer :) Hımm, I want to do this without refreshing/redirecting the page. I will try your solution if I can't find a "better" way. Thanks again.
Answer: You need Views show more module with ajax under views advanced setting. This module provides Initial item selection option, and rest of the item you can put in the section of on-click.
Steps-

Download and enable the module.
Select show more pager in the Pager section as shown in the image. Then go for setting for that. Now in my case I took 15 items, and I want to initially show 5 items and on clicking rest of the item. So I did put 5 under the Initial items and 10 items under Items to display as shown in second image. And under Animation section select Scroll to new content. Save this, so pager setting ends here.
Under advanced setting of views enable, Use Ajax: Yes

Views Block UI

Pager UI

Out put image:
Initial stage

After clicking show more

It does not require the page refresh to load content.
Comment: Thanks a lot for the answer. It does what I exactly need. I'm using the EVA module and at first it doesn't work then I found that (https://www.drupal.org/node/2672220) and then it worked.


dimension of an ideal (definition)

Question: Let $A$ be a commutative ring and $I$ an ideal. When we refer to the "dimension" of $I$, what exactly do we mean? Is it the Krull dimension of $A/I$? In particular, i am trying to understand the meaning of the "dim" function in Macaulay2.
Answer: I believe $\operatorname{dim} I$ can mean either of two things: $\operatorname{dim} A/I$ or $\operatorname{dim} I=\operatorname{dim} I /\operatorname{ann}(I)$, where we view $I$ as an $A$-module.
Comment: Do you have an example where the dimension of $I$ means $\operatorname{dim} I /\operatorname{ann}(I)$? Actually I never seen this!

dimension of an ideal (definition)


Avoiding numerical error propagation

Question: I simulated a MA(1) process $y_t = \mu + \epsilon_t + \theta \epsilon_{t-1}$ in R and tried to recover the error terms $\epsilon_t$ just by computing them successively (supposing I know the parameters $\mu$ and $\theta$).

# Variables
n = 30
mu = 10
theta = 5
sigma = 3

# Simulation of the MA(1) process
y = rep(1, n)
epsilon1 = rep(1, n)

prev.epsilon = 0
for (t in 1:n)
{
    epsilon1[t] = rnorm(1, mean = 0, sd = sigma)
    y[t] = mu + epsilon1[t] + theta * prev.epsilon
    prev.epsilon = epsilon1[t]
}

# Recovery of the error terms
epsilon2 = rep(1, n)

epsilon2[1] = y[1] - mu
for (t in 2:n)
    epsilon2[t] = y[t] - mu - theta * epsilon2[t - 1]

The problem is that that recovery process involves numerical errors that propagate until the recovered values of $\epsilon_t$ radically diverge from the true ones. Yet, I fixed the sample size to 30, which is very small. The values start diverging from the 18th term and here are the last values:

> epsilon1[n]
[1] -0.6801702
> epsilon2[n]
[1] -595.0506

How can I deal with that issue? Note that the actual sample size is much larger than 30.
Answer: Let $\mathbf \varepsilon = (\varepsilon_1, \varepsilon_2, \ldots, \varepsilon_n)$, $\mathbf y = (y_1,y_2,\ldots, y_n)$, and $\mathbf{\mu} = (\mu, \mu, \ldots, \mu)$.  The relationship among these vectors given in the question is
$$\mathbf y - \mathbf\mu = \mathbf{X}\mathbf \varepsilon$$
The matrix $\mathbf{X} = \mathbf{I} + \theta\mathbf{J}$ where $\mathbf{I}$ is the $n$ by $n$ identify matrix and $\mathbf J$ is the $n$ by $n$ matrix with $1$ on the immediate subdiagonal (that is, where $i = j+1$) and $0$ elsewhere.
The problem is that when $|\theta| \gt 1$, $\mathbf{X}$ can be practically singular.  (Since $\mathbf{X}^{-1} = \mathbf{I} + \sum_{i=1}^{n-1} (-1)^i \theta^i \mathbf{J}^i$ and the $i^\text{th}$ powers of $\mathbf J$ are also subdiagonal matrices with $1$s (on the diagonal $i$ steps below the main one), the largest entry in the inverse of $\mathbf X$ is $(-1)^{n-1}\theta^{n-1}$.  This can easily overflow floating point representations.  It will obliterate all precision once $(n-1)\log_{2}|\theta| \gt 52$, which for $\theta=5$ occurs once $n\ge 24$.)
R will even tell you about this problem:
n <- 30
theta <- 5; mu <- 10; sigma <- 3
set.seed(17); epsilon <- rnorm(n, sd=sigma)
x <- diag(1, n) + matrix(c(0, diag(1, n)[-n^2]), n, n) * theta
solve(x, rep(0, n))

Error in solve.default(x, rep(0, n)) :
    system is computationally singular: reciprocal condition number = 7.15828e-22

All statistical software provides a way around this: compute the generalized inverse (aka "least squares fit").  In R this can be done with lm (among other tools):
y <- mu + x %*% epsilon           # Compute the series `y`
d <- as.data.frame(cbind(y-mu, x))# Create a data frame for computing the solution
fit <- lm(V1 ~ . - 1, data=d)     # Obtain the solution
epsilon.hat <- coef(fit)          # Extract it from `fit`

This time there are no complaints.  Just for fun, I ran this procedure for $n=3000$.  Here is a plot of the recovered values of $\mathbf \varepsilon$ against the original ones, with the diagonal line (of perfect equality) superimposed for reference:
plot(epsilon, epsilon.hat, col="#00000060")
abline(c(0,1), col="#e0000080", lwd=2)

The recovery is not perfect, as evidenced by the single off-diagonal plotting symbol.  Experimentation suggests this is unavoidable; it is rare for the recovered errors exactly to equal the original ones.  The problems occur at the very end of the sequence, as evidenced by the vertical departures from zero (marked by the horizontal gray line):
res <- epsilon.hat - epsilon              # Residuals
plot(n-0:9, head(rev(res), 10), type="b",
     xlab="Index (t)", ylab="Residual", main="Last residuals")
abline(h=0, col="Gray", lty=2)

The very last one is NA (because lm recognized problems and dropped a variable, I believe).

Nevertheless, for such an unstable series that's a pretty good showing.
Comment: Thank you very much for this detailed answer and that working solution. I didn't suspect that a basic arithmetic task such as recovering errors from a MA(1) process could hide a matrix inversion... The issue is that my sample size will go way beyond 3000.
Answer: Your linear recurrence relation for $\epsilon_t$ is unstable. If you know $\epsilon_1$ with some absolute error $\delta$, then the subsequent values for $\epsilon_t$ will have absolute error on the order of $\theta^t \delta$.
Note that the error doesn't have to come from the estimation error for the parameters, it could also be the roundoff error coming from finite-precision floating-point arithmetic on your computer (then $\delta=O(10^{-16})$ in double precision). Note that $5^{30}\approx 10^{21}$.
Thus this is what you would expect when $|\theta|>1$. This is a mathematical property of the linear recurrence relation you've written down and the value of $\theta$ that you chose. Moving average processes with $|\theta|>1$ are called non-invertible.
Comment: Well, I chose any value for $\theta$ because MA(1) processes are always stationary. But I didn't think of the consequences of non-invertibility.

Avoiding numerical error propagation


Mixed effects model with cross random effects and nested random effects

Question: I'm a beginner with Mixed effects model, and I'm having a hard time trying to fit the model to my data.
My data has the following properties :

I have two disjointed groups of participants
All participants perform the same trials
There are three trial difficulties
During each trial, we measure each participant's response every 20 ms. Total trial time is 5000ms

I'm interested in comparing the performance of each group in trials of the same difficulty.
From what I've read about mixed effects models, my fixed effects should be Time, Group and Trial type.
I also think I need to use the interaction of Group and Trial, so that I get coefficients for each combination
Regarding the random effects, I'm not so sure but I think that

Participants are a nested random effect of Group
Trial type is a cross random effect of Group
Time is a cross random effect of Participant

Is that correct?
In addition I'm not sure how to represent this structure in the formula.
I've tried several formulas but all oh them returned NLL of - 220k
Would appreciate your help
Thanks
Answer: Interesting problem - I'll chime in with some thoughts though I am curious to hear what others on this forum have to say.
First, I think it will help if you think of your modelling in slightly different terms.
What are the random grouping factors in your modelling? Presuming that your subjects are representative of a larger set of subjects you are really interested in and your trials are representative of a larger set of trials you are really interested in, then you have two random grouping factors: Subject and Trial.  Since all trials are the same for each subject, these two random grouping factors are indeed crossed.
You can imagine the subjects included in your study forming one pile and the trials included in your study forming another pile.  Ideally, the subjects in your study were selected at random from the larger set of subjects and the trials in your study were selected at random from the larger set of trials; this would be a way to ensure their representativeness.
Now, imagine that each subject in your suject pile is paired (or crossed) with each trial in your trial pile. For each such pairing, you collect the value of your response variable every 20ms until 5000ms elapse.
Each of your two types of piles has certain properties you can measure; these will result in pile-specific predictors.
The subject pile has a property called Group, which divides the subjects in that pile into Group 1 and Group 2. In this sense, Group is a subject-level predictor.
The trial pile has a property called Trial_Type, which divides the trials in that pile into Trial Type 1, Trial Type 2 and Trial Type 3. In this sense, Trial_Type is a trial-level predictor.
There is also a Time predictor, measured at the lowest level of your data hierarchy - indeed, each time you measure your response variable for a (subject,trial) pairing, you also record the value of the Time predictor.
You didn't indicate the nature of your response variable; let's assume you can treat this response variable as a continuous variable.  If you only measured the response variable once for each (subject,trial) pairing, your model could perhaps be specified like this in R under appropriate assumptions for the conditional distribution of the response variable :
lmer(response ~ Group*Trial_Type + (1|Subject) + (1|Trial)

This model includes (crossed) random effects for Subject and Trial and fixed effects for Group and Trial_Type.
If you only measured your response variable at a relatively small number of times (say, four times for simplicity), then you would have to include Time in your model.  You could include it like so, for example:
lmer(response ~ Time*Group*Trial_Type +  (1 + Time|Subject) +
                (1 + Time|Trial)

This last model includes both a fixed effect of time (which can depend on Group and Trial_Type) and a random effect of time across Subjects and a random effect of time across Trials. The reason you can allow for these random effects is because the value of Time was recorded repeatedly within each Subject and also within each Trial.
Note that only predictors measured at the lowest level of your data hierarchy can have random effects in your model, as is the case for the Time predictor.
The difficulty in your setting is that you have quite a large number of values for Time within each (subject,trial) pairing.  So you will likely need to use a function like gam or bam to fit your model (see the mgcv package in R). This would allow you to consider a fixed effect of Time that is smooth and possibly nonlinear in addition to considering random effects of Subject and Trial as well as random effects of Time (smooth, nonlinear) across Subject and across Trial.  You will likely need to look into factor-smooth interactions (https://fromthebottomoftheheap.net/2017/10/10/difference-splines-i/) and hierarchical generalized additive models (https://peerj.com/articles/6876/) to solve your problem.


Draw multiple shapes using loop - Android Canvas

Question: I am very new to android development and have been trying to draw a square comprised of multiple smaller rectangles of different colours... Like a Mosaic essentially.
Basically at the moment I am reading values from a file which assigns the colour to the smaller Rects. I am using a pair of nested for loops to try to draw the small Rects sequentially, line by line. However when the program finishes there is only one small Rect drawn which is the last one to be drawn and its colour corresponds to the first value read from the file.
Here is some of my code to show you what I mean:
public SnapshotDraw(Context context) {
    super(context);

    for(int a = 0; a < 63; a++){
        for(int b = 0; b < 63; b++){
            fileName = PREFIX + "2" + EXTENSION;

            try {
                bf = new BufferedReader(new FileReader(fileName));
                tokens = new StringTokenizer(bf.readLine(), " \n");
                weight = Byte.parseByte(tokens.nextToken());

                x_scalar = b*MAG;
                y_scalar = a*MAG;

                mDrawable = new ShapeDrawable(new RectShape());
                mDrawable.getPaint().setColor(colour.getColour(weight));
                mDrawable.setBounds((X_OFFSET + x_scalar), (Y_OFFSET + y_scalar), ((MAG + X_OFFSET) + x_scalar), ((MAG + Y_OFFSET) + y_scalar));

            } catch (FileNotFoundException ex) {
                Logger.getLogger(NetworkUtilities.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(NetworkUtilities.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

protected void onDraw(Canvas canvas) {
    mDrawable.draw(canvas);
}

This except is from a class which extends View and is called inside an onCreate() method in an Activity.
I would appreciate any guidance in this and thanks in advance!!
Cheers.
Comment: Ok so I put the tokens line inside the outer for loop and it is returning one square in final position with the correct colour corresponding to is position in the datafile... So one issue down and one still to go!! Why does this code only print out 1 Rect (the last Rect) and not all of them?
Answer: You are constructing the BufferedReader inside the loops, so bf.readLine() will always return the same line. Try moving bf and tokens (be aware that the use of StringTokenizer is discouraged) out of the loops.
Comment: @travega: "StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code." http://download.oracle.com/javase/6/docs/api/java/util/StringTokenizer.html
Comment: Hi Tedil,

Thanks for the reply I never knew they were discouraged!! Why is that?
Unfortunately I am just getting null pointer exceptions now...!
Answer: Ok I got it sorted! Here is what I did to solve it:
public SnapshotDraw(Context context) {
    super(context);
    setFocusable(true);

    mBitmap = Bitmap.createBitmap(475, 720, Bitmap.Config.ALPHA_8);
}

@Override
protected void onDraw(Canvas canvas) {
    canvas.drawColor(Color.BLACK);

    Paint p = new Paint();
    float y = 10;

    try {
        fileName = PREFIX + "2" + EXTENSION;
        bf = new BufferedReader(new FileReader(fileName));

        for(int a = 0; a < 63; a++){
            tokens = bf.readLine().split(" \n");
            for(int b = 0; b < 63; b++){

                weight = Byte.parseByte(tokens[b]);

                x_scalar = b*MAG;
                y_scalar = a*MAG;

                p.setColor(new Colour().getColour(weight));
                canvas.drawRect((X_OFFSET + x_scalar), (Y_OFFSET + y_scalar), ((MAG + X_OFFSET) + x_scalar), ((MAG + Y_OFFSET) + y_scalar), p);
            }
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(NetworkUtilities.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(NetworkUtilities.class.getName()).log(Level.SEVERE, null, ex);
    }

    canvas.drawBitmap(mBitmap, 10, y, p);
}

Much the same as before but changed the way I draw to the Bitmap. It looks beautiful btw!!


Finding out what file was called immediately before error

Question: I'm getting the following errors in dblog whenever I look at a page:
Notice: Undefined offset: 0 in _menu_check_access() (line 635 of /home/mysite/public_html/includes/menu.inc).
Notice: Undefined offset: 1 in _menu_check_access() (line 635 of /home/mysite/public_html/includes/menu.inc).
I know it's not Menu that's causing the issue, but rather, some module is passing permissions incorrectly via hook_menu.
I remember reading a long time ago that one way to find out which module is causing core to emit notices, is to drop a function right before the line in question. Alas, I cannot find that page at all.
Any thoughts?
Comment: Are you able to install XDebug? It makes life awfully easy and only takes about 10 minutes to setup with Eclipse
Comment: That's a thought. Alas, I'm kind of triaging a production instance that somebody else has updated -- I'd have to freshly clone the site to local.
Comment: Bummer :/ What about a different approach - loop through the return from `module_invoke_all('menu')` and check that the `access arguments` for each is a valid, non-empty array. It'll produce some false positives (not all menu items use `user_access()` and not all have arguments) but it should narrow things down a bit
Answer: If you are tracking down a weird error, editing core is perfectly acceptable.

Make sure everything is in your RCS.
Edit includes/menu.inc
Place a print_r(debug_backtrace()) near line 635, preferable at the top of _menu_check_access().  Alse print_r() the arguments.
Trigger the problem.
Figure out what happened.
Revert the site to the checked in RCS version.

My guess is you are getting weird path, and the argument is wonky for your access check.  In other words, you are trying to access check something that should really 404.
Comment: +1, Instead of printing entire stack, you could also print the last called function . `$trace  = debug_backtrace();array_shift($trace);print_r($trace[0]['function']);`
Comment: I'm getting a lot of output from that and nothing's really sticking out. I'm trying to add some exception handling (Via http://stackoverflow.com/questions/10520390/stop-script-execution-upon-notice-warning), but I get the unhelpful "The website encountered an unexpected error. Please try again later." message. Any thoughts?
Comment: @2-Stroker -- That's helpful; debug_backtrace'ing a Drupal site outputs an obscene amount of text. Thanks!
Comment: I would recommend installing the devel module and using dpm(debug_backtrace()); - It gives much more useful output for data of this scale.
Comment: Apologies for the late accept; this is a rather good answer if unable or unwilling to install debugging tools. Otherwise, Clive's suggestion to clone to local and use Xdebug is a really good idea. Using a proper development methodology is much better than trying to triage a live site!


How to set lateinit Kotlin property to null

Question: The below class has a very unique lifecycle, which requires me to temporarily null out lateinit properties
class SalesController : BaseController, SalesView {
    @Inject lateinit var viewBinder: SalesController.ViewBinder
    @Inject lateinit var renderer: SalesRenderer
    @Inject lateinit var presenter: SalesPresenter
    lateinit private var component: SalesScreenComponent

    override var state = SalesScreen.State.INITIAL  //only property that I want to survive config changes

    fun onCreateView(): View {  /** lateinit variables are set here */ }
    fun onDestroyView() {
         //lateinit variables need to be dereferences here, or we have a memory leak
         renderer = null!! //here's the problem: throws exception bc it's a non-nullable property

}
    }
Here's how it's used by the framework.
controller.onCreateView() //same instance of controller
controller.onDestroyView() //same instance of controller
controller.onCreateView() //same instance of controller
controller.onDestroyView() //same instance of controller

My lateinit properties are injected by dagger, and I need to set them to null in onDestroyView - or have a memory leak. This however is not possible in kotlin, as far as I am aware (without reflection). I could make these properties nullable, but that would defeat the purpose of Kotlin's null safety.
I'm not quite sure how to solve this. Ideally there could be some type of annotation processor that would generate java code to null out specific variables automatically in onDestroyView?
Comment: why you have a leak? maybe the problem is on the SalesController rather than on its properties? I've never needed to explicitly set to null a property injected by Dagger to avoid leak problems...
Comment: @Massimo Conductor's controller instances survive config changes https://github.com/bluelinelabs/Conductor
Comment: If you need to nullify them, you don't need to have `lateinit` then. And I'm pretty sure you are don't have any leak there, you are just mixing some definitions. You would leak if your presenter would reference your View, not vice-versa
Answer: Kotlin lateinit properties use null as an uninitialized flag value, and there's no clean way to set null in the backing field of a lateinit property without reflection.

However, Kotlin allows you to override the properties behavior using delegated properties. Seems like there's no delegate that allows that in kotlin-stdlib, but if you need exactly this behavior, you can implement your own delegate to do that, adding some code to your utils:
class ResettableManager {
    private val delegates = mutableListOf<ResettableNotNullDelegate<*, *>>()

    fun register(delegate: ResettableNotNullDelegate<*, *>) { delegates.add(delegate) }

    fun reset() { delegatesToReset.forEach { it.reset() } }
}

class Resettable<R, T : Any>(manager: ResettableManager) {
    init { manager.register(this) }

    private var value: T? = null

    operator fun getValue(thisRef: R, property: KProperty<*>): T =
            value ?: throw UninitializedPropertyAccessException()

    operator fun setValue(thisRef: R, property: KProperty<*>, t: T) { value = t }

    fun reset() { value = null }
}

And the usage:
class SalesController : BaseController, SalesView {
    val resettableManager = ResettableManager()
    @set:Inject var viewBinder: SalesController.ViewBinder by Resettable(resettableManager)
    @set:Inject var renderer: SalesRenderer by Resettable(resettableManager)
    @set:Inject var presenter: SalesPresenter by Resettable(resettableManager)

    fun onDestroyView() {
        resettableManager.reset()
    }
}

Comment: I didn't think you could have `@Inject` on a 'member property with delegate'.
Comment: @mfulton26, thanks for the remark! Do you think it will work with `@set:Inject`?
Comment: Good thinking. I think it will (I'm not using Dagger or anything but at least that compiles).
Comment: This is perfect. Works great - except I'm not sure what to do now with named injections. normally I did `@field:[Inject Named("bold")]`, but you can't use `@field` with delegated properties
Comment: @hotkey nope. Dagger2 ignores the `@Named` part


How to set onclicklistener to Drawable on canvas?

Question: I do not have imageview,I have drwable and I draw it on canvas like this:
drawable.draw(canvas);

How can I set onclicklistener to drawable ?
I use this project : https://code.google.com/p/android-multitouch-controller/
(I want to use on click listener because I want to remove drawable on canvas)
thanks in advance.
Answer: A drawable does not have any facility to receive events or otherwise interact with the user. It's just a visual response as far as the android os is concerned and is often used as fetched resource.
You might be better off creating a view. Then override the
onDraw(android.graphics.Canvas)

But if you must, consider the getBounds in your endeavours.
Comment: I want to use on click listener because I want to remove drawable on canvas
Comment: then perhaps in the nearest view you handle the input checking if the touch point is within the getBounds, delete if so.
Comment: I want to need on long listener or on long touch listener, because I want to delete that drawable ?


The integral of a closed form along a closed curve is proportional to its winding number

Question: Source: Guillemin-Pollack Exercise 4.8.2.

Let $\gamma$ be a smooth closed curve in $\mathbb{R}^2 - \{0\}$ and $\omega$ any closed $1$-form on $\mathbb{R}^2 - \{0\}$. Prove that$$\oint_\gamma \omega = W(\gamma, 0) \int_{S^1} \omega,$$where $W(\gamma, 0)$ is the winding number of $\gamma$ with respect to the origin. $W(\gamma, 0)$ is defined just like $W_2(\gamma, 0)$, but using degree rather than degree mod $2$; that is, $W(\gamma, 0) = \text{deg}(\gamma/|\gamma|)$. In particular, conclude that$$W(\gamma, 0) = {1\over{2\pi}}\oint_\gamma d\,\text{arg}.$$

My solution:
Consider the mapping $f: \gamma \mapsto S^1$ defined by $f(x) = x/|x|$. Then we can consider the pullback of $\omega$ under this mapping to get$$\oint_\gamma f^*\omega = (\deg f)\int_{S^1} \omega = W(\gamma, 0) \int_{S^1} \omega = 2\pi\,{W(\gamma, 0)}.$$Therefore, if we can show that $f: \mathbb{R}^2 - \{0\} \mapsto S^1$ is homotopic to the identity mapping, we will be able to show the desired result. Consider the homotopy $H(x, t) = x/(t|x| + (1-t))$. This is the desired homotopy, so the result holds because$$\oint_\gamma f^*\omega = \oint_\gamma \iota^* \omega = \oint_\gamma \omega = \oint_\gamma d\,\text{arg}.$$My question is, is what I have correct? I feel rather unsure with the material. For starters, is $f: \gamma \mapsto S^1$ defined by $f(x) = x/|x|$ the right notation/even valid? Does anyone more experienced have any intuition they could possibly help?
Answer: For the most part, the proof is correct. The definition of the map $f$ makes perfect sense.  Pullback under $f$ makes sense enough (although at this point you're really pulling back under $\iota\circ f$ where $\iota$ is the inclusion of $S^1$ into $\mathbb{R}^2$).
But this part is both wrong and unnecessary:

$$  W(\gamma, 0) \int_{S^1} \omega = 2\pi\,{W(\gamma, 0)}$$

There's no reason for $\int_{S^1} \omega$ to be equal to $2\pi$. It can be any real number whatsoever; after all, one can multiply $\omega$ by a constant.
Similarly, this step is both wrong and unnecessary:

$$
\oint_\gamma \omega = \oint_\gamma d\,\text{arg}.$$

Eliminating the wrong steps, you end up with a chain of equalities
$$W(\gamma, 0) \int_{S^1} \omega  = \cdots = \oint_\gamma \omega$$ which is what was required.


Villarceau circles of the square torus

Question: I'm talking of ordinary tori in 3D (donuts). According to a paper I read and my understanding, "the" square torus is the torus with $R/r = \sqrt{2}$ (where $R$ and $r$ are the major and the minor radii).

Why is it called "square"?

Is is true that two Villarceau circles on the square torus meet at a right angle?

If this is true, do you have a reference for this fact? I googled with no luck.
Answer: Speaking holomorphically, a torus is obtained from quotienting the Euclidean plane by a lattice. Two tori are equivalent if and only if their lattices are similar (one is a non-zero complex multiple of the other).
A square torus comes from the lattice of Gaussian integers, $\mathbf{Z} + i\mathbf{Z}$, or another square lattice.
Assume $a$ and $b$ are positive real numbers satisfying $a^{2} + b^{2} = 1$. A rectangular torus (i.e., whose lattice is rectangular) with aspect ratio $b/a$ may be obtained in two steps: Parametrize the flat torus in the three-sphere
$$
T(u, v) = (a\cos u, a\sin u, b\cos v, b\sin v),
$$
then map to Euclidean three-space by stereographic projection from $(0, 0, 0, 1)$:
$$
X(u, v) = \frac{1}{1 - b\sin v}(a\cos u, a\sin u, b\cos v).
$$
The flat torus parametrization is a local isometry from the Euclidean plane and stereographic projection from the three-sphere is conformal, so this parametrization is conformal.
If $a = b = 1/\sqrt{2}$, the preceding formula is a conformal parametrization of a square torus.
Villarceau circles are images of lines of slope $\pm1$ in the Euclidean plane, so yes, they meet at right angles.
<>
You may enjoy this interactive web program for drawing on a square torus. (Usage instructions are at the bottom of the linked page.) Particularly, you can test the claim about Villarceau circles by drawing diagonal lines.
Comment: Yes; for a rectangular torus they're images of lines parallel to the diagonals of a fundamental rectangle.
Comment: Thanks. When you claim that Villarceau circles are the images of lines with slope $\pm 1$, this is the case only for the square torus, right?

Villarceau circles of the square torus


Why aren't these eigenvectors orthogonal?

Question: As far as I know, the matrix: $$M = \begin{pmatrix}1 & 0 & i\sqrt{3} \\ 0 & 2 & 0 \\ -i\sqrt{3} & 0 & 3 \end{pmatrix} $$
Is hermitian with eigenvalues: $\lambda_1 = 0, \lambda_2 = 2, \lambda_3 = 4$.
And corresponding eigenvectors:
$V_{\lambda_1 = 0} = \begin{pmatrix}-i\sqrt{3} \\ 0 \\ 1\end{pmatrix} $,
 $V_{\lambda_2 = 2} = \begin{pmatrix}0\\ 1 \\ 0\end{pmatrix} $,
 $V_{\lambda_3 = 4} = \begin{pmatrix}\dfrac{i}{\sqrt{3}}\\ 0 \\ 1\end{pmatrix} $
Since these are eigenvectors of distinct eigenvalues they should be orthogonal but the first and third are not orthogonal.
Why is this?
Comment: Maybe they are hermitian orthogonal.
Answer: They are orthogonal. \begin{align}V_0^HV_2&=0\\ V_2^HV_4&=0\\ V_0^HV_4&=\begin{pmatrix}i\sqrt3&0&1\end{pmatrix}\cdot\begin{pmatrix}\frac i{\sqrt3}\\ 0\\ 1\end{pmatrix}=0\end{align}
Comment: I did not check that the original eigenvectors are OK, but there is a sign difference in the top term of your vertical vector.
Comment: @Andrei Like the one you do when you take the Hermitian of something?
Comment: Ah! Thank you so much
Comment: @SaucyO'Path thanks. I somehow missed that.


Send signals to remote process with Python

Question: There are two machines, where one has a script wait_for_signal.sh, and the second one has a script named controller.py. The code of each script is shown below.
The purpose of the controller.py is to spawn a subprocess that calls the wait_for_signal.sh script through ssh. When the controller needs to exit it needs to send an interrupt to the remote process that runs wait_for_signal.sh.
wait_for_signal.sh
#!/bin/bash
trap 'break' SIGINT
trap 'break' SIGHUP

echo "Start loop"

while true; do
  sleep 1
done

echo "Script done"

controller.py
import os
import signal
import subprocess

remote_machine = user@ip
remote_path = path/to/script/

remote_proc = subprocess.Popen(['ssh', '-T', remote_machine,
                               './' + remote_path + 'wait_for_signal.sh'],
                               shell=False, stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE)

# do other stuff

os.kill(remote_proc.pid, signal.SIGINT)

Currently, the signal send is to the process that started the ssh connection on the local machine and not the remote machine. This causes the local process to stop but the remote process continues to execute.
How does ssh work and what type of signals does it send to the remote machine when it is stopped? How can I send the appropriate signal to the remote process, which was started by the ssh connection?
Answer: You're invoking ssh with the -T option, meaning that it won't allocate a PTY (pseudo-TTY) for the remote session. In this case, there's no way to signal the remote process through that ssh session.
The SSH protocol has a message to send a signal to the remote process. However, you're probably using OpenSSH for either the client or the server or both, and as far as I can tell, OpenSSH doesn't implement the signal message. So the OpenSSH client can't send the message, and the OpenSSH server won't act on it.
There is an SSH extension to send a "break" message which is supported by OpenSSH. In an interactive session, the OpenSSH client has an escape sequence that you can type to send a break to the server. The OpenSSH server handles break messages by sending a break to the PTY for the remote session, and unix PTYs will normally treat a break as a SIGINT. However, breaks are fundamentally a TTY concept, and none of this will work for remote sessions which don't have a PTY.
I can think of two ways to do what you want:

Invoke ssh with the -tt parameter instead of -T. This will cause ssh to request a TTY for the remote session. Running the remote process through a TTY will make it act like it's running interactively. Killing the local ssh process should cause the remote process to receive a SIGHUP. Writing a Ctrl-C to the local ssh process's standard input should cause the remote process to receive a SIGINT.

Open another ssh session to the remote host and use killall or some other command to signal the process that you want to signal.


Is $\mathrm{Hom}_{R}(A,\prod_{i\in I} B_{i}) \cong \prod_{i\in I}\mathrm{Hom}_{R}(A, B_{i})$?

Question: Let $R$ be a ring, $A$ is a left $R$-module, and $(B_{i})_{i\in I}$ is a family of left $R$-module. We have:
$$\mathrm{Hom}_{R}(A,\prod_{i\in I} B_{i}) \cong \prod_{i\in I}\mathrm{Hom}_{R}(A, B_{i}).$$
However, I've seen an exercise:

If $Z_{i} \cong \mathbb{Z}$, then $\mathrm{Hom}_{\mathbb{Z}}(\prod_{i\in I}Z_{i},\mathbb{Z})$ is not isomorphic to $\prod_{i\in I} \mathrm{Hom}_{\mathbb{Z}}(Z_{i},\mathbb{Z})$.

If we use the first statement, the exercise will be wrong. It means that both of them is an isomorphism.
Comment: Generally, (covariant) representable functors preserve limits. The dual statement is, that contravariant representable functors send colimits to limits.
Comment: Your explantion is hard for me :(. Could you show me specifically?
Answer: It's true that $Hom_{R}(A,\prod_{i\in I} B_{i}) \cong \prod_{i\in I}Hom_{R}(A, B_{i})$ : that is the definition of a product in a category.
On the other hand, $Hom_{R}(\bigoplus_{i\in I} B_{i},A) \cong \prod_{i\in I}Hom_{R}(B_{i}, A)$, because the coproduct is $\bigoplus$ and not $\prod$.
And in general since $\bigoplus B_i\neq \prod B_i$ you don't have $Hom_{R}(\prod_{i\in I} B_{i},A) \cong \prod_{i\in I}Hom_{R}(B_{i}, A)$.
Explicitly : if you take $A = B_i = \mathbb{Z}$, and for every $i$ you choose $Id_\mathbb{Z}\in Hom_R(B_i,A)$, this will give you a morphism $\bigoplus_{i\in I} \mathbb{Z}\to \mathbb{Z}$ but not a morphism $\prod_{i\in I} \mathbb{Z}\to \mathbb{Z}$ because the image of $(1,1,\dots)$ would be an infinite sum of $1$ (whereas in $\bigoplus_{i\in I} \mathbb{Z}$ all the families of elements are finite so you can always take $(n_i)_{i\in I}\mapsto \sum_{i\in I}n_i$).
Comment: No, of course $Hom_{R}(\prod_{i\in J} B_{i},A)$ exists, for instance you always have the zero morphism. What I'm saying is that $Hom_{R}(\prod_{i\in I} B_{i},A) \neq \prod_{i\in I}Hom_{R}(B_{i}, A)$ in general. In the example I give, on the right side you have $(Id_\mathbb{Z})_i$, but it has no equivalent on the left side.
Comment: I am sorry. I would like to ask that your main idea is $Hom_{R}(\prod_{i\in J} B_{i},A)$ can not be defined, is it right? Because take $f\in Hom_{R}(\prod_{i\in J} B_{i},A)$ then $f(1,1,....)$ can not be defined?
Comment: "Not isomorphic" is not the same as "not canonically isomorphic".
Comment: It's true that I simplified a bit, but I strongly doubt that the OP wanted to know that there is no abstract isomorphism between the two (and in any case there isn't).
Comment: Ok, again. With $B_{i}=\mathbb{Z}, i\in I$, take $(Id_{\mathbb{Z}}, Id_{\mathbb{Z}},...)$ in $\prod_{i\in I} Hom(\mathbb{Z},\mathbb{Z})$. We do not have element in $Hom_{Z}(\prod_{i\in I} \mathbb{Z_{i}},\mathbb{Z})$. But I am sorry that what about $f=(Id_{\mathbb{Z}})_{i} in Hom_{Z}(\prod_{i\in I} \mathbb{Z_{i}},\mathbb{Z}).$. It can be equal $(Id_{\mathbb{Z}})_{i}$, right?
Comment: I mean that $j_{i}$ is embedding map,$ j_{i}: \mathbb{Z} \mapsto \prod_{i\in I}\mathbb{Z}$. With $f$ in $Hom(\prod_{i\in I} \mathbb{Z}, \mathbb{Z})$ we have $(fj_{i})_{i\in I} \in \prod_{i\in I}Hom(\mathbb{Z},\mathbb{Z})$ . It means we always have $2$ element being equivalent on the both side, right? :( Actually, I do not understand why you said that it has no equivalent on the left side


How to find integration without any sort of modification to the current function?

Question: I want to integrate a difficult single variable function but I don't want to modify the given function i.e. factorising, rationalizing, etc.
The question is:
$$f(x)= (x^3-4x^2+4x)(x^2-4)^{-1}$$
The answer turns out to be equals to:
$g(x)= (x^2/2)+4\ln(|x-4|)+C$ after factorising the question. But I don't want this!
If you can see, there is something special about the question itself.
At $x=2$ the $f(x)=0/0$. But when we calculate derivative of $g(x)$ we get,
$h(x)= (x^2-4x+4)(x-4)^{-1}$ but $h(x)$ is not equals to $0/0$ at $x=2$...
So I want a $F(X)$ whose derivative will give "exactly" my original given $f(x)$- no factorization, no rationalization, etc...
(You can use u-substitution but be careful my objective shall be achieved)
and I'm well aware that $h(x)$ is equivalent to $g(x)$...
In short, I want a F(X) such that its derivative is exactly equals to my given f(x)- it doesn't matter what techniques you use! You can even use technique other than integration if possible.
Thank you for spending your precious time
Respected Regards,
Swayam Jha
Comment: Strange question... As the derivative of $g$ is $f$ and the antiderivative is unique apart a constant you're done.
Comment: Sorry my mistake, i have mistakenly written that x in denominator. Thanks for pointing it out!
Comment: Out of curiosity, why don't you want to use things like factoring, rationalizing, etc?
Comment: I have specified the reason already! Please read it again carefully.
Comment: is this a question you made up or is it given to you by someone else?
Comment: The question, I mean the f(x) I have taken from my course book but the objective is my own!
Comment: The simplest way to see that $f(2) =0$ is to use the definition of $f$:  $$f(x)= \frac{x^3-4x^2+4x}{x^2-4x}$$ and simply substitute $x$ by $2$:

$$f(2)= \frac{2^3-4\cdot 2^2+4\cdot 2}{2^2-4\cdot 2}=  \frac{8-16+8}{4-8}=  \frac{0}{-4}=0$$
Comment: I personally really dislike these "solve ____ without ____ " type problems.
Comment: @SwayamJha But then... $g(x)= (x^2/2)+4\ln(|x-4|)+C$ is **not** the integral of $f(x)= (x^3-4x^2+4x)(x^2-4)^{-1}$.  Please note that $g'(x)= (x^2-4x+4)(x-4)^{-1}$. It is no longer a matter of multipliying both the numerator and the denominator by $x$.
Answer: What you are asking is not really possible.
The antiderivative of $\dfrac xx$ is $x$ for all $x\ne0$, the derivative of which is $1$.
You might try to express as
$$x\frac xx,$$ formally giving the derivative
$$\frac xx+x\frac{x-x}{x^2}$$ and it would be arbitrary to say that this is $\dfrac xx$ rather than $\dfrac xx+\dfrac{x-x}x$ or other forms.

Also trying $$\frac{x^2}x,$$ we have
$$\frac{2x^2-x^2}{x^2}=\,?$$
Comment: So isn't it possible by any means? I mean there might be a F(x) must exist whose derivative is equals to our original f(x)....?
Comment: @sergeiivanov: your comments have nothing to do with my answer. Please move them.
Comment: No I ain't genius like Ramanujan who can guess. But I got what i wanted. @Sal cleared my query and gave the solution.
Comment: @sergeiivanov: just understand that you commented at the wrong place.
Answer: The trouble is that you are treating the indeterminate form $f(2)=0/0$ as a number, while $f(2)$ is well defined, as you can verify by looking at the graph. Applying L'Hopital (or by whatever method you like$^\dagger$), we see that $f(2)=0$. As expected, $g'(2)=0$, so $g'(2)=f(2)$. If you really wanted, I suppose you could write
$$ g'(x)=\frac{4}{x-4}+x=\frac{x^2-4x+4}{x-4}$$
Multiply top and bottom by $x-2$
$$ g'(x)=\frac{(x^2-4x+4)(x-2)}{(x-4)(x-2)}=\frac{x^3-6x^2+12x-8}{x^2-6x+8}$$
Which also has the indeterminate form $0/0$ at $x=2$
EDIT: actually, just multiply $g'$ by $1=x/x$ and we recover your original function
$$ g'(x)=\frac{(x^2-4x+4)(x)}{(x-4)(x)}=\frac{x^3-4x^2+4x}{x^2-4x}=f(x)$$
$\dagger$ It is simplest by reversing the last step (dividing by $1=x/x$)
$$f(x)= \frac{x^3-4x^2+4x}{x^2-4x}=\frac{x^2-4x+4}{x-4}$$
Evaluating the right hand side at $x=2$ gives $0/2=0$
Comment: Yeah after your edit I got the answer...... But explain on more time why f(2)=0? By looking at the graph?
Comment: Edited my post with how to find $f(2)$


How to import more-vert icon in material-ui for react?

Question: I tried a lot but i am not able to find a way to do it. Where is its exact location in material-ui? I saw some people using it. Any help is appreciated.
My best guess was :
import MoreVertIcon from '@material-ui/icons/more-vert';

Answer: Make sure you install the icon library with npm install -S @material-ui/icons and then import it like this:
import MoreVertIcon from '@material-ui/icons/MoreVert';

If you wonder what the name of a particular icon is, you can see them listed here.
Answer: Mui v5 import:
import MoreVertIcon from '@mui/icons-material/MoreVert';

https://mui.com/components/material-icons/?query=MoreVert&selected=MoreVert
Answer: Before use material ui icon You may need to import for that.
Steps:-

Open CMD
Copy this command:- " npm install -S @material-ui/icons "
Import icon that you want " import MoreVertIcon from '@material-ui/icons/more-vert'; "

Thanks


Grobner basis sufficient condition

Question:
Assume $f \in K[x_1,\dots ,x_m],x_i\in F$
$$p \in K[x_1,\dots, x_m], p = \sum_{i}\phi_ix_1^{{a}_{i1}}x_2^{a_{i2}}\dots x_n^{a_{in}}, L(p) := \phi _lx^l : x^a \prec x^l \forall a\in A(p) \backslash\{l\}$$
$$\textbf{th. 1}: [\forall f_i, f_j \in\{f_1,f_2 \dots,f_n\} = F : \nexists \lambda \in F: L(f_i) = \lambda L(f_j) ] \rightarrow [F - \text{Grobner basis}] (\textbf{It isn't true, following Marcus Ritt's counterexample})$$
$$\textbf{th. 2}: [\forall f_i, f_j \in\{f_1,f_2 \dots,f_n\} = F : \forall i \neq j : L(f_i) \text{ and } L(f_j) \text{ are mutually prime} ] \rightarrow [F - \text{Grobner basis}]$$

Looks like this feature works in general, but i don't know, how to prove it. Is it true, that if left-hand condition is true, then $S$-polynomial $S(f_i,f_j) \overset{F}{\rightsquigarrow} 0$ (reducible to zero), so i could use Buchberger criteria ?
Comment: No, but then please give the definition of $L$.
Comment: Do you have a reference for the theorem? What's the definition of $L$?
Comment: idk, i found this statement by myself and want to prove it, should i edit "th." to "st." ?
Comment: $L(f_i)$ is the "leading" (greatest monomial)
Comment: in lexicographical order i mean
Answer: No, for example $F=\{f_1,f_2\}$ with $f_1=x^2y-2y^2+x$ and $f_2=x^3-2xy$ satisfies your criterion, but is not a Gröbner basis, since $S(f_1,f_2)=x^2$.
Comment: hmm, you're right, but is it true, if we assume that, $\forall i\neq j : L(f_i)$ and $L(f_j)$ are mutually prime? In this case I think, it should work

Grobner basis sufficient condition


A question about double zeta values

Question: \begin{align*}
 &\zeta \left( {\bar 2,2} \right) + 2\zeta \left( {\bar 3,1} \right) = \frac{5}{{16}}\zeta \left( 4 \right), \\
 &\zeta \left( {\bar 4,2} \right) + 4\zeta \left( {\bar 5,1} \right) = \frac{1}{4}\zeta \left( {4,2} \right) - \frac{{37}}{{64}}\zeta \left( 6 \right) + \frac{1}{2}{\zeta ^2}\left( 3 \right), \\
 &\zeta \left( {\bar 6,2} \right) + 6\zeta \left( {\bar 7,1} \right) =  - \frac{9}{8}\zeta \left( {6,2} \right) - \frac{{1887}}{{256}}\zeta \left( 8 \right) + 6\zeta \left( 3 \right)\zeta \left( 5 \right).
\end{align*}
Based on the above three results, I conjecture that
\begin{align*}
 \zeta \left( {\bar 8,2} \right) + 8\zeta \left( {\bar 9,1} \right) =& {a_1}\zeta \left( {8,2} \right) + {a_2}\zeta \left( 2 \right)\zeta \left( {6,2} \right) + {a_3}\zeta \left( {10} \right) + {a_4}{\zeta ^2}\left( 5 \right) \\
  &+ {a_5}\zeta \left( 3 \right)\zeta \left( 7 \right) + {a_6}\zeta \left( 2 \right)\zeta \left( 3 \right)\zeta \left( 5 \right) + {a_7}{\zeta ^2}\left( 3 \right)\zeta \left( 4 \right)\quad ?.
\end{align*}
Here the coefficients $a_i\ (i=1,2,3,4,5,6,7)$ are rational numbers.
In general, the combined alternating mzvs
$$\zeta \left( {{\overline {2m}},2} \right) + 2m\zeta \left( {{\overline {2m + 1}},1} \right)=?\quad (m\in \mathbb{N}).$$
It can be expressed in terms of non-alternating mzvs and zeta values?
Here the double zeta values are defined by
\begin{align*}
\zeta \left( {p,q} \right): = \sum\limits_{{n_1} > {n_2} > 0} {\frac{1}{{n_1^pn_2^q}}} ,\zeta \left( {\bar p,q} \right): = \sum\limits_{{n_1} > {n_2} > 0} {\frac{{{{\left( { - 1} \right)}^{{n_1}}}}}{{n_1^pn_2^q}}} \quad (p,q\in \mathbb{N}).
\end{align*}
Answer: Your conjecture is quite likely to be true. Let's us take the case $m=4$. We have:
\begin{eqnarray}
\zeta(\bar{8},2)+8\zeta(\bar{9},1)&=& {\bf H}^{(2)}_8(-1) + 8 {\bf H}^{(1)}_9(-1) -9 Li_{10}(-1) \\
&=&
\left( \left\{\zeta(\bar{2},8) - \zeta(\bar{8},2)\right\} - \frac{255}{256} {\bf H}^{(2)}_8(+1) + \frac{237}{32} \zeta(3) \zeta(7)+\frac{15}{4} \zeta(5)^2 - \frac{108201}{5120} \zeta(10)\right) -9 Li_{10}(-1) \\
\end{eqnarray}
where in the second line we used my answer to Calculating alternating Euler sums of odd powers . The quantity in curly brackets looks "symmetric" so it is quite likely that it reduces to MZVs at plus unity only. I don't have aproof for that now but by using the MZV-interface http://wayback.cecm.sfu.ca/cgi-bin/EZFace/zetaform.cgi I figured out that :
\begin{equation}
\left\{\zeta(\bar{2},8) - \zeta(\bar{8},2)\right\}= \frac{1}{2560}\left(-2637 \zeta(10)+1800 \zeta(3) \zeta(7)+840 \zeta(5)^2-270 \zeta(8,2)\right)
\end{equation}
Bringing this all together we get the following:
\begin{eqnarray}
\zeta(\bar{8},2)+8\zeta(\bar{9},1)&=&\frac{3}{1024} \left( 1392 \zeta(5)^2 + 2768 \zeta(3) \zeta(7) -4839 \zeta(10) - 376 \zeta(8,2)\right)
\end{eqnarray}
as expected.
When I look at my list Calculating alternating Euler sums of odd powers of MZVs at minus unity I can indeed see a pattern you conjecture. As a matter of fact there will be many more relationships of this kind one of them being:
\begin{eqnarray}
&&A_m^{(0)} \cdot\left((2m-1) \zeta(\bar{2 m},2) + \binom{2 m}{2} \zeta(\bar{2m+1},1)+\zeta(\bar{3},2m-1) \right)=\\
&& A_m^{(1)} \zeta(2 m,2) + A_m^{(2)} \zeta(2m+2) + \sum\limits_{j=1}^{\lfloor \frac{m}{2} \rfloor} A_m^{(2+j)}\zeta(2 j+1) \zeta(2m-2j+1)
\end{eqnarray}
where
\begin{eqnarray}
A_m^{(j)} = \left(
\begin{array}{rrrrr}
4&3 &-1&&&\\
32&0&0&9&&\\
512&-1260&-6391&5280&0\\
1024&-3570&-37023&22008&9840&\\
8192&-36828&-637549&300096&265248
\end{array}
\right)_{m=1}^5
\end{eqnarray}
where $m$ and $j$ label the rows and the columns  of the matrix above, respectively.
Comment: Very nice! Do you know that the closed form of multiple zeta values of depth four and weight=10,11,12, for example $\zeta(5,3,1,1),\zeta(6,2,1,1)$?

A question about double zeta values


What are the Real #'s and Imaginary?

Question: $5e^{-i(7\pi/6)}$
I figured $5e$ was real and $-(7\pi/6)$ was imaginary. I was wrong. Anyone have any thoughts as to what is real / imaginary in the complex number?? Thanks for any responses!
Comment: If a complex number is written in the form $a+bi$, then $a$ is the real part and $b$ is the imaginary part. Unfortunately, $"\!5e^{-i7\pi/6}\!"$ isn't in the form $a+bi$.
Comment: so how do you separate what is real and imaginary??
Comment: Do you know Euler's formula for $e^{i\theta}$?
Comment: Well it isn't given on the module i am using so i figured to answer the question you didn't need to know it.
Comment: However; at the end it states Your answers should be decimals with 2 digits to the right of the decimal point? Question A: The real part of this complex number is ____ and Question B: The Imaginary part of this number is _____
Comment: @AkivaWeinberger You still need $a,b\in\Bbb R$.
Comment: @Vim Yes, that's true. Thank you.
Answer: Euler's formula says:
$$e^{i\theta}=\cos\theta+i\sin\theta$$
Thus:
\begin{align}
5e^{-i7\pi/6}&=5\left(\cos\left(-\frac{7\pi}6\right)+i\sin\left(-\frac{7\pi}6\right)\right)\\
&=5\cos\left(-\frac{7\pi}6\right)+i5\sin\left(-\frac{7\pi}6\right)
\end{align}
You can simplify that.
Comment: Ok I see that; however, I am asked what the real part / imaginary parts are and told that they should be decimals with 2 digits to the right of the decimal point. (submitted 2ce and on 3rd submission = wrong so I wanna be sure of final answer)
Answer: A:) The Real Part of this number is -4.33
B:) The Imaginary part of this number is 2.5
(The module stated these as the correct answers)
Comment: This is worthless without an explanation.

What are the Real #'s and Imaginary?


Como fazer uma "equivalência" de IO em Java e C++?

Question: Eu fiz o seguinte código em C++:
#include <iostream>
template <typename type> class Foo
{
    public:
    Foo(type FooTest)
    {
        std::cout << "Foo " << FooTest;
    }
};

int main
{
    new Foo<double>(10.0);
}

Output: "Foo 10".
Java: (MainClass.java)
public class MainClass
{

        public static void main(String[] args)
        {
            new Foo<Double>(10.0);
        }
}

    class Foo<type>
    {
        public Foo(type FooTest)
        {
            System.out.print("Foo ");
            System.out.print(FooTest);
        }
    }

Output: "Foo 10.0".
Este, apenas um caso para demonstrar o que ocorre, o output é diferente nos dois casos para double. Como eu posso igualá-los (Java = 10 e C++ = 10.0) ?
Comment: Não é o foco da pergunta mas acho importante ressaltar que seu código em C++ faz algumas coisas não recomendadas/desnecessárias, como a utilização de `new` neste caso ( causando um vazamento de memória ) e a criação de uma classe para uma função que poderia ser solta.
Comment: @TiagoGomes É claro. Se eu quiser fazer um código **demonstrativo**, não devo me preocupar muito com melhorias; mesmo assim, para fazer um código semelhante em Java, o correto é usar orientação-a-objetos.
Answer: A formatação padrão no C++ tenta agir de forma "inteligente" e descarta zeros a partir da casa decimal que não interferem no valor, se você colocar 1.1 nos dois, verá que a saída será a mesma.
Para ter uma formatação de precisão fixa você pode usar o manipulador std::setprecision acompanhado do std::fixed.
Comment: +1 por usar o std :). Em Java (se houvesse como manipulá-lo), eu faria um cast do objeto para Double. Você conhece uma solução melhor?
Comment: @LucasHenrique Não entendi a pergunta, o que está indo pra saída já é um valor `Double` então pra quê o cast que você diz que faria?
Comment: Por exemplo, (em Java,) fazer uma função que cheque se o número tem casas decimais não nulas. Se retornar falso (não tem), transformar o número em int para mostrá-lo como `10`. `bool has_decimal(double num) { return num%1==0;}`
Comment: @LucasHenrique ah, não faço idéia nem programo Java pra falar a verdade, recomendo uma busca nas opções de formatação nas bibliotecas. Você pode pender pra um dos lados: usar formatação fixa no dois, ou tentar seguir o que o C++ faz no Java, que nem você está perguntando.
Comment: @LucasHenrique A resposta pro Java ter esse comportamento é essa: http://stackoverflow.com/a/14126736/1000282
Answer: Pode usar o printf :)
C / C++
printf("Foo %.01f", fooTest);

Java
System.out.printf("Foo %.01f", fooTest);

É claro que esse é um caso específico para double, como você está usando um tipo genérico seria interessante declarar uma interface comum em ambos os sistemas (ou então declarar wrappers que façam a sobrescrita do o operator<< no C++ e o método toString no Java), de forma que cada tipo saiba como "se imprimir".
Comment: Para o C++ você pode utilizar as funções width e precision. Veja http://www.cplusplus.com/reference/ostream/ostream/
Comment: Sim, e no Java o [DecimalFormat](http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html), mas é bacana usar o mesmo método nos dois :).


Spheres as Homogeneous Spaces

Question: Any odd dimensional sphere $S^{2n+1}$ can be expressed as an homogenous space of $SU(n+1)$ by $S^{2n+1} \simeq SU(n+1)/SU(n)$. Any even dimensional sphere $S^{2n}$ sphere can be expressed as an homogeneous space of $SO(n)$ according to $S^{2n} \simeq SO(n)/SO(n-1)$. Can we make for a switch here? In explicit, can one realize the odd spheres as $SO(n)$ homogeneous spaces, and can one realize the even spheres as $SU(n)$ homogeneous spaces.
Comment: Are you sure about your statement $S^{2n}=Sp(n)/Sp(n-1)$ ? What is the proof ?
Comment: I meant to write SO(n) not Sp, it is hopefully ok now.
Comment: Yes, now it is not a duplicate. You still have $Sp(n)$ in the text, though.
Comment: For $Sp(n)$ see [here](http://math.stackexchange.com/questions/1651906/spheres-as-symplectic-homogeneous-spaces).
Comment: Fixed now. Thanks.
Answer: The first part of the question has a positive answer, since we have
$$
S^n\cong SO(n+1)/SO(n)
$$
also for odd $n$. For the case $SU(n)$ this is not possible in this way, however it might be realized in a different way, e.g.,
$$
S^6\cong G_2/SU(3),
$$
where $n=6$ is even.
Comment: And $S^2=CP^1(\mathbb C)$ is also $SU(2)/ U(1)$
Comment: The last identity is nice. Thanks a lot!

Spheres as Homogeneous Spaces


Custom theme breaks spinner apperance

Question: I am currently working on dynamically changing themes with a settings option. The themes are very simple and only change background color. After changing theme, the spinners do not look right see image http://imageshack.us/photo/my-images/600/baddropdown.png/
I solved the first issue (the spinner itself) with a custom spinner item that sets the background transparent
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
     android:ellipsize="marquee"
     android:layout_height="wrap_content"
     android:layout_width="match_parent"
     android:singleLine="true"
     style="?android:attr/spinnerItemStyle"
     android:background="@android:color/transparent"
     android:id="@android:id/text1" />

I tried the same with a custom spinner_dropdown_item but it did not work.  Any ideas what I can try to get the default spinner appearance would be greatly appreciated.
EDIT: I was able to change the spinner_dropdown_item background http://imageshack.us/photo/my-images/10/halfbaddropdown.png/ but the drop down prompt background and separators are the application backgrounds color but I want the default appearance.
NOTE: removed an image link so I could post the newest.
EDIT: Issue has been resolved, acctually ended up being a simple fix. Had to change my custom theme which was

in styles.xml to

and define the color in colors.xml
Answer: Issue has been resolved, acctually ended up being a simple fix. Had to change my custom theme which was

in styles.xml to

and define the color in colors.xml

Custom theme breaks spinner apperance


Custom Entity with a uid property

Question: We seem to be experiencing a very unexpected problem.
We have created a custom entity called feature and it has a uid property. The schema is as follows:
<code>$schema['feature'] = array(
  'fields' => array(
    'fid' => array(
      'description' => 'feature id',
      'type' => 'serial',
      'not null' => TRUE,
    ),
    'bundle' => array(
      'description' => 'bundle name',
      'type' => 'varchar',
      'length' => 32,
      'not null' => TRUE,
    ),
    'nid' => array(
      'description' => 'Node ID.',
      'type' => 'int',
      'not null' => TRUE,
    ),
    'tid' => array(
      'description' => 'Taxonomy Term ID.',
      'type' => 'int',
      'not null' => TRUE,
    ),
    'uid' => array(
      'description' => 'User ID.',
      'type' => 'int',
      'not null' => TRUE,
    ),
    'created' => array(
      'description' => 'created timestamp',
      'type' => 'int',
      'not null' => TRUE,
    )
  ),
  'unique keys' => array(
    'primary key' => array('fid'),
    'nid-tid-uid' => array('nid', 'tid'),
  )
);
</code>
An entity is then picked up with
<code>$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'feature')
  ->entityCondition('bundle', 'disabled')
  ->propertyCondition('tid', $tid)
  ->propertyCondition('nid', $nid)
  ->addMetaData('account', user_load(1));
$result = $query->execute();

if (isset($result['feature'])) {
  $features = entity_load('feature', array(reset($result['feature'])->fid));
  $feature =  reset($features); // $feature here as the wrong uid
}
</code>
However, no matter what permutation I try, the uid is always set to 1.
The database has the correct information - so the data is being stored correctly.
The entity has views integration and pulling the data in through views works correctly as well.
Outputting the $feature always gives a uid = 1.
I even have traced through the EntityAPIController with little luck.
I tried loading an unrelated entity (Field Collection Item). This entity does not have a uid field. However, after entity_load it seems that a uid property is set.
Does this mean that having a uid property on an entity is just not possible? There does not seem to be any documentation to suggest that this is the case though.
I know that I can just rename it to aid or something else but am curious as to the cause here.
Thanks...
Comment: I use `uid` in custom entities all the time, it's definitely not reserved/disallowed or anything like that. Have you implemented a custom controller or are you using `EntityAPIController` straight up?
Comment: a custom controller but it just adds a created field - so nothing exciting... I found another entity which seems to be using a uid field as well - so this seems very strange indeed... :-/
Answer: I left it overnight, and by the following day, the issue was gone.... :-/
Comment: I'm having the exact same problem on my local machine. So far I tried: `drush cc all`, `drush cron`, restarting mysql, rebooting my computer. Still have the same problem. Next step --- I will leave it overnight and hope that it magically disappears :)
Comment: Cron likely ran and/or cleared caches.
Comment: In the end it was solved by restoring an earlier backup of the database (which was OK for me since it was only a site on my local dev computer)

Custom Entity with a uid property


Máscara de Horas ou TimePicker JavaFX

Question: Tenho um TextField aonde entro com a hora, porém sempre tenho que digitar os :. Como posso colocar uma máscara nesse TextField ou então se for mais simples um TimePicker?
Answer: Acredito que o ideal seria usar o DatePicker do JFXtras:

Comment: O DatePicker eu já consigo usar o problema é um TimePicker
Answer: aqui nesse site https://community.oracle.com/thread/2552039 tem uma solução, mas o melhor mesmo seria criar uma skin.
import java.util.regex.Pattern;

import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.IntegerBinding;
import javafx.beans.property.ReadOnlyIntegerProperty;
import javafx.beans.property.ReadOnlyIntegerWrapper;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.IndexRange;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class TimeTextFieldTest extends Application {

 @Override
  public void start(Stage primaryStage) {
  VBox root = new VBox(5);
  root.setPadding(new Insets(5));
  Label hrLabel = new Label();
  Label minLabel = new Label();
  Label secLabel = new Label();
  TimeTextField timeTextField = new TimeTextField();
  hrLabel.textProperty().bind(Bindings.format("Hours: %d", timeTextField.hoursProperty()));
  minLabel.textProperty().bind(Bindings.format("Minutes: %d", timeTextField.minutesProperty()));
  secLabel.textProperty().bind(Bindings.format("Seconds: %d", timeTextField.secondsProperty()));

  root.getChildren().addAll(timeTextField, hrLabel, minLabel, secLabel);
  Scene scene = new Scene(root);
  primaryStage.setScene(scene);
  primaryStage.show();
  }

  public static void main(String[] args) {
  launch(args);

  }

  public static class TimeTextField extends TextField {

    enum Unit {HOURS, MINUTES, SECONDS};

    private final Pattern timePattern ;
    private final ReadOnlyIntegerWrapper hours ;
    private final ReadOnlyIntegerWrapper minutes ;
    private final ReadOnlyIntegerWrapper seconds ;

    public TimeTextField() {
      this("00:00:00");
    }
    public TimeTextField(String time) {
      super(time);
      timePattern = Pattern.compile("\\d\\d:\\d\\d:\\d\\d");
      if (! validate(time)) {
        throw new IllegalArgumentException("Invalid time: "+time);
      }
      hours = new ReadOnlyIntegerWrapper(this, "hours");
      minutes = new ReadOnlyIntegerWrapper(this, "minutes");
      seconds = new ReadOnlyIntegerWrapper(this, "seconds");
      hours.bind(new TimeTextField.TimeUnitBinding(Unit.HOURS));
      minutes.bind(new TimeTextField.TimeUnitBinding(Unit.MINUTES));
      seconds.bind(new TimeTextField.TimeUnitBinding(Unit.SECONDS));
    }

    public ReadOnlyIntegerProperty hoursProperty() {
      return hours.getReadOnlyProperty();
    }

    public int getHours() {
      return hours.get() ;
    }

    public ReadOnlyIntegerProperty minutesProperty() {
      return minutes.getReadOnlyProperty();
    }

    public int getMinutes() {
      return minutes.get();
    }

    public ReadOnlyIntegerProperty secondsProperty() {
      return seconds.getReadOnlyProperty();
    }

    public int getSeconds() {
      return seconds.get();
    }

    @Override
    public void appendText(String text) {
      // Ignore this. Our text is always 8 characters long, we cannot append anything
    }

    @Override
    public boolean deleteNextChar() {

      boolean success = false ;

      // If there's a selection, delete it:
      final IndexRange selection = getSelection();
      if (selection.getLength()>0) {
        int selectionEnd = selection.getEnd();
        this.deleteText(selection);
        this.positionCaret(selectionEnd);
        success = true ;
      } else {
        // If the caret preceeds a digit, replace that digit with a zero and move the caret forward. Else just move the caret forward.
      int caret = this.getCaretPosition();
      if (caret % 3 != 2) { // not preceeding a colon
        String currentText = this.getText();
        setText(currentText.substring(0, caret) + "0" + currentText.substring(caret+1));
        success = true ;
      }
      this.positionCaret(Math.min(caret+1, this.getText().length()));
      }
      return success ;
    }

    @Override
    public boolean deletePreviousChar() {

      boolean success = false ;

      // If there's a selection, delete it:
      final IndexRange selection = getSelection();
      if (selection.getLength()>0) {
        int selectionStart = selection.getStart();
        this.deleteText(selection);
        this.positionCaret(selectionStart);
        success = true ;
      } else {
      // If the caret is after a digit, replace that digit with a zero and move the caret backward. Else just move the caret back.
        int caret = this.getCaretPosition();
        if (caret % 3 != 0) { // not following a colon
          String currentText = this.getText();
          setText(currentText.substring(0, caret-1) + "0" + currentText.substring(caret));
          success = true ;
        }
        this.positionCaret(Math.max(caret-1, 0));
      }
      return success ;
    }

    @Override
    public void deleteText(IndexRange range) {
      this.deleteText(range.getStart(), range.getEnd());
    }

    @Override
    public void deleteText(int begin, int end) {
      // Replace all digits in the given range with zero:
      StringBuilder builder = new StringBuilder(this.getText());
      for (int c = begin; c<end; c++) {
        if (c % 3 != 2) { // Not at a colon:
          builder.replace(c, c+1, "0");
        }
      }
      this.setText(builder.toString());
    }

    @Override
    public void insertText(int index, String text) {
      // Handle an insert by replacing the range from index to index+text.length() with text, if that results in a valid string:
      StringBuilder builder = new StringBuilder(this.getText());
      builder.replace(index, index+text.length(), text);
      final String testText = builder.toString();
      if (validate(testText)) {
        this.setText(testText);
      }
      this.positionCaret(index + text.length());
    }

    @Override
    public void replaceSelection(String replacement) {
      final IndexRange selection = this.getSelection();
      if (selection.getLength()==0) {
        this.insertText(selection.getStart(), replacement);
      } else {
        this.replaceText(selection.getStart(), selection.getEnd(), replacement);
      }
    }

    @Override
    public void replaceText(IndexRange range, String text) {
      this.replaceText(range.getStart(), range.getEnd(), text);
    }

    @Override
    public void replaceText(int begin, int end, String text) {
      if (begin==end) {
        this.insertText(begin, text);
      } else {
      // only handle this if text.length() is equal to the number of characters being replaced, and if the replacement results in a valid string:
      if (text.length() == end - begin) {
        StringBuilder builder = new StringBuilder(this.getText());
        builder.replace(begin, end, text);
        String testText = builder.toString();
        if (validate(testText)) {
          this.setText(testText);
        }
          this.positionCaret(end);
      }
      }
    }

    private boolean validate(String time) {
      if (! timePattern.matcher(time).matches()) {
        return false ;
      }
      String[] tokens = time.split(":");
      assert tokens.length == 3 ;
      try {
        int hours = Integer.parseInt(tokens[0]);
        int mins = Integer.parseInt(tokens[1]);
        int secs = Integer.parseInt(tokens[2]);
        if (hours < 0 || hours > 23) {
          return false ;
        }
        if (mins < 0 || mins > 59) {
          return false ;
        }
        if (secs < 0 || secs > 59) {
          return false ;
        }
        return true ;
      } catch (NumberFormatException nfe) {
        // regex matching should assure we never reach this catch block
        assert false ;
        return false ;
      }
    }

    private final class TimeUnitBinding extends IntegerBinding {

      final Unit unit ;
      TimeUnitBinding(Unit unit) {
        this.bind(textProperty());
        this.unit = unit ;
      }
      @Override
      protected int computeValue() {
        // Crazy enum magic
        String token = getText().split(":")[unit.ordinal()];
        return Integer.parseInt(token);
      }

    }

  }
}

Aqui tem um exemplo de skin só que é para formatar dinheiro.
https://github.com/thiagofdso/MoneyTest

Máscara de Horas ou TimePicker JavaFX


how to disentangle the influence of two correlated dummy variables

Question: I am analyzing the effect of two factors on performance in an easily measured test. The two independent variables are "category" variables, let's call them "strategy" and "manager". Each test result is assigned to a single manager and a single strategy. There are 106 managers and they can choose among 18 strategies. Manager and strategy are somewhat correlated; certain managers favor certain strategies, though no manager limits himself to only one.
The dataset includes hundreds of test results and their associated manager and strategy.  If the managers and strategies have been translated to unique integers, this can be represented as a list that looks like {{12, 15, 0.0951909}, {43, 11, 0.078721}, {112, 11, -0.520077}, etc.}
What is the best technique for determining the degree to which the test result varies with manager and strategy?
Answer: This is what analysis of variance (ANOVA) is created for. In particular, you should use a two-way ANOVA that

examines the influence of two different categorical independent variables on one continuous dependent variable

This can be easily done with SPSS or R. Ideally, you would also test for interaction effects if the main effects are significant.
Comment: Thanks. The data violates some ANOVA assumptions but this approach may be as good as I'm going to be able to do.


Rules with condition on taxonomy

Question: Im doing a simple Rules that when a content is created of type X, and has taxonomy term of T1, simple action to display a message in the page.

Events: After saving new content (rules_entity_insert:node)
Conditions:

Node is of type
How to configure this item to select taxonomy term???

Action: Show a message on the site
Comment: I realize this is a D8 question, but it might help if you edit your question to explain how you would do this with rules in D7 ... eg by including an export (or screenprint using the Rules UI) in your question.
Comment: Yes, I added tag to determine its in D8. Honestly I dont see any documentation in the web how to configure taxonomy term as condition in D8. As mentioned in the question, its just as easy as "if content has taxonomy term of T1". I believe this is an easy option for D7. Im not really good at creating custom rules but if this simple approach is not configurable from the UI, then I think I will proceed to creating one.
Answer: add one condition that checks if the node has field_term_ref (term reference) equal to what term name you wish for it.

Choose the action "Set a data value".
Choose the taxonomy term reference field to set.
"Switch to the direct input mode" button to reveal the terms available in your taxonomy field.
Comment: I would love to see something like an exported rule to demonstrate a ***working*** sample of this. Please edit your answer to include such rule ...
Comment: @alexb: Thanks for your response, and it looks like a simple answer but not detailed. Yes please, can you break it down to include a rule?
Comment: I've added an list of steps, hope it helps

Rules with condition on taxonomy


Simplify Matrix Expression, and General Tips For Simplifying Matrix Expressions?

Question: this is a step in my Textbook Deep Learning when talking about Bayesian Linear Regression, but the context is not too important.
I'm wondering how the author goes about simplifying from 5.75 to 5.76. I'm not too familiar on how to expand certain matrix-vector products, and I've been getting similar things as him but not the exact same.

I thought I was able to expand the $(y-Xw)^T(y-Xw)$ term, which I thought expands into $(y^Ty + w^TX^TXw)$. The $w^TX^TXw$ term is there in the expansion, but I don't understand where the $-2y^TXw$ term comes from.
I don't really know what to do with the next part.
I was wondering if someone could help me out to see why the matrix and vectors simplify like that, and maybe give a few in-general tips to simplifying matrix expressions in general? I can't seem to find any helpful resources on it and I run into them quite a bit.
Thanks!
Answer: Analagous to $(a-b)^2 = a^2 - 2ab + b^2$, we have
$$(y-Xw)^\top (y-Xw) = y^\top y - 2y^\top X w + w^\top X^\top X w.$$
Similarly,
$$(w-\mu)^\top \Lambda^{-1} (w-\mu) = w^\top \Lambda^{-1} w - 2 \mu^\top \Lambda^{-1} w + \mu^\top \Lambda^{-1} \mu.$$
As SoufHay noted, terms that don't involve $w$ can be considered constants, and can be thrown away by being absorbed into the proportionality symbol $\propto$.
Answer: If you simplify the two products, you'll have some terms that don't depend on $w$, you can get rid of those since they are constants, and we're using just the $\propto$ symbol and not the $=$ symbol.


Crop an image instead of stretching it

Question: When I insert an image in a container with fixed width and height, the image stretches to fit that space. Is there a way to display the image at its normal size, but with the excess clipped out?
Answer: The modern way is to use object-fit: none; (or the more common object-fit: cover; if you want to scale, but without stretching).
img {
    object-fit: cover;
}

97% of browser sessions support this as of 2022 May. — Can I use?

If you want to anchor the image to the top left corner instead of the center, add:
img {
    object-position: 0 0;
}

Comment: I'm finding this centers the image, rather than anchoring it in the top-left. Any suggestions to correct that?
Comment: You can put object-position: 0 0;
Answer:

Then in the above DIV you can play with CSS

width/height
background-position

to create different crop effects.
Answer: You can use the CSS clip property:
#image_element
{
position:absolute;
clip:rect(0px,60px,200px,0px);
}

The downside of using clip is that the element has to be absolutely positioned, and is only available with the 'rect' shape.
See:

https://www.w3schools.com/cssref/pr_pos_clip.asp
http://www.cssplay.co.uk/menu/clip_gallery
Answer: Use this :
http://www.w3schools.com/css/pr_background-position.asp
background-position: 5px 5px;
and then set the height and width of the div
height: 55px;
width: 55px;
Answer: Show it as a background image

Crop an image instead of stretching it


$a \in (0, 1)$, Borel subset $A$ of $[-1, 1]$ where $\lim_{r \to 0+} {{m(A \cap [-r, r])}\over{2r}} = a$?

Question: Let $a \in (0, 1)$. What is a Borel subset $A$ of $[-1, 1]$ where$$\lim_{r \to 0+} {{m(A \cap [-r, r])}\over{2r}} = a?$$
Answer: Let $A=A^-\cup A^+,$ where $A^+=\cup_{n=1}^\infty [1/(n+1),1/(n+1)+a(1/n-1/(n+1))),$ i.e., take the left $a$ of each interval $[1/n,1/(n+1))$, and $A^-=-A=\{-x\mid x\in A^+\}$. $A$ is borel being a countable union of intervals, and for any $r=1/k\le 1$,
$$
m(A\cap[-r,r])=2\sum_{n=k}^\infty a(1/n-1/(n+1))=2a/k.
$$
Then for any $r\in [1/(k+1),1/k],$
$$ (2r)^{-1}m(A\cap[-r,r])\le (2/(k+1))^{-1}m(A\cap[-1/k,1/k])=a(k+1)/k,$$
and
$$ (2r)^{-1}m(A\cap[-r,r])\ge (2/k)^{-1}m(A\cap[-1/(k+1),1/(k+1)])=ak/(k+1),$$
errors that vanish as $r\to 0^+$.


SPF Outlook Web App (OWA) undeliverable email

Question: PROBLEM:
Outlook.com web app (OWA), synchronized with my local server via IMAP and SMTP(STARTTLS), returns "Undeliverable message" for all messages sent.
PROPOSAL: (rejected)
This returning message points the issue comes up with the SPF and sugests updating DNS entry with a dynamic IP xx.xxx.xx.xxx A dynamic IP??? Nope.
PROPOSAL: (not working)
Mocosoft sugests updating SPF entry with this entry ip4:184.108.40.206/19 ip4:184.108.40.206/19 ip4:220.127.116.11/16 include:spf.protection.outlook.com
Working? Nope.
This was the "undeliverable message" received.

Technical details
  InvalidRecipientsException: Invalid recipients were provided for the message: 'firstname.lastname@example.com' (550 5.7.23 : Recipient address rejected: Message rejected due to: domain owner discourages use of this host. Please see http://www.openspf.net/Why?s=mfrom;firstname.lastname@example.com;ip=184.108.40.206;r=
  ). --> Respuesta del servidor SMTP inesperada. Esperado: 250, real: 550, respuesta completa: 550 5.7.23 : Recipient address rejected: Message rejected due to: domain owner discourages use of this host. Please see http://www.openspf.net/Why?s=mfrom;email@example.com;ip=188.8.131.52;r=

Failure code: 8f93
Comment: For a resolution to your problem, please post the actual domain you are having the issue with. Note that your domain and its DNS records are already public information, so you are not revealing anything useful to an attacker.
Answer: SOLUTION:
In my absolute despair, and watching that my entry with google was working include:_spf.google.com, I throw the dice and found the solution in an underline "_". Just include this into your DNS SPF entry:
include:_spf.protection.outlook.com

This worked for me perfectly! Hope works for you too.
Bonus1. A correct entry could be like this:
spf1: ip4:xxx.xxx.xxx.xxx include:_spf.protection.outlook.com ~all

Bonus2. Or this
spf1: include:example.com include:_spf.protection.outlook.com ~all

UPDATE MXtoolbox passed ok with _spf.protection.outlook.com and working perfectly in three different domains at the moment in my dedicated server, hosted by ionos (old 1and1). mxtoolbox report.
Thank you for your comments.
Comment: But looking on internet, spf.protection.outlook.com does have a txt resolution with spf settings. _spf.protection.outlook.com doesn't appear to exist. So whatever made it work should not be proposed as a good solution anyway. Perhaps you exceeded the maximum dns resolution allowed (10) ? There are online sites to check for anomalies. eg: https://www.kitterman.com/spf/validate.html or https://mxtoolbox.com/spf.aspx
Comment: `spf.protection.outlook.com` having an SPF `TXT` record and `_spf.protection.outlook.com` not, this is clearly a misguiding answer.
Comment: With OP's domain obfuscated, it's not easy. spf.protection.outlook.com txt entry ends with "-all" thus probably forcing denial despite the subsequent "~all" on OP's dns. OP's server IP and actual domain would probably be needed. Currently OP just removed any strong protection (by having "~all" be evaluated and more often than not accepted for emails).
Comment: Are you understanding that the entry `include:_spf.protection.outlook.com` is doing completely nothing because there's nothing behind _spf.protection.outlook.com? This can't be an answer.


How do I add category to Objective C class in a pod?

Question: I need to extend the functionality of a library Pod written in Objective C (the rest of the project is in Swift). I created the MyClass+Category .h and .m files (as a Category), with the pod selected as target, but I get a file not found error in the header at:
<code>#import <MyLib/MyLib.h>
</code>
How do I get the category's header to find the original class?
An alternative would be to write the extension in Swift, are there any gotchas there I should be aware of?
Also grateful for any better ways there might be.
Comment: Usually you will have to address the framework: `#import `. Can you be a little bit clearer about the structure of the class you are attempting to categorize?
Comment: That seems to have done it. Strange that Xcode asks me which class I am creating a category for, then gives me an import statement that doesn't work. I'll edit the post to reflect the actual import statement I got, in case it helps someone else.
Comment: Cocoapods generates umbrella header file with ugly `-umbrella` suffix. Thy `#import `
Answer: Adding a Bridging Header in Your Project. then import your category in BridgingHeader class. you easily access your category.
how to add header file please see this link.
https://stackoverflow.com/a/39615171/8687925


Changing part of a message's color in tkinter messagebox

Question: I have a TKinter messagebox like the one below. I would like to change part of the message to a different color. For example in the messagebox below I would like the language to be Blue. Is this possible?
Comment: Show your code. What have you tried?
Comment: I don't think you can change the properties of this Tkinter dialog.
Comment: You need to create your own message box: `Toplevel` + `Label` + `Button`. You can achieve it I think.
Comment: Or to use a Canvas and to draw your buttons, image and text...
Comment: Yep! I was going to add `Canvas` too.
Comment: I don't think you can change the colour of only a segment of a labeltext. What you could do is split the label into the "The languages of […]" part and a second, separate label for the language.
Comment: Yes, you need to separate text parts.
Answer: It's not possible to change such options of Tkinter Standard Dialogs. You need to create your own dialog. You'll also need to separate the text parts. I've tried to make something similar in the image that the OP has posted above:
from tkinter import *
root = Tk()

def choosefunc(option):
    if option == "cancel":
        print("Cancel choosen")
    else:
        print("OK choosen")

def popupfunc():

    tl = Toplevel(root)
    tl.title("Languages")

    frame = Frame(tl)
    frame.grid()

    canvas = Canvas(frame, width=100, height=130)
    canvas.grid(row=1, column=0)
    imgvar = PhotoImage(file="pyrocket.png")
    canvas.create_image(50,70, image=imgvar)
    canvas.image = imgvar

    msgbody1 = Label(frame, text="The", font=("Times New Roman", 20, "bold"))
    msgbody1.grid(row=1, column=1, sticky=N)
    lang = Label(frame, text="language(s)", font=("Times New Roman", 20, "bold"), fg='blue')
    lang.grid(row=1, column=2, sticky=N)
    msgbody2 = Label(frame, text="of this country is: Arabic", font=("Times New Roman", 20, "bold"))
    msgbody2.grid(row=1, column=3, sticky=N)

    cancelbttn = Button(frame, text="Cancel", command=lambda: choosefunc("cancel"), width=10)
    cancelbttn.grid(row=2, column=3)

    okbttn = Button(frame, text="OK", command=lambda: choosefunc("ok"), width=10)
    okbttn.grid(row=2, column=4)

label = Label(root, text="Click to proceed:")
label.grid()

button = Button(root, text="Click", command=popupfunc)
button.grid()

(Image URL: https://i.stack.imgur.com/V0Nz1.jpg)


Edit details in itunes connect

Question: Hi Therem Just a quick question. Is it possible to change details about an app that is currently sitting in iTunes connect but with no binary that has been uploaded.
For example I would like to start developing and testing inApp Purchases but the app is not at a stage to have finalised screen shots and a icon etc... So If i create the app id etc and add it to the iTunes store with black images for screenshots can I change that later before approval?
Thanks T
Answer: Yes, you can. Most metadata can also be changed beyond the point of AppStore approval.
Editable beyond approval are:

Description
(Whats new in this Version)
Support URL
Marketing URL
Privacy Policy URL

Editable before approval are:

all of the above
Screenshots
Comment: Narf, right - the chicken egg issue :D ... good luck with your app!
Comment: Keywords can only be changed with a new version of your App. Same with Screenshots.
Comment: I don't quite understand why Apple does not let us change a few metadata even after the app gets approved. To edit a screenshot and a keyword one will have to upload/submit a newer version of the app is difficult to digest. Although, Apple then has its own reasons of piracy and misuse of this feature. So, lets now start submitting our apps with all metadata in place before finally going for approval.
Comment: Thanks Till, Just a little bit stressed that I will use black screenshots etc and be stuck with them haha! Will accept your answer in 10 minutes T
Comment: Can keywords also be changed?
Comment: I can not say for sure about the keywords. They are not changeable as soon as you got approved, thats for sure. Another factor that comes into the equation is if that app has once been approved and if you only plan to supply an update. However, if you never got approved, there is nothing preventing you from creating a new app - just the app-name will have to be changed. So how about you simply start with a fake app that you never plan to release under that name?
Comment: Thats true, but I need to begin allowing inApppurchase packages to be reviewed and sampled in app. However I have now just found that they can only be submitted with the app binary which means I will have to wait untill the app is ready for approval anyway :)
Comment: There may be reasons not to permit keywords to be added for an existing binary, but you also cannot _remove_ them.
Answer: For future visitors: you will find Apple's current documentation regarding 'locked' and 'unlocked' iTunes Connect app properties here:
https://developer.apple.com/library/ios/documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/Appendices/Properties.html

Edit details in itunes connect


Identificar inputs em uma div

Question: Gente eu gostaria de saber se existe alguma forma de identificar inputs dentro de uma div, sem usar nome, id ou class.
Exemplo:

      <input type='text'>

      <input type='text'>

      <input type='text>

     <button onclick='enviar(enviar-o-texto-do-primeiro-input, enviar-o-texto-do-segundo-input , enviar-o-texto-do-terceiro-input);>enviar</button>

Eu queria poder enviar os texto dos input sem usar id, class, nome, pois estou criando as div automaticamente e se botar um id para cada um, todas as outras div vão ter o mesmo id nos input.
Answer: Pode pegar pelo nome da tag usando .getElementsByTagName() com os índices dos elementos, começando do 0. Mas antes é preciso pegar a div pai com .parentNode.
Para isso, basta enviar à função o próprio botão com this:

function enviar(botao){
   var text_1 = botao.parentNode.getElementsByTagName("input")[0].value;
   var text_2 = botao.parentNode.getElementsByTagName("input")[1].value;
   var text_3 = botao.parentNode.getElementsByTagName("input")[2].value;
   console.log(text_1, text_2, text_3);
}

   <input type='text' value="A">
   <input type='text' value="B">
   <input type='text' value="C">
   <button onclick='enviar(this)'>enviar</button>

No caso de não ter um número definido de inputs, uma outra abordagem seria contar quantos intputs a div contém e adicionar os textos numa array:

function enviar(b){

   var textos = [];
   var bts = b.parentNode.getElementsByTagName("input");
   for(var botao of bts){
      textos.push(botao.value);
   }

   console.log(textos);

}

   <input type='text' value="A">
   <input type='text' value="B">
   <input type='text' value="C">
   <button onclick='enviar(this)'>enviar</button>

Você terá uma array com os textos e poderá usá-los como quiser.
Comment: Muito obrigado, eu consegui fazer do jeito que vc falou. existe aqui algum canto de botar a pergunta como resolvida ou de marca a sua como melhor resposta?
Comment: Tem à esquerda, abaixo das setas de votação.

Identificar inputs em uma div