Visualising many variables in one plot

Question: I'd like to show how the values of certain variables (~ 15) change over time, but I'd also like to show how the variables differ from each other in each year. So I created this plot:

But even when changing the colour scheme or adding different line/shape types this looks messy. Is there a better way to visualise this kind of data?
Test data with R code:
structure(list(Var = structure(c(1L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 6L,
6L, 6L, 6L, 6L, 6L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 8L, 8L, 8L, 8L,
8L, 8L, 8L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 11L, 11L, 11L, 11L, 11L,
11L, 11L, 12L, 12L, 12L, 12L, 12L, 12L, 13L, 14L, 14L, 14L, 14L,
14L, 14L, 14L, 16L, 16L, 16L, 16L, 16L, 16L, 17L, 17L, 17L, 17L,
17L, 17L, 17L, 18L, 18L, 18L, 18L, 18L, 18L, 18L), .Label = c("A",
"B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N",
"O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"), class = "factor"),
    Year = c(2015L, 1991L, 1993L, 1996L, 2000L, 2004L, 2011L,
    2015L, 1991L, 1993L, 1996L, 2000L, 2004L, 2011L, 2015L, 1991L,
    1993L, 1996L, 2000L, 2004L, 2011L, 2015L, 1993L, 1996L, 2000L,
    2004L, 2011L, 2015L, 1991L, 1993L, 1996L, 2000L, 2004L, 2011L,
    2015L, 1991L, 1993L, 1996L, 2000L, 2004L, 2011L, 2015L, 1991L,
    1993L, 1996L, 2000L, 2004L, 2011L, 2015L, 1991L, 1993L, 1996L,
    2000L, 2004L, 2011L, 2015L, 1993L, 1996L, 2000L, 2004L, 2011L,
    2015L, 2015L, 1991L, 1993L, 1996L, 2000L, 2004L, 2011L, 2015L,
    1991L, 1993L, 1996L, 2000L, 2011L, 2015L, 1991L, 1993L, 1996L,
    2000L, 2004L, 2011L, 2015L, 1991L, 1993L, 1996L, 2000L, 2004L,
    2011L, 2015L), Val = c(25.6, 22.93, 20.82, 24.1, 24.5, 29,
    25.55, 24.5, 24.52, 20.73, 25.8, 25.5, 29.5, 27.7, 25.1,
    25, 24.55, 26.75, 25, 30.5, 27.25, 25.1, 22.4, 27.07, 26,
    29, 27.2, 24.2, 23, 24.27, 27.68, 27, 30.5, 28.1, 24.9, 23.75,
    22.75, 27.25, 25, 29, 28.45, 24, 20.25, 17.07, 24.45, 25,
    28.5, 26.75, 24.9, 21.25, 20.65, 25.1, 24.5, 26.5, 25.35,
    23.5, 21.93, 26.5, 24.5, 29, 29.1, 26.4, 28.1, 23.75, 26.5,
    28.05, 27, 30.5, 25.65, 23.3, 23.25, 24.57, 26.07, 27.5,
    28.85, 27.7, 22, 23.43, 26.88, 27, 30.5, 29.25, 28.1, 23,
    23.8, 28.32, 27, 29.5, 29.15, 27.6)), row.names = c(1L, 4L,
5L, 6L, 7L, 8L, 9L, 10L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L,
21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 32L, 35L,
36L, 37L, 38L, 39L, 40L, 41L, 44L, 45L, 46L, 47L, 48L, 49L, 50L,
53L, 54L, 55L, 56L, 57L, 58L, 59L, 62L, 63L, 64L, 65L, 66L, 67L,
68L, 69L, 70L, 71L, 72L, 73L, 74L, 75L, 78L, 79L, 80L, 81L, 82L,
83L, 84L, 87L, 88L, 89L, 90L, 91L, 92L, 95L, 96L, 97L, 98L, 99L,
100L, 101L, 104L, 105L, 106L, 107L, 108L, 109L, 110L), na.action = structure(c(2L,
3L, 11L, 12L, 33L, 34L, 42L, 43L, 51L, 52L, 60L, 61L, 76L, 77L,
85L, 86L, 93L, 94L, 102L, 103L), .Names = c("2", "3", "11", "12",
"33", "34", "42", "43", "51", "52", "60", "61", "76", "77", "85",
"86", "93", "94", "102", "103"), class = "omit"), class = "data.frame", .Names = c("Var",
"Year", "Val"))

Comment: Can you post the data? It's easy enough to find roughly similar examples, but to keep the thread tied together, people having the same sandbox to play in would help. Also, what's the significance of the green zone?
Comment: See also suggestions in http://stats.stackexchange.com/questions/126480/color-and-line-thickness-recommendations-for-line-plots
Comment: @NickCox Sure, should have thought of that earlier! I left out the green zone as it's not essential (it only shows the range of values which is considered "sufficient")
Answer: Fortuitously or otherwise, your example is of optimal size (up to 7 values for each of 15
groups) first, to show that there is a problem graphically; and second, to allow other and
fairly simple solutions. The graph is of a kind often called spaghetti by people in
different fields, although it's not always clear whether that term is meant as affectionate
or abusive. (The term spaghetti was used by Gene Zelazny in 1985, but may well be much older
yet.) The graph does show the collective or family behaviour of all the groups, but it is
fairly hopeless at showing the detail to be explored.
One standard alternative is just to show the separate groups in separate panels, but that in
turn can make precise group-to-group comparisons difficult; each group is separated from its
context of the other groups.
So why not combine both ideas: a separate panel for each group, but also show the other
groups as backdrop? This hinges crucially on highlighting the group which is in focus and on
downplaying the others, which is easy enough in this example given some use of line colour,
thickness etc. In other examples, marker or point symbol choices might be natural instead.

In this case, details of possible practical or scientific importance or interest are
highlighted:

We only have one value for A and M.

We don't have all values for all given years in all other cases.

Some groups plot high, some low, and so forth.

I won't attempt an interpretation here: the data are anonymous, but that is the researcher's
concern in any case.
Depending on what is easy or possible in your software, there is scope for changing small
details here, such as whether axis labels and titles are repeated (there are simple
arguments both for and against).
The larger issue is how far this strategy will work more generally. The number of groups is
the major driver, more so than the number of points in each group. Roughly speaking, the
approach might work up to about 25 groups (a 5 x 5 display, say): with more groups, not only
do the graphs become smaller and more difficult to read, but even the researcher loses the
inclination to scan all the panels. If there were hundreds (thousands, ...) of groups, it
would usually be essential to select a small number of groups to show. Some mix of criteria
such as selecting some "typical" and some "extreme" panels would be needed; that should be
driven by project goals and some idea of what makes sense for each dataset. Another approach
that can be efficient is to emphasize a small number of series in each panel. So, if there
were 25 broad groups, each broad group could be shown with all others as backdrop.
Alternatively, there could be some averaging or other summarization. Using (e.g.) principal
or independent components might also be a good idea.
Although the example calls for line plots, the principle is naturally much general. Examples
could be multiplied, scatter plots, model diagnostic plots, etc.
Similar but not identical ideas
Cleveland (1985, pp.74, 203, 205, 268) shows graphs in which summary curves
for groups are repeated with data shown separately for each group.
(Note: these graphs do not appear in Cleveland 1994.)
Wallgren et al. (1996, pp.47, 69) use the same idea.
Cleveland, W.S. 1985. Elements of Graphing Data. Monterey, CA: Wadsworth.
Cleveland, W.S. 1994. Elements of Graphing Data. Summit, NJ: Hobart Press.
Wallgren, A., B. Wallgren, R. Persson, U. Jorner, and J.-A. Haaland.
1996. Graphing Statistics and Data: Creating Better Charts. Newbury
Park, CA: SAGE.
Zelazny (1985 and later editions) has a different twist:
Zelazny, G. 1985. Say It With Charts: The Executive's Guide to Successful Presentations.
Homewood, IL: Dow Jones-Irwin. See p.39 for a graph with four panels: series A compared in
turn with series B, C, D, E. See also p.111.
Same pages in 4th edition: Zelazny, G. 2001. Say It With Charts: The Executive's Guide to
Visual Communication. New York: McGraw-Hill. See p.39 for a graph with four panels: series
A compared in turn with series B, C, D, E. See also p.111.
Direct examples [others are most welcome]
Koenker, R. 2005. Quantile Regression. Cambridge: Cambridge University
Press. See pp.12-13.
Carr, D.B. and Pickle, L.W. 2010. Visualizing Data Patterns with Micromaps. Boca Raton,
FL: CRC Press. See p.85.
Cox, N.J. 2010. Graphing subsets. Stata Journal 10: 670-681.
Yau, N. 2013. Data Points: Visualization That Means Something.
Indianapolis, IN: John Wiley. See p.224.
Rougier, N.P., Droettboom, M. and Bourne, P.E. 2014.
Ten simple rules for better figures.
PLOS Computational Biology 10(9): e1003833.
doi:10.1371/journal.pcbi.1003833
link here
Schwabish, J.A. 2014. An economist's guide to visualizing data. Journal
of Economic Perspectives 28: 209-234.
Knaflic, C.N. 2015. Storytelling with Data: A Data Visualization Guide
for Business Professionals. Hoboken, NJ: Wiley. See p.233.
Unwin, A. 2015. Graphical Data Analysis with R. Boca Raton, FL: CRC
Press. See pp.121, 217.
Berinato, S. 2016.
Good Charts: The HBR Guide to Making Smarter, More Persuasive Data Visualizations.
Boston, MA: Harvard Business Review Press. See p.74.
Cairo, A. 2016.
The Truthful Art: Data, Charts, and Maps for Communication.
San Francisco, CA: New Riders. See p.211
Camões, J. 2016. Data at Work: Best Practices for Creating Effective Charts
and Information Graphics in Microsoft Excel. San Francisco, CA: New
Riders. See p.354.
Standage, T. 2016. Go Figure: The Economist Explains: Things You Didn't Know You Didn't Know. London: Profile Books. See p.177.
Wickham, H. 2016. ggplot2: Elegant Graphics for Data Analysis. Cham: Springer.
See p.157.
Schwabish, J. 2017.  Better Presentations: A Guide for Scholars, Researchers, and Wonks.  New York: Columbia University Press. See p.98.
Kriebel, A. and Murray, E. 2018. #MakeoverMonday: Improving How We Visualize and Analyze
Data, One Chart at a Time. Hoboken, NJ: John Wiley. See p.303.
Grant, R. 2019. Data Visualization: Charts, Maps, and Interactive Graphics.
Boca Raton, FL: CRC Press. See p.52.
Koponen, J. and Hildén, J. 2019.
The Data Visualization Handbook.
Espoo: Aalto ARTS Books. See p.101.
Tufte, E.R. 2020. Seeing with Fresh Eyes: Meaning, Space, Data, Truth.
Cheshire, CT: Graphics Press. See p.26 [original work by John Burn-Murdoch, but showing 0 on logarithmic scale (!) and alphabetical order by countries, which could be tuned]
Note: The graph was created in Stata. subsetplot must be installed first with ssc inst subsetplot. Data were copied and pasted from R and value labels were defined to show years as 90 95 00 05 10 15. The main command is
subsetplot connected Val Year, by(Var) c(L) lcolor(gs12) backdrop(line) xtitle("") combine(imargin(small)) subset(lcolor(blue) mcolor(blue))

Comment: Sorry, I have no idea about how to do anything in SAS. Surely anything Stata can do, R can do as well or better, or so its users keep telling me....
Comment: +1, wonderful, is there an R or SAS function that is able to do this type of chart? It's really great.
Comment: I really like this idea! Just wondering about the best way to plot this in R using ggplot2. I'll just wait a bit before I accept the answer, hope that's fine.
Comment: @NickCox Not a problem at all, I figured it out, it looks really good and is perfect for my purpose.
Comment: @NickCox, two more references are 1. [The Elements of Graphing Data by W.S. Cleveland](http://www.amazon.com/gp/product/0963488414?keywords=elements%20of%20graphing%20data&qid=1453300848&ref_=sr_1_1&sr=8-1).A new book,  2. [Storytelling with Data: A Data Visualization Guide for Business Professionals by Cole Nussbaumer Knaflic](http://www.amazon.com/Storytelling-Data-Visualization-Business-Professionals/dp/1119002257/ref=sr_1_1?s=books&ie=UTF8&qid=1453300881&sr=1-1&keywords=storytelling+with+data).This book (#2) has a case study chapter called "Strategies for avoiding the spaghetti graph".
Comment: @forecaster Thanks, but Knaflic is already in my references. I have been through both of Cleveland's books and I don't think there is any example there of precisely this idea. There are numerous examples of the "small multiples" strategy. The point is not to document cases in which subsets are plotted separately (long since a standard idea), but to document cases in which each subset is plotted separately, **with the other subsets as backdrop or substrate**. I'd be happy to amend the references if you can supply pages with examples of the kind.
Comment: Nevertheless Cleveland had a similar idea in 1985, now documented.
Answer: As a complement to Nick's answer, here's some R code for making a similar plot using simulated data:
library(ggplot2)

get_df <- function(label="group A", n_obs=10, drift=runif(1)) {
    df <- data.frame(time=seq(1, n_obs), label=label)
    df$y <- df$time * drift + cumsum(rnorm(n_obs))
    return(df)
}
df_list <- lapply(sprintf("group %s", toupper(letters[1:9])),
                  function(label) { get_df(label) })
df <- do.call(rbind, df_list)
df$label2 <- df$label

p <- (ggplot(df, aes(x=time, y=y, group=label2)) +
      geom_line(size=0.9, alpha=0.8,
                data=df[, c("time", "y", "label2")], color="grey") +
      geom_line(size=1.1, color="black") +
      ylab("") +
      theme_bw() +
      theme(panel.border=element_blank()) +
      theme(strip.background=element_blank()) +
      facet_wrap(~ label))
p
ggsave("example_facet.png", p, width=10, height=8)

Comment: There is also [gghighlight](https://github.com/yutannihilation/gghighlight) package available
Answer: For those wanting to use a ggplot2 approach in R consider the facetshade function in the package extracat.  This offers a general approach, not just for line plots.  Here is an example with scatterplots (from the foot of this page):
data(olives, package="extracat")
library(scales)
fs1 <- facetshade(data = olives,
                  aes(x = palmitic, y = palmitoleic), f =
                      . ~ Area)
fs1 + geom_point(colour = alpha("black", 0.05)) +
      geom_point(data = olives, colour = "red") +
      facet_wrap(f=~Area, nrow=3) +
          theme(legend.position="none")

EDIT: Using Adrian's simulated dataset from his earlier answer:
library(extracat)
facetshade(df, aes(x=time, y=y), f = .~label, bg.all = FALSE,
            keep.orig = TRUE) +
           geom_line(aes(x=time, y=y,
             group=orig.label),colour = alpha(1,0.3)) +
           geom_line(data=df, aes(colour=label), size = 1.2)
           + xlab("") + ylab("")

Another approach is to draw two separate layers, one for the background and one for the highlighted cases.  The trick is to draw the background layer using the dataset without the faceting variable.  For the olive oil dataset the code is:
data(olives, package="extracat")
ggplot(olives, aes(palmitic, palmitoleic)) +
  facet_wrap(~Area, nrow=3) +
  geom_point(data=olives %>% select(-Area),
        colour=alpha("black", 0.05)) +
  geom_point(data=olives, colour="red") +
  theme(legend.position="none")

Comment: @martin  Actually it is and that is also Adrian's solution.  Note that he uses two identical labelling variables so that one can be dropped in the background layer.  The coding idea is more obvious with the tidyverse notation below and, as so often, elegant formatting of graphics can mask the important parts of code.

`ggplot(df %>% select(-label), aes(x=time, y=y, group=label2)) +
  geom_line(alpha=0.8, color="grey") + labs(y=NULL) +
  geom_line(data=df, color="red") + facet_wrap(~ label)`
Comment: This seems like a nice general approach (+1), but the particular example is more relating to a different problem. A bunch of repeated scatter plots with differently highlighted regions is not gonna work for the question which is about time series.
Answer: Here is a solution inspired by Ch. 11.3, the section on "Texas Housing Data", in Hadley Wickham's Book on ggplot2. Here I fit a linear model to each time series , take the residuals (which are centered around mean 0), and draw a summary line in a different color.
library(ggplot2)
library(dplyr)
#works with dplyr version 0.4.3.9000 from Github (hadley/dplyr@4f2d7f8), or higher

df1 <- as.data.frame(list(Var = structure(c(1L, 2L, 2L, 2L, 2L, 2L, 2L,
                                 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 6L,
                                 6L, 6L, 6L, 6L, 6L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 8L, 8L, 8L, 8L,
                                 8L, 8L, 8L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 11L, 11L, 11L, 11L, 11L,
                                 11L, 11L, 12L, 12L, 12L, 12L, 12L, 12L, 13L, 14L, 14L, 14L, 14L,
                                 14L, 14L, 14L, 16L, 16L, 16L, 16L, 16L, 16L, 17L, 17L, 17L, 17L,
                                 17L, 17L, 17L, 18L, 18L, 18L, 18L, 18L, 18L, 18L), .Label = c("A",
                                                                                "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N",
                                                                                "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"), class = "factor"),
               Year = c(2015L, 1991L, 1993L, 1996L, 2000L, 2004L, 2011L,
                        2015L, 1991L, 1993L, 1996L, 2000L, 2004L, 2011L, 2015L, 1991L,
                        1993L, 1996L, 2000L, 2004L, 2011L, 2015L, 1993L, 1996L, 2000L,
                        2004L, 2011L, 2015L, 1991L, 1993L, 1996L, 2000L, 2004L, 2011L,
                        2015L, 1991L, 1993L, 1996L, 2000L, 2004L, 2011L, 2015L, 1991L,
                        1993L, 1996L, 2000L, 2004L, 2011L, 2015L, 1991L, 1993L, 1996L,
                        2000L, 2004L, 2011L, 2015L, 1993L, 1996L, 2000L, 2004L, 2011L,
                        2015L, 2015L, 1991L, 1993L, 1996L, 2000L, 2004L, 2011L, 2015L,
                        1991L, 1993L, 1996L, 2000L, 2011L, 2015L, 1991L, 1993L, 1996L,
                        2000L, 2004L, 2011L, 2015L, 1991L, 1993L, 1996L, 2000L, 2004L,
                        2011L, 2015L),
               Val = c(25.6, 22.93, 20.82, 24.1, 24.5, 29,
                       25.55, 24.5, 24.52, 20.73, 25.8, 25.5, 29.5, 27.7, 25.1,
                       25, 24.55, 26.75, 25, 30.5, 27.25, 25.1, 22.4, 27.07, 26,
                       29, 27.2, 24.2, 23, 24.27, 27.68, 27, 30.5, 28.1, 24.9, 23.75,
                       22.75, 27.25, 25, 29, 28.45, 24, 20.25, 17.07, 24.45, 25,
                       28.5, 26.75, 24.9, 21.25, 20.65, 25.1, 24.5, 26.5, 25.35,
                       23.5, 21.93, 26.5, 24.5, 29, 29.1, 26.4, 28.1, 23.75, 26.5,
                       28.05, 27, 30.5, 25.65, 23.3, 23.25, 24.57, 26.07, 27.5,
                       28.85, 27.7, 22, 23.43, 26.88, 27, 30.5, 29.25, 28.1, 23,
                       23.8, 28.32, 27, 29.5, 29.15, 27.6)),
               row.names = c(1L, 4L,
                           5L, 6L, 7L, 8L, 9L, 10L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L,
                           21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 32L, 35L,
                           36L, 37L, 38L, 39L, 40L, 41L, 44L, 45L, 46L, 47L, 48L, 49L, 50L,
                           53L, 54L, 55L, 56L, 57L, 58L, 59L, 62L, 63L, 64L, 65L, 66L, 67L,
                           68L, 69L, 70L, 71L, 72L, 73L, 74L, 75L, 78L, 79L, 80L, 81L, 82L,
                           83L, 84L, 87L, 88L, 89L, 90L, 91L, 92L, 95L, 96L, 97L, 98L, 99L,
                           100L, 101L, 104L, 105L, 106L, 107L, 108L, 109L, 110L),
               na.action = structure(c(2L,
                          3L, 11L, 12L, 33L, 34L, 42L, 43L, 51L, 52L, 60L, 61L, 76L, 77L,
                          85L, 86L, 93L, 94L, 102L, 103L),
                .Names = c("2", "3", "11", "12","33", "34", "42", "43", "51", "52", "60",
                           "61", "76", "77", "85", "86", "93", "94", "102", "103"), class = "omit"),
                class = "data.frame", .Names = c("Var","Year", "Val"))

df1 %>%
        group_by(Var) %>%
        do(mutate(.,resid = resid(lm(Val ~ Year, data=., na.action = na.exclude)))) %>%
        ggplot(aes(Year, resid)) +
        labs(y=paste0("Val "), x="Year") +
        geom_line(aes(group = Var), alpha = 1/5) +
        geom_line(stat = "summary", fun.y = "mean", colour = "red")

Comment: The main idea here seems to be that you could add a summary curve of some kind to help the eye and mind. Agreed, but in your answer you could spell out the trade-off on shifting to mean (or reference level) 0 rather than leaving the original units and values. Subject-matter experts and/or clients might well think in terms of 24 or 28 or whatever values are. Naturally the data here are just a vehicle for the discussion but the point is highly general.

Visualising many variables in one plot


Trying to upgrade phpMyAdmin in MAMP

Question: I'm trying to upgrade phpMyAdmin on my installation of MAMP. Everybody points to this page for instructions, but I get stuck at step 3 because I don't have a /Library/Application Support/appsolute folder from which to copy the config.inc.php file.
Answer: You may be looking in your /Username/Library/Application Support/appsolute folder. Ensure you are looking in your Mac's base directory, ie. in your Finder window click on Macintosh HD to locate your base Library.
The link you share with the instructions works perfectly for me.

Trying to upgrade phpMyAdmin in MAMP


no unique solution - linear equation

Question: I am asking myself:
How can I show that a linear equation $xm + yn = z$, for $x,y,z \in \mathbb{Z}$, cannot have a unique solution $(m,n) \in \mathbb{Z} \times \mathbb{Z}$?
Comment: One way to see this is by taking $\pmod{m}$.
Comment: Maybe you can use the notion that the equation can be "simplified" as the following... $(x+n)(y+m)=z+yx+nm$
Answer: There are many solutions if these is one solution. let $x_0, y_0$ be the unique solution of $mx_0+ny_0=z$. Then
there are infintely many solutuins  given as $$x=x_0+nj,~ y=y_0-jm,~ j \in Z.$$
Or no solution if $x_0, y_0$ do not exist.
Comment: But doesn't there either exist infinitely many solutions or no solution?
Comment: @Tithus248 Yes you are right, See my edit now.

no unique solution - linear equation


Translate following C# synchronization logic to Stored Procedure

Question: I have following Entity Framework Logic, and I want to translate to Stored Procedure, I have tried using exclusive lock in Stored Procedure but it results in lots of timeouts...
Think of Page as some sort of Hard disk which has 4 columns
Pages
   PageID
   SpaceAvailable
   SpaceOccupied
   TotalSpace

and I need to allocate my objects in the pages as the space is available, if object can not fit, it will get the next available page.
// a static lock to prevent race condition
static object Locker = new Object();

long AllocateNewPage(MyContext context, int requestedSize){
   long pageID = 0;

   // what is T-SQL lock equaivalent?
   lock(Locker){
      using(TransactionScope scope = new TransactionScope()){
         var page = context.Pages
                        .Where(x=>x.SpaceAvailable>requestedSize)
                        .OrderBy(x=>x.PageID)
                        .First();
         page.SpaceOccupied = page.SpaceOccupied + requestedSize;
         page.SpaceAvailable = page.SpaceAvailable - requestedSize;
         context.SaveChanges();
         scope.Commit();
         pageID = page.PageID;
      }
   }
   return pageID;
}

Following is Stored Procedure I have written but it results in lots of timeout as I have set 5 seconds for timeout, where else same thing runs correctly and quite fast in C#, the only problem is, I have to move this to Stored Procedure as database will now serve multiple clients.
CREATE procedure [GetPageID]
(
    @SpaceRequested int
)
AS
BEGIN

    DECLARE @DBID int
    DECLARE @lock int
    DECLARE @LockName varchar(20)

    SET @LockName = 'PageLock'

    BEGIN TRANSACTION

        -- acquire a lock
        EXEC @lock = sp_getapplock
                            @Resource = @LockName,
                            @LockMode = 'Exclusive',
                            @LockTimeout = 5000

        IF @lock<>0 BEGIN
            ROLLBACK TRANSACTION
            SET @DBID = -1
            SELECT @DBID
            return 0
        END
        SET @DBID = coalesce((SELECT TOP 1 PageID
                                  FROM Pages
                                  WHERE SpaceAvailable > @SpaceRequested
                                  ORDER BY PageID ASC ),0)
        UPDATE Pages SET
            SpaceAvailable = SpaceAvailable - @SpaceRequested,
            SpaceOccupied = SpaceOccupied + @SpaceRequested
        WHERE PageID = @DBID

        EXEC @lock = sp_releaseapplock @Resource = @LockName

    COMMIT TRANSACTION

    SELECT @DBID
END

I dont know much about Stored Procedures, but I need to allocate pages in locked mode so that no page will be over filled.
AM I OVER THINKING ?
Even if I am running in transaction do I still need locking?
Answer: Yes, you are overthinking. Let SQL Server manage the locks.
create procedure [GetPageID]
  @SpaceRequested int
as
begin
  set nocount on;

  begin tran;

  update top (1) pages
  set
    SpaceAvailable -= @SpaceRequested,
    SpaceOccupied += @SpaceRequested
  output
    inserted.PageID
  where
    SpaceAvailable > @SpaceRequested
  order by PageID asc;

  commit tran;

end;

The above can also be written in a two-step fashion you're showing in your question (in case you prefer it or your SQL Server version is old enough):
create procedure [GetPageID]
  @SpaceRequested int
as
begin
  set nocount on;

  begin tran;

  declare @page_id int;

  select top (1) @page_id = PageID
  from pages with (updlock, rowlock)
  where SpaceAvailable > @SpaceRequested
  order by PageID asc;

  update Pages
  set
    SpaceAvailable = SpaceAvailable - @SpaceRequested,
    SpaceOccupied = SpaceOccupied + @SpaceRequested
  where
    PageID = @page_id;

  commit tran;

  select @page_id;

end;

Comment: Thanks for your answer, but why have you modified my current logic, you think it was incorrect? I am not expert in SP so I am just asking out of curiosity, it looks like you are doing select and update both in one statement?
Comment: I did not modify the logic, I modified implementation. You are doing many unnecessary things, these were removed. The only select is from `@res` table, the update statement doesn't select anything, though it returns the page ID. Now that I wrote this, I realised I could simply output to the client without the temp table.
Comment: Does this also mean that I dont need stored procedure if I am encapsulating same logic within a TransactionScope?
Comment: @AkashKava No, it's better to have a stored procedure. LINQ or EF wouldn't put an update lock when fetching data for you to compare/amend later. There's a [check on update](http://stackoverflow.com/questions/330053/how-much-overhead-does-update-check-have-for-linq-updates), that is, it will check at the moment of the update that the row hasn't changed since the read operation, and only update if it has not, but this way you will have to rerun read/update cycle multiple times until it succeeds, whereas a stored proc will succeed first time.


Datepicker in popup

Question: how to add Jquery datepicker in dynamically loaded textbox.i.e., When i click a button , the popup containing textboxes from external page will shows in the present page. in that textbox i want to use datepicker.
i have used following ajax for Loading a external page

Following for Popup

following is for call thae popup page
//php coding
<a class="login-window" href="#inline"  title="Business Details" onclick="javascript:manageapp('<?php echo $patientlist[$i]['ap_id']; ?>','<?php echo $patientlist[$i]['apc'];?>')">

?>
//php coding
any body can help me to fix this problem
Answer: <!doctype html>

    <meta charset="utf-8" />
    <title>jQuery UI Datepicker - Default functionality</title>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />

   <link rel="stylesheet" href="/resources/demos/style.css" />

Date: <input type="text" id="datepicker" />

And for more deatils please follow the link http://jqueryui.com/datepicker/
Answer: I find the solutions , do it as follows, Add the datepicker function in Ajax return function ie in success

Answer: try this:
$(document).on('load', 'your_datepicker_class_or_id', function(){
   $(this).datepicker();
});

and assuming that you have these to referenced above your js stuff:

Comment: hi jai, thanks for your response , i tried this but it is not working, i insert a alert in that Jquery function ,its not working

Datepicker in popup


What's the differences between Object Storage and Key-Value Database?

Question: It seems a same thing from users aspect.
Answer: A key-value database does not care about the contents or format of the value. It just allows you to store stuff under keys, and get it back again, and iterate keys.
Object Storage or Document Databases can look at the contents of the data you store in them, and allow you to query or index on something other than the key.
The would be one distinction to draw. But googling around for Object Storage, it seems that this is a rather ill-defined buzzword.
Comment: Can apparently mean integrating into a programming language to persist "live" objects (so that would be something very much different): http://stackoverflow.com/questions/4881088/what-is-object-storage-wrt-cloud-computing
Answer: First of all, storage backend and database are two product forms. Storage backend can be different storage models such as kv / block / device, and database has more data models. So both just follow the same data model.


Lemma 4.3. Aluffi Algebra Chapter VIII.

Question: The following is from the book Aluffi's "Algebra. Chapter 0" :

How the (red-circled) equality holds? Esp. the l.h.s of the equality is $λ_{i_1 \dotsi_l}$ for one chosen ordered $i_1 < \dots <i_l$ but the r.h.s is a sum over all possible choices such that $i_1 < \dots <i_l$.
Answer: I don't like the fact that the same notation is used for the fixed index and the indexing of the summation, so let me rewrite the equality, and then explain it : the author claims that
$$\lambda_{i_1...i_l} = \overline{\varphi_I}(\sum_{1\leq j_1 < ... < j_l\leq r} \lambda_{j_1...j_l}e_{j_1}\wedge ...\wedge e_{j_l})$$
Now the reason for this is the following : $\overline{\varphi_I}$ is linear, so the rhs is $\displaystyle\sum_{1\leq j_1 < ... < j_l\leq r}\lambda_{j_1...j_l}  \overline{\varphi_I}(e_{j_1}\wedge ...\wedge e_{j_l})$
But now if $(j_1...j_l)\neq (i_1...i_l)$ and they're both strictly ordered $l$-tuples, then there can be no permutation $\sigma$ such that $\sigma(j_k)=i_k$ for all $k$. Indeed such a $\sigma$ would then be an increasing bijection $\{j_1,...,j_l\}\to \{j_1,...,j_l\}$, thus (by induction on $k$ if you don't know that result) the identity, in other words $(j_1,...,j_l) = (i_1,...,i_l)$.
Therefore, by definition, for $(j_1,...,j_l)\neq (i_1,...,i_l)$, $\overline{\varphi_I}(e_{j_1}\wedge ...\wedge e_{j_l}) = \varphi_I(e_{j_1},...,e_{j_l}) = 0$.
So the only remaining index in the sum is $(i_1<...<i_l)$, and its $\overline{\varphi_I}$ is $1$ by definition, so you do get the equality
Answer: It's by definition of $\varphi_I$:
If $(j_1,\dots,j_\ell)=J\ne I=(i_1,\dots, i_\ell)$ and both sequences are increasing, then there is no permutation $\sigma$ of $J$ exists such that $\sigma(J)=I$, hence
$$\bar\varphi_I(e_{j_1}\land\dots\land e_{j_\ell}) \ =\ 0$$

Lemma 4.3. Aluffi Algebra Chapter VIII.


change select box into text box in javascript

Question: <select style="height:25px;"class="textbox">
    <option selected>Select item</option>
    <option value="1" >Gold cad.</option>
    <option value="2">Gold rawa</option>
    <option value="3">Silver 9999</option>
    <option value="4">Silver chorsa</option>
</select>

I want to show select box element in textbox by replacing select box with text box on click
Comment: So if the user accidentally clicks the wrong item they're stuck with it? What about users who make their selection via the keyboard?
Comment: i am wondering why would you like to do that. I think what you are trying to say here is a autocomplete textbox just like you get when you search in facebook or google.
Answer: Refer this LIVE DEMO
Javascript:
var dropDown = document.getElementById("dropdown")
dropDown.onchange = function() {
    var dropDownValue = this.options[this.selectedIndex];
    dropDown.style.display = 'none';

    var textBox = document.getElementById("textbox");
    textBox.style.display = 'block';
    textBox.value = dropDownValue.text;
};

HTML:
<select style="height:25px;" id="dropdown">
    <option selected>Select item</option>
    <option value="1" >Gold cad.</option>
    <option value="2">Gold rawa</option>
    <option value="3">Silver 9999</option>
    <option value="4">Silver chorsa</option>
</select>
<input type="text" id="textbox" class="inactive" />

CSS:
.inactive {
    display: none;
}

Answer: Something like this helps you:
$('select.textbox').change(function(){
  $('<input>')
     .attr('name', $(this).attr('name'))
     .val($(this)
     .find('option:selected'))
     .insertAfter($(this).hide());
});

Answer: For example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>

<input id="text" type="text"  width="150px" height="20px" onfocus="toggle()" />

Gold cad

Gold rawa

Silver 9999

this is example ,even it so bad.


Como organizar o HTML?

Question: Observe a imagem;

Preciso colocar a letra "á" aqui no meio como mostra a seta, mas não sei como fazer isso, já tentei de várias formas. O código abaixo é o meu HTML:

                  Período:

                       <input autocomplete="off" id="idPeriodoInicio" class="form-control monthPicker listar_uj" name="periodoInicio" id="periodoInicio"  placeholder="Período Inicial">

                        <input autocomplete="off"  id="idPeriodoFim" class="form-control monthPicker listar_uj" name="periodoFim" id="periodoFim" placeholder="Período Final">

Comment: Ao invés de utilizar row's e col's, tente utilizar a classe form-inline nos componentes.
Comment: como posso fazer isso?
Comment: Vou responder como pergunta.
Answer:

   Período:
     <input autocomplete="off" id="idPeriodoInicio" class="form-control monthPicker listar_uj" name="periodoInicio" id="periodoInicio"  placeholder="Período Inicial">
     <input autocomplete="off"  id="idPeriodoFim" class="form-control monthPicker listar_uj" name="periodoFim" id="periodoFim" placeholder="Período Final">

Agora vá adequando a sua necessidade com os estilos do css.
Comment: vale a pena incluir o css por trás da classe "form-inline", você está assumindo que o OP está usando bootstrap. Além de poder confundir outras pessoas mais leigas.
Comment: Entendi que ele usou bootstrap pelas outras classes implementadas (form-control, control-label, form-group, row e col's), sendo assim dei a dica utilizando o bootstrap.

Como organizar o HTML?


android stable location provider

Question: I'm not sure which location providers I should use:
20 seconds is the maximum time I can manage without location.
The accuracy is less important for me, I can manage with accuracy of 500m.
Comment: so what is your question exactly
Comment: which location provider should I use? network? gps? both?
Comment: see my answer, and read about the locationmanager
Answer: Take a look at the location manager class. It will give you the information about location. And because you need an accuracy of 500m , I would suggest you to use gps, as networks(assuming you mean cellular) will have a lesser accuracy.

android stable location provider


Error: "emulator-5554 disconnected! Cancelling activity launch'?

Question:
Possible Duplicate:
HelloAndroid]emulator-5554 disconnected! Cancelling 'com.example.helloandroid.HelloAndroid activity launch'!

i removed the Eclipse and than install it again and than run my program, it will run. but after some time this error came again
 emulator-5554 disconnected! Cancelling  activity launch'!
i did not understand why it happens again and again....:(
i had open devices as well
Comment: Did you try closing Eclipse and all the emulators / disconnecting the devices you have connected, and then reopening eclipse? I have this issue often (Windows 7 x64)
Comment: i had restarted mine system but it came back........:( i am using windows xp
Comment: Yes do like as @hotVeryspicy said. And if possible then when ever you start adb just select the option of wipe user data. Sometimes it will be also helpfull to you
Answer: ya it is happening, for that just try to reset your adb  by going to "DDMS" environment open "Devices" tab and in that top right corner you have "view menu" click on it you will get an option called "reset adb" just do that, may helps
Comment: no effect dude
same error occurs........:(
Comment: dude i am totally stuck with this hectic error... i had uninstall it eclipse and than error remove. now it came back.....:(
Comment: then sorry friend no more idea on it
Comment: at first I got this error, then I opened DDMS and did reset ADB as per this answer, then I started getting some exceptions in eclipse DDMS logs, so I closed android emulator and relaunched app in debug mode it worked fine. Thanks a lot.
Comment: +1. Worth mentioning: I typically perform the 'reset' via the command line using `adb kill-server`, then `adb start-server`. (I've found it to be a more _guaranteed_ solution)
Answer: Your Device may not have enough memory to install this .apk file. Your should Uninstall unnecessary application from settings > Manage Application > Click Uninstall onClicking Useless application and also clear data of that app.
i had also follow the steps and change the environmental settings for java
it helped me alot and now the cancellation of emulator had almost minimal. and my program is running
do check this website
http://www.mybringback.com/bringers/java-programming/the-basics/441/setting-up-jre-on-you-computer-so-you-can-begin-java-programming/


Regex JS: Selecting all spaces not within quotes for multiple quotes in a row

Question: So I need to select all spaces not between quotes and delete them, I am using regex in Javascript notation.
For example:
" Test Test " ab c " Test" "Test " "Test" "T e s t"

becomes
" Test Test "abc" Test""Test ""Test""T e s t"

UPDATE:
I am looking for a solution that would work in the above test setting:
https://www.regextester.com/
The goal is to effectively tokenize this long sentence by these spaces not included within quotes, but I figured the answer to the above question was more concise and easier to read/answer.
All Spaces not within quotes should be highlighted in the above setting. If they are highlighted in the above setting they would be parsed as follows:
[" Test Test ",ab,c," Test","Test ","Test","T e s t"]

My attempted solution was:
(,|;\s|\s)+(?![^\[]*\])(?![^\(]*\))(?![^\{]*\})(?![^"].*")

Comment: @anubhava Added attempted solution and more clarity.
Answer: Replace "quotes or space" with "the same thing or nothing":

input = `" Test Test " ab c " Test" "Test " "Test" "T e s t"`

result = input.replace(/(".*?")|( )/g, (_, $1, $2) => $1 || '')

console.log(result)
Comment: Hi @gog. I just edited my question to hopefully make it a bit clearer as to what I am aiming for. I apologize for not including more detail to begin with.
Answer: You may use this regex for .split:
\s+(?=(?:(?:[^"]*"){2})*[^"]*$)

This regex will split on spaces if those are outside double quotes by using a lookahead to make sure there are even number of quotes after space.
RegEx Demo

const str = '" Test Test " ab c " Test" "Test " "Test" "T e s t"';

var arr = str.split(/\s+(?=(?:(?:[^"]*"){2})*[^"]*$)/);

console.log(arr);

/* OUTPUT
[
  "\" Test Test \"",
  "ab",
  "c",
  "\" Test\"",
  "\"Test \"",
  "\"Test\"",
  "\"T e s t\""
]
*/
Answer: We can try a regex replacement approach with a callback function:

var input = '" Test Test " ab c " Test" "Test " "Test" "T e s t"';
var output = input.replace(/".*?"|[^"]+/g, (x) => x.match(/^".*"$/) ? x : x.replace(/\s+/g, ""));
console.log(output);

The strategy here is to match, alternatively, either a term in double quotes, or any other content not involving a doubly quoted term.  The case of the former, we do no substitution.  In the case of the latter, we remove all whitespace characters.
Comment: Hi @Tim Biegeleisen. Just edited my question above to provide more detail as to my use case to hopefully make it a bit clearer as to what I am aiming for. I apologize for not including more detail to begin with.
Answer: The answer is the following:
(,|;\s|\s+(?=(?:[^"]*"[^"]*"[^"]*)*$))+(?![^\[]*\])(?![^\(]*\))(?![^\{]*\})

First part handles selection of , ;\s and spaces and  the second half makes sure they are not in quotes. Next part handles ignoring things not encased in quotes. And then the last part handles brackets etc.
Comment: As you note this regex is way more complex than what I posted above in my answer. Did that work for you?
Comment: Yes yours worked as well for that specific task, but as for "select all spaces not between quotes" so then i could delete etc I found that this monstrosity of a solution worked well as it works for enclosed (), {}, "", etc.
Comment: See even after my comment to add clarity your question only shows double quoted text and expected output with spaces removed from quoted text. If you don't post all requirements in question you will never get any working answer. If you edit your question and show few more examples then I can certainly much simpler regex than this one.
Comment: The extra stuff is just a plus. Thats why I upvoted your answer but accepted mine. The primary thing I was asking for was something to "select all spaces not between quotes and delete them." Thats why in the update after your comment asking for clarification I wrote "All Spaces not within quotes should be highlighted in the above setting..." referencing the regextester link included. Thats why I upvoted your answer but accepted this one for the question as it works as desired in the regextester and selects all the spaces which I can then delete later. I hope that clarifies.
Comment: No doubt, it is your choice to mark any answer as accepted. However at present this answer seems to be solving some problem which is not even part of the question. Just think about a future visitor to this post after few months/years, how will that person correlate posted question and this answer?
Comment: If you can edit your answer to include selection followed by replace I would prefer to accept yours. But if you could modify your answer that would be preferable as selection followed by replacement is the intended behavior. Could you do this?
Comment: In replacement do you want me to remove double quotes e.g. `'\" Test Test \"'` to this: `' Test Test '` ?


Where are fivestar data stored?

Question: On a D7 site using fivestar , I'd like to extract data from the module but there is not such table or node in the database and looking at the source code, I could not figure out in which table/fields the fivestart data are related/stored.
So appreciate your help about this.
Answer: Fivestar module defines a field.
Add a field to a content type. If fx you add a field named "test" of type fivestar reting to a content type then you can find the table with the name "field_data_field_test".
Comment: There is no table with this name: `field_data_field_fivestar` or any name containing `fivestar`.
Answer: The table does not have 'fivestar' in the name - try looking for the content type, or the word 'vote', or the axis name, in table names.  For example, I have a (test) content type named 'Review' with three voting axes.  The Fivestar fields are as follows:

field_data_field_review_votes_average
field_data_field_review_vote_axis_one
field_data_field_review_vote_axis_three
field_data_field_review_vote_axis_two

Where are fivestar data stored?


split line via regex in javascript?

Question: I have this structure of text :
1.6.1 Members................................................................ 12
1.6.2 Accessibility.......................................................... 13
1.6.3 Type parameters........................................................ 13
1.6.4 The T generic type aka <T>............................................. 13

I need to create JS objects :
{
  num:"1.6.1",
  txt:"Members"
},
{
  num:"1.6.2",
  txt:"Accessibility"
} ...

That's not a problem.
The problem is that I want to extract values via Regex split via positive lookahead :

Split via the first time you see that next character is a letter

What have i tried :
'1.6.1 Members........... 12'.split(/\s(?=(?:[\w\. ])+$)/i)

This is working fine :
["1.6.1", "Members...........", "12"] // I don't care about the 12.

But If I have 2 words or more :
'1.6.3 Type parameters................ 13'.split(/\s(?=(?:[\w\. ])+$)/i)

The  result is :
["1.6.3", "Type", "parameters................", "13"] //again I don't care about 13.
Of course I can join them , but I want the words to be together.
Question :
How can I enhance my regex NOT to split words ?
Desired result :
["1.6.3", "Type parameters"]
or
["1.6.3", "Type parameters........"] // I will remove extras later
or
["1.6.3", "Type parameters........13"]// I will remove extras later
NB
I know I can do split via " " or by other simpler solution but I'm seeking ( for pure knowledge) for an enhancement for my solution which uses positive lookahead split.
Full online example :
nb2 :
The text can contain capital letter in the middle also.
Comment: Hey Royi, did any of the solutions work for you, or do you need any tweaks? Please note that we gave you Match instead of Split solutions because [Match All and Split are two sides of the same coin](http://www.rexegg.com/regex-style.html#splitvsmatch), you get the same array but in this case matching is much easier.
Answer: You can use this regex:
/^(\d+(?:\.\d+)*) (\w+(?: \w+)*)/gm

And get your desired matches using matched group #1 and matched group #2.
Online Regex Demo
Update: For String#split you can use this regex:
/ +(?=[A-Z\d])/g

Regex Demo
Update 2: With the possibility of having capital letters also in chapter names following more complex regex is needed:
var re = /(\D +(?=[a-z]))| +(?=[a-z\d])/gmi;
var str = '1.6.3 Type Foo Bar........................................................ 13';
var m = str.split( re );
console.log(m[0], ',', m.slice(1, -1).join(''), ',', m.pop() );

//=> 1.6.3 , Type Foo Bar........................................................ , 13

Comment: Not was OP was asking ("which uses positive lookahead split"), and overly complicated too.
Comment: The updated answer is brilliant, but hopefully there no words in the middle of the title starts with uppercase letter.
Comment: Ah so you can have capital letters in between also!! will need to find new ways to split it. btw my earlier regex will work fine with this case as well. Give me some time to try something different for `String#split` (if at all possible)
Comment: Thank you for reply. But I mentioned something in my NB ( again - for pure knowledge reagrding positive lookahead splits).
Comment: But I am not using `String#split`. This regex is for `String#match`
Comment: I understand . but do I know now better splits via lookahead ? no. I'm looking for a solution **via that path**. ( im not the DV)
Comment: check updated answer for regex to be used in `String#split` using **positive lookahead**
Comment: @RoyiNamir I don't think splitting by lookahead alone will work. If the space before `B...` is valid, then the space between `A B...` is valid, you need look BACK and check if `A` makes the space valid.
Comment: @Diryboy You're right. it's not a working solution.his solution is based on capital letters . http://i.stack.imgur.com/YucYk.jpg
Comment: @anubhava please see this. your solution is based on capitals. http://i.stack.imgur.com/YucYk.jpg .working here ( but completly notsafe)
Comment: @Diryboy there is no such gaurantee for that !. I would mention it in my question. what about titles like `The T generic type`... ?
Comment: @anubhava can you elaborate your solution to work with ALL titles ? like `1.31 The T generic type......13`
Answer: EDIT: Since you added 1.6.1 The .net 4.5 framework.... to the requirements, we can tweak the answer to this:
^([\d.]+) ((?:[^.]|\.(?!\.))+)

And if you want to allow sequences of up to three dots in the title, as in 1.6.1 She said... Boo!..........., it's an easy tweak from there ({3} quantifier):
^([\d.]+) ((?:[^.]|\.(?!\.{3}))+)

Original:
^([\d.]+) ([^.]+)

In the regex demo, see the Groups in the right pane.
To retrieve Groups 1 and 2, something like:
var myregex = /^([\d.]+) ((?:[^.]|\.(?!\.))+)/mg;
var theMatchObject = myregex.exec(yourString);
while (theMatchObject != null) {
    // the numbers: theMatchObject[1]
    // the title: theMatchObject[1]
    theMatchObject = myregex.exec(yourString);
}

OUTPUT
Group 1     Group 2
1.6.1       Members
1.6.2       Accessibility
1.6.3       Type parameters
1.6.4       The T generic type aka <T>**
1.6.1       The .net 4.5 framework

Explanation

^ asserts that we are a the beginning of the line
The parentheses in ([\d.]+) capture digits and dots to Group 1
The parentheses in ((?:[^.]|\.(?!\.))+) capture to Group 2...
[^.] one char that is not a dot, | OR...
\.(?!\.) a dot that is not followed by a dot...
+ one or more times
Comment: It's indeed the most simple way.
Comment: That's an easy tweak... Done. :)
Comment: Also, added an additional tweak in case you'd like to allow sequences of up to three dots in the title, as in `1.6.1 She said... Boo!...........`, as well as full explanation.
Comment: Casimirs dolution is the shortest one , but since i said explicitly using positive look ahead - i chosed anubhava solution  ps +1
Comment: You choose whatever you like, but right now mine is the only one that works with `1.6.1 The .net 4.5 framework....` or `1.6.1 She said... Boo!...........`, right? :)
Answer: You can use this pattern too:
var myStr = "1.6.1 Members................................................................ 12\n1.6.2 Accessibility.......................................................... 13\n1.6.3 Type parameters........................................................ 13\n1.6.4 The T generic type aka <T>............................................. 13";

console.log(myStr.split(/ (.+?)\.{2,} ?\d+$\n?/m));

About a way with a lookahead :
I don't think it is possible. Because the only way to skip a character (here a space between two words), is to match it on the occasion of the previous occurence of a space (between the number and the first word). In other words, you use the fact that characters can not be matched more than one time.
But if, except the space where you want to split, all the pattern is enclosed in a lookahead, and since the substring matched by this subpattern in the lookahead isn't a part of the match result (in other words, it's only a check and the corresponding characters are not eaten by the regex engine), you can't skip the next spaces, and the regex engine will continue his road until the next space character.

split line via regex in javascript?


form of symmetric matrix of rank one

Question: The question is:
Let $C$ be a symmetric matrix of rank one. Prove that $C$ must have the form $C=aww^T$, where $a$ is a scalar and $w$ is a vector of norm one.
I think we can easily prove that if $C$ has the form $C=aww^T$, then $C$ is symmetric and of rank one. Why we need $w$ is of norm one?
Comment: If a matrix is rank-one, all its columns are  multiple of each other. This implies the matrix has the form $C_{ij}=a_ib_j$. Since $C$ is assumed symmetric, we can also choose $a_i=b_i$.
Answer: $C$ is a symmetric matrix and thus has eigen decomposition $C=\sum_{i=1}^{N}\lambda_iu_iu_i^H$. If it is rank one, all eigenvalues except one will be zero, thus $C=\lambda uu^H$ where $\lambda$ is the non-zero eigenvalue and $u$ is the corresponding unit norm eigen vector.
Comment: Hi @dineshdileep, in this formula, $C=\sum_{i=1}^{N}\lambda_iu_iu_i^H$, suppose $C$ is symmetric positive definite, so, can N be less than the rank of $C$ ?. Could we have an approximation of the form $C=\sum_{i=1}^{r}\lambda_iu_iu_i^T$, where $r << N$?
Comment: $N$ is the dimension of matrix $C$ and $C$ will have $N$ eigenvalues. Now $r$ of them can be non-zero and others being zero will allow what you want. You might be interested in principal component analysis and low rank approximation literature. For instance, there are theorems on the closest $k-$ rank approximation. For instance, the closest rank-one approximation to $C$ will be the rank one matrix $\lambda_1 u_1 u_1^H$ corresponding to the largest eigenvalue (assuming positive definite $C$) and so on and so forth.
Comment: Thank you @dineshdileep
Comment: I have another related question. In the case of low rank approximation, can we use von Neumann divergence to measure the goodness of the fit between the two parts ?
Answer: dineshdileep has already provided what is perhaps the natural solution to this problem. Let me present another.
Any matrix has what is called a rank factorization. In the case of a rank $1$ matrix, every row in the matrix is a multiple of some specific row. Let $\mathbf{y}$ be that row and let $\mathbf{x}$ be the vector of multiples associated with $\mathbf{y}$. Then $A$ naturally factors as
$$A=\mathbf{x}\mathbf{y}^\mathrm{T}$$
We may factor out the magnitudes to get
$$A = \|\mathbf{x}\|\|\mathbf{y}\|\,\mathbf{\hat{x}}\mathbf{\hat{y}}^\mathrm{T}$$
So far this decomposition holds for any matrix, symmetric or not. Our goal now is to prove that $\mathbf{x} = \pm\mathbf{y}$ in the case of symmetry.
Suppose then that $A$ is symmetric with decomposition $A = c\mathbf{x}\mathbf{y}^\mathrm{T}$ where $\mathbf{x}$ and $\mathbf{y}$ are unit vectors. By symmetry, we get
$$\mathbf{x}\mathbf{y}^\mathrm{T} = \mathbf{y}\mathbf{x}^\mathrm{T}$$
Multiplying on the left by $\mathbf{y}^\mathrm{T}$ and on the right by $\mathbf{x}$, we get
$$1=\|\mathbf{x}\|^2\|\mathbf{y}\|^2 = (\mathbf{x}^\mathrm{T}\mathbf{x})(\mathbf{y}^\mathrm{T}\mathbf{y}) = \mathbf{x}^\mathrm{T}\mathbf{y}\mathbf{x}^\mathrm{T}\mathbf{y} = (\mathbf{x}\cdot\mathbf{y})^2$$
which of course implies
$$|\mathbf{x}\cdot \mathbf{y}| = 1 = \|\mathbf{x}\|\|\mathbf{y}\|$$
This is the equality case of Cauchy-Schwarz, which holds if and only if $\mathbf{x}$ and $\mathbf{y}$ are linearly dependent. The two are both unit vectors so it follows that $\mathbf{x} = \pm\mathbf{y}$. Therefore we have
$$A = \pm c \mathbf{x}\mathbf{x}^\mathrm{T}$$
as required.
Comment: were you out of MSE for a while? was missing your insightful answers for some time.
Comment: @dineshdileep Well, I haven't been as active as I was before due to lack of time, but I've always been around. Thanks for asking!
Comment: In $A = \|\mathbf{x}\|\|\mathbf{y}\|\,\mathbf{\hat{x}}\mathbf{\hat{y}}^\mathrm{T}$, do $\mathbf{\hat{x}}$, $\mathbf{\hat{y}}$ represent unit vectors?
Comment: @Ian Yes, the hats represent unit vectors.

form of symmetric matrix of rank one


datepicker not working jquery

Question: im trying to use jquery from online to generate my datepicker. in my markup it is:
<asp:TextBox ID="PStart" runat="server"></asp:TextBox>

followed by

and in my header of my site master i have included:
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />

    <link rel="stylesheet" href="/resources/demos/style.css" />

one point to note is that this date picker is nested within an update panel which is only suposed to update after completeing the form and the submit/save button is clicked. i have set shildren as triggers to false and update mode to conditional but its not being displayed, far less for making a choice.
Comment: It is working fine for me [DEMO](http://jsfiddle.net/7JJNu/)
Comment: @abc123 not a valid demo since he is using asp net.
Comment: @Dom it proves that the issue isn't with the javascript, jquery, jquery-ui....the issue here is likely that his ID isn't `PStart` when the page is rendered...he needs to inspect element using a broswer...it is likely all mangled from asp.net...there are 3 solutions to this problem but i'd need him to validate it.
Comment: @New2This in your `Site.Master`, do you have a placeholder in the header? If so, is it before or after the header code you provided?
Comment: @Dom it is inside the header
Answer: Without seeing more of your code, it is impossible to say for sure. However, assuming there are no errors, the problem probably lies with <asp:ContentPlaceHolder> & <asp:Content> being called.
When using placeholders, asp controls change their IDs to the following format: {ContentPlaceHolderID}_ElementID.
I recommend either :

changing <asp:TextBox ID="PStart" runat="server"></asp:TextBox> to <input id="PStart" type="text"/>
inspect the page and find the actual id for that element (most likely "#{ContentPlaceHolderID}_PStart").

Hope this helps and let me know if you have any questions!

Site.Master:
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="WebApplication1.SiteMaster" %>
<!DOCTYPE html>

    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />

    <asp:ContentPlaceHolder runat="server" ID="HeadContent" />

    <form runat="server">

            <asp:ContentPlaceHolder runat="server" ID="MainContent" />

    </form>

Default.aspx:
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<asp:Content runat="server" ContentPlaceHolderID="HeadContent">

</asp:Content>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
    <asp:TextBox ID="PStart" runat="server"></asp:TextBox>
    <input type="text" id="PStart"/>
</asp:Content>

RESULT:

datepicker not working jquery


Unsubscribe Newsletter

Question: I was implemented "simplenews_register" module in my drupal project. so, Whenever user want to register in this site He has to enter his user name,email address,password and at the same time he want to subscribe any existing newsletter  then he check the related newsletter  check box. Then, automatically user will receive one mail regarding to subscribe link . So, he want to subscribe then he will click that link .
Here my requirement is if user has been subscribed any newsletter then automatically he has to receive "Unsubscribe" link . So, for this requirement what I have to do please guide me.
Comment: Hello Narendra. What is your question, exactly?
Answer: Unsubscribe links are automatically included when emails are sent via simplenews.
By the way, if you're using simplenews-2.x, you don't need the simplenews_register module; that functionality is included.

Unsubscribe Newsletter


Como abrir um URL direto da notificação

Question: Quero ciar um aplicativo para abrir URLs que se redirecionam para a Play Store e quero que apenas carregue o URL direto na notificação sem abir nenhum layout, e que apareça no filtro de intenção do android, Ex: (Concluir esta ação utilizando: Chrome, Navegador, Redirect Browser).Mas não sei como fazê-lo. Comecei criar o codigo:
public class MainActivity  extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        public void alerta (View v) {

        Notification.Builder notification = new Notification.Builder(this);
        notification.setContentTitle("Carregando página da Web...");
        notification.setContentText("A Play Store se abrira ao concluir");
        notification.setSmallIcon((R.drawable.ic_launcherrb));
        notification.setSound(Uri.parse("/system/media/audio/notifications/Argon.ogg"));

        notification.build();

        NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        int NOTIFICATION_ID = 0;
        nm.notify(NOTIFICATION_ID, notification.build());

}}

Alguém pode me ajudar??
Answer: Deve criar um PendingIntent da seguinte forma:
Intent intent= new Intent(Intent.ACTION_VIEW,Uri.parse(A_Sua_URL));
PendingIntent pIntent = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);

e adicioná-lo à notificação assim:
notification.setContentIntent(pIntent);

Como abrir um URL direto da notificação


Sklearn Combine Multiple Feature Sets in Pipeline

Question: I have two set of data that I want to transform using the count vectorizer. The first is for product_title and the second is for product_description. I am attempting to auto-classify the products into around 5 different categories and around 50 different sub-categories. I expect the text in the product_title to be more relevant so I would want the ability to weight it differently then the text in the product_descriptions. I am trying to create a script to combine them. So far this is what I have:
from __future__ import print_function

from pprint import pprint
from time import time
import logging

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.linear_model import SGDClassifier
from sklearn.grid_search import GridSearchCV
from sklearn.pipeline import Pipeline

print(__doc__)

# Display progress logs on stdout
logging.basicConfig(level=logging.INFO,format='%(asctime)s %(levelname)s %(message)s')

data = {'data':[],'target1':[],'target2':[]}
tempdata = {'data1':[],'data2':[]}
with open('coors.csv', mode='r') as infile:
    reader = csv.reader(infile)
    for row in reader:
        data['data'].append(row[0])
        tempdata['data1'].append(row[-2])
        tempdata['data2'].append(row[-1])

###############################################################################
# define a pipeline combining a text feature extractor with a simple
# classifier
pipeline = Pipeline([
    ('vect', CountVectorizer()),
    ('tfidf', TfidfTransformer()),
    ('clf', SGDClassifier()),
])

# uncommenting more parameters will give better exploring power but will
# increase processing time in a combinatorial way
parameters = {
    'vect__max_df': (0.5, 0.75, 1.0),
    #'vect__max_features': (None, 5000, 10000, 50000),
    'vect__ngram_range': ((1, 1), (1, 2)),  # unigrams or bigrams
    #'tfidf__use_idf': (True, False),
    #'tfidf__norm': ('l1', 'l2'),
    'clf__alpha': (0.00001, 0.000001),
    'clf__penalty': ('l2', 'elasticnet'),
    #'clf__n_iter': (10, 50, 80),
}

if __name__ == "__main__":
    # multiprocessing requires the fork to happen in a __main__ protected
    # block

    # find the best parameters for both the feature extraction and the
    # classifier
    grid_search = GridSearchCV(pipeline, parameters, n_jobs=-1, verbose=1)

    print("Performing grid search...")
    print("pipeline:", [name for name, _ in pipeline.steps])
    print("parameters:")
    pprint(parameters)
    t0 = time()
    grid_search.fit(data.data, data.target)
    print("done in %0.3fs" % (time() - t0))
    print()

    print("Best score: %0.3f" % grid_search.best_score_)
    print("Best parameters set:")
    best_parameters = grid_search.best_estimator_.get_params()
    for param_name in sorted(parameters.keys()):
        print("\t%s: %r" % (param_name, best_parameters[param_name]))

The problem I am having is with:
pipeline = Pipeline([
    ('vect', CountVectorizer()),
    ('tfidf', TfidfTransformer()),
    ('clf', SGDClassifier()),
])

I would need to somehow run something like:
combined_features = FeatureUnion([('title', data['data1']), ('description', data['data2']))

And I would need to run combined_features so that a CountVectorizer is applied to each data['data1'] and data['data2'] and then the features are combined and run through the pipeline. I would prefer to do this so that I can just feed to feature sets and the targets to the pipeline and it would do the rest. The result would allow duplicates. For example theoretically there could be features like computer_title and computer_description. Any advice on how to integrate this would be helpful.
Answer: The Feature Union with Heterogeneous Data Sources example from the scikit-learn docs also has a simple ItemSelector Transformer that basically picks one feature from a dict (or other structure) to work with, which could be combined with a FeatureUnion.
class ItemSelector(BaseEstimator, TransformerMixin):
    """For data grouped by feature, select subset of data at a provided key.

    The data is expected to be stored in a 2D data structure, where the first
    index is over features and the second is over samples.  i.e.

    >> len(data[key]) == n_samples

    Please note that this is the opposite convention to sklearn feature
    matrixes (where the first index corresponds to sample).

    ItemSelector only requires that the collection implement getitem
    (data[key]).  Examples include: a dict of lists, 2D numpy array, Pandas
    DataFrame, numpy record array, etc.

    >> data = {'a': [1, 5, 2, 5, 2, 8],
               'b': [9, 4, 1, 4, 1, 3]}
    >> ds = ItemSelector(key='a')
    >> data['a'] == ds.transform(data)

    ItemSelector is not designed to handle data grouped by sample.  (e.g. a
    list of dicts).  If your data is structured this way, consider a
    transformer along the lines of `sklearn.feature_extraction.DictVectorizer`.

    Parameters
    ----------
    key : hashable, required
        The key corresponding to the desired value in a mappable.
    """
    def __init__(self, key):
        self.key = key

    def fit(self, x, y=None):
        return self

    def transform(self, data_dict):
        return data_dict[self.key]

Comment: Why do we need to have this class? Why is only FeatureUnion not enough to append features?
Answer: If you're willing to use Pandas, sklearn-pandas looks like it does what you want.
But it would be nice to have a simple built-in method for what seems like a fairly common need.
Answer: You'd need to run your pipeline once for each featuresets and then combine the results in some sort of a classifier ensemble if you want to assign different weights to them. There is VotingClassifier you may want to use.


Drupal 8: "Page cache maximum age" is not working for anonymous users

Question: I have set a page cache maximum age for anonymous users in Drupal 8, but it seems not to have any effects. Accesing the pages as an anonymous user, changes are visible immediately, and I can't see any headers about max-age on the source code.
I have installed some cache modules as Internal Dynamic Page Cache,     Internal Page Cache and Supercache, but I don't think these should interfere with the cache on the client side.
Any suggestions?
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/74545/discussion-on-question-by-jmzea-drupal-8-page-cache-maximum-age-is-not-workin).
Comment: admin->development->performance->enable cache
Answer: There was discussion in the chat, but there are still some things that can be answered.
The maximum age setting actually has not much to do with the built-in caching mechanisms of Drupal, as confusing as that is. It only controls the Cache-Control max-age header that is sent if the page is considered cacheable.
If you don't see a X-Drupal-Cache: HIT/MISS header in the response then that means your page is not cacheable. There are a number of things that can cause that, check if you have a session cookie (if yes, you need to figure out what's in there and who sets it), check that no module that you are using disables the page cache. For example captcha.module does that if you display a captcha as that can't be cached (not something like the built-in image captcha at least).
If you see that header then it is working. The Page cache modules actually don't care about that setting, they cache the page forever. However, any relevant change on the page automatically invalidates that page and fresh content is served. See https://www.drupal.org/docs/8/api/cache-api/cache-tags for more information on how that works.


Is there a rule that protects the goalkeeper in the 6yard-box?

Question: After yesterday's red card for Nani in Manchester United against Real Madrid (March 5th 2013) I decided to read the entire Rulebook Laws of the Game by FIFA (IFAB), including the guidelines for referees concerning the interpretation of the rules. Sadly enough, this was my first time that I read the rules, although playing Football for nearly 20 years now.
I got the answer to my initial question whether the sending off was justified, but the rulebook raised a lot of different questions. The problem is that I found no clues to some common understandings of the game, for example that it is forbidden to clamp the ball between the legs in order to make it unreachable for the opponent.
The main issue, however, is that I could not find anything regarding the Goalkeeper receiving special treatment in the 6yard box (other than being dressed differently and being allowed to use the hands on the ball), as it is often pointed out and ruled as foul play.
Can anyone help me finding the rules for that, or clarifying these issues? Are there other official rules besides FIFA's Laws of the Game?
Thanks in advace!
Comment: Probably the question title needs to be modified. I think he has a valid question.
Comment: @ACB The validity of this question is not of concern. It's, as you state, the title and the wording, "Can anyone help me finding the rules for that." I understand a [rule clarification](http://meta.sports.stackexchange.com/a/332/527) is what's being asked, but it didn't come off as clear to me...and I am suggesting clarity to remove the potential of the question not being clear.
Comment: The 6 yard box is only there for restarts purposes. the 6 yard box plays no part in the general open play of the game or should not be considered special in any decision making by the ref, although it may seem that way
Comment: +1 I couldn't find it anywhere in the laws or in the interpretation, but I found it in an old law book... So the rule was there!
Comment: Do you happen to have the title of that book?
Comment: Welcome to Sports SE! At its current form, it feels like a [source request](http://sports.stackexchange.com/faq)...but I do feel that a legit question is here. What exactly happened during Man U against Real Madrid that you are seeking (non FIFA) rules for?
Comment: Hello! No I am not really seeking a source request, I am wondering about the rumours about the goalkeeper receiving special treatment in the 6yard box, as I always thought this rule exists, but does not in the official rules.
Comment: @fischi I suggest an edit as it wasn't clear to me what you were looking for (clamping the ball between the legs or goalkeeper receiving special treatment, for example). The wording, "Can anyone help me finding the rules for that" raised concern that you may have been requesting a source...but it's a legit question nonetheless.
Comment: @edmastermind29 okay, did that :) hope it is clear this way!
Answer: They are no more rules, only the FIFA ones.
I was searching, but only find links in spanish about it. But all is way back to 2006, when there was a big change in the laws of the game and in the interpretation.
Before that, you couldn't touch the goalie inside the goal box. Now, you can, if you don't commit any other type of foul in the same play, and you can't do it with excesive force.
The problem with clamping the ball, if that you are impeding your adversary from playing it, since any movement he make would be a dangerous move to yourself.
All I could find, was old newspaper news, in which some referees tell about it, but couldn't find a better source.
this,
this  and
this
All in spanish, sorry!
Answer: Regulations of the UEFA Champions League 2012-15 Cycle states that all match will be player according to International Football Association Board (IFAB) Laws of the Game:

15.01 Matches are played in conformity with the Laws of the Game promulgated by the International Football Association Board (IFAB).

International Football Association Board (IFAB) is the body that determines the Laws of the Game of association football, FIFA Laws of the Game are determined and updated by the IFAB and it was last modified at the 126th Annual General Meeting of the International Football Association Board (IFAB) in England (Surrey) on 3 March 2012. These came into force on 1 June 2012.
On FIFA Laws of the Game LAW 5 - The Referee under Injured players sections you can see full procedure when dealing with injured players, the main rules that relevant to your question are:
The referee must adhere to the following procedure when dealing with injured
players:
• play is allowed to continue until the ball is out of play if a player is, in the
opinion of the referee, only slightly injured
• play is stopped if, in the opinion of the referee, a player is seriously injured
• after questioning the injured player, the referee may authorise one, or at
most two doctors, to enter the field of play to assess the injury and arrange
the player's safe and swift removal from the field of play
• a player is not allowed to receive treatment on the field of play
• any player bleeding from a wound must leave the field of play. He may not
return until the referee is satisfied that the bleeding has stopped.
• as soon as the referee has authorized the doctors to enter the field of play,
the player must leave the field of play, either on a stretcher or on foot. If a
player does not comply, he must be cautioned for unsporting behavior
• an injured player may only return to the field of play after the match has
restarted

But all of this are irrelevant to goalkeeper since there is and exception when the injured player is the goalkeeper:

Exceptions to this ruling are to be made only when:
  • a goalkeeper is injured

And for Offences committed against goalkeepers you can read the following rules:

LAW 12 – FOULS AND MISCONDUCT
  Offences committed against goalkeepers
  • It is an offence for a player to prevent a goalkeeper from releasing
  the ball  from his hands
  • A player must be penalised for playing in a dangerous manner if he kicks or attempts to kick the ball when the
  goalkeeper is in the process of releasing  it
  • It is an offence to restrict the movement of the goalkeeper by unfairly impeding him,
  e.g. at the taking of a corner kick
Comment: Thank you very much! So in essence, just like any other Player, the Goalkeeper must not be fouled, but there is no special treatment involved, is it?


What's the point in answering an already answered question?

Question: I have noticed that there is the common habit of answering an already answered question (if the answer is not already accepted). But what's the point in doing that?
If the previous answer is incomplete, I thought I should comment it to make the author editing it or to add any missing point. Instead, most of the people here write a new answer, which content is the same of the previous one but with a couple of clarifications or more in depth analysis.
Is this normal practice? Or it would be better to comment if the answer is not adding any significant point? And moreover, should we down-vote this "copy" answers?
Answer: If you think you can write an answer that is more complete, clearer, more rigorous, better supported by evidence, or that otherwise improves on an existing answer then you should do so. You should do this even if there is some overlap with a pre-existing answer.
The purpose of this site is to ensure that the best possible answer for each question gets posted. Absolutely the best way to achieve that is to have people posting improvements on existing answers when they see the opportunity to do so. In fact, the behaviour is actively encouraged by the stack exchange networks, which uses the number of answers per-question as a metric for evaluating the success of the site.
The whole reason for having a voting mechanism on the site is so that the community can choose the best answer and drive it to the top so that it is also the most visible. Nobody will feel offended if you try to improve on an answer they wrote (because everyone here understands that this is a collaborative effort to produce the best economics resource that we can). Unless an answer is an exact duplicate (in which case it should be flagged as spam), each answer should be evaluated on its own merits. An answer should be down-voted only if you think it is wrong, misleading, or fails to address the question. An answer should be up-voted if you think it does a good job of answering the question. If there is more than one answer that does a good job then you should up-vote all of them.
Answer: I have had answers that I perceived as very similar to my own posted a few times. I sill don't think downvoting the 'rival' answer is justified. Sometimes the phrasing is different, or the clarification and extra point could be a significant improvement. If it is just a simple copy: People can see the time of posting on both answers.
Let the OP and the wisdom of the masses decide. Seems to me that this usually works 'in a fair way' and the few times it doesn't it does not result in a serious systemic problem.
Comment: +1 And when the times of posting of two answers are close, it's quite possible that the person who posted the second answer did not even see the first while they were focused on composing their own.
Comment: Sure, I was not pointing it out as a major problem. I was just asking to know the best practice
Comment: @AdamBailey For example [here](http://economics.stackexchange.com/questions/15206/what-is-the-name-of-the-economics-free-trade-punnett-square/15207#15207) where the short answer was posted just 2 minutes before the more thorough lengthy answer. Obviously the long answer was started much earlier.


TypeError: $ is not a function - in firefox console

Question: Getting type "TypeError: $ is not a function" when the below code is entered in firefox console. I don't know any thing about java script. can anyone fix this.
setInterval(function(){ $('.reserve-btn').trigger('click'); console.log('Working.. Dont press any key until we add your phone to your cart.'); },10);

Comment: I admire your courage and frankly admitting to not knowing anything about javascript.
Comment: I think u did't added jquey-Min or added after method declaration
Comment: First of all, `Java !== JavaScript`
Comment: the jQuery library hasn't been referenced in the document / site
Answer: Add this in the  of your page

Comment: Thanks its working.. after adding above code.


a question about the UIAlertView

Question: all
it will show a UIAlertView when i click a button on the view
<code>UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: @"Will you?"
message:@"will you go there?"
delegate:self
cancelButtonTitle:@"No"
otherButtonTitles:@"Yes" nil];
</code>
i want to give two selector to the two button,when i click the 'NO' button,do nothing,but just close this alertview,if i click the Yes button,that means i choose a selector called 'donextthing' , so how can i do?thanks
Answer: In your .h add the UIAlertViewDelegate, something like this:
<code>@interface yourView : UIViewController <UIAlertViewDelegate> {
</code>
And in your .m add this after your UIAlertView:
<code>- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *alertIndex = [alertView buttonTitleAtIndex:buttonIndex];

    if([alertIndex isEqualToString:@"Yes"])
    {
        //Do something
    }
}
</code>

a question about the UIAlertView


setting template file using template_preproccess_page not working

Question: I have a list of pages with url
?q=value/abc/1
?q=value/abc/2
?q=value/abc/3
?q=value/abc/4

for which i require a specific template.I have written a template_preprocess_page function,but it does not call the required tpl file.But if i set the test variable as
$test = array("value/abc/1");
the template file is being used.Could someone tell me what i am doing wrong..??
function template_preprocess_page(&$var){
 $test = array("value/abc/%");
        if(in_array($_GET['q'], $test)){
            $var['template_file'] = 'testing';
        }
}

Comment: You've tagged this as Drupal 6 _and_ 7...which are you actually using? And I'd be interested to know where you've seen an example that uses `template_file` I've never seen that used before
Comment: https://drupal.org/node/223440,
Comment: So I can guess you're using Drupal 6 from that? Read the examples again, you have typos and small errors in your code that don't match up with what you've tried to copy
Comment: tanx for joinin in @Clive :)
Answer: Assuming D6 then, in template.php:
/**
 * Implements hook_preprocess_page
 */
function THEMENAME_preprocess_page(&$variables){
 if (strpos($_GET['q'], 'value/abc') === 0) {
   $variables['template_file'] = 'testing';
 }
}

Clear theme registry, or all caches at admin > config > performance to apply.
More info:

There are two special variables that these hooks can set:
  'template_file' and 'template_files'. These will be merged together to
  form a list of 'suggested' alternate template files to use, in reverse
  order of priority. template_file will always be a higher priority than
  items in template_files. theme() will then look for these files, one
  at a time, and use the first one that exists.
  https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme/6
Comment: Heh, no worries, `template_file` is a curious feature, D7 has a similar feature in `theme_hook_suggestion` vs `theme_hook_suggestions` Cheers.
Comment: That's not right. Have a look at the docs the OP linked to, you have the same typo and error that I mentioned in the comments (although you did fix up the path-test nicely)
Comment: Hi Clive, You can use `template_file` to add a single suggestion, rather than an array in `template_files`. ( more info added on that ) I adjusted the function name from template_preprocess_page. Can you be more specific if other error(s) there?
Comment: Oh sorry I didn't realise that, my bad :) those are the only 2 'errors' I was talking about, I was trying to encourage the OP to double check his code against the examples as it didn't match up. Didn't realise it didn't _need_ to!
Comment: tanx for the info @DavidThomas.. :)
Answer: I believe what you want is to set up five content-type templates. You can read more about this here and in this tutorial. Essentially if you wish to use a template, you need to create a content-type for it. Then you can use your content-type machine name (let's say your content type's machine name is "foo" then your template PHP file will be titled "page--foo.tpl.php"
You have to then add this to the top of your template.php in your main theme:
function YourTheme_process_page(&$variables) {
      $variables['theme_hook_suggestions'][] = 'page__'. $variables['node']->type;
}

Then you can add a content page for each content type and give it the path you need (ie value/abc/1 or value/abc/2 etc).
If the processing you do with your URL value is minimal, then you can also just retrieve the value through the PHP $_GET function and then use it in your PHP processing as needed (after sanitizing the variable of course).
Comment: I think we're leaning towards the OP using Drupal 6 (although for some reason he seems reluctant to share that information). This is a good answer for D7 but won't work for D6


Objective C initializer basics

Question: I have a question about initializers that overlaps with memory management. I'm confident that this is a perfectly functional initializer (even tho it calls setters in the init method which is discouraged) . . .
@synthesize age = _age, name = _name, delegate = _delegate;

- (id)initWithName:(NSString *)name Age:(int)age delegate:(MyDelegateClass *)delegate
{
    if (self = [super init]) {

        [self setName:name];
        [self setAge:age];
        [self setDelegate:delegate];
     }

  return self;

}

But what about this initializer? Do i need to allocate memory for those ivars or does it just work out of the box like this?
- (id)initWithName:(NSString *)name Age:(int)age delegate:(MyDelegateClass *)delegate
{
    if (self = [super init]) {

        _name = name;
        _age = age;
        _delegate = delegate;
     }

  return self;

}

Answer: A few things:

(void) return type won't work.  Make it (id)
compiler will warn on the assignment in the conditional, use two lines
it's common practice to set ivars directly in init, not referring to self*
neither of your forms you suggest allocate memory.  that's done when the object is allocated.

so ...
- (id)initWithName:(NSString *)name age:(int)age delegate:(MyDelegateClass *)delegate {

    self = [super init];
    if (self) {
        _name = name;
        _age = age;
        _delegate = delegate;
    }
    return self;
}

Comment: This is fine, assuming ARC. Otherwise, you need to retain the ivars of any retained properties.
Comment: Point 2 can be negated by putting 2 parenthesis like this `if ((self = [super init]))`
Comment: so i wouldnt have to do, for example, _name = [NSString alloc] initWithString:name]  ?
Comment: Not able to confirm your 2) point. Otherwise, it's the right answer.
Answer: Normally, you'll want to copy strings rather than assign them -- even though you've specified that name is an NSString*, the object it points to might actually be a NSMutableString. So do this:
_name = [name copy];

Objective C initializer basics


PHP Forcing interface implementation

Question: I have an SystemInfoFactory class in my application which has a getSystemInfo() method:
/**
 * Returns SystemInfo object based on which OS
 * server uses
 *
 * @return SystemInfoInterface SystemInfo object
 */
public function getSystemInfo()
{
    $os = $this->getOS();

    $systemInfo = null;

    switch ($os) {
        case "Linux":
            $systemInfo = new LinuxInfo();
            break;
        case "Darwin":
            $systemInfo = new OSXInfo();
            break;
        case "Windows":
            $systemInfo = new WindowsInfo();
            break;
    }
    return $systemInfo;
}

So it chooses appropriate object according to host system. Now, each "info class" implements SystemInfo interface (methods like getArchitecture, getCPU etc.), but as you see, nowhere in my code is it checked whether returned object really implements interface. Would it be considered "good practice" to check if selected $systemInfo object implements it before returning it? It obviously isn't required, but in case somebody extends this application (adds BSD support for example) and forgets to implement all methods it might be harder for him to debug.
Comment: Shouldn't PHP throw an error when somebody uses an Interface but doesn't implement all methods??
Comment: It will, but the fact is, he can just implement all interface methods without explicitly defining `implements SystemInfoInterface` in his class and the code will work without problems.
Comment: Currently, he could just simply forget to implement one of the methods and application will throw an `undefined method` error at some point, but the real problem source could be buried deep in call stack.
Comment: Yeah, that's a problem with PHPs dynamic typing. Not sure how to solve that.
Answer: Absolutely it would be good practice. You are defining in your docblock that your method returns an instance of SystemInfo. Your callers should be able to rely on that. This is simple in your code:
/**
 * Returns SystemInfo object based on which OS
 * server uses
 *
 * @return SystemInfoInterface SystemInfo object
 */
public function getSystemInfo()
{
    $os = $this->getOS();

    $systemInfo = null;

    switch ($os) {
        case "Linux":
            $systemInfo = new LinuxInfo();
            break;
        case "Darwin":
            $systemInfo = new OSXInfo();
            break;
        case "Windows":
            $systemInfo = new WindowsInfo();
            break;
        default:
            throw new \RuntimeException('System not supported');
            break;
    }

    if (!$systeminfo instanceof SystemInfo) {
        throw new \RuntimeException('Invalid SystemInfo object returned');
    }

    return $systemInfo;
}

Make sure you declare that you'll be throwing exceptions from this method call. The exception here makes it very clear what's going on, rather than having to chase through an "undefined method" error later on in the code.
Answer: I think, the keyword in here is Duck Typing. The interface of an object is defined by its methods and attributes rather than its ancestors and implemented interfaces.
Have a look at this: http://en.wikipedia.org/wiki/Duck_typing
Back to PHP: It's perfectly valid and no bad style if you do not check if the object implements your interface. If the code crashes the implementor of the class has to be blamed. I would find it annoying if the code is messed up with if ($obj instanceof FancyInterface) {.
Comment: You're propagating horrible coding practices. The method indicates it's going to return an object of a certain type. If it doesn't, it's bad code. Period. End of story. Why in the world would you have interfaces if not for these reasons? Always, always, __always__ code to interface. Not implementation.
Comment: Of course one should code against an interface. But if a class is supposed to implement an interface I expect it to do that. I don't want to have to check every object if it implements certain methods or interfaces. I expect them to do what they promise they can. That's one benefit of Duck Typing.
Comment: That's an expectation that'll cost you a lot of wasted debugging time that 3 additional lines of code could have solved. Note that this is only even necessary for factory-based methods due to their variable return values. Otherwise, you can simply type-hint your method arguments with the interface and it only costs you a few characters.
Comment: Type hinting is, where applicable, very great. Of course, defining object types in docblock is a must too. Checking for interfaces at central parts of the software, like factories, only is OK for me too. But, hell, i can not agree to checking for interfaces at all possible parts of classes, scripts, whatever. I understood your answer that way because you didn't mention it the way you did it here in the comments. I would go that far to only check with `instanceof` where third party libs are part of the game - whether i deliver objects to 3rd party or i accept objects from 3rd party.
Comment: If a method is returning one object, and it's controlled by the developer, then not checking it's implementation of an interface is acceptable. My argument is that in a factory method such as this (which may, at some point, be changed to a more abstract factory approach), when the OP said that others may extend and add support for other platforms or add new objects, I think that it's a cheap and reasonable check to make.
Comment: I agree with you, @ColinMorelli. Let's have a beer some time ;)
Comment: FYI: One of the most intelligent conversations I have had via comments on SO. But I don't want to blow this out any longer. Your perspective is understood, I get it, and I agree now. I'll let this question float back to being on topic.

PHP Forcing interface implementation


Is it wrong to have two voices move from a perfect fifth to a perfect octave?

Question: I had a teacher once tell me that although not forbidden, it is not advisable to have the same two voices move from a perfect fifth to a perfect octave (specifically referring to a four-part chorale for SATB chorus). I don't see any reason for this and haven't been able to find anything that addresses that issue specifically. Is that true? And if so, why should it be avoided in good voice leading?
This can be seen between the tenor and bass in beats 2 and 3 of this bar.
Comment: I think this question is related to my first question in SE about "prohibition of the parallels of fifth" and is also answered there (especially the answers concerning  history, epoch, harmony and style:
https://music.stackexchange.com/questions/78011/why-are-in-music-theory-perfect-fifth-parallels-forbidden
Comment: you should be more precise: do you concern a counterpoint of 2 voices, is it a task in counterpoint study or do is it an arrangement of 3 or  4 voices, or even a piano piece?
Answer: I have to respectfully disagree with the individual that made this claim. The fact is that it's very common for a perfect fifth to move to an octave; we see it all the time in the V–I progression!

The claim that this is wrong is likely to prevent hidden octaves (also known as "indirect," "covered," "exposed," or "similar" octaves/fifths). In short, these are perfect fifths or octaves that are approached by similar motion between two voices. But there are wildly varying rules for situations in which these fifths/octaves are okay:

If neither the soprano nor the bass are involved, it's fine.
If one of the voices moves by semitone, it's fine.
If the upper voice moves by step, it's fine.

Not knowing the individual that shared this stipulation with you, I can't say which rule s/he prefers.
It's also possible this individual was referring to the fact that two voices "fuse" together when in perfect intervals, and the whole point of counterpoint is for these voices not to fuse together, but rather be independent. Perhaps they felt that two consecutive perfect intervals, even of different sizes, led to this fusing? But that's not a rule that I'm familiar with.
Comment: Thank you so much for your incredibly helpful answer! It makes perfect sense.
Comment: It's been almost 40 years since I took a music theory class, but the recommendation in the question sounds familiar, I don't think it's something this teacher came up with.
Answer:
such rules must have been "invented" by purist teachers as  chicane for  the students
or generalized from a rule of counterpoint of 2 voices.

There is fundamentalism in every subjects - not only in religion.
Comment: from me!
and probably  from Diether da la Motte. (Harmonielehre, Kontrapunkt)
Comment: Where are these quotes from?
Answer: In four-part harmony, this rule is not on the "most important" list, but the perfect intervals, sounding so open, can draw attention to themselves when one is followed by another. This can make them stick out in a chorale setting where it contrasts with most of the movement. When the two voices are moving in the same direction, this effect is exaggerated. It can usually be avoided. Often in V-I cadences, if the soprano is on the 2nd scale degree moving down to the tonic, and the bass is in root position moving from V-I, the movement from a P5 to a P8 is in contrary motion, which lessens the effect.
There are many choices that need to be made when part-writing. Sometimes there is no better choice than to move from a P5 to a P8 between two voices, in order to avoid worse movement somewhere else.


Add custom permission to specific module "group" on permissions page

Question: Using a custom module, how can a permission be added to a core/contributed module "group" on the permissions page without hacking the core/contributed module?
Example:
Answer: As already said, it would not be a good idea to list a permission implemented by a module together the permissions implemented by another module; it would difficult for users to find the permissions implemented by, for example, custom_module.module, when it is listed together the ones implemented by user.module.
If you really need to change the order used to list the permissions (but then, is it really necessary), then I would suggest to change how the list of permissions is shown: instead of listing them basing on the module implementing it, you could list them basing on different criteria.
To do this, you would need to:

Implement hook_theme_registry_alter() to alter the theme function called when theme('user_admin_perm') is invoked.
Implement your theme function looking at the code of theme_user_admin_perm().

Is it worth doing it? It could be, depending on your customer.
Considering that the first official release for Drupal 7 has been released, and the code for Drupal 7 would change, it is probably not worth doing it. I would rather try to understand why the customer wants to change the order of the permissions listed in the administration page, and explain the reason why changing it is a bad idea; if the customer insists the code needs to be implemented for their own purposes, then I would make him understand that the code should be rewritten when the site passes to Drupal 7, and it is not worth spending time for such changes, when it is possible to use the same time to implement something that  it is really necessary.
Comment: I agree, after explaining all this to the client he decided against it.  But `hook_theme_registry_alter()` and `theme_user_admin_perm()` worked great in the test runs, thanks
Answer: There's no hook_perm_alter and those permissions are grouped by module, so likely th way would be to get in there would be with hook_form_alter on those forms (there's is per role permission forms along with the main one; not sure if they are using the same form_id).
Should still define the permission via yourmodule_perm so anything else can know the permission exists.
Personally, I'd advised against it; let your permission by where it would be so there's no "I installed this module and can't find the permission!  oh, why was the permission under a different module?!!"
Comment: I wasn't too big on the idea either, but a client wanted to know if it was possible so thought I'd ask
Comment: +1 (only virtual, as I have used all my votes already) for pointing out it would not be a good idea to list the permissions of a module together the permissions defined from another module.
Answer: There are two ways to accomplish what you ask for.
Either through hook_form_alter or by overriding the form's theme function: theme_user_admin_perm.
For a standard contrib module, this wouldn't be a good idea, as people tend to look for a module's permission by browsing for it's name. If your module does some alterations to the standard user permission flow, it might not be a bad idea to show the added permission along with the default ones from the user module.
Comment: Yea, persuaded the client that it's better to leave it under custom module's name for future clarity. Thank you for `theme_user_admin_perm`, did not know about that one.


Htaccess - document root

Question: Gostaria de fazer o seguinte:
#diretorio não existe
www.teste.com.br/diretorio

toda a vez que acessar esse endereço, o apache abriria:
#outro_diretorio/pagina esse existira
www.teste.com.br/outro_diretorio/pagina

porém toda a navegação seria exibida ao usuário a partir www.teste.com.br/diretorio dando a impressão que o conteúdo esteja dentro da pasta "diretorio". Não sei se me fiz entender.
Answer: Consegui, era isso que estava precisando:
RewriteRule ^meu_diretorio_que_nao_existe\/(.*)$ diretorio/outro_diretorio/$1 [QSA,L]

Htaccess - document root