Grouping coefficients in plot R

Question: I was looking to group coefficient from a single model in a dot and whisker plot:
Here is a sample:

    ## Simulate data
    set.seed(42)
    n <- 1e3

    d <- data.frame(
      # Covariates
      projects_0_300_minus2 = rnorm(n),
      projects_0_300_minus1 = rnorm(n),
      projects_0_300_0 = rnorm(n),
      projects_0_300_1 = rnorm(n),
      projects_0_300_2 = rnorm(n),
      projects_300_600_minus2 = rnorm(n),
      projects_300_600_minus1 = rnorm(n),
      projects_300_600_0 = rnorm(n),
      projects_300_600_1 = rnorm(n),
      projects_300_600_2 = rnorm(n),
      projects_600_800_minus2 = rnorm(n),
      projects_600_800_minus1 = rnorm(n),
      projects_600_800_0 = rnorm(n),
      projects_600_800_1 = rnorm(n),
      projects_600_800_2 = rnorm(n),
      # Individuals and firms
      id = factor(sample(20, n, replace=TRUE)),
      firm = factor(sample(13, n, replace=TRUE)),
      # Noise
      u = rnorm(n)
    )

    # Effects for individuals and firms
    id.eff <- rnorm(nlevels(d$id))
    firm.eff <- rnorm(nlevels(d$firm))

    # Left hand side
    d$y <- d$projects_0_300_minus2 + 0.5*d$projects_0_300_minus1 + d$projects_0_300_0 + 0.5*d$projects_0_300_1 +d$projects_0_300_2  +d$projects_300_600_minus2 +d$projects_300_600_minus1 + 0.5*d$projects_300_600_0 +d$projects_300_600_1 + 0.5*d$projects_300_600_2  + 0.5*d$projects_600_800_0 +d$projects_600_800_minus2 + 0.5*d$projects_600_800_minus1 +d$projects_600_800_0 + 0.5*d$projects_600_800_1 +d$projects_600_800_2+ id.eff[d$id] + firm.eff[d$firm] + d$u

## extract predictor names
    d_pred <- subset(d, select = -c(id,firm,u,y))
    d_pred_names <- names(d_pred)

## model
    Formula <- formula(paste("y ~ ", paste(d_pred_names, collapse=" + "),"| id + firm | 0 | 0"))
    results <- felm(Formula, data = d)

    #extract names for grouping of coefficient s
    projects_minus2 <- names(d[ , grepl( "00_minus2" , names( d ) ) ])
    projects_minus1 <- names(d[ , grepl( '00_minus1' , names( d ) ) ])
    projects_0 <- names(d[ , grepl( "00_0" , names( d ) ) ])
    projects_1 <- names(d[ , grepl( "00_1" , names( d ) ) ])
    projects_2 <- names(d[ , grepl( "00_2" , names( d ) ) ])

## plot individual BUT WANT TO GROUP THESE INTO ONE PLOT
    Turnover_projects_minus2 <- jtools::plot_coefs(results, coefs = projects_minus2) + labs(title = 'Turnover_projects -2')
    Turnover_projects_minus1 <- jtools::plot_coefs(results, coefs = projects_minus1) + labs(title = 'Turnover_projects -1')
    Turnover_projects_0 <- jtools::plot_coefs(results, coefs = projects_0) + labs(title = 'Turnover_projects 0')
    Turnover_projects_1 <- jtools::plot_coefs(results, coefs = projects_1) + labs(title = 'Turnover_projects 1')
    Turnover_projects_2 <- jtools::plot_coefs(results, coefs = projects_2) + labs(title = 'Turnover_projects 2')

    ggarrange(Turnover_projects_minus2, Turnover_projects_minus1, Turnover_projects_0,Turnover_projects_1,Turnover_projects_2,
                    ncol = 2, nrow = 5)

Using this image as an example:

I would like the variables that include seperately: 0-300, 300-600, 600-800, which will be on the Y axis where the above image has 'wt' , 'cyl', 'disp'.
Then, for each one of these, they would grouped by 5 points that include 'minus2', 'minus1' , '0' , '1' , '2' like the above image where 'model1', 'model2', 'model3' are grouped together.
Something like this i think but couldnt get it work..:
https://www.cgoodman.com/blog/archives/2019/12/03/custom-coefficient-graphs/
Answer: To my mind, it would be easier to obtain the estmates with confidence intervals directly from your model and plot these. Taking your felm output results, we can do:
library(tidyverse)

plot_df <- as.data.frame(summary(results)$coef) %>%
  rownames_to_column() %>%
  mutate(var1 = sub("^.*_(\\d+_\\d+)_.*$", "\\1", rowname),
         var1 = sub("_", " - ", var1),
         var2 = sub("^.*_(.*)$", "\\1", rowname),
         var2 = factor(var2, c("minus1", "minus2", 0:2)),
         upper = Estimate + 1.96 * `Std. Error`,
         lower = Estimate - 1.96 * `Std. Error`) %>%
  select(var1, var2, Estimate, lower, upper)

This gives us the two variables required for grouping, the estimates, and the confidence intervals:
plot_df
#>         var1   var2  Estimate     lower     upper
#> 1    0 - 300 minus2 0.9377860 0.8725008 1.0030712
#> 2    0 - 300 minus1 0.4913298 0.4253458 0.5573139
#> 3    0 - 300      0 1.0522792 0.9884674 1.1160910
#> 4    0 - 300      1 0.4887432 0.4232850 0.5542015
#> 5    0 - 300      2 0.9327972 0.8685721 0.9970223
#> 6  300 - 600 minus2 0.9883478 0.9257882 1.0509073
#> 7  300 - 600 minus1 0.9717786 0.9052546 1.0383026
#> 8  300 - 600      0 0.5193846 0.4546181 0.5841512
#> 9  300 - 600      1 1.0052123 0.9400112 1.0704134
#> 10 300 - 600      2 0.4651625 0.4003738 0.5299512
#> 11 600 - 800 minus2 1.0270672 0.9627909 1.0913436
#> 12 600 - 800 minus1 0.5258786 0.4608404 0.5909167
#> 13 600 - 800      0 1.4825069 1.4190417 1.5459721
#> 14 600 - 800      1 0.5573935 0.4916004 0.6231867
#> 15 600 - 800      2 1.0396711 0.9741703 1.1051719

We can now plot this however we choose using ggplot, such as
ggplot(plot_df, aes(x = Estimate, y = var2)) +
  geom_linerange(aes(xmin = lower, xmax = upper), size = 1,
                 color = "deepskyblue4", alpha = 0.5) +
  geom_point(size = 3, color = "deepskyblue4") +
  scale_y_discrete(labels = seq(-2, 2), expand = c(0.25, 0)) +
  labs(y = NULL) +
  facet_grid(var1~., switch = "y") +
  theme_minimal(base_size = 20) +
  theme(strip.placement = "outside",
        axis.text.y = element_text(size = 12),
        panel.spacing.y = unit(0, "mm"))

Or
ggplot(plot_df, aes(x = var1, y = Estimate, color = var2)) +
  geom_linerange(aes(ymin = lower, ymax = upper), size = 1,
                 position = position_dodge(width = 0.5)) +
  geom_point(position = position_dodge(width = 0.5), size = 3) +
  coord_flip() +
  labs(x = NULL, color = NULL) +
  scale_color_brewer(palette = "Set1", labels = seq(-2, 2)) +
  theme_minimal(base_size = 20)

Created on 2022-09-10 with reprex v2.0.2
Comment: Worked perfectly -- thank you!

However, using the GGplot i ran into a strange issue. My X axis is: 0-300, 300-600, 600-800,800-1000,1000-1200,1200-1400,1400-1600 etc

and in the plot, its ordered as 0-300, 1000-1200,1200-1400,1400-1600,300-600,600-800,800-1000. Is there anyway using your code above to order it accordingly the actual distance bins: 0-300, 300-600, 600-800,800-1000,1000-1200,1200-1400,1400-1600 etc
Comment: This is because ggplot turns character variables into factor levels. These are organised in alphabetical order. If you want them in a particular order, mutate var1 into a factor, with the levels in the order you want them
Comment: boom! thank you -- worked well

Grouping coefficients in plot R


Probability related to exclusion inclusion principle of three sets

Question:
In a group consisting of 40 students, 22 of them join in IMO, 17 students join in IBO, and 20 students join in ICO. Meanwhile there are several students join in two events in which IMO and IBO, IMO and ICO, and IBO and ICO are respectively followed by the number of 12, 8, and 8 students. Furthermore, there are 5 students who join at all three events.
What is the probability of selecting one student who doesn't join at IBO and ICO?

My process of the solution is only making the symbols of the statements in the problem i.e.
M = IMO, B = IBO, C = ICO
$n(S) = 40$, $n(M) = 22$,   $n(B) = 17$,  $n(C) = 20$,
$$n(M \wedge B) = 12$$
$$n (M\wedge C) = 8$$
$$n(B \wedge C) = 8$$
$$n(M\wedge B\wedge C) = 5$$
I attempt with this
$$P(B \wedge C)'  = 1 - P(B \cup C) = 1 - [P(B) + P(C) - P(B\wedge C)]$$
is it correct?
Answer: I guess you are looking for the probability that the chosen student is not attaining IBO and ICO (but he is allowed to attain all 3)? Then you are interested in $1-\mathbb{P}[\text{IBO and ICO but not IMO}]=\mathbb{P}[\text{IBO and ICO}]-\mathbb{P}[\text{IBO and ICO and IMO}]=\frac{8}{40}-\frac{5}{40}=\frac{3}{40}$
In general you just have to count the guys in the partition. Best way is to draw 3 circles in a general position (hence they all intersect each other) and then find the number of students in all the areas!
For example for the students only doing IBO: There are 5 students doing all three courses, hence there are 8-3=5 who only do ICO and IBO (but not all 3) and 12-5=7 who only do IBO and IMO. Since 17 people took the IBO cours and 5 of them do all three, 7 IBO and IMO and 3 do IBO and ICO, you know that there are only 2 guys doing IBO and nothing more.
Similary you get that the "only ICO", "only IMO" students are 9, resp. 7. By adding all disjoint events you see that only 36 students attain a class.
Now you can easily calculate any probability just by adding the numbers in the right partitions and dividing by 40.


Prove that $d_n>(n-1)!$ for all $n\geq4$.

Question: Problem: Prove that $d_n>(n-1)!$ for all $n\geq4$.
$d_n$comes from the derangement where $$d_n=(n-1)(d_{n-1}+d_{n-2})=n!\sum_{m=0}^{n}\dfrac{(-1)^m}{m!}=n!\Bigg(1-\frac{1}{1!}+\frac{1}{2!}-\cdots +\dfrac{(-1)^n}{n!}\Bigg)$$
I've used induction, but do not have a solid proof, yet. Any ideas?
Comment: if the recurrence holds, then the statement is true by induction. Are you asking if the recurrence is true?
Answer: Strong induction:
$n=4$, do the math
now, by strong induction apply disequality to $d_{n-1}$ and $d_{n-2}$: $d_n = (n-1)(d_{n-1} + d_{n-2}) > (n-1)((n-2)! + (n-3)!) = (n-1)! + (n-1)(n-3)! $
Now remove the second term, you get a $d_n > (n-1)!$
Comment: You don't even need strong induction: since $d_n\ge 0$, you can argue that if $d_n>(n-1)!$, then $$d_{n+1}=n(d_n+d_{n-1})\ge nd_n>n(n-1)!=n!\;.$$


Exception handling with scala futures

Question: I have a problem with Scala Futures. I have a function that takes two parameters: x: Future[Int] and y: Future[Int].
The function should return a future that completes with:

value of x if x completes successfully,
value of y if x fails and y completes successfully,
the exception that failed y if x fails and y fails.

I cannot seem to figure out how to do this.
The code currently:
def myFunction(x: Future[Int], y: Future[Int]): Future[Int] = {
  x.onSuccess {
    case result => return Future(result)
  }
  x.onFailure {
    case e =>
      y.onSuccess {
        case res => return Future(res)
      }
      y.onFailure {
        case f => throw f
      }
  }
}

Answer: Simply:
x.recoverWith { case _ => y }

Comment: Thanks, just what I needed!

Exception handling with scala futures


Can the Bonferroni correction or another correction for multiple comparisons be used in a logistic regression?

Question: Can the Bonferroni correction or another correction for multiple comparisons be used in a logistic regression? I have only seen it used in ANOVAs. Also, is there a test I can use in SPSS for this?
Answer: Yes it can be. I don't know SPSS (and questions about software are off topic here) but it ought to be possible there. In any case, Bonferroni is simple to do by hand. Just divide the alpha value by the number of comparisons. So, if you wanted p < 0.05 with 4 comparisons, you would then need 0.0125.


Could someone show me how this is implemented in main()? (question on void pointers)

Question: I got the below snippet from Algorithms in a nut shell
void sortPointers (void **ar, int n,
int (*cmp)(const void *, const void *)) {

int j;

for (j = 1; j < n; j++) {
   int i = j-1;
   void *value = ar[j];
   while (i >= 0 && cmp (ar[i], value) > 0) {
   ar[i+1] = ar[i];
   i--;
}

ar[i+1] = value;
}
}

https://www.amazon.com/Algorithms-Nutshell-OReilly-George-Heineman/dp/059651624X
They do not provide the main() implementation of
sortPointers

so i have some problems figuring out what does **ar do
when i attempted to do a test code on
**arrPtr = x

it returns the error that you cannot cast void ** on a int *.
this surprises me as the book clearly says you feed an array into the function.
int main()
{
    var x[3] = { 2 , 4 , 3};

    void **arrPtr = x[0];

    return 0;
}

a side question as well.
void *value = ar[j];

is this a unneeded step? the CMP function was able to take ar[i] as a argument, shouldnt it be able to take ar[j] as is?
Comment: Are you trying to learn C or C++? These languages are very different, but they have enough in common to cause major confusion in novices when approached simultaneously.
Comment: `ar` is an array of pointers.
Comment: the type of `arrPtr` is `void**` the `*` in pointer variables can be placed next to the name of the variable or the type, but either way it's part of the type. So that means this is a "pointer to pointer"
Comment: hi both.. a side question as well.

void *value = ar[j];

is this a unneeded step? the CMP function was able to take ar[i] as a argument, shouldnt it be able to take ar[j] as is?
Comment: @tkausl could you illustrate that as a main() implementation? I think i am having problems visualizing that.
Comment: what is the main() implementation supposed to do?
Comment: @ChrisRollins sorry my language is not the most clear.

I think what I am trying to ask if that if someone could show me how this function is implemented.

BEING

int main()
{
    sortPointers(array, n, cmp)

}

how does the above look like in a proper implementation.

as of now I only have the function, which is really really confusing on visualizing the different parameters/arguments.
Comment: `main()` needs something like `int* ar[] = { new int{2}, new int{4}, new int{3} };` to sort, then you need a compare/less function like `[](const void* pa, const void* pb) { int a = *pa, b = *pb; return a < b ? -1 : a == b ? 0 : 1; }` (shown as a lambda).  More generally, if you want to learn C++ and not C, get another book.  C++ has templates to provide type-safe and more understandable code instead of this C-style hackery.
Comment: @TonyDelroy Thank you that was exactly what I am trying to request for .

its a pity the book only have C implementation that reads like abstract art
Comment: @jamesdlin sorry fixed it, i was having problems with uploading my question
Comment: @youcantcme: oh - you'll actually need an explicit cast: `int a = *static_cast(pa), ...`    I'm afraid I can't recommend a text book - both off topic and it's been so long since I was learning anything like this I wouldn't know which book was worthwhile.  I think there's a C++ book recommendation list linked off the S.O. C++ page, or google-able.
Comment: @TonyDelroy

I just tried

    int* ar[] = { new int{2}, new int{4}, new int{3} };

the compiler refuses to build.

It only builds with

    void* ar[] = { new int{2}, new int{4}, new int{3} };
Comment: @TonyDelroy that static_cast thing is new to me. I will read up on it. Thank you for the book recommendation as well.

i am only tackling C because this book is a great reference for algos (less technical in math areas so that it is actionable while remaining readable). its the C implementation that makes it tough .

i primarily use C#
thanks man
Comment: FWIW, `static_cast` above is a more restrictive alternative to the C style `*(const int*)pa`, which means *"hey, pa actually points at an integer constant, dereference the pointer value and access the integer"*.  Without a cast, the compiler won't know what type of data the `void*` is pointing too - that's kind of the point of using `void`: type erasure.
Comment: @TonyDelroy thanks for that tip mate. appreciated.
Comment: Note: About the only time you want to use a `void` pointer in C++ is when you have to work with an old program or a program written in C.Virtually every other case is handles with templates or inheritance. Learn what you can from C programming resources, but know that there may be solution that takes better advantage of C++.
Answer: In C we have the function qsort which is a generic function to sort arrays. It can sort all kind of arrays (e.g. arrays of int, arrays of double and even arrays of custom structs). All it requires is that the user provide a "compare" function for comparing two elements.
The sortPointers seems to be pretty much the same except it does not sort arrays of elements but instead sorts an array of pointers to elements.
As far a I can see the idea is to use it like:
#include <stdio.h>
#include <stdlib.h>

int cmp(const void * a, const void * b)
{
    int* pa = (int*)a;
    int* pb = (int*)b;
    if (*pa > *pb) return 1;
    if (*pa < *pb) return -1;
    return 0;
}

void sortPointers (void **ar, int n,
                   int (*cmp)(const void *, const void *))
{
    int j;

    for (j = 1; j < n; j++) {
       int i = j-1;
       void *value = ar[j];
       while (i >= 0 && cmp (ar[i], value) > 0) {
           ar[i+1] = ar[i];
           i--;
        }

        ar[i+1] = value;
    }
}

void pp(int **ar, int n)
{
    for(int i=0; i<n; ++i)
        printf("Address %p holds the value %p and points to %d, i.e. arr[%d] points to %d\n", (void*)(&ar[i]), (void*)ar[i], *ar[i], i, *ar[i]);
}

#define ELEM 3

int main(void)
{
    int* arr[3];
    for(int i=0; i<ELEM; ++i) arr[i] = malloc(sizeof(int));
    *arr[0] = 5;
    *arr[1] = 8;
    *arr[2] = 2;

    pp(arr, ELEM);
    sortPointers((void**)arr, ELEM, cmp);
    printf("------------------------\n");
    pp(arr, ELEM);

    for(int i=0; i<ELEM; ++i) free(arr[i]);

    return 0;
}

Output:
Address 0x7fff9a7d0270 holds the value 0xeeb010 and points to 5, i.e. arr[0] points to 5
Address 0x7fff9a7d0278 holds the value 0xeeb030 and points to 8, i.e. arr[1] points to 8
Address 0x7fff9a7d0280 holds the value 0xeeb050 and points to 2, i.e. arr[2] points to 2
------------------------
Address 0x7fff9a7d0270 holds the value 0xeeb050 and points to 2, i.e. arr[0] points to 2
Address 0x7fff9a7d0278 holds the value 0xeeb010 and points to 5, i.e. arr[1] points to 5
Address 0x7fff9a7d0280 holds the value 0xeeb030 and points to 8, i.e. arr[2] points to 8

However, the whole function seems to be a waste of time. The standard qsort can do this for you so why write a special function? As written above qsort can sort all kind of arrays so it can also sort an array of pointers. The compare function just needs to be a bit different. Simply use qsort like:
// Compare function
int cmp_qsort(const void * a, const void * b)
{
    int** pa = (int**)a;
    int** pb = (int**)b;
    if (**pa > **pb) return 1;
    if (**pa < **pb) return -1;
    return 0;
}

// Call from main like:
qsort(arr, ELEM, sizeof(int*), cmp_qsort);

The output will be the same (except for the address that change every time you run it) and you don't need a custom sort function like sortPointers.


Gaussian orthogonal ensemble and Haar measure

Question: I have been struggling with a probably easy question but I cannot prove it, so any insights would be really helpful.
If I have a random matrix $X \in GOE(N)$, namely from the Gaussian orthogonal ensemble, we know that it can be written as $X=ULU^{T}$, where $U$ is an orthogonal matrix consisting of the eigenvectors of $X$ and $L$ is diagonal with the eigenvalues as entries. Can I say that this particular $U$ is Haar distributed?
I think that the answer is related to the $GOE$ being translation-invariant and the fact that the Haar measure is the unique measure on $\mathbb{O}(N)$, with this property, but I cannot write a proper proof.
Answer: Careful: $U$ is not unique.  In particular, you can always replace $U$ by $-U$.  So you could arrange e.g. that $U_{11} \ge 0$, in which case it is certainly not Haar distributed.
But maybe the question is whether it is possible to do the diagonalization in such a way that $U$ is Haar distributed.
I think the way to proceed is as follows:  let $V$ be a Haar distributed orthogonal matrix independent of $X = U L U^T$,
and consider $Y = V U L U^T V^T = (VU) L (VU)^T$.  Then $Y$ is again in the GOE, and $VU$ is Haar distributed.
Comment: Thank you for your answer. Could you elaborate on why VU is Haar distributed?
Comment: Because the distribution is invariant under multiplication on the left by any orthogonal matrix, and that characterizes probability measures on the orthogonal group.


Display image based on a output in one window (Python)

Question: I have an implementation of k-NN algorithm in Python, that returns the class label of an input. What I need is to show an image assigned to the class label in one window while output is coming (by refreshing the window). Problem is, I am not very experienced in GUI programming, thus I need some resources and assistance to start with. What libraries, books and tutorials could you recommend? Pieces of code would be appreciated too.
Answer: There are many libraries allow you add images to your program such as Turtle, PIL.ImagTk and Canvas and you can even use Pygame to a best performance.
PIL.ImagTk and Canvas:
from Tkinter import *
from PIL import ImageTk
backgroundImage = PhotoImage("image path (gif/PPM)")
canvas = Canvas(width = 200, height = 200, bg = 'blue')
canvas.pack(expand = YES, fill = BOTH)

image = ImageTk.PhotoImage(file = "C:/Python27/programas/zimages/gato.png")
canvas.create_image(10, 10, image = image, anchor = NW)

mainloop()

Turtle:
import turtle

screen = turtle.Screen()

# click the image icon in the top right of the code window to see
# which images are available in this trinket
image = "rocketship.png"

# add the shape first then set the turtle shape
screen.addshape(image)
turtle.shape(image)

screen.bgcolor("lightblue")

move_speed = 10
turn_speed = 10

# these defs control the movement of our "turtle"
def forward():
turtle.forward(move_speed)

def backward():
   turtle.backward(move_speed)

def left():
   turtle.left(turn_speed)

def right():
    turtle.right(turn_speed)

turtle.penup()
turtle.speed(0)
turtle.home()

# now associate the defs from above with certain keyboard events
screen.onkey(forward, "Up")
screen.onkey(backward, "Down")
screen.onkey(left, "Left")
screen.onkey(right, "Right")
screen.listen()

Now let's change the background
import turtle

screen = turtle.Screen()

# this assures that the size of the screen will always be 400x400 ...
screen.setup(400, 400)

# ... which is the same size as our image
# now set the background to our space image
screen.bgpic("space.jpg")

# Or, set the shape of a turtle
screen.addshape("rocketship.png")
turtle.shape("rocketship.png")

move_speed = 10
turn_speed = 10

# these defs control the movement of our "turtle"
def forward():
    turtle.forward(move_speed)

def backward():
    turtle.backward(move_speed)

def left():
    turtle.left(turn_speed)

def right():
    turtle.right(turn_speed)

turtle.penup()
turtle.speed(0)
turtle.home()

# now associate the defs from above with certain keyboard events
screen.onkey(forward, "Up")
screen.onkey(backward, "Down")
screen.onkey(left, "Left")
screen.onkey(right, "Right")
screen.listen()

for Turtle:
http://blog.trinket.io/using-images-in-turtle-programs/


generating ssh-keys for a non root user with salt

Question: I need to generate ssh-keys(public/private pair) for a user say helen. This user is already in all my salt minions. How do I generate ssh keys for this user from my salt master?
For root user I generated the keys using this command and it worked fine:
salt '*application-server-*' cmd.run "ssh-keygen -q -N '' -f /root/.ssh/id_rsa"

I can issue the following command which can generate ssh-keys for helen; but the permissions and ownerships will be different; so need to issue commands again to correct permissions and ownerships:
salt '*application-server-*' cmd.run "ssh-keygen -q -N '' -f /home/helen/.ssh/id_rsa"

Is there any way in salt to run this command as user helen instead of root?
In general, is there a way in salt to run a command as a non root user?
Answer: Using the salt command
salt '*application-server-*' cmd.run \
    "ssh-keygen -q -N '' -f /home/helen/.ssh/id_rsa" \
    runas=helen

http://docs.saltstack.com/en/latest/ref/modules/all/salt.modules.cmdmod.html#salt.modules.cmdmod.run
Using a state
You can specify the user when using the cmd state by setting the runas  to the user name to run the command as:
generate_ssh_key_helen:
  cmd.run:
    - name: ssh-keygen -q -N '' -f /home/helen/.ssh/id_rsa
    - runas: helen
    - unless: test -f /home/helen/.ssh/id_rsa

http://docs.saltstack.com/en/latest/ref/states/all/salt.states.cmd.html#salt.states.cmd.run
Comment: I look at the salt state of your answer. AFAIK this generates a new key every time this state gets called. Is there a way to create they key only if it does not exist yet?
Comment: You're absolutely right. You need to make sure this state is executed only once, by setting a specific grain, for example. You can set a grain with another state that depends on this one, then check if the grain exists in your sls file to enable or disable the state.
Comment: In versions prior than 2016.3, the state parameter wasn't `runas` but `user`.
Comment: You can also do: `- creates: /home/helen/.ssh/id_rsa`


virtualbox: How to change the place of controls in fullscreen mode

Question: I am trying to move controls (https://skitch.com/otarasenko/rqepn/xp-running) to the top of the Guest machine in fullscreen mode. how do I do that?
Answer: Settings > General > Advanced > Mini ToolBar: Show At Top Of Screen
Answer: 2018 called - in VirtualBox 5.2 this checkbox moved under: Settings > User Interface > Mini Toolbar > Show At Top Of Screen


Trouble with 'Update Web Reference"

Question: Occasionally I have a problem when I attempt to update a web reference in Visual Studio 2008 (this also happened in VS2005).  It has happened in several different solutions.
When I have a solution with a (.NET 2.0) web service and a project that references the web service I get "There was an error downloading 'http://localhost:3890/MyWebService.asmx' Unable to connect to the remote server.".  Obviously, the port number in the example is an example only, it could be any port number.
The web reference is set to 'Dynamic URL' and the web service is using the ASP.NET Development Server web server rather than IIS.  When the error occurs the icon for the service never shows up in the system tray.
I have found two workarounds.  The more drastic workaround is to delete the web reference and recreate it.  This has worked for me everytime, but has caused some confusion for Subversion and AnkhSVN.
Recently it occurred to me to set the web service as the startup project, start it, and mouse over the ASP.NET Development Server icon on the system tray to find out the port number that it has chosen.  Then, edit the port number in the WebReferenceUrl property of the web reference.  After doing this I can update the web reference.
While this works I feel that there must be a better way.  It seems that VS and Cassini should be able to resolve this without manual intervention.  Am I missing something, or is this another case of Microsoft getting the difficult things right and the simple basics wrong?
I have attempted to search an answer for this issue and have found several threads describing the problem.  But, no one has identified a real solution.
Answer: Right-click the service in Solution Explorer, and choose "View in Browser". That will cause the service to start, and you'll be able to use "Add Web Reference".
Comment: worked well, when combined with answer from 'u07ch' it resolved everything
Answer: You can force the port of the test web site in visual studio.
Open the properties window in visual studio it with "F4" or via the toolbar - "View" -> "Properties Window".
Left click on your web site in the "Solution Explorer" window.  Notice the drop down list for the "Use dynamic ports" setting.  If you set this to "False", you'll then be able to specify a fixed port in the "Port number" field.
Set this to your desired port value.
Launch your web site.  You'll see the port used matches the value you specified.
Comment: worked well, when combined with answer from 'John Saunders' it worked great.
Answer: Go to project Properties-> Settings -> [Update the Service Url]
It Works.
Answer: Check appconfig file and update the port number accordingly
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-ask).

Trouble with 'Update Web Reference"


In WF 4.0, is there any way to have an activity imported through a service reference use Azure endpoint discovery?

Question: Working with WF, WCF, and the most recent Azure SDK, I have a simple sequential activity, and I have added a service reference and rebuilt the project so my service methods are all imported as activities. So far, so good, but my service will run on the emulator or in the cloud with an internal endpoint, so I need to use RoleEnvironment to discover the endpoint at runtime.
Is there any way I can get the imported activity to do this, or do I just have to write a custom activity? I can't see a way, as the only property the activity exposes is an Endpoint configuration value.
And if I have to write a custom activity, can I pass the endpoint in to my generated activity (so could my custom activity be a wrapper around it)?
Answer: Briefly, to tidy this up: I don't think it is possible. I ended up writing a custom activity to do it, which was straightforward enough.


Porque está me retornando esse erro no console?

Question:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

Drag

            Drop

Drop

Drop

Drop

Drop

A minha aplicação de Dran And Drop funciona normal porém quando eu tento arrastar o elemento arrastável (Drag) para dentro do elemento que contém ele mesmo (Drop) é retornado um erro no console:
Uncaught DOMException: Failed to execute 'appendChild' on 'Node': The new child element contains the
parent.at HTMLDivElement.drop.<computed>.ondrop

O erro por completo é:
test2.html:113 Uncaught DOMException: Failed to execute 'appendChild' on 'Node': The new child element contains the parent.
at HTMLDivElement.drop.<computed>.ondrop (file:///C:/Users/leandro/Desktop/test/test2.html:113:30)

Porque está me retornando esse erro?
Answer: Você está tentando inserir um nó dentro dele mesmo. Você resolve isso verificando com um if se o elemento arrastado é diferente do elemento onde ele vai ser largado:
if(event.target != document.querySelector(`#${data}`)){
  // se for diferente, vc faz o appendChild
}

Veja:

let drag = document.querySelector("#drag");
let drop = document.querySelectorAll(".drop");

drag.ondragstart = (event) => {
   event.dataTransfer.setData("text/plain", event.target.id);
}

for (i = 0; i < drop.length; i ++) {
   drop[i].ondragover = (event) => {
       event.preventDefault();

       event.target.style.border = "3px dashed #33e0c9";
   }

   drop[i].ondragleave = (event) => {
       event.target.style.border = "none";
   }

   drop[i].ondrop = (event) => {
       let data = event.dataTransfer.getData("text");
       if(event.target != document.querySelector(`#${data}`)){
          event.target.appendChild(document.querySelector(`#${data}`));
          event.target.style.border = "none";
       }
   }
}
* {
   margin: 0;
   padding: 0;
}

::selection {
   background: transparent;
}

body {
   background: rgb(164, 53, 229);
}

#container {
   width: 620px;
   height: 500px;
   border: 2px solid #e2b72b;
   margin: 50px auto 0 auto;
   position: relative;
}

#drag, .drop {
   width: 100px;
   height: 100px;
   text-align: center;
   line-height: 100px;
   font-size: 20px;
   font-family: arial;
}

#drag {
   background: #ffffff;
   cursor: move;
   color: #000000;
   position: absolute;
   left: 0;
   top: 0;
}

.drop {
   background: #b3b3b385;
   color: #ffffff;
   position: relative;
   position: absolute;
}

.drop:nth-of-type(1) {
   left: 20px;
   top: 20px;
}

.drop:nth-of-type(2) {
   left: 140px;
   top: 20px;
}

.drop:nth-of-type(3) {
   left: 260px;
   top: 20px;
}

.drop:nth-of-type(4) {
   left: 380px;
   top: 20px;
}

.drop:nth-of-type(5) {
   left: 500px;
   top: 20px;
}

Drag

      Drop

Drop

Drop

Drop

Drop

Comment: Perfeito! era isso mesmo, vlw! :)


Get-PnPAzureADUser : Code: Request_UnsupportedQuery

Question: I have this weird behavior inside my PnP Power Shell:-
now if i write this Power Shell i will get results:-
Get-PnPAzureADUser -Filter  {AccountEnabled eq true and Mail  eq 'firstname.lastname@example.com'}

but if i define the Mail inside a variable i will get this error:-
PS C:\windows\system32> $rrr = "firstname.lastname@example.com"
PS C:\windows\system32> Get-PnPAzureADUser -Filter  {AccountEnabled eq true and Mail  eq $rrr}
Get-PnPAzureADUser : Code: Request_UnsupportedQuery
Message: Unsupported Query.
Inner error:
        AdditionalData:
        date: 2022-12-28T22:13:33
        request-id: 3f8d45ef-ab8e-49c9-bf6e-41e4a56c11e3
        client-request-id: 3f8d45ef-ab8e-49c9-bf6e-41e4a56c11e3
ClientRequestId: 3f8d45ef-ab8e-49c9-bf6e-41e4a56c11e3
At line:1 char:1
+ Get-PnPAzureADUser -Filter  {AccountEnabled eq true and Mail  eq $rrr ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Get-PnPAzureADUser], PSInvalidOperationException
    + FullyQualifiedErrorId : InvalidOperation,PnP.PowerShell.Commands.Principals.GetAzureADUser

Or this
PS C:\windows\system32> $rrr = "'email@example.com'"
PS C:\windows\system32> Get-PnPAzureADUser -Filter  {AccountEnabled eq true and Mail  eq $rrr}
Get-PnPAzureADUser : Code: Request_UnsupportedQuery
Message: Unsupported Query.
Inner error:
        AdditionalData:
        date: 2022-12-28T22:13:33
        request-id: 3f8d45ef-ab8e-49c9-bf6e-41e4a56c11e3
        client-request-id: 3f8d45ef-ab8e-49c9-bf6e-41e4a56c11e3
ClientRequestId: 3f8d45ef-ab8e-49c9-bf6e-41e4a56c11e3
At line:1 char:1
+ Get-PnPAzureADUser -Filter  {AccountEnabled eq true and Mail  eq $rrr ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Get-PnPAzureADUser], PSInvalidOperationException
    + FullyQualifiedErrorId : InvalidOperation,PnP.PowerShell.Commands.Principals.GetAzureADUser

Any advice? how i can pass the Mail as a variable inside the Get-PnPAzureADUser??
Answer: Use a expandable string instead of a script block to formulate your filter:
$rrr = "email@example.com"
Get-PnPAzureADUser -Filter "AccountEnabled eq true and Mail eq '$rrr'"


Using Fourier series to determine if a function is odd or even

Question: Determine if the following function is odd or even using Fourier series.
$$f(x)=x^5\sin x$$
If a function is even then $b_n=0$ and you have to evaluate $a_n=\frac 2 \pi \int_0^\pi f(x) \cos nx \, dx$
And if a function is odd then $a_n=0$ and you have to evaluate $b_n=\frac 2 \pi \int_0^\pi f(x)\sin nx \, dx$
However, this means that I have to do integration by parts five times. Is there a more efficient method to determine if the function is even or odd?
Comment: Fourier series are probably one of the *least* efficient methods of determining whether a function is even...
Comment: "Is there a more efficient method to determine if the function is even or odd?" Yes. Check the *definition* of odd functions.
Comment: BEFORE calculating the integrals, you should check whether $f$ is odd/even. This might save much time.
Comment: The product of two odd functions is even, with Fourier series or not.
Answer: You do not need complicated tools to determine whether a function $f(x)$ is odd, even or neither-nor.
A function $f(x)$ is even, if and only if the equation $f(-x)=f(x)$ holds for every $x$ for which both $f(x)$ and $f(-x)$ are defined and it is odd if and only if the equation $f(-x)=-f(x)$ holds for every $x$ for which both $f(x)$ and $f(-x)$ are defined.
In your example, we have $f(-x)=(-x)^5\sin(-x)=(-x^5)\cdot (-sin(x))=x^5\cdot sin(x)=f(x)$, so $f$ is even.
Answer: If a function is even then $b_n=0$ and you have to evaluate $b_n=\frac {2}{\pi}∫_{-\pi}^{\pi} f(x)\sin nx\ dx$
Note, you do not have to find any of the values of $a_n.$  You need to show that all the values of $b_n$ equal 0.
And, note the limits of integration.
Similarly: If a function is odd then $a_n=0$ and you have to evaluate $a_n=\frac {2}{\pi}∫_{-\pi}^{\pi} f(x)\cos nx\ dx$
$b_n=\frac {2}{\pi}∫_{-\pi}^{\pi} x^5\sin nx\ dx$
Now, rather than evaluating, and performing integration by parts 5 times.
I suggest you show that:
$a_n=\frac {2}{\pi}∫_{-\pi}^{\pi} \cos nx\ dx = 0$
and
b_n=\frac {2}{\pi}∫_{-\pi}^{\pi} x\sin nx\ dx = 0$
Then use induction to show that
$a_n=\frac {2}{\pi}∫_{-\pi}^{\pi} x^m\cos nx\ dx = 0$ when $m$ is even
and
$b_n=\frac {2}{\pi}∫_{-\pi}^{\pi} x^m\sin nx\ dx = 0$ when $m$ is odd


Why does AngularJS select all options instead of just the one clicked?

Question: In my AngularJS app I have an HTML form with some option elements, and when I change one option the other options also get changed. After reloading the page I can change individual values.
A function changeVariant is called on change and the values will be changed.
What causes this and how can I fix it?
Comment: Link points to http://webserver/Websites/saunadrome/reserveren/?arr=93#/stap/3 and does not work. If you want to provide example, make a plunker or something.
Comment: check scope variable name of all option is all are same.
Comment: Changed the link, now it goes to the correct page.
Answer: This is the angularjs feature 2 way binding. if a scope variable is changed in controller the reference (object reference) value will also get changed in corresponding html pages. to restrict this you have to break the object reference. please check the below url to get some idea.
https://www.bennadel.com/blog/2863-breaking-direct-object-references-at-cache-boundaries-in-angularjs.htm


Load variable from URL

Question: My example page url is http://example.com/itemurl/?23 where 23 is the item number.
On that page, I need to pull that 23 and make it a variable so I can append it to the url in an Ajax call to get an xml file:
Here is my script:

I need the url in the script to be https://example.com/getxml/23 but I'm not sure how to accomplish this.
Comment: http://stackoverflow.com/questions/979975/how-to-get-the-value-from-the-url-parameter
Comment: strange url structure using `?` but not using `=` to create GET key/value pair
Answer: The line with url should look like this:
url: "https://example.com/getxml/"+window.location.search.substr(1),

Load variable from URL


Python 3.* on Gentoo

Question: How to install python 3.* on Gentoo without compiling by hand?
Are there any ebuild or overlay  for this?
UPDATE:
now it's absolutely possible without any hacks
Comment: I love that server fault has become the go to place for these questions.  Far easier than asking on 4 different linux forums.
Comment: @sparks god forbid we go to distro ML/Forum and ask the people that actually know...
Comment: bizarre that this was closed as off-topic. This is the kind of server configuration problem that I would first think of searching here for.
Answer: Apparently in python-experimental, according to http://bugs.gentoo.org/250186
Answer: Python 3.1 is now available on Gentoo in the unstable category.
Comment: Yes, and most other things. In fact, installing 3.1 won't overwrite /usr/bin/python with the new version yet since so many things still need 2.X logic.
Comment: I'd detoured to Arch for a while, and didn't see that Gentoo had an upgrade. *hug*

Guessing that I still need 2.* for Portage, though.

Python 3.* on Gentoo


On the Normability of Quasi-Banach Spaces

Question: N. J. Kalton wrote in his 1982 paper Convexity Conditions for Non-Locally Convex Lattices a statement that
lattice 1-convexity is equivalent to normability.
I cannot see why this is immediate. Kalton did not point to any reference of this statement neither.
Related notations are as follows.
$\|\cdot\|$ is called a quasi-norm on $X$ if $\|x\|>0$ for $x\in X, x\ne 0$, $\|\alpha x\|=|\alpha|\|x\|$ for $\alpha\in\mathbb{R}, x\in X$, $\|x_{1}+x_{2}\|\leq C(\|x_{1}\|+\|x_{2}\|)$ for $x_{1},x_{2}\in X$, some constant $C>0$.
$X$ is said to be normable if there is a norm $\|\cdot\|'$ such that $c\|\cdot\|\leq\|\cdot\|'\leq c\|\cdot\|$ for some constant $c>0$.
$X$ is said to be $1$-convex if
\begin{align*}
\left\|\sum_{i=1}^{n}|x_{i}|\right\|\leq M\sum_{i=1}^{n}\|x_{i}\|
\end{align*}
for $x_{1},...,x_{n}\in X$, some constant $M>0$. Here we assume that $X$ has an order lattice and so $|x_{i}|$ is an element of the lattice space $X$.
Answer: Just found a hint somewhere else.
Consider
\begin{align*}
\|x\|'=\inf\left\{\sum_{i=1}^{n}\|x_{i}\|: x=\sum_{i=1}^{n}x_{i}, x_{i}\in X\right\},
\end{align*}
then $\|\cdot\|'$ is a norm satisfying that
\begin{align*}
M^{-1}\|x\|\leq\|x\|'\leq\|x\|.
\end{align*}


Let |G| = 100, $H\leq G$ with |H| = 25. If $g\in G$ with $|g| = 5^{k}$ for some non-negative integer k, prove that $g \in H$

Question: I'm not exactly too sure how to prove this. I know by Lagrange's theorem that G can have subgroups with orders, 1, 2, 5, 10, 20, 25, 50, 100. We're to assume that the group operation is multiplication.
Any help is appreciated
Comment: Let $g$ act on the cosets of $H$ by right multiplication. What does it mean for $g$ to fix a coset?
Answer: Here is an elementary approach. Suppose $g\in G$ with $|g|=5^k$. By Lagrange's theorem, $5^k$ must divide $|G|=100$, so $k=0$, $1$ or $2$.
Case 1. $k=0$.
In this case, $g=e$ (the identity element), and so $g\in H$.
Case 2. $k=1$. Let $K=\langle g \rangle = \{g, g^2, g^3, g^4, e\}$ be the subgroup generated by $g$. Consider the subset $H\cdot K = \{h \cdot k: h\in H \text{ and } k\in K\}$ of $G$ (which is not necessarily a subgroup of $G$). Then it is an elementary fact that $|H\cdot K| = \frac{|H|\cdot |K|}{|H\cap K|}$. If $g\notin H$, then $H\cap K$ is a proper subgroup of $K$, and since $|K|=5$ is prime, we get $|H\cap K|=1$. But then
$|H\cdot K| = \frac{25\cdot 5}{1} = 125 > 100 = |G|$, a contradiction.
Case 3. $k=2$. This is similar to Case 2. Indeed, let $K=\langle g \rangle$ which has size $25$. If $g\notin H$, then $H\cap K$ is a proper subgroup of $K$, so by Lagrange's theorem (applied to $H\cap K\subset K$), we get $|H\cap K|\leq 5$. Again, we get $|H\cdot K|=  \frac{|H|\cdot |K|}{|H\cap K|} \geq \frac{25\cdot 25}{5} = 125 > 100 = |G|$, a contradiction.
Answer: Hint By Sylow Theorems $g$ belongs to a 5-Sylow subgroup and
$$n_5 \equiv 1 \pmod{5} \\
n_5|4$$
Comment: This seems a bit too "advanced" for the topics we've covered this far in our course. Is there perhaps a way you could attempt this using Lagrange's theorem? We have yet to cover "Sylow Theorem" so your solution doesn't make much sense to me


How can I solve this integral with complex number

Question: $$\int_{|z-1| = 1}\frac{1}{(1-z^2)}dz$$
I tried to do this by residue calculus
 $$I=2\pi*iRes(f(z),1)$$
but I coudn't get the answer..
I would be grateful if you could give a clue.
Additional question)
$$\int_{|z| = 3}\frac{z}{(1-z^2)}dz$$
Is $$I=2\pi*i{Res(f,0)}+Res(f,1)$$ and the answer is 0 right?
Answer: HINT:
Note that
$$\frac{1}{1-z^2}=\frac{1/2}{1-z}+ \frac{1/2}{1+z}$$
The poles are at $z=\pm 1$ and the residues are $\pm 1/2$.  Now, which poles, if any are contained in $|z-1|<1$?  Which are contained in $|z-1| <3$?
Answer: (1) We have $\int_{|z-1| = 1}\frac{1}{(1-z^2)}dz=2\pi iRes(f(z);1)$
$Res(f(z);1)=\displaystyle \lim_{z\to1}\frac{z-1}{(1-z^2)}=\frac {-1}2$
$\int_{|z-1| = 1}\frac{1}{(1-z^2)}dz=2\pi i\times\frac{-1}{2}=-\pi i$
(2)$\int_{|z| = 3}\frac{z}{(1-z^2)}dz=2\pi i(Res(f;1)+Res(f;-1))$
$Res(f(z);1)=\displaystyle \lim_{z\to1}\frac{(z-1)z}{(1-z^2)}=\frac {-1}2$
$Res(f(z);-1)=\displaystyle \lim_{z\to-1}\frac{(z+1)z}{(1-z^2)}=\frac {-1}2$
$\int_{|z| = 3}\frac{z}{(1-z^2)}dz=2\pi i(\frac{-1}{2}-\frac{1}{2})=-2\pi i$


Data-Bind e OnClick no mesmo botão

Question: Eu tenho um botão que possui um data-bind, chamando uma função JS que está funcionando perfeitamente.
Porém, preciso chamar outra função no mesmo botão, só que em C#, na classe CSS da minha pagina, se eu deixo o data-bind e o onclick, apenas o data-bind funciona, mas se eu tiro o data-bind, o onclick funciona normalmente. Segue código:
<asp:LinkButton ID="btnBuscar" runat="server" onclick="btnVisualizar_Click"
    Text="Buscar" class="btn btn-info" data-bind="click: buscar"/>

Nesse caso, apenas o data-bind está sendo chamado, o onclick não funciona.
Vale ressaltar que se eu tirar o data-bind, a outra função funciona normalmente.
Comment: Se tu precisa chamar as duas funções, acho que tu pode chamar a segunda função dentro a primeira função a ser chamada no JS.
Comment: Entendi @EdwardRamos, mas como eu poderia chamar a outra função? Posso mandar a função que eu utilizo no js adiantando que é uma função que chama o mapa do google.
Comment: Aparentemente sim...
Answer: Tu pode chamar a segunda função dentro da primeira função (acho que isso vai resolver o teu problema), se for apenas isso, tenta fazer assim:
<asp:LinkButton ID="btnBuscar" runat="server" onclick="btnVisualizar_Click"
    Text="Buscar" class="btn btn-info"/>

JS:
function btnVisualizar_Click() {
    buscar(); // chama a segunda função
    alert("A função chamada foi 'btnVisualizar_Click'");
}

function buscar() {
    alert("A função chamada foi 'buscar'");
}

Qualquer coisa, comenta ai que a gente ajuda.

Data-Bind e OnClick no mesmo botão


Erro Champ inconnu dans on clause - SQL

Question: Tenho a seguinte situação, com 3 tabelas:
ocorrencias: Possui 6 colunas: tipo_falha_1 até tipo_falha_6. É um código de 2 digitos, de 1 até 20.
tipo_falha: Possui a descrição das falhas. O campo cod é ligado a ocorrências pelo tipo_falha acima citado. Além disso, possui a coluna tipo_servico com um código que vincula ao tipo de serviço. Exemplo: Falha elétrica(tipo_falha), Elétrico (tipo_servico).
tipo_servico: Possui a descrição do servico cujo tipo_falha aponta. O campo cod é ligado a tipo_servico da tabela tipo_falha.
Minha necessidade seria gerar uma consulta, com 6 colunas, dos tipos de falha do 1 até o 6, trazendo resultado onde tiver dado e null onde não tiver nada. Tentei o SQL abaixo, mas está retornando o erro:
#1054 - Champ 'o.tipo_falha_1' inconnu dans on clause.

O que posso estar fazendo errado?
SELECT tf1.NOME desc1, tf2.NOME AS desc2, tf3.NOME AS desc3, tf4.NOME AS desc4, tf5.NOME AS desc5, tf6.NOME AS desc6
               FROM ocorrencias o, tipo_servico ts LEFT JOIN
               tipo_falha tf1
               on tf1.cod = o.tipo_falha_1 LEFT JOIN
               tipo_falha tf2
               on tf2.cod = o.tipo_falha_2 LEFT JOIN
               tipo_falha tf3
               on tf3.cod = o.tipo_falha_3 LEFT JOIN
               tipo_falha tf4
               on tf4.cod = o.tipo_falha_4 LEFT JOIN
               tipo_falha tf5
               on tf5.cod = o.tipo_falha_5 LEFT JOIN
               tipo_falha tf6
               on tf6.cod = o.tipo_falha_6
               where
               o.cod= 1

Comment: Tu tá vendo que tu tá dizendo pra dar `LEFT JOIN` de `tipo_servico` ligando pela `ocorrencias`, e depois não tem join nenhum pela `ts` né? Se funcionasse, provavelmente iria trazer uma lambança no resultado final. Acredito que só inverter a ordem do `ts` pelo `o` não vai resolver, é melhor dar uma olhada na estrutura da tabela, porque isso só iria dar erro se a tabela não possuísse esse campo.
Answer: Você está fazendo um LEFT JOIN de tipo_falha com tipo_servico, mas a condição do join usa um campo que está em ocorrencias.
  FROM ocorrencias o, tipo_servico ts LEFT JOIN
               tipo_falha tf1
               on tf1.cod = o.tipo_falha_1

Já que você não usa tipo_servico para nada, por que você não faz assim?
  FROM ocorrencias o LEFT JOIN
               tipo_falha tf1
               on tf1.cod = o.tipo_falha_1

Erro Champ inconnu dans on clause - SQL


Django timezone.now().time displays incorrect time zone

Question: The subject is the simplest way that I can break down the problem that I am getting.
I'm using Django 2.1
settings.py
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/New_York'
USE_I18N = True
USE_L10N = True
USE_TZ = True

views.py
message = timezone.now().time
message2 = timezone.now

The above code is the fastest way to show the problem that I have. When I print 'message' I'm given a time different than what I get from 'message2' although they are both pulling the same value.
My model saves a datetimefield using the auto_now_add feature.
models.py
class Comment(models.Model):
    date_time = models.DateTimeField(auto_now_add=True, blank=True)

When I display the field in HTML as
{{ comment.date_time }}

the correct date and time appears. However when I use my own formatting and break up the code as
{{ comment.date_time.date }}: {{ comment.date_time.time }}

then I cannot get the time to display in the correct timezone. I've tried the following alterations all to no avail.
{% load tz %}

{% localtime on %}
{{ comment.date_time.time }}
{% endlocaltime %}

{{ comment.date_time.time|localtime }}
{{ comment.date_time.time|timezone:"America/New_York" }}

Does anyone know of a way to address this?
Comment: You can use `python manage.py shell` for quick tests instead of having to create and instantiate models.
Answer: Try this,
pass timezone.now() to timezone.localtime
from django.utils import timezone
timezone.localtime(timezone.now())

More info here.
Comment: When using

    'from django.utils import timezone'
    'timezone.localtime(timezone.now().time)'

I get the following error

    'builtin_function_or_method' object has no attribute "utcoffset"'

My issue is specific to displaying 'timezone.now().time' as its correct value as it shows in 'timezone.now'
Answer: The problem is that you're using trying to use time objects instead of datetime objects. The localtime and timezone template tags and filters are expecting datetime objects.
If you want a custom format in the template, use the date filter. If for whatever reason that can't give you the format you want, you will need to do the conversion yourself in the view rather than relying on the template, e.g.:
from django.utils.timezone import localtime

def view():
    local = localtime(comment.date_time)
    date_string = str(local.date())  # or whatever custom format you want
    time_string = str(local.time())  # or whatever custom format you want

Answer: from django.utils import timezone
timezone.localtime(timezone.now())

Also, in the settings.py you must change:
TIME_ZONE = 'America/New_York'

A list of the time zone database names can be found on: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones


Can I use two minor scales in the same song?

Question: I've been composing a song, using the chord progression Am - G#° - Dm7/A - E (i - VII - iv - V), that is using the Harmonic minor scale.
The song has some melodies, that appear in different parts. The melodies are following the harmonic minor scale, but sometimes, I use G natural instead of G#.
The melodies that use G natural sound good to me, but I don't really know if this relationship between the two scales is correct practice.
Can I mix natural minor scale and harmonic minor scale in the same song?
Can I play G natural in a G#° chord?
EDIT: This is the song:

Thanks a lot for the help!
Comment: Remember, music theory isn't a prescription for what sounds good or bad. It is a body of notions and terminology allowing you to put words to and discuss _what_ sounds good or bad, and perhaps _why_, so that it may in a more systematic manner be repeated, tweaked or avoided in the future. Basically, you can do whatever you want, music theory isn't ever going to stop you, but it might help you learn and get better for next time.
Comment: Yes, you can. You can do everything that you want - if you find, it sounds good, and if you want that it sounds bad, too.
Comment: @Arthur When I started composing music, I just did it by ear. To me the music I was composing sounded good, but sometimes I looked for something theoretical and what I was doing didn't fitted.
Answer:
If it sounds good, it's good
There is no rule forbidding you to change the scale in your song. In fact in jazz songs scales can change very often and they still can sound good and melodic.
To understand what's happening in your example, I'd point that G#o triad notes come from the E7 chord, which is a dominant in the key of Am. Dominant chords often use all sort of altered notes, to make them more dissonant, and increase strength of resolution to the tonic. In this case, I'd say "G" is in fact Fx, an augmented 9th of the E chord. Some frequently used scales which you may want to try are E half-whole (E F Fx G# A# B C# D), or E super-locrian (E F Fx G# A# C D) which typically permits adding the perfect fifth, B. But in the end, trust your ears!
Answer: In classical harmonic theory, there is only the minor mode. The three (or so) "scales" are common usages within that mode. Most pieces (songs, symphonies, etc.) use all forms of scale within the same piece. As noted by user107905, if it sounds good, it's good. Theory comes into play when you cannot find something good (and presents ideas that one will discover working alone; there's not enough time.)
Answer: Can I mix the natural and harmonic minor scales in the same song?
Yes. It's helpful to think of "minor" as a collection of options rather than a single scale you have to commit to. Natural minor (Aeolian) is the "true" minor according to the key signature, and Harmonic minor and Melodic minor are representations of how composers modify Natural minor in their music.
So when you write "in minor", the "scale" available to you looks like this:
X:0
T:A minor note choices
K:none
M:none
L:1/4
"_1"A, "_2"B, "_b3"C "_4"D "_5"E "_b6"F "_6"^F "_b7"G "_7"^G A

A related question, with a related answer, came up here:
What scale is used with this descending bassline progression?
Can I play G, when a G#° chord is played?
Again, yes. It will be quite dissonant, but if that's the sound you want at a certain moment of the piece, then there's no reason to avoid it. As mentioned by @user1079505, you can think of G as Fx -- the #9 in an E7#9 chord. From that point of view, the voicing that will likely work best (with deference to your tastes as the composer) will be to put the G# below the D, and G (Fx) above.
In this example, the various options for B are given in parentheses.
X:0
T:Voicing G#dim against G
K:none
M:none
L:1/1
%%score (V1 V2 V3 V4 V5 V6)
[V:V1] "<("">)"B,
[V:V2] ^G
[V:V3] "<("">)"B
[V:V4] d
[V:V5] =g
[V:V6] "<("">)"b


how to monitor "create user" action on linux platform?

Question: currently on linux platform,
if someone or some app create a user.
Does other apps be able to get this message immediately?
if yes, app can use which way to know a user is created ?
thanks in advance
Comment: is polling on /etc/passwd file every x seconds enough for you?
Comment: thanks. but this is not what I want. I just wonder if there is some scheme to notify other user a new user is created.
Answer: You may use similar script like below to examine the /etc/passwd file continuously. You may vary "sleep" command to determine the delay. If you run this script in background, it will send mail when new users are added or removed. You can feed these results to desired application by altering the code.
<code>#!/bin/bash

unalias cp &>/dev/null

OLD=`wc -l "/etc/passwd" | awk '{print $1}'` && /bin/cp -f /etc/passwd /etc/passwd.old

while true ; do

sleep 1

NEW=`wc -l "/etc/passwd" | awk '{print $1}'` && MID=${NEW} && /bin/cp -f /etc/passwd /etc/passwd.copy

 if [[ ${NEW} -gt ${OLD} ]]

   then

   DIFF=`expr ${NEW} - ${OLD}`

   USERS=`tail -n ${DIFF} "/etc/passwd.copy" | awk -F: '{ print $1 }'`

   echo -e "New user(s):\n ${USERS} " | mail -s "New Users Created! at `date +%c`" email@example.com

 elif [[ ${NEW} -lt ${OLD} ]]

   then

   USERS=`diff -y /etc/passwd /etc/passwd.old | awk -F">" '{print $2}'| awk -F: '{print $1}' | grep -E -v "^$"`

   echo -e "User(s)removed:\n ${USERS[@]}" | mail -s "Users removed at `date +%c`" email@example.com

 fi

sleep 1

OLD=${MID} && /bin/cp -f /etc/passwd.copy /etc/passwd.old

done
</code>


Algorithm for finding orthogonal complement in inner product spaces

Question: Is there a general procedure for calculating a basis for the orthogonal complement of a given subspace (with a given basis)? For $\mathbb R^n$ this amounts to finding the nullspace of a matrix with the basis vectors for rows, but this is just because of the definition of the standard inner product.
What about the general case?
Comment: @MattSamuel cowabunga!
Comment: You should upvote any answers that you found helpful as well.
Comment: @MattSamuel I can't upvote
Comment: Well if that's the case then I guess you're exempt!
Answer: Find a basis for the subspace. Extend to a basis of the whole vector space. Orthogonalize the entire basis using Gram-Schmidt, with the basis of the subspace first; this will give you an orthogonal basis of the subspace, and the remaining vectors will form a basis for the orthogonal complement.
Answer: Take a closer look at what you're doing when you use the algorithm that you describe for computing an orthogonal complement relative to the Euclidean scalar product $\langle\cdot,\cdot\rangle$: you're solving the homogeneous system of linear equations $$\begin{align}
\langle\mathbf w_0,\mathbf x\rangle &= 0 \\
\langle\mathbf w_1,\mathbf x\rangle &= 0 \\
\vdots \\
\langle\mathbf w_m,\mathbf x\rangle &= 0 \\
\end{align}$$ where the $\mathbf w_k$ are a basis for the subspace. This can be written as the single equation $W^T\mathbf x=0$, where $W$ is the matrix with these basis vectors as its columns. Solving this amounts to finding the nullspace of $W^T$, as you said.
For an arbitrary inner product $(\cdot,\cdot)$ over $\mathbb R^n$, you can set up a similar system of linear equations and solve it to find the orthogonal complement relative to that inner product. To express this system in matrix form, we take advantage of the fact that any inner product over $\mathbb R^n$ can be expressed in terms of the Euclidean scalar product as $(\mathbf u,\mathbf v)=\langle\mathbf u,A\mathbf v\rangle$, where $A$ is a fixed symmetric positive-definite matrix. This matrix is given by $A_{ij}=(\mathbf e_i,\mathbf e_j)$, where the $\mathbf e_k$ are the standard basis vectors. With this matrix in hand, the system of equations can be written $W^TA\mathbf x=0$, so finding the orthogonal complement of the subspace is a matter of computing the nullspace of $W^TA$.
The process for $\mathbb C^n$ is similar, except that the inner product matrix will be Hermitian and you need to use conjugate transposes.
Answer: If the subspace with known basis is of dimension $k$ and the full space is $\mathbb{R}^n$, take a set of  $n-k$ random vectors $v_k$. Subtract the projection onto the basis for each random vector $v_k$ and each basis vector $i$, $$v_k = v_k - P_i(v_k)$$Now you will have a basis for the complementary subspace: $\{v_1,\cdots,v_{n-k}\}$.
Construct your projection like so:
$$P = SDS^{\dagger}$$ with $D$ diagonal and $D_{jj} = \delta_{(j\leq k)}$, and the first $k$ columns of $S$ be basis vectors and the rest zeros, $S^\dagger$ denotes pseudo-inverse.
Furthermore stuff $v_k$ as columns into $V$. Now just do $(I-P)V$ and you will have a basis of the complementary space as the columns of this product.
Comment: @darkmoor I could explain, but it is much more worth if you experiment with it and figure out how it works. Why don't you try it and build up your own intuition.
Comment: @darkmoor yes that should be right. So $P$ removes the parts which the first subspace can represent and left after subtracting it from $I$ will be the parts which the complementary space spans.
Comment: @darkmoor Just be careful to make sure $u$ is normalized! The outer product needs to have eigenvalue 1.
Comment: Hi, sorry for my delayed comment, is it possible to provide a little more details? Is you approach related to QR factorization? Can you please elaborate a little more?
Comment: @darkmoor I don't see a connection to QR factorization, but I may be missing something. Sure I can add a minimal example.
Comment: Thanks for the response.Please let me ask a few things. What $P_i(v_k)$ means? Also how $S$ is defined? Also, what is the intuition of $(I-P)V$? Thanks again!
Comment: OK I got it, sorry. Please let me add an example. If the given basis is a single vector $u\in \mathbb{R}^n$ and $V\in \mathbb{R}^{n \times n-k}$, then, $P = uu^T$ and the orthogonal subspace is defined by the columns of $\tilde{V} = [I-uu^T]V$. Am I right?


Drums - Having trouble playing bass 16th notes

Question: The title is an understatement. I've been trying for months, and I can't for the life of me play bass drum 16th notes while playing 8th notes on the hi-hat. I can play snare 16th notes and hi-hat 8th notes just fine, but if I try to play the same thing on the bass drum, I end up hitting the hi-hat irregularly. Basically, whenever I hit the bass drum, my body involuntarily also hits the hi-hat. If I "speed up" my hi-hat to 16th notes, I can easily play bass drum 16th notes.
What should I do? I feel like this problem is really holding me back from getting better overall, and I feel like the longer I ignore this problem, the more difficult it will be to break.
I would really like answers more substantial than "just practice". If that's the bottom line, then so be it, but I'll be more inclined to accept an answer with some specific advice, such as a particular song or beat or technique I can try.
Comment: I'm no expert... do the usual - slow way down till you can do it to that slowww tempo. Also, I think 16ths on kick are usually done with 2 pedals on the kick drum, eh?
Comment: That's called a "double bass pedal", which is one option, however I should be able to do it with only one foot. I think that a "double bass pedal" is mostly used for 32nd notes.
Comment: Hi five man. Been trying hard to get it down. I mess it up when two strokes are to be played. Like 4 e **& a** for example. The song I am trying is Blackfield's 'Where is my love'.
Answer: It is actually just practice but you need some consciousness while doing it. First of all it's a very very common problem so no need to alienate yourself.
Second, the problem is how you approach playing. You are trying to replay the, I would casually say, the muscle memory recording. Probably you had some nice time or you thought it sounds cool or you have never managed to play it properly and replicating every time you attempt to play it.
The main argument is to play it extremely slow (I'm talking about 40-50 bpm here) until you get exactly what limb is doing while playing
<code>*-*-*-*-
----o---
--------
o--o---o
</code>
well I assume you know how to read drum tabs but it's actually du-dum du-tah exercise.
Note that there is no hihat pedal involved and your mind should acknowledge that in slow tempos.
Long story short you need to reburn your muscle memory without the hihat pedal involved.
Answer: It could be a problem of your sitting position and your body balance. If you're sitting too low or unbalanced on the stool, you might get problems because you need one leg to stabilize yourself while playing with the other one.
Try practicing at very slow tempos first, as slow as you need to go to be able to play it. Think of quarters and eighth and try both ways (left foot quarters, right foot eighth and the other way). In this tempo, carefully analyze how your upper body reacts while the feet move. The more you have to work with your upper body to keep balaced, the more difficult it will be to play faster or more complicated rhythms with your feet.
Answer: Double kick pedals are not specific to 32nd notes! It also makes playing 8th, 16th and 32nd notes far easier to play... your best bet is to get one and practice using two feet. you are essentially only playing 8th notes with each foot then halving the effort it takes. You could also use the "Heel Toe" technique.
In regards to the comment, to perform Heel Toe, start with you heel raised off the pedal board and stomp with the ball of your foot.
After this immediately slide your foot forward and bounce with your heel off the pedal board again.
After this motion immediately bring the ball of your foot down again to complete the second stroke. It should feel like the base of your foot is sweeping up the pedal board. That will get you a double stroke.
Further explanations are in the link.


Using polymer paper-button with button_to in rails

Question: I am trying to use polymer 1.0 in rails 4 with the polymer-rails and polymer-elements-rails gems. How do I use the button_to under the  tags?
<paper-button raised>
<%= button_to "About", "pages/about", :method => :get %>
About</paper-button>

This actually creates two buttons. The button with button_to is functional.
Is some other element is required for this?
Answer: You can't do it this way because your Rails helper method is generating a standard HTML Button tag (probably with a wrapping Form element), and then it's being inserted.
In Polymer, you're expected to use the on-click attribute on the element to call a method in the containing element.
<paper-button on-click="buttonClicked> for example.
This makes using the standard Rails helper methods unusable, and you'll have to find another way to handle the click event, or indeed make your own custom Polymer element and a matching Rails helper.
Comment: Just tried to answer this in the iOS app and for some reason my HTML is missing. Sorry
Comment: Thanks for the explaination @stef. Please try to add HTML example later.
Comment: If polymer forces to use onclick attribute, then isn't it a loss of rails functionality. The simplicity of rails is no more
Comment: You can still use Rails helpers alongside Polymer elements, but Paper elements are sufficiently complex that you'd be better off looking at Iron ones and seeing if you get anywhere.


Detecting the interdependence of autocorrelated sequences

Question: It is easy enough to detect interdependence of two discrete-time white noise sequences - one just takes cross-covariance and compares it with variance. But what if both time series are "non-white", that is, there's long-range autocorrelation (like two Brownian random walks)? I assume one resorts to some kind of whitening, where one can read more about this?
Comment: "Long-range autocorrelation" does not necessarily imply non-stationarity. Is therefore your question about two stationary, or two non-stationary, autocorrelated processes?
Comment: Yes, you're quite correct, - I meant that in the first case, subsequent samples are uncorrelated.
Comment: Welcome to the site @tristes (+1). Just curious: Are there three of you? ;-)
Comment: No wheat around, so far as I can see :-)
Answer: When examining the possible cross-correlation between two white noises, we can separate and investigate distinctly whether they are "contemporaneously correlated" and/or whether they are "non-contemporaneously correlated". This is a useful distinction  -knowing whether a variable "leads" or "lags" another, contrasted to them moving contemporaneously is important, especially for forecasting.
Now if we have two auto-correlated, but still covariance-stationary processes, then, as I have recently answered here, any continuous transformation/combination of them will be also stationary, and so the sample moments(time-averages) will be strongly consistent estimators of the ensemble moments(expected values):
$$\frac 1T\sum_{t=1}^{T}(X_t-\mu_x)(Y_t-\mu_y) \rightarrow_{a.s} E(X_t-\mu_x) (Y_t-\mu_y) = {Cov} (X_t,Y_t)$$
In other words, we do not need to "whiten" the processes to test for cross-correlation between them.
The problem we have here is that we cannot distinguish between contemporaneous and non-contemporaneous cross-correlation, since the two variables are functions each of their own past, but also of a current shock.
To take the standard example, assume that both processes are zero-mean $AR(1)$. Then
since they are both stationary, they have an $MA(\infty)$ representation, so
$${Cov} (X_t,Y_t) = E\Big (\psi(L)\varepsilon_t\cdot \phi(L)u_t\Big)$$
where $\varepsilon_t,\;u_t$ are the white noise building blocks of $X_t$ and $Y_t$ and $\psi(L),\; \phi(L)$ are polynomials in the lag operator. So this covariance, apparently between the contemporaneous realizations of the two processess, will include the term (coefficient of the lag polynomials ommited) $E(\varepsilon_tu_t)$ but also products of all lags and leads like $E(\varepsilon_tu_{t-1})$, $E(\varepsilon_{t-5}u_{t-2})$ etc, and it can be non-zero because any one of them is not zero. And the same will happen if we try ${Cov} (X_t,Y_s),\; t>s$. For applied forecasting matters, we can of course compare the actual values of, say, $\hat {Cov} (X_t,Y_t)$ and $\hat {Cov} (X_t,Y_{t-1})$ and if it so happens that the second is visibly larger than the first we could say that "$Y$ leads $X$", and use this relation for our purposes - but the underlying confounding of contemporaneous and non-contemporaneous cross-correlation does not go away.
ADDENDUM: A pre-whitening algorithm in the time domain
(As given in Søren Bisgaard & Murat Kulahci (2011) book "TIME SERIES ANALYSIS AND FORECASTING BY EXAMPLE", chapter 8, p. 208)
The chapter is about "Transfer Function Models"
Step 1: Fit an ARIMA model to the input $X_t$
Step 2: Prewhiten the input series $X_t$ (i.e., compute the residuals for $X_t$)
Step 3: Prewhiten the output series $Y_t$ using the same model fitted to the input $X_t$
Step 4: Compute the cross correlation between the prewhitened $X_t$ 's and $Y_t$ 's
Note: you can also look up prewhitening using spectral analysis.
Comment: We don't need to whiten processes to calculate their cross-correlation, - OK, maybe, but so computed cross-correlation no longer serves as a useful indicator of the presence of common component in those time series.
Comment: Why? It identifies common components alright - and as such it is useful in forecasting, as I wrote. I am also adding an algorithm for prewhitening in my answer, since it is of interest to you.
Comment: Brownian process is AR(1) with $\varphi=1$, and is not wide-sense stationary. Cross-correlation criterium does not work for detecting interdependence of two browninan walks. But if you compute cross-correlation of the difference between two successive values, then you easily detect interdependence. That is the kind of "whitening" I have in mind.
Comment: ...which refers to non-stationary processes, for which actually, "whiteninig" may be simpler, in the case the processes are Integrated (and they need to be also co-integrated).
Comment: OK, the reference in your answer update is the kind of reference I am looking for. Thank you.


Is Magento 2 Official Documentation easy to understand for newbie?

Question: When i started learning magento 2, I went through the official documentation. But it was so complex and deep that i didn't grasp the concepts well, so i decided to look for easy to understand tutorials.
Do you find it complex too? (Please answer).
Do you think a newbie can understand it well? (Please answer).
I think if the documentation is written well,it will make developer life hell lot easy.
Do you think the documentation needed to change??
Comment: This question should not be asked here, Magento meta site is for discussing the workings and policies of Magento Stack Exchange . Magento Learning or Issues  should not be discussed here.
Answer:
Do you find it complex too?

No, I think the documentation is very clear, but you should not read it from the beginning to the end at one time, just use it as a handbook.

Do you think a newbie can understand it well?

Yes. In case you are interested in "How the plugins work?" you can find the answer in the documentation and you can understand it. Documentation is clear by the specific questions, but it hides a wide information which you should learn manually by debugging the Magento 2 code-base.

Do you think the documentation needed to change?

Yes, it should grow :)
I recommend you to search some thematic blog-posts on the web, which can make some aspects of the Magento 2 more clear (when you write a code all things looks hard, but when it completely works it looks so easy).
Comment: Thanks for the elaborated answer, really appreciated.
Comment: Yes, it should grow


Adding token in the views header and footer

Question: I have created webform and displaying the webform submission data using views. In above the submission data, I mean in the header, I want to display the data from the webform body field. I tried using adding the "Global: Unfiltered text" and placing the token of the body field. But when I view the page, it is not showing the body content instead of showing the token itself.
Please tell me how to use token of the webform body field in the header without using "Global: PHP"?
Comment: Did you check the box "Use tokens from the first row"?
Comment: Yes I did but it just showing me the token itself instead of replacement
Answer: The "Use replacement tokens from the first row" checkbox is essential. It works with either the "Global: Text Area" option or "Global: Unfiltered text." Here is a screenshot of both working:

Comment: I have given like that only but its not working.
Comment: Token replacement happening only there is some content. If there is no content, then token replacement is not working...Please suggest me if anything i need to add to get this replacement to work.


Retrieving JSON Objects using javascript

Question: i have a problem in retrieving json objects. how to retrieve the objects inside the "choices" key object? thanks for your help...
Comment: There are probably dozens of questions just like this one on SO *every day*.  Do some research and try something FCOL
Comment: thank you but i did this before and now what i want to do is to get to the next level where in i want to get the objects inside the "choices" dynamically, so that even there are lots of choices i wont bother to get the objects manually. thank you very much
Answer: Assuming you have a var assigment like var myobj = { ...  } where ... is your json object in the post, then you would access all the choices data points like this:
myobj.questions[0].choices.a
myobj.questions[0].choices.b
myobj.questions[1].choices.a
myobj.questions[1].choices.b

Are you asking something more specific about how to loop through all questions and choices?
Update:  After your comment, I think you might be looking for something more like this:
for (var qi=0; qi < myobj.questions.length; qi++) {
    var q = myobj.questions[qi];
    console.log(q.ques);
    for (var choiceKey in q.choices) {
        console.log("    " + choiceKey + " --> " + q.choices[choiceKey]);
    }
}

Simply replace the console.log() statements with whatever logic you need.  The output of running the above code on your example JSON is this:
how old are you?
    a --> 19
    b --> 20
question two?
    a --> answer1
    b --> answer2

Comment: thank you but i did this before and now what i want to do is to get to the next level where in i want to get the objects inside the "choices" dynamically, so that even there are lots of choices i wont bother to get the objects manually. thank you very much
Answer: Like so (to loop)
for (var i = 0; i < data.questions.length; i++) {
    console.log(data.questions[i].choices.a);
    console.log(data.questions[i].choices.b);
}

Comment: thank you but i did this before and now what i want to do is to get to the next level where in i want to get the objects inside the "choices" dynamically, so that even there are lots of choices i wont bother to get the objects manually. thank you very much
Answer: for (var i=0; i<questions.length; i++) {
    var choices = questions[i].choices;
    console.log(choices.a);
    console.log(choices.b);
}

Comment: thank you but i did this before and now what i want to do is to get to the next level where in i want to get the objects inside the "choices" dynamically, so that even there are lots of choices i wont bother to get the objects manually. thank you very much


Variable selection for multiple regression from large number of predictors

Question: I have 20 response variables $Y = (Y_1, \dots, Y_{20})$, and 1600 predictor variables $X = (X_1, \dots, Y_{1600})$. There are 128 observations. I wanted to know which pairs of $X$ can best predict each of $Y$.
So I generated all the combinations of $(Y_i, X_j, X_k)$ and did linear regressions for each combination to find R-squared. Based on R-squared, I extracted top 100 combinations to further analyses which pairs of $X$ are the best predictors for $Y$.
I haven't consider multicollinearity between any pair of predictors. Should I consider multicollinearity?
My goal is to find the best pairs of $X_j,$ $X_k$ that can predict a $Y_k$. Can you give some suggestions to further improve this procedure to make it statistically valid ?
Comment: 128 observations.
Comment: How many observations do you have?
Answer: Your problem is known as the $p>n$ problem, so you have more covariates than observations. In standard regression the inverse of the variance-covariance matrix is not positive definite and hence there is no solution to the normal equations (least squares estimation). One approach is to use some form of penalized regression, like Lasso or Ridge Regression. Their goal is to minimize the number of included predictors to your model.
The approach of pairwise elements of $X$ as predictors will probably always be inferior to models including more predictors, except in the special case that you know a priori that there are exactly two predictors that have to be found.
Comment: Yes, That is true, there can be more than two variables that can influence the model. But what does it means to have a high R-squred for a combination ? can we consider that combination is associated together in some way ?


Advanced Forum - how do I delete a forum?

Question: I'm using Advanced Forum - how can I remove the default forum created (General Discussion)?
Answer: Structure > Forums > You should see General Discussion listed, hit the Edit Forum link > Scroll down and hit the delete button
Comment: Well, that was easy enough. Is there a way to do it programmatically?
Comment: I don't know, just wondering, why would you want to do it programmatically?
Comment: @NoSssweat because some things MUST be done programmatically, if you have multiple environments like local, dev, staging, production etc. with multiple developers working on the project and use version control systems for deploying between those environments.
Answer: To delete a forum programmatically, you can use the following code (in an update script for example):
<code>// First load the terms with the name "General discussion"
$terms = taxonomy_get_term_by_name('General discussion', 'forums');
if (is_array($terms) && !empty($terms)) {
  // Since $terms is an array, we take the first (and ideally the only) item.
  $term = reset($terms);
  taxonomy_term_delete($term->tid);
}
</code>


How to Reverse Fragment Animations on BackStack?

Question: I thought the system would reverse animations on the backstack when the back button is pressed when using fragments using the following code:
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.setCustomAnimations(R.anim.slide_in, R.anim.hyperspace_out);
ft.replace(R.id.viewContainer, new class(), "layout").addToBackStack(null).commit();

Answer: According to the android documentation for custom animation:
Change:
ft.setCustomAnimations(R.anim.slide_in, R.anim.hyperspace_out);

To:
ft.setCustomAnimations(R.anim.slide_in, R.anim.hyperspace_out, R.anim.hyperspace_in, R.anim.slide_out );

and now the backstack animates - In reverse!!
Comment: btw, I know this isn't connected to your question and answer, but could you maybe link me to something that explains customAnimations a little bit? :P
Comment: AreusAstarte: see http://developer.android.com/reference/android/app/FragmentTransaction.html#setCustomAnimations(int, int, int, int)
Comment: Hi im actually using Content transition, is working fine, but when  i press back and go to previous fragment the background just disapear animateing the views but also overlying with the prevoious ones, any way to avoid this?
Answer: Use the Correct animation
I have used the following and its working like a charm
slide_in_left.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="@android:integer/config_mediumAnimTime" >
    <objectAnimator
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:duration="500"
        android:propertyName="x"
        android:valueFrom="1000"
        android:valueTo="0"
        android:valueType="floatType" />
</set>

slide_in_right.xml
 <?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="@android:integer/config_mediumAnimTime" >

    <objectAnimator
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:duration="500"
        android:propertyName="x"
        android:valueFrom="0"
        android:valueTo="1000"
        android:valueType="floatType" />

</set>

slide_out_left.xml
   <set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="@android:integer/config_mediumAnimTime" >

    <objectAnimator
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:duration="500"
        android:propertyName="x"
        android:valueFrom="0"
        android:valueTo="-1000"
        android:valueType="floatType" />

</set>

slide_out_right.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="@android:integer/config_mediumAnimTime" >

    <objectAnimator
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:duration="500"
        android:propertyName="x"
        android:valueFrom="-1000"
        android:valueTo="0"
        android:valueType="floatType" />

</set>

Then Use following while adding fragment
setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_left,
                                R.anim.slide_out_right, R.anim.slide_in_right)

and it will worked 100%
Comment: Note this will not work if you are using the support fragment manager or if your fragment extends the support version of Fragment
Comment: @DanielShatz You must use translations rather than objectAnimators. For instance, slide_in_left.xml would be: `` See this answer: http://stackoverflow.com/a/5151774/1738090
Comment: I am trying this out (on Marshmallow device - didnt try other versions). It doesnt work.          final FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();

        fragmentTransaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left,
                R.anim.enter_from_left, R.anim.exit_to_right); fragmentTransaction.replace(R.id.fl_right_container, detailFragment); fragmentTransaction.replace(R.id.fl_left_container, subcategoriesFragment, TestActivity.TAG_SUBCATEGORIES_FRAGMENT);
        fragmentTransaction.commit();
Comment: @w3bshark How to get such animations working using `FragmentManager` and `Fragment` from support library?
Answer: in my case
fragmentTransaction.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right,
                       R.anim.slide_in_right, R.anim.slide_out_left);

would create perfect animation.
slide_in_right
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="50%p" android:toXDelta="0"
               android:duration="@android:integer/config_mediumAnimTime"/>
    <alpha android:fromAlpha="0.0" android:toAlpha="1.0"
           android:duration="@android:integer/config_mediumAnimTime" />
</set>

slide_out_left
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="0" android:toXDelta="-50%p"
               android:duration="@android:integer/config_mediumAnimTime"/>
    <alpha android:fromAlpha="1.0" android:toAlpha="0.0"
           android:duration="@android:integer/config_mediumAnimTime" />
</set>

Comment: I thought of doing it my self, but I am too lazy. And I said somebody should have post this on StackOverflow and here it is! haha
Comment: Nobody had posted this before and I quite believed that time was my turn to post this answer, to help s.o who might be in the same shoes as me... lol @F.Mysir
Answer: .setCustomAnimations(R.animator.fragment_fade_in,
        R.animator.fragment_fade_out,
        R.animator.fragment_fade_p_in,
        R.animator.fragment_fade_p_out)

Replace the above with:
mFragmentManager.beginTransaction()
    .setCustomAnimations(R.animator.fragment_fade_in,
            R.animator.fragment_fade_out,
            R.animator.fragment_fade_p_in,
            R.animator.fragment_fade_p_out)
    .replace(R.id.main_container, FragmentPlayerInfo.getInstance(data))
    .addToBackStack(FragmentPlayerInfo.TAG)
    .commit();

Comment: @TarikW i'm bit late, but order is important in this, you need to call setCostomAnimations before replace, addToBackStack methods
Comment: I do not know why it work (: , but when added animation after `replace` and `addToBackstack`, is not worked
Comment: I would recommend you to add an explanation on how your recommendation helps.
Answer: This is as mentioned in Fragment Transaction class .
/**
     * Set specific animation resources to run for the fragments that are
     * entering and exiting in this transaction. The popEnter
     * and popExit animations will be played for enter/exit
     * operations specifically when popping the back stack.
     *
     * @param enter An animation or animator resource ID used for the enter animation on the
     *              view of the fragment being added or attached.
     * @param exit An animation or animator resource ID used for the exit animation on the
     *             view of the fragment being removed or detached.
     * @param popEnter An animation or animator resource ID used for the enter animation on the
     *                 view of the fragment being readded or reattached caused by
     *                 {@link FragmentManager#popBackStack()} or similar methods.
     * @param popExit An animation or animator resource ID used for the enter animation on the
     *                view of the fragment being removed or detached caused by
     *                {@link FragmentManager#popBackStack()} or similar methods.
     */
    @NonNull
    public abstract FragmentTransaction setCustomAnimations(@AnimatorRes @AnimRes int enter,
            @AnimatorRes @AnimRes int exit, @AnimatorRes @AnimRes int popEnter,
            @AnimatorRes @AnimRes int popExit);

so finally you can use method like this
 mFragmentManager.beginTransaction()
                        .replace(R.id.container, fragment)
                        .setCustomAnimations(R.anim.slide_left,//enter
                                             R.anim.slide_out_left,//exit
                                             R.anim.slide_right,//popEnter
                                             R.anim.slide_out_right)//popExit
                        .addToBackStack(fragment.toString())
                        .commit();

Answer: this work for me!! this code for fragment! if you want to use this code in activity, delete at the beginning getActivity()!!
getActivity().getSupportFragmentManager()
        .beginTransaction()
        .setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.fade_out,android.R.anim.slide_in_left, android.R.anim.fade_out)
        .replace(R.id.fragment_container, new YourFragment)
        .addToBackStack(null)
        .commit();

Good luck to you!!


lower bound of modified Besselfunction

Question: i'm looking for an lower bound for the modified Bessel function of the first kind $I_\nu(x)$ of a +ive real argument.
There should be one of the form
$$ce^{x^\alpha} \le I_\nu(x)$$.
Answer: This cannot be valid for $c,\alpha>0$ and all positive $x$, because for $x\rightarrow 0$ the LHS approaches $c$ while the RHS approaches $0$ for $\nu > 0!$ You have
$$\frac{(\tfrac{1}{2}x)^{\nu}}{\Gamma(\nu+1)} \le I_{\nu}(x)$$ for all $x,\nu > 0$ and asymptotic expansions for large $x:$
$$I_{\nu}(x) \sim \frac{e^x}{\sqrt{2\pi x}}\left(1 + O(x^{-1})\right) $$
Comment: true, but then there could be a bound like $$c(e^{x^\alpha}-1)\le I_\nu(x)$$

lower bound of modified Besselfunction


Is it okay to expose .yml or .install files to public?

Question: As per my knowledge the static files like css/js inside core/modules etc should be read by http server user. So normally I give read permission recursively to http user for directories like core, theme, modules etc. But these directory contains some .yml or .install files e.g drupal/web/core/modules/user/user.install which gets downloaded automatically when someone visits my site example.com/core/modules/user/user.install .
So is it okay to expose those files to public ? and what steps can be taken to avoid it ? I checked some popular sites they also expose those files. So bit confused.
Note: Drupal default .htaccess may take  care of these thing for Apache server only but what about other servers like nginx ? However I think Drupal is hard coded to be used with Apache server only.
Comment: @Hudri please don't vote down if you have no appropriate answer for the question. I am using NGINX and it doesn't obey .htaccess files.
Comment: Voting isn't based on whether or not you know the answer to a question. But either way, @Hudri's comment does happen to implicitly answer the question. Drupal core sees fit to use a whitelist for the /core folder, so you can assume you should do the same in whatever web server you're using
Comment: @Clive Thanks. But I am not totally agree with Hudri . Because the question clearly states that if any security issue is there if I expose those files ?
Comment: That's not official, it's an Nginx recipe. There isn't an officially supported nginx config. Perusio's one is a good starting point, but some might argue a bit too packed with features that most won't need
Comment: This is neither enabled by default, nore necessary. Drupal ships with a well-designed `~/web/.htaccess` that "whitelists" static assets in `/core`etc, don't fix things that aren't broken
Comment: Sorry, but not changing my downvote. Yes .htaccess does not work for nginx, but [the very first google hit on "drupal 8 nginx"](https://www.nginx.com/resources/wiki/start/topics/recipes/drupal/) answers your question.
Comment: Infact I checked some popular drupal sites if they have exposed those files or not and I see those are exposed. So this question came to my mind.
Comment: As per @Hudri I double checked if my nginx server blocks differs from https://www.nginx.com/resources/wiki/start/topics/recipes/drupal/ . But it doesn't help. yml files are still being exposed by using the official guide.
Comment: It definitely works with Nginx it just does not come with confit out of the box because Apache is far more common and popular in hosting environments.
Answer: No.
The web server (e.g. via apache's  directive) needs to be able to read (not write) the index.php file (and occasionally others such as update.php), and also static files such as .css/.js, pdfs and images.
The php interpreter is not limited by  directives and so most other files required by php do not have to be visible.
As Hudri said, leave the .htaccess files as they are, configure the server to notice them (AllowOverrides) and refer to an appropriate guide, such as:
https://www.drupal.org/docs/develop/local-server-setup/linux-development-environments/installing-php-mysql-and-apache-under
Comment: What's with the "upvote this", "don't downvote this" on this one?! Votes should only be applied when the beholder thinks a post warrants them, not just because a question/answer/comment happens to have been posted. Asking for/against them is considered noise and not something we need to have taking up valuable brain space in the comments :)
Comment: @SkyRar a specific example would be arbitrary and I suspect not particularly helpful to you. Suffice to say you'd be exposing some of the code that runs the website, and/or its configuration. Having that information is likely to help a potential attacker more than it would hinder them, therefore it's prudent not to allow that to happen.
Comment: Thanks. Can you please tell me what may be security issue if those files are exposed ? I see some popular sites also expose those files. So I am bit confused that upto what extent security risks are there ? I know it is a broad question. But you can give an example please.
Comment: SkyRar - Drupal 8, configured properly out of the box is pretty secure. Follow the guides until you know more about the topic.
Comment: When I visit "core/modules/user/user.install" on any of my sites I get a 403 from Apache.
Comment: @Kevin I have mentioned in question that using other than Apache server.


What happen if first rule of first iptable chain target is `RETURN`?

Question: The article Linux Firewall Tutorial: IPTables Tables, Chains, Rules Fundamentals define the RETURN target value as follow:

RETURN – Firewall will stop executing the next set of rules in the
  current chain for this packet. The control will be returned to the
  calling chain.

Question
I was discussing with a colleague on the effect of a such a target's value has the first rule of the first chain.
As there is no calling chain, what would happen to the packet? Would it be rejected or accepted?
Answer: You mean e.g.
iptables -F INPUT
iptables -I INPUT 1 -j RETURN

From man iptables:

If [...] a rule in a built-in chain with target RETURN is matched, the
  target specified by the chain policy determines the fate of the
  packet.

The chain policy is set with iptables -P, and can be found at the beginning of the output of iptables -L -n -v, eg:
Chain INPUT (policy DROP 32 packets, 6666 bytes)

which shows a policy of DROP on the INPUT chain.
Comment: Neither.  As it says above, the `RETURN` will do nothing at all, and the chain policy will take over.  To find or set the chain policy, see my edit above.
Comment: This is the first answer I found that actually explains RETURN in a simple yet accurate manner. +1
Comment: Why, thank you, aggregate!  It's nice to know one's efforts are appreciated, and better yet, useful.
Comment: What is the _target specified by the chain policy_ here?
Comment: Will the RETURN be equivalent to a `DROP` or a `ACCEPT`?


Can you prove this equality?

Question: In their book An Introduction to Optimization, on the chapter on gradient algorithms, to prepare for discussing convergence properties of the descent methods, authors Chong and Zak have following:

$f(x) = \frac{1}{2}x^TQx-b^Tx$, where $Q$ is symmetric and $Q>0$.
...
$V(x)=f(x)+\frac{1}{2}(x^*)^TQx^*=\frac{1}{2}(x-x^*)^T Q (x-x^*)$, where $x^*$ is the solution point obtained by solving $Qx=b$, that is, $x^*=Q^{-1}b$

I could not follow the equation $f(x)+\frac{1}{2}(x^*)^TQx^*=\frac{1}{2}(x-x^*)^T Q (x-x^*)$.  Can you prove it?
Comment: can you simplify $f(x)+\frac{1}{2}(x^*)^TQx^*$?
Comment: @LinAlg: What do you mean by simplifying?
Answer: \begin{align}
V(x)=&f(x)+\frac{1}{2}(x^*)^TQx^* \\
=&\frac12 x^TQx-b^Tx+ \frac{1}{2}(x^*)^TQx^* \\
=&\frac12 x^TQx-(Qx^*)^Tx+ \frac{1}{2}(x^*)^TQx^* \\
=&\frac12 x^TQx-(x^*)^TQx+ \frac{1}{2}(x^*)^TQx^* \quad(\because Q^T=Q)\\
=&\frac12 x^TQx-\frac12(x^*)^TQx-\frac12(x^*)^TQx+ \frac{1}{2}(x^*)^TQx^*\\
=&\frac12 x^TQx-\frac12x^TQx^*-\frac12(x^*)^TQx+ \frac{1}{2}(x^*)^TQx^* \quad(\because Q^T=Q)\\
=& \frac{1}{2}x^T Q (x-x^*) - \frac{1}{2}(x^*)^T Q (x-x^*) \\
=&\frac{1}{2}(x-x^*)^T Q (x-x^*)
\end{align}

Can you prove this equality?