Chelsyx has uploaded a new change for review. ( 
https://gerrit.wikimedia.org/r/327139 )

Change subject: add geo breakdown
......................................................................

add geo breakdown

Change-Id: I7a4d371f40fbb4ec822008ae3866870688621154
---
M functions.R
M server.R
A tab_documentation/first_visit_geo.md
A tab_documentation/last_action_geo.md
A tab_documentation/most_common_geo.md
A tab_documentation/traffic_ctr_geo.md
M ui.R
M www/stylesheet.css
8 files changed, 1,449 insertions(+), 10 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/wikimedia/discovery/prince 
refs/changes/39/327139/1

diff --git a/functions.R b/functions.R
index 7ee1f65..0398f8c 100644
--- a/functions.R
+++ b/functions.R
@@ -1,9 +1,21 @@
 library(polloi)
+library(ggplot2)
 library(data.table)
 library(reshape2)
 library(magrittr)
+library(toOrdinal)
+library(xts)
+library(dplyr)
+library(tidyr)
 
 source("extras.R")
+
+# Capitalize the first letter
+simpleCap <- function(x) {
+  s <- strsplit(x, " ")[[1]]
+  paste(toupper(substring(s, 1,1)), substring(s, 2),
+        sep="", collapse=" ")
+}
 
 # Read in the traffic data
 read_clickthrough <- function(){
@@ -129,6 +141,155 @@
 
 }
 
+read_geo <- function() {
+
+  all_country_data <- polloi::read_dataset("portal/all_country_data.tsv", 
col_types = "Dcididid")
+  first_visits_country <- 
polloi::read_dataset("portal/first_visits_country.tsv", col_types = "Dccid")
+  last_action_country <- 
polloi::read_dataset("portal/last_action_country.tsv", col_types = "Dccid")
+  most_common_country <- 
polloi::read_dataset("portal/most_common_country.tsv", col_types = "Dccid")
+  data("countrycode_data", package="countrycode")
+  countrycode_data$country.name[c(44,54,143)] <- c("Cape Verde", "Congo, The 
Democratic Republic of the", "Macedonia, Republic of" )
+  countrycode_data$continent[countrycode_data$country.name %in% c("British 
Indian Ocean Territory","Christmas Island","Taiwan, Province of China")] <- 
"Asia"
+  countrycode_data$continent[countrycode_data$country.name %in% 
c("Bermuda","Canada","Greenland","Saint Pierre and Miquelon","United States")] 
<- "Northern America"
+  countrycode_data$continent[countrycode_data$continent == "Americas"] <- 
"South America"
+
+
+  all_country_data <- 
all_country_data[!duplicated(all_country_data[,1:2],fromLast=T),]
+  all_country_data_prop <- all_country_data %>%
+    group_by(date) %>%
+    mutate(event_prop=round(events/sum(events),4)*100, 
visit_prop=round(n_visit/sum(n_visit),4)*100, 
session_prop=round(n_session/sum(n_session),4)*100) %>%
+    
select(date,country,event_prop,ctr,visit_prop,ctr_visit,session_prop,ctr_session)
 %>% ungroup()
+  us_mask <- grepl("^U\\.S\\.", all_country_data$country)
+  us_data <- all_country_data[us_mask,]
+  all_country_data <- us_data %>%
+    mutate(clicks = events*ctr, click_v=n_visit*ctr_visit, 
click_s=n_session*ctr_session) %>%
+    group_by(date) %>%
+    summarise(country="United States", events=sum(events), 
ctr=round(sum(clicks)/sum(events),4),
+              n_visit=sum(n_visit), 
ctr_visit=round(sum(click_v)/sum(n_visit),4),
+              n_session=sum(n_session), 
ctr_session=round(sum(click_s)/sum(n_session),4)) %>%
+    rbind(all_country_data[!us_mask,]) %>%
+    arrange(date, country)
+  us_mask <- grepl("^U\\.S\\.", all_country_data_prop$country)
+  us_data_prop <- all_country_data_prop[us_mask,]
+  all_country_data_prop <- us_data_prop %>%
+    group_by(date) %>%
+    summarise(country="United States", event_prop=sum(event_prop),
+              visit_prop=sum(visit_prop), session_prop=sum(session_prop)) %>%
+    left_join(all_country_data[, 
c("date","country","ctr","ctr_visit","ctr_session")], by=c("date","country")) 
%>%
+    rbind(all_country_data_prop[!us_mask,]) %>%
+    
select(date,country,event_prop,ctr,visit_prop,ctr_visit,session_prop,ctr_session)
 %>%
+    arrange(date, country)
+  colnames(all_country_data) <- c("Date", "Country", "No. Events",
+                                  "Overall Clickthrough Rate", "No. Visit", 
"Clickthrough Rate Per Visit",
+                                  "No. Session", "Clickthrough Rate Per 
Session")
+  colnames(all_country_data_prop) <- c("Date", "Country", "No. Events",
+                                       "Overall Clickthrough Rate", "No. 
Visit", "Clickthrough Rate Per Visit",
+                                       "No. Session", "Clickthrough Rate Per 
Session")
+  colnames(us_data) <- c("Date", "Country", "No. Events",
+                         "Overall Clickthrough Rate", "No. Visit", 
"Clickthrough Rate Per Visit",
+                         "No. Session", "Clickthrough Rate Per Session")
+  colnames(us_data_prop) <- c("Date", "Country", "No. Events",
+                              "Overall Clickthrough Rate", "No. Visit", 
"Clickthrough Rate Per Visit",
+                              "No. Session", "Clickthrough Rate Per Session")
+  region_mask <- match(stringi::stri_trans_general(all_country_data$Country, 
"Latin-ASCII"), countrycode_data$country.name)
+  all_country_data$Region <- countrycode_data$continent[region_mask]
+  all_country_data$Region[is.na(all_country_data$Region)] <- "Other"
+  region_mask <- 
match(stringi::stri_trans_general(all_country_data_prop$Country, 
"Latin-ASCII"), countrycode_data$country.name)
+  all_country_data_prop$Region <- countrycode_data$continent[region_mask]
+  all_country_data_prop$Region[is.na(all_country_data_prop$Region)] <- "Other"
+  all_country_data <<- all_country_data[, c(1:2, 9, 3:8)] %>% arrange(Date, 
Country)
+  all_country_data_prop <<- all_country_data_prop[, c(1:2, 9, 3:8)] %>% 
arrange(Date, Country)
+  us_data <<- us_data %>% mutate(Region="Northern America") %>% select(c(1:2, 
9, 3:8)) %>% arrange(Date, Country)
+  us_data_prop <<- us_data_prop %>% mutate(Region="Northern America") %>% 
select(c(1:2, 9, 3:8)) %>% arrange(Date, Country)
+
+
+  first_visits_country <- 
first_visits_country[!duplicated(first_visits_country[,1:3],fromLast=T),]
+  colnames(first_visits_country) <- c("Date", "Action", "Country", "No. 
Session", "Proportion")
+  first_visits_country$Proportion <- first_visits_country$Proportion*100
+  first_visits_country_prop <- tidyr::spread(first_visits_country[,-4], 
key=Action, value=Proportion, fill=0)
+  first_visits_country <- tidyr::spread(first_visits_country[,-5], key=Action, 
value=`No. Session`, fill=0)
+  colnames(first_visits_country_prop) <- 
sapply(colnames(first_visits_country_prop), simpleCap)
+  colnames(first_visits_country) <- sapply(colnames(first_visits_country), 
simpleCap)
+  us_mask <- grepl("^U\\.S\\.", first_visits_country$Country)
+  first_visits_us <- first_visits_country[us_mask, ]
+  first_visits_country <- first_visits_us %>% select(-Country) %>% 
group_by(Date) %>%
+    summarise_each(funs(sum)) %>% mutate(Country="United States") %>%
+    rbind(first_visits_country[!us_mask,])
+  us_mask <- grepl("^U\\.S\\.", first_visits_country_prop$Country)
+  first_visits_us_prop <- first_visits_country_prop[us_mask, ]
+  first_visits_country_prop <- first_visits_us_prop %>% select(-Country) %>% 
group_by(Date) %>%
+    summarise_each(funs(sum)) %>% mutate(Country="United States") %>%
+    rbind(first_visits_country_prop[!us_mask,])
+  region_mask <- 
match(stringi::stri_trans_general(first_visits_country$Country, "Latin-ASCII"), 
countrycode_data$country.name)
+  first_visits_country$Region <- countrycode_data$continent[region_mask]
+  first_visits_country$Region[is.na(first_visits_country$Region)] <- "Other"
+  region_mask <- 
match(stringi::stri_trans_general(first_visits_country_prop$Country, 
"Latin-ASCII"), countrycode_data$country.name)
+  first_visits_country_prop$Region <- countrycode_data$continent[region_mask]
+  first_visits_country_prop$Region[is.na(first_visits_country_prop$Region)] <- 
"Other"
+  first_visits_country <<- first_visits_country[, c(1, 8:9, 2:7)] %>% 
arrange(Date, Country)
+  first_visits_country_prop <<- first_visits_country_prop[, c(1, 8:9, 2:7)] 
%>% arrange(Date, Country)
+  first_visits_us <<- first_visits_us %>% mutate(Region="Northern America") 
%>% select(c(1:2, 9, 3:8)) %>% arrange(Date, Country)
+  first_visits_us_prop <<- first_visits_us_prop %>% mutate(Region="Northern 
America") %>% select(c(1:2, 9, 3:8)) %>% arrange(Date, Country)
+
+
+  last_action_country <- 
last_action_country[!duplicated(last_action_country[,1:3],fromLast=T),]
+  colnames(last_action_country) <- c("Date", "Action", "Country", "Events", 
"Proportion")
+  last_action_country$Proportion <- last_action_country$Proportion*100
+  last_action_country_prop <- tidyr::spread(last_action_country[,-4], 
key=Action, value=Proportion, fill=0)
+  last_action_country <- tidyr::spread(last_action_country[,-5], key=Action, 
value=Events, fill=0)
+  colnames(last_action_country_prop) <- 
sapply(colnames(last_action_country_prop), simpleCap)
+  colnames(last_action_country) <- sapply(colnames(last_action_country), 
simpleCap)
+  us_mask <- grepl("^U\\.S\\.", last_action_country$Country)
+  last_action_us <- last_action_country[us_mask, ]
+  last_action_country <- last_action_us %>% select(-Country) %>% 
group_by(Date) %>%
+    summarise_each(funs(sum)) %>% mutate(Country="United States") %>%
+    rbind(last_action_country[!us_mask,])
+  us_mask <- grepl("^U\\.S\\.", last_action_country_prop$Country)
+  last_action_us_prop <- last_action_country_prop[us_mask, ]
+  last_action_country_prop <- last_action_us_prop %>% select(-Country) %>% 
group_by(Date) %>%
+    summarise_each(funs(sum)) %>% mutate(Country="United States") %>%
+    rbind(last_action_country_prop[!us_mask,])
+  region_mask <- 
match(stringi::stri_trans_general(last_action_country$Country, "Latin-ASCII"), 
countrycode_data$country.name)
+  last_action_country$Region <- countrycode_data$continent[region_mask]
+  last_action_country$Region[is.na(last_action_country$Region)] <- "Other"
+  region_mask <- 
match(stringi::stri_trans_general(last_action_country_prop$Country, 
"Latin-ASCII"), countrycode_data$country.name)
+  last_action_country_prop$Region <- countrycode_data$continent[region_mask]
+  last_action_country_prop$Region[is.na(last_action_country_prop$Region)] <- 
"Other"
+  last_action_country <<- last_action_country[, c(1, 8:9, 2:7)] %>% 
arrange(Date, Country)
+  last_action_country_prop <<- last_action_country_prop[, c(1, 8:9, 2:7)] %>% 
arrange(Date, Country)
+  last_action_us <<- last_action_us %>% mutate(Region="Northern America") %>% 
select(c(1:2, 9, 3:8)) %>% arrange(Date, Country)
+  last_action_us_prop <<- last_action_us_prop %>% mutate(Region="Northern 
America") %>% select(c(1:2, 9, 3:8)) %>% arrange(Date, Country)
+
+
+  most_common_country <- 
most_common_country[!duplicated(most_common_country[,1:3],fromLast=T),]
+  colnames(most_common_country) <- c("Date", "Action", "Country", "No. Visit", 
"Proportion")
+  most_common_country$Proportion <- most_common_country$Proportion*100
+  most_common_country_prop <- tidyr::spread(most_common_country[,-4], 
key=Action, value=Proportion, fill=0)
+  most_common_country <- tidyr::spread(most_common_country[,-5], key=Action, 
value=`No. Visit`, fill=0)
+  colnames(most_common_country_prop) <- 
sapply(colnames(most_common_country_prop), simpleCap)
+  colnames(most_common_country) <- sapply(colnames(most_common_country), 
simpleCap)
+  us_mask <- grepl("^U\\.S\\.", most_common_country$Country)
+  most_common_us <- most_common_country[us_mask, ]
+  most_common_country <- most_common_us %>% select(-Country) %>% 
group_by(Date) %>%
+    summarise_each(funs(sum)) %>% mutate(Country="United States") %>%
+    rbind(most_common_country[!us_mask,])
+  us_mask <- grepl("^U\\.S\\.", most_common_country_prop$Country)
+  most_common_us_prop <- most_common_country_prop[us_mask, ]
+  most_common_country_prop <- most_common_us_prop %>% select(-Country) %>% 
group_by(Date) %>%
+    summarise_each(funs(sum)) %>% mutate(Country="United States") %>%
+    rbind(most_common_country_prop[!us_mask,])
+  region_mask <- 
match(stringi::stri_trans_general(most_common_country$Country, "Latin-ASCII"), 
countrycode_data$country.name)
+  most_common_country$Region <- countrycode_data$continent[region_mask]
+  most_common_country$Region[is.na(most_common_country$Region)] <- "Other"
+  region_mask <- 
match(stringi::stri_trans_general(most_common_country_prop$Country, 
"Latin-ASCII"), countrycode_data$country.name)
+  most_common_country_prop$Region <- countrycode_data$continent[region_mask]
+  most_common_country_prop$Region[is.na(most_common_country_prop$Region)] <- 
"Other"
+  most_common_country <<- most_common_country[, c(1, 7:8, 2:6)] %>% 
arrange(Date, Country)
+  most_common_country_prop <<- most_common_country_prop[, c(1, 7:8, 2:6)] %>% 
arrange(Date, Country)
+  most_common_us <<- most_common_us %>% mutate(Region="Northern America") %>% 
select(c(1:2, 8, 3:7)) %>% arrange(Date, Country)
+  most_common_us_prop <<- most_common_us_prop %>% mutate(Region="Northern 
America") %>% select(c(1:2, 8, 3:7)) %>% arrange(Date, Country)
+}
+
 fill_out <- function(x, start_date, end_date, fill = 0) {
   temp <- data.frame(date = seq(start_date, end_date, "day"))
   y <- dplyr::right_join(x, temp, by = "date")
diff --git a/server.R b/server.R
index c568767..f57659f 100644
--- a/server.R
+++ b/server.R
@@ -2,6 +2,7 @@
 library(shinydashboard)
 library(dygraphs)
 library(shinyjs)
+library(highcharter)
 
 source("functions.R")
 
@@ -14,18 +15,20 @@
     on.exit(progress$close())
     progress$set(message = "Downloading clickthrough data...", value = 0)
     read_clickthrough()
-    progress$set(message = "Downloading language visit data...", value = 1/7)
+    progress$set(message = "Downloading language visit data...", value = 1/8)
     read_langs()
-    progress$set(message = "Downloading dwell-time data...", value = 2/7)
+    progress$set(message = "Downloading dwell-time data...", value = 2/8)
     read_dwelltime()
-    progress$set(message = "Downloading country data data...", value = 3/7)
+    progress$set(message = "Downloading country data data...", value = 3/8)
     read_country()
-    progress$set(message = "Downloading user-agent data...", value = 4/7)
+    progress$set(message = "Downloading user-agent data...", value = 4/8)
     read_useragents()
-    progress$set(message = "Downloading pageview data...", value = 5/7)
+    progress$set(message = "Downloading pageview data...", value = 5/8)
     read_pageviews()
-    progress$set(message = "Downloading referral data...", value = 6/7)
+    progress$set(message = "Downloading referral data...", value = 6/8)
     read_referrals()
+    progress$set(message = "Downloading geographical breakdown data...", value 
= 7/8)
+    read_geo()
     progress$set(message = "Finished downloading datasets.", value = 1)
     existing_date <<- Sys.Date()
   }
@@ -425,6 +428,8 @@
     }
   })
 
+  outputOptions(output, "lv_languages_container", suspendWhenHidden=FALSE)
+
   observeEvent(input$lv_sort, {
 
     # Make legend small in case of Top 10 or Bottom 50, otherwise make it big:
@@ -506,4 +511,774 @@
       dyEvent(as.Date("2016-09-13"), "B (schema switch)", labelLoc = "bottom", 
color = "white")
   })
 
+  # General Geo Breakdowns
+  cntr_reactive <- reactiveValues(selected_metric_a = NULL, selected_metric_f 
= NULL, selected_metric_l = NULL, selected_metric_m = NULL)
+
+  all_country_data_dt <- reactive({
+    if (input$cntr_sort_a %in% c("us_a", "custom_a")){
+      fnl_tbl <- all_country_data %>%
+        rbind(us_data) %>%
+        filter(Date >= input$date_all_country[1]
+               & Date <= input$date_all_country[2]
+               & Country %in% selected_country_a()) %>%
+        arrange(Date, Country)
+    } else{
+      fnl_tbl <- all_country_data %>%
+        filter(Date >= input$date_all_country[1]
+               & Date <= input$date_all_country[2]
+               & Country %in% selected_country_a())
+    }
+    return (fnl_tbl)
+  })
+  all_country_data_prop_dt <- reactive({
+    if (input$cntr_sort_a %in% c("us_a", "custom_a")){
+      fnl_tbl <- all_country_data_prop %>%
+        rbind(us_data_prop) %>%
+        filter(Date >= input$date_all_country[1]
+               & Date <= input$date_all_country[2]
+               & Country %in% selected_country_a()) %>%
+        arrange(Date, Country)
+    } else{
+      fnl_tbl <- all_country_data_prop %>%
+        filter(Date >= input$date_all_country[1]
+               & Date <= input$date_all_country[2]
+               & Country %in% selected_country_a())
+    }
+    return (fnl_tbl)
+  })
+  observeEvent(input$traffic_select, {
+    cntr_reactive$selected_metric_a <- switch(input$traffic_select,
+                                              events = "No. Events",
+                                              visits = "No. Visit",
+                                              sessions = "No. Session",
+                                              ctr_all = "Overall Clickthrough 
Rate",
+                                              ctr_vst = "Clickthrough Rate Per 
Visit",
+                                              ctr_ses = "Clickthrough Rate Per 
Session"
+    )
+  })
+  selected_country_a <- reactive({
+    all_country_temp<- all_country_data %>%
+      filter(all_country_data$Date >= input$date_all_country[1]
+             & all_country_data$Date <= input$date_all_country[2]) %>%
+      
select_(.dots=c("Country",paste0("`",cntr_reactive$selected_metric_a,"`"))) %>%
+      group_by(Country) %>%
+      summarize_(.dots =
+                   if(input$traffic_select %in% 
c('events','visits','sessions')) as.formula(paste0("~ 
sum(`",cntr_reactive$selected_metric_a,"`)")) else as.formula(paste0("~ 
median(`",cntr_reactive$selected_metric_a,"`)"))
+      ) %>%
+      ungroup() %>%
+      as.data.frame()
+    all_country_temp <- all_country_temp[order(all_country_temp[,2], 
all_country_temp[,1]),]
+    result <- switch(input$cntr_sort_a,
+                     top10_a = {tail(all_country_temp, 10)$Country},
+                     bottom50_a = {head(all_country_temp, 50)$Country},
+                     us_a = unique(us_data$Country),
+                     all_a = unique(all_country_data$Country),
+                     all_nus_a = 
unique(all_country_data$Country)[!grepl("United States", 
unique(all_country_data$Country))],
+                     custom_a = input$cntr_a
+    )
+    return(result)
+  })
+  observeEvent(input$cntr_sort_a, {
+    toggleClass("cntr_a_legend", "small", length(selected_country_a())>7 & 
input$cntr_combine_a==F)
+    toggleClass("cntr_a_legend", "large", length(selected_country_a())<=7 | 
input$cntr_combine_a)
+    if (input$cntr_sort_a %in% c("bottom50_a","all_a","all_nus_a")) {
+      updateCheckboxInput(session, "cntr_combine_a", value = TRUE)
+    } else {
+      updateCheckboxInput(session, "cntr_combine_a", value = FALSE)
+    }
+  })
+  output$all_country_dygraph <- renderDygraph({
+    if (input$cntr_combine_a == T){
+      if (input$traffic_select == 'ctr_all'){
+        data4dygraph <- all_country_data_dt() %>%
+          mutate(clicks=`No. Events`*`Overall Clickthrough Rate`) %>%
+          group_by(Date) %>%
+          summarize("Overall Clickthrough Rate"=sum(clicks)/sum(`No. Events`)) 
%>%
+          rename(date=Date) %>%
+          fill_out(start_date = input$date_all_country[1], end_date = 
input$date_all_country[2])
+      } else if (input$traffic_select == 'ctr_vst'){
+        data4dygraph <- all_country_data_dt() %>%
+          mutate(clicks=`No. Visit`*`Clickthrough Rate Per Visit`) %>%
+          group_by(Date) %>%
+          summarize("Clickthrough Rate Per Visit"=sum(clicks)/sum(`No. 
Visit`)) %>%
+          rename(date=Date) %>%
+          fill_out(start_date = input$date_all_country[1], end_date = 
input$date_all_country[2])
+      } else if(input$traffic_select == 'ctr_ses'){
+        data4dygraph <- all_country_data_dt() %>%
+          mutate(clicks=`No. Session`*`Clickthrough Rate Per Session`) %>%
+          group_by(Date) %>%
+          summarize("Clickthrough Rate Per Session"=sum(clicks)/sum(`No. 
Session`)) %>%
+          rename(date=Date) %>%
+          fill_out(start_date = input$date_all_country[1], end_date = 
input$date_all_country[2])
+      } else{
+        data4dygraph <- {
+          if(input$prop_a) all_country_data_prop_dt() else 
all_country_data_dt()
+        } %>%
+          
select_(.dots=c("Date","Country",paste0("`",cntr_reactive$selected_metric_a,"`")))
 %>%
+          group_by(Date) %>%
+          
summarize_(value=paste0("sum(`",cntr_reactive$selected_metric_a,"`)")) %>%
+          rename(date=Date) %>%
+          fill_out(start_date = input$date_all_country[1], end_date = 
input$date_all_country[2])
+        names(data4dygraph)[2] <- 
paste0(isolate(cntr_reactive$selected_metric_a))
+      }
+    } else{
+      if (length(selected_country_a())>1){
+        data4dygraph <- {
+          if(input$prop_a) all_country_data_prop_dt() else 
all_country_data_dt()
+        } %>%
+          
select_(.dots=c("Date","Country",paste0("`",cntr_reactive$selected_metric_a,"`")))
 %>%
+          tidyr::spread_(., key_col="Country", 
value_col=cntr_reactive$selected_metric_a, fill=0) %>%
+          rename(date=Date) %>%
+          fill_out(start_date = input$date_all_country[1], end_date = 
input$date_all_country[2])
+      } else{
+        data4dygraph <- {
+          if(input$prop_a) all_country_data_prop_dt() else 
all_country_data_dt()
+        } %>%
+          select_(.dots=c("Date", 
paste0("`",cntr_reactive$selected_metric_a,"`"))) %>%
+          rename(date=Date) %>%
+          fill_out(start_date = input$date_all_country[1], end_date = 
input$date_all_country[2])
+        names(data4dygraph)[2] <- paste0(isolate(selected_country_a()))
+      }
+    }
+    data4dygraph[is.na(data4dygraph)] <- 0
+    data4dygraph %>%
+    {
+      tryCatch(polloi::smoother(., smooth_level = 
polloi::smooth_switch(input$smoothing_global, input$smoothing_cntr_a)),
+               error = function(e) {
+                 stop("Cannot apply spline smoothing on one or more of the 
selected countries.")
+               }, finally = NULL)
+    } %>%
+      polloi::make_dygraph(xlab = "Date",
+                           ylab = ifelse(input$prop_a & input$traffic_select 
%in% c('events','visits','sessions'),
+                                         paste0("Proportion of ", 
cntr_reactive$selected_metric_a, " (%)"),
+                                         cntr_reactive$selected_metric_a),
+                           title = paste0(ifelse(input$prop_a & 
input$traffic_select %in% c('events','visits','sessions'),
+                                                 paste0("Out of all countries, 
the proportion of ", cntr_reactive$selected_metric_a, " (%)"),
+                                                 
cntr_reactive$selected_metric_a),
+                                          " from ", ifelse(input$cntr_sort_a 
%in% c("all_a","all_nus_a"), ifelse(input$cntr_sort_a=="all_a","All 
Countries","All Countries but U.S."), paste0(selected_country_a(), collapse=", 
")))) %>%
+      dyRangeSelector(fillColor = "gray",
+                      strokeColor = "white",
+                      retainDateWindow = TRUE) %>%
+      dyOptions(strokeWidth = 3, labelsKMB = TRUE, drawPoints = FALSE, 
pointSize = 3, includeZero = TRUE,
+                titleHeight = 60, logscale = input$cntr_logscale_a) %>%
+      dyAxis("x", rangePad = 8) %>%
+      dyLegend(width = 400, labelsDiv = "cntr_a_legend", show = "always", 
showZeroValues = FALSE) %>%
+      dyCSS(css = "www/inverse.css") %>%
+      dyEvent(as.Date("2016-09-13"), "Schema Switch", labelLoc = "bottom", 
color = "black")
+  })
+  output$traffic_pie_pl <- renderHighchart({
+    if(input$traffic_select %in% c('events','ctr_all')){
+      this_metric <- "No. Events"
+    } else if(input$traffic_select %in% c('visits','ctr_vst')){
+      this_metric <- "No. Visit"
+    } else{
+      this_metric <- "No. Session"
+    }
+    data4pie <- all_country_data_dt() %>%
+      group_by(Region) %>%
+      mutate_(region_total=paste0("sum(`",this_metric,"`)")) %>%
+      group_by(Region, Country) %>%
+      mutate_(country_total=paste0("sum(`",this_metric,"`)")) %>%
+      select(Region, Country, country_total, region_total) %>%
+      unique() %>% ungroup() %>% arrange(Region, Country)
+    data4pie_us <- us_data %>%
+      filter(us_data$Date >= input$date_all_country[1]
+             & us_data$Date <= input$date_all_country[2]) %>%
+      group_by(Country) %>%
+      summarise_(us_total=paste0("sum(`",this_metric,"`)")) %>% ungroup()
+    hc <- highchart() %>%
+      hc_chart(type = "pie", plotBackgroundColor=NULL, plotBorderWidth=NULL, 
plotShadow=F) %>%
+      hc_title(text = paste0(this_metric, " by Country"),
+               style = list(color = "#ECF0F5")) %>%
+      hc_tooltip(pointFormat = '{point.y} ({point.percentage:.1f}%)') %>%
+      hc_plotOptions(
+        pie = list(
+          shadow = FALSE,
+          center = c("50%", "50%")
+        )
+      ) %>%
+      hc_add_series(data = data4pie %>% select(name=Region, y=region_total) %>%
+                      mutate(drilldown=tolower(name)) %>% unique() %>% 
list_parse(),
+                    size = '60%',
+                    name = "All Continents",
+                    dataLabels = list(distance = -60,
+                                      color = 'black',
+                                      formatter = JS("function () {
+                                                     return this.percentage > 
5 ? this.point.name : null;
+  }"))
+                   ) %>%
+      hc_add_series(data = data4pie %>% select(name=Country, y=country_total) 
%>%
+                      mutate(drilldown=ifelse(name=="United States","united 
states", NA)) %>% unique() %>% list_parse(),
+                    name = "All Countries", size = '100%', innerSize = "60%") 
%>%
+      hc_drilldown(
+        allowPointDrilldown = TRUE,
+        series = data4pie %>% mutate(id=tolower(Region)) %>%
+          select(name=Country, y=country_total, id) %>%
+          unique() %>%
+          split(.$id) %>%
+          lapply(function(x){
+            list(id= as.character(unique(x[,3])),
+                 data=list_parse(x[,-3]))
+          }) %>%
+          magrittr::set_names(NULL) %>%
+          append(list(list(
+            id="united states",
+            data=list_parse2(data4pie_us)
+          )))
+      )
+    hc
+  })
+  output$all_country_tbl <- DT::renderDataTable(
+    {if(input$prop_a){
+      fnl_dt <- all_country_data_prop_dt()
+      colnames(fnl_dt) <- c("Date", "Country", "Region", "Events Proportion",
+                            "Overall Clickthrough Rate", "Visits Proportion", 
"Clickthrough Rate Per Visit",
+                            "Sessions Proportion", "Clickthrough Rate Per 
Session")
+    } else{
+      fnl_dt <- all_country_data_dt()
+    }
+      fnl_dt},
+    options = list(lengthMenu = list(c(15, 30, 60), c('15', '30', '60')), 
pageLength = 15)
+  )
+
+  first_visits_country_dt <- reactive({
+    if (input$cntr_sort_f %in% c("us_f", "custom_f")){
+      fnl_tbl <- first_visits_country %>%
+        rbind(first_visits_us) %>%
+        filter(Date >= input$date_first_visit[1]
+               & Date <= input$date_first_visit[2]
+               & Country %in% selected_country_f()) %>%
+        arrange(Date, Country)
+    } else{
+      fnl_tbl <- first_visits_country %>%
+        filter(Date >= input$date_first_visit[1]
+               & Date <= input$date_first_visit[2]
+               & Country %in% selected_country_f())
+    }
+    return (fnl_tbl)
+  })
+  first_visits_country_prop_dt <- reactive({
+    if (input$cntr_sort_f %in% c("us_f", "custom_f")){
+      fnl_tbl <- first_visits_country_prop %>%
+        rbind(first_visits_us_prop) %>%
+        filter(Date >= input$date_first_visit[1]
+               & Date <= input$date_first_visit[2]
+               & Country %in% selected_country_f()) %>%
+        arrange(Date, Country)
+    } else{
+      fnl_tbl <- first_visits_country_prop %>%
+        filter(Date >= input$date_first_visit[1]
+               & Date <= input$date_first_visit[2]
+               & Country %in% selected_country_f())
+    }
+    return (fnl_tbl)
+  })
+  observeEvent(input$action_select_f, {
+    cntr_reactive$selected_metric_f <- switch(input$action_select_f,
+                                              nact_f = "No Action",
+                                              olv_f = "Other Languages",
+                                              oproj_f = "Other Projects",
+                                              prln_f = "Primary Links",
+                                              search_f = "Search",
+                                              secln_f = "Secondary Links"
+    )
+  })
+  selected_country_f <- reactive({
+    all_country_temp<- first_visits_country %>%
+      filter(first_visits_country$Date >= input$date_first_visit[1]
+             & first_visits_country$Date <= input$date_first_visit[2]) %>%
+      
select_(.dots=c("Country",paste0("`",cntr_reactive$selected_metric_f,"`"))) %>%
+      group_by(Country) %>%
+      summarize_(value=paste0("sum(`",cntr_reactive$selected_metric_f,"`)")) 
%>%
+      arrange(value, Country)
+    result <- switch(input$cntr_sort_f,
+                     top10_f = {tail(all_country_temp, 10)$Country},
+                     bottom50_f = {head(all_country_temp, 50)$Country},
+                     us_f = unique(first_visits_us$Country),
+                     all_f = unique(first_visits_country$Country),
+                     all_nus_f = 
unique(first_visits_country$Country)[!grepl("United States", 
unique(first_visits_country$Country))],
+                     custom_f = input$cntr_f
+    )
+    return(result)
+  })
+  observeEvent(input$cntr_sort_f, {
+    toggleClass("cntr_f_legend", "small", length(selected_country_f())>7 & 
input$cntr_combine_f==F)
+    toggleClass("cntr_f_legend", "large", length(selected_country_f())<=7 | 
input$cntr_combine_f)
+    if (input$cntr_sort_f %in% c("bottom50_f","all_f","all_nus_f")) {
+      updateCheckboxInput(session, "cntr_combine_f", value = TRUE)
+    } else {
+      updateCheckboxInput(session, "cntr_combine_f", value = FALSE)
+    }
+  })
+  output$first_visit_country_dygraph <- renderDygraph({
+    if (input$cntr_combine_f == T){
+      data4dygraph <- {
+        if(input$prop_f) first_visits_country_prop_dt() else 
first_visits_country_dt()
+      } %>%
+        
select_(.dots=c("Date","Country",paste0("`",cntr_reactive$selected_metric_f,"`")))
 %>%
+        group_by(Date) %>%
+        summarize_(value=paste0("sum(`",cntr_reactive$selected_metric_f,"`)")) 
%>%
+        rename(date=Date) %>%
+        fill_out(start_date = input$date_first_visit[1], end_date = 
input$date_first_visit[2])
+      names(data4dygraph)[2] <- 
paste0(isolate(cntr_reactive$selected_metric_f))
+    } else{
+      if (length(selected_country_f())>1){
+        data4dygraph <- {
+          if(input$prop_f) first_visits_country_prop_dt() else 
first_visits_country_dt()
+        } %>%
+          
select_(.dots=c("Date","Country",paste0("`",cntr_reactive$selected_metric_f,"`")))
 %>%
+          tidyr::spread_(., key_col="Country", 
value_col=cntr_reactive$selected_metric_f, fill=0) %>%
+          rename(date=Date) %>%
+          fill_out(start_date = input$date_first_visit[1], end_date = 
input$date_first_visit[2])
+      } else{
+        data4dygraph <- {
+          if(input$prop_f) first_visits_country_prop_dt() else 
first_visits_country_dt()
+        } %>%
+          select_(.dots=c("Date", 
paste0("`",cntr_reactive$selected_metric_f,"`"))) %>%
+          rename(date=Date) %>%
+          fill_out(start_date = input$date_first_visit[1], end_date = 
input$date_first_visit[2])
+        names(data4dygraph)[2] <- paste0(isolate(selected_country_f()))
+      }
+    }
+    data4dygraph[is.na(data4dygraph)] <- 0
+    data4dygraph %>%
+    {
+      tryCatch(polloi::smoother(., smooth_level = 
polloi::smooth_switch(input$smoothing_global, input$smoothing_cntr_f)),
+               error = function(e) {
+                 stop("Cannot apply spline smoothing on one or more of the 
selected countries.")
+               }, finally = NULL)
+    } %>%
+      polloi::make_dygraph(xlab = "Date",
+                           ylab = ifelse(input$prop_f, paste0("Proportion of 
", cntr_reactive$selected_metric_f, " (%)"), cntr_reactive$selected_metric_f),
+                           title = paste0(ifelse(input$prop_f, "Out of all 
countries, the proportion of clicks to ", "The number of clicks to "), 
cntr_reactive$selected_metric_f, " from ", ifelse(input$cntr_sort_f %in% 
c("all_f","all_nus_f"), ifelse(input$cntr_sort_f=="all_f","All Countries","All 
Countries but U.S."), paste0(selected_country_f(), collapse=", ")), " at first 
visit")) %>%
+      dyRangeSelector(fillColor = "gray",
+                      strokeColor = "white",
+                      retainDateWindow = TRUE) %>%
+      dyOptions(strokeWidth = 3, labelsKMB = TRUE, drawPoints = FALSE, 
pointSize = 3, includeZero = TRUE,
+                titleHeight = 60, logscale = input$cntr_logscale_f) %>%
+      dyAxis("x", rangePad = 8) %>%
+      dyLegend(width = 400, labelsDiv = "cntr_f_legend", show = "always", 
showZeroValues = FALSE)  %>%
+      dyCSS(css = "www/inverse.css") %>%
+      dyEvent(as.Date("2016-09-13"), "Schema Switch", labelLoc = "bottom", 
color = "black")
+  })
+  output$first_visit_pie_pl <- renderHighchart({
+    data4pie <- first_visits_country_dt() %>%
+      group_by(Region) %>%
+      
mutate_(region_total=paste0("sum(`",cntr_reactive$selected_metric_f,"`)")) %>%
+      group_by(Region, Country) %>%
+      
mutate_(country_total=paste0("sum(`",cntr_reactive$selected_metric_f,"`)")) %>%
+      select(Region, Country, country_total, region_total) %>%
+      unique() %>% ungroup() %>% arrange(Region, Country)
+    data4pie_us <- first_visits_us %>%
+      filter(first_visits_us$Date >= input$date_first_visit[1]
+             & first_visits_us$Date <= input$date_first_visit[2]) %>%
+      group_by(Country) %>%
+      
summarise_(us_total=paste0("sum(`",cntr_reactive$selected_metric_f,"`)")) %>% 
ungroup()
+    hc <- highchart() %>%
+      hc_chart(type = "pie", plotBackgroundColor=NULL, plotBorderWidth=NULL, 
plotShadow=F) %>%
+      hc_title(text = paste0("Number of ", cntr_reactive$selected_metric_f, " 
by Country"),
+               style = list(color = "#ECF0F5")) %>%
+      hc_tooltip(pointFormat = '{point.y} ({point.percentage:.1f}%)') %>%
+      hc_plotOptions(
+        pie = list(
+          shadow = FALSE,
+          center = c("50%", "50%")
+        )
+      ) %>%
+      hc_add_series(data = data4pie %>% select(name=Region, y=region_total) %>%
+                      mutate(drilldown=tolower(name)) %>% unique() %>% 
list_parse(),
+                    size = '60%',
+                    name = "All Continents",
+                    dataLabels = list(distance = -60,
+                                      color = 'black',
+                                      formatter = JS("function () {
+                                                     return this.percentage > 
5 ? this.point.name : null;
+  }"))
+                   ) %>%
+      hc_add_series(data = data4pie %>% select(name=Country, y=country_total) 
%>%
+                      mutate(drilldown=ifelse(name=="United States","united 
states", NA)) %>% unique() %>% list_parse(),
+                    name = "All Countries", size = '100%', innerSize = "60%") 
%>%
+      hc_drilldown(
+        allowPointDrilldown = TRUE,
+        series = data4pie %>% mutate(id=tolower(Region)) %>%
+          select(name=Country, y=country_total, id) %>%
+          unique() %>%
+          split(.$id) %>%
+          lapply(function(x){
+            list(id= as.character(unique(x[,3])),
+                 data=list_parse(x[,-3]))
+          }) %>%
+          magrittr::set_names(NULL) %>%
+          append(list(list(
+            id="united states",
+            data=list_parse2(data4pie_us)
+          )))
+      )
+    hc
+  })
+  output$first_visits_by_country_tbl <- DT::renderDataTable(
+    {if(input$prop_f) first_visits_country_prop_dt() else 
first_visits_country_dt()},
+    options = list(lengthMenu = list(c(15, 30, 60), c('15', '30', '60')), 
pageLength = 15)
+  )
+
+
+  last_action_country_dt <- reactive({
+    if (input$cntr_sort_l %in% c("us_l", "custom_l")){
+      fnl_tbl <- last_action_country %>%
+        rbind(last_action_us) %>%
+        filter(Date >= input$date_last_action[1]
+               & Date <= input$date_last_action[2]
+               & Country %in% selected_country_l()) %>%
+        arrange(Date, Country)
+    } else{
+      fnl_tbl <- last_action_country %>%
+        filter(Date >= input$date_last_action[1]
+               & Date <= input$date_last_action[2]
+               & Country %in% selected_country_l())
+    }
+    return (fnl_tbl)
+  })
+  last_action_country_prop_dt <- reactive({
+    if (input$cntr_sort_l %in% c("us_l", "custom_l")){
+      fnl_tbl <- last_action_country_prop %>%
+        rbind(last_action_us_prop) %>%
+        filter(Date >= input$date_last_action[1]
+               & Date <= input$date_last_action[2]
+               & Country %in% selected_country_l()) %>%
+        arrange(Date, Country)
+    } else{
+      fnl_tbl <- last_action_country_prop %>%
+        filter(Date >= input$date_last_action[1]
+               & Date <= input$date_last_action[2]
+               & Country %in% selected_country_l())
+    }
+    return (fnl_tbl)
+  })
+  observeEvent(input$action_select_l, {
+    cntr_reactive$selected_metric_l <- switch(input$action_select_l,
+                                              nact_l = "No Action",
+                                              olv_l = "Other Languages",
+                                              oproj_l = "Other Projects",
+                                              prln_l = "Primary Links",
+                                              search_l = "Search",
+                                              secln_l = "Secondary Links"
+    )
+  })
+  selected_country_l <- reactive({
+    all_country_temp<- last_action_country %>%
+      filter(last_action_country$Date >= input$date_last_action[1]
+             & last_action_country$Date <= input$date_last_action[2]) %>%
+      
select_(.dots=c("Country",paste0("`",cntr_reactive$selected_metric_l,"`"))) %>%
+      group_by(Country) %>%
+      summarize_(value=paste0("sum(`",cntr_reactive$selected_metric_l,"`)")) 
%>%
+      arrange(value, Country)
+    result <- switch(input$cntr_sort_l,
+                     top10_l = {tail(all_country_temp, 10)$Country},
+                     bottom50_l = {head(all_country_temp, 50)$Country},
+                     us_l = unique(last_action_us$Country),
+                     all_l = unique(last_action_country$Country),
+                     all_nus_l = 
unique(last_action_country$Country)[!grepl("United States", 
unique(last_action_country$Country))],
+                     custom_l = input$cntr_l
+    )
+    return(result)
+  })
+  observeEvent(input$cntr_sort_l, {
+    toggleClass("cntr_l_legend", "small", length(selected_country_l())>7 & 
input$cntr_combine_l==F)
+    toggleClass("cntr_l_legend", "large", length(selected_country_l())<=7 | 
input$cntr_combine_l)
+    if (input$cntr_sort_l %in% c("bottom50_l","all_l","all_nus_l")) {
+      updateCheckboxInput(session, "cntr_combine_l", value = TRUE)
+    } else {
+      updateCheckboxInput(session, "cntr_combine_l", value = FALSE)
+    }
+  })
+  output$last_action_dygraph <- renderDygraph({
+    if (input$cntr_combine_l == T){
+      data4dygraph <- {
+        if(input$prop_l) last_action_country_prop_dt() else 
last_action_country_dt()
+      } %>%
+        
select_(.dots=c("Date","Country",paste0("`",cntr_reactive$selected_metric_l,"`")))
 %>%
+        group_by(Date) %>%
+        summarize_(value=paste0("sum(`",cntr_reactive$selected_metric_l,"`)")) 
%>%
+        rename(date=Date) %>%
+        fill_out(start_date = input$date_last_action[1], end_date = 
input$date_last_action[2])
+      names(data4dygraph)[2] <- 
paste0(isolate(cntr_reactive$selected_metric_l))
+    } else{
+      if (length(selected_country_l())>1){
+        data4dygraph <- {
+          if(input$prop_l) last_action_country_prop_dt() else 
last_action_country_dt()
+        } %>%
+          
select_(.dots=c("Date","Country",paste0("`",cntr_reactive$selected_metric_l,"`")))
 %>%
+          tidyr::spread_(., key_col="Country", 
value_col=cntr_reactive$selected_metric_l, fill=0) %>%
+          rename(date=Date) %>%
+          fill_out(start_date = input$date_last_action[1], end_date = 
input$date_last_action[2])
+      } else{
+        data4dygraph <- {
+          if(input$prop_l) last_action_country_prop_dt() else 
last_action_country_dt()
+        } %>%
+          select_(.dots=c("Date", 
paste0("`",cntr_reactive$selected_metric_l,"`"))) %>%
+          rename(date=Date) %>%
+          fill_out(start_date = input$date_last_action[1], end_date = 
input$date_last_action[2])
+        names(data4dygraph)[2] <- paste0(isolate(selected_country_l()))
+      }
+    }
+    data4dygraph[is.na(data4dygraph)] <- 0
+    data4dygraph %>%
+    {
+      tryCatch(polloi::smoother(., smooth_level = 
polloi::smooth_switch(input$smoothing_global, input$smoothing_cntr_l)),
+               error = function(e) {
+                 stop("Cannot apply spline smoothing on one or more of the 
selected countries.")
+               }, finally = NULL)
+    } %>%
+      polloi::make_dygraph(xlab = "Date",
+                           ylab = ifelse(input$prop_l, paste0("Proportion of 
", cntr_reactive$selected_metric_l, " (%)"), cntr_reactive$selected_metric_l),
+                           title = paste0(ifelse(input$prop_l, "Out of all 
countries, the proportion of sessions whose last action is ", "The number of 
sessions whose last action is "), cntr_reactive$selected_metric_l, " from ", 
ifelse(input$cntr_sort_l %in% c("all_l","all_nus_l"), 
ifelse(input$cntr_sort_l=="all_l","All Countries","All Countries but U.S."), 
paste0(selected_country_l(), collapse=", ")))) %>%
+      dyRangeSelector(fillColor = "gray",
+                      strokeColor = "white",
+                      retainDateWindow = TRUE) %>%
+      dyOptions(strokeWidth = 3, labelsKMB = TRUE, drawPoints = FALSE, 
pointSize = 3, includeZero = TRUE,
+                titleHeight = 60, logscale = input$cntr_logscale_l) %>%
+      dyAxis("x", rangePad = 8) %>%
+      dyLegend(width = 400, labelsDiv = "cntr_l_legend", show = "always", 
showZeroValues = FALSE)  %>%
+      dyCSS(css = "www/inverse.css") %>%
+      dyEvent(as.Date("2016-09-13"), "Schema Switch", labelLoc = "bottom", 
color = "black")
+  })
+  output$last_action_pie_pl <- renderHighchart({
+    data4pie <- last_action_country_dt() %>%
+      group_by(Region) %>%
+      
mutate_(region_total=paste0("sum(`",cntr_reactive$selected_metric_l,"`)")) %>%
+      group_by(Region, Country) %>%
+      
mutate_(country_total=paste0("sum(`",cntr_reactive$selected_metric_l,"`)")) %>%
+      select(Region, Country, country_total, region_total) %>%
+      unique() %>% ungroup() %>% arrange(Region, Country)
+    data4pie_us <- last_action_us %>%
+      filter(last_action_us$Date >= input$date_last_action[1]
+             & last_action_us$Date <= input$date_last_action[2]) %>%
+      group_by(Country) %>%
+      
summarise_(us_total=paste0("sum(`",cntr_reactive$selected_metric_l,"`)")) %>% 
ungroup()
+    hc <- highchart() %>%
+      hc_chart(type = "pie", plotBackgroundColor=NULL, plotBorderWidth=NULL, 
plotShadow=F) %>%
+      hc_title(text = paste0("Number of ", cntr_reactive$selected_metric_l, " 
by Country"),
+               style = list(color = "#ECF0F5")) %>%
+      hc_tooltip(pointFormat = '{point.y} ({point.percentage:.1f}%)') %>%
+      hc_plotOptions(
+        pie = list(
+          shadow = FALSE,
+          center = c("50%", "50%")
+        )
+      ) %>%
+      hc_add_series(data = data4pie %>% select(name=Region, y=region_total) %>%
+                      mutate(drilldown=tolower(name)) %>% unique() %>% 
list_parse(),
+                    size = '60%',
+                    name = "All Continents",
+                    dataLabels = list(distance = -60,
+                                      color = 'black',
+                                      formatter = JS("function () {
+                                                     return this.percentage > 
5 ? this.point.name : null;
+  }"))
+                   ) %>%
+      hc_add_series(data = data4pie %>% select(name=Country, y=country_total) 
%>%
+                      mutate(drilldown=ifelse(name=="United States","united 
states", NA)) %>% unique() %>% list_parse(),
+                    name = "All Countries", size = '100%', innerSize = "60%") 
%>%
+      hc_drilldown(
+        allowPointDrilldown = TRUE,
+        series = data4pie %>% mutate(id=tolower(Region)) %>%
+          select(name=Country, y=country_total, id) %>%
+          unique() %>%
+          split(.$id) %>%
+          lapply(function(x){
+            list(id= as.character(unique(x[,3])),
+                 data=list_parse(x[,-3]))
+          }) %>%
+          magrittr::set_names(NULL) %>%
+          append(list(list(
+            id="united states",
+            data=list_parse2(data4pie_us)
+          )))
+      )
+    hc
+  })
+  output$last_action_by_country_tbl <- DT::renderDataTable(
+    {if(input$prop_l) last_action_country_prop_dt() else 
last_action_country_dt()},
+    options = list(lengthMenu = list(c(15, 30, 60), c('15', '30', '60')), 
pageLength = 15)
+  )
+
+
+  most_common_country_dt <- reactive({
+    if (input$cntr_sort_m %in% c("us_m", "custom_m")){
+      fnl_tbl <- most_common_country %>%
+        rbind(most_common_us) %>%
+        filter(Date >= input$date_most_common[1]
+               & Date <= input$date_most_common[2]
+               & Country %in% selected_country_m()) %>%
+        arrange(Date, Country)
+    } else{
+      fnl_tbl <- most_common_country %>%
+        filter(Date >= input$date_most_common[1]
+               & Date <= input$date_most_common[2]
+               & Country %in% selected_country_m())
+    }
+    return (fnl_tbl)
+  })
+  most_common_country_prop_dt <- reactive({
+    if (input$cntr_sort_m %in% c("us_m", "custom_m")){
+      fnl_tbl <- most_common_country_prop %>%
+        rbind(most_common_us_prop) %>%
+        filter(Date >= input$date_most_common[1]
+               & Date <= input$date_most_common[2]
+               & Country %in% selected_country_m()) %>%
+        arrange(Date, Country)
+    } else{
+      fnl_tbl <- most_common_country_prop %>%
+        filter(Date >= input$date_most_common[1]
+               & Date <= input$date_most_common[2]
+               & Country %in% selected_country_m())
+    }
+    return (fnl_tbl)
+  })
+  observeEvent(input$action_select_m, {
+    cntr_reactive$selected_metric_m <- switch(input$action_select_m,
+                                              olv_m = "Other Languages",
+                                              oproj_m = "Other Projects",
+                                              prln_m = "Primary Links",
+                                              search_m = "Search",
+                                              secln_m = "Secondary Links"
+    )
+  })
+  selected_country_m <- reactive({
+    all_country_temp<- most_common_country %>%
+      filter(most_common_country$Date >= input$date_most_common[1]
+             & most_common_country$Date <= input$date_most_common[2]) %>%
+      
select_(.dots=c("Country",paste0("`",cntr_reactive$selected_metric_m,"`"))) %>%
+      group_by(Country) %>%
+      summarize_(value=paste0("sum(`",cntr_reactive$selected_metric_m,"`)")) 
%>%
+      arrange(value, Country)
+    result <- switch(input$cntr_sort_m,
+                     top10_m = {tail(all_country_temp, 10)$Country},
+                     bottom50_m = {head(all_country_temp, 50)$Country},
+                     us_m = unique(most_common_us$Country),
+                     all_m = unique(most_common_country$Country),
+                     all_nus_m = 
unique(most_common_country$Country)[!grepl("United States", 
unique(most_common_country$Country))],
+                     custom_m = input$cntr_m
+    )
+    return(result)
+  })
+  observeEvent(input$cntr_sort_m, {
+    toggleClass("cntr_m_legend", "small", length(selected_country_m())>7 & 
input$cntr_combine_m==F)
+    toggleClass("cntr_m_legend", "large", length(selected_country_m())<=7 | 
input$cntr_combine_m)
+    if (input$cntr_sort_m %in% c("bottom50_m","all_m","all_nus_m")) {
+      updateCheckboxInput(session, "cntr_combine_m", value = TRUE)
+    } else {
+      updateCheckboxInput(session, "cntr_combine_m", value = FALSE)
+    }
+  })
+  output$most_common_country_dygraph <- renderDygraph({
+    if (input$cntr_combine_m == T){
+      data4dygraph <- {
+        if(input$prop_m) most_common_country_prop_dt() else 
most_common_country_dt()
+      } %>%
+        
select_(.dots=c("Date","Country",paste0("`",cntr_reactive$selected_metric_m,"`")))
 %>%
+        group_by(Date) %>%
+        summarize_(value=paste0("sum(`",cntr_reactive$selected_metric_m,"`)")) 
%>%
+        rename(date=Date) %>%
+        fill_out(start_date = input$date_most_common[1], end_date = 
input$date_most_common[2])
+      names(data4dygraph)[2] <- 
paste0(isolate(cntr_reactive$selected_metric_m))
+    } else{
+      if (length(selected_country_m())>1){
+        data4dygraph <- {
+          if(input$prop_m) most_common_country_prop_dt() else 
most_common_country_dt()
+        } %>%
+          
select_(.dots=c("Date","Country",paste0("`",cntr_reactive$selected_metric_m,"`")))
 %>%
+          tidyr::spread_(., key_col="Country", 
value_col=cntr_reactive$selected_metric_m, fill=0) %>%
+          rename(date=Date) %>%
+          fill_out(start_date = input$date_most_common[1], end_date = 
input$date_most_common[2])
+      } else{
+        data4dygraph <- {
+          if(input$prop_m) most_common_country_prop_dt() else 
most_common_country_dt()
+        } %>%
+          select_(.dots=c("Date", 
paste0("`",cntr_reactive$selected_metric_m,"`"))) %>%
+          rename(date=Date) %>%
+          fill_out(start_date = input$date_most_common[1], end_date = 
input$date_most_common[2])
+        names(data4dygraph)[2] <- paste0(isolate(selected_country_m()))
+      }
+    }
+    data4dygraph[is.na(data4dygraph)] <- 0
+    data4dygraph %>%
+    {
+      tryCatch(polloi::smoother(., smooth_level = 
polloi::smooth_switch(input$smoothing_global, input$smoothing_cntr_m)),
+               error = function(e) {
+                 stop("Cannot apply spline smoothing on one or more of the 
selected countries.")
+               }, finally = NULL)
+    } %>%
+      polloi::make_dygraph(xlab = "Date",
+                           ylab = ifelse(input$prop_m, paste0("Proportion of 
", cntr_reactive$selected_metric_m, " (%)"), cntr_reactive$selected_metric_m),
+                           title = paste0(ifelse(input$prop_m, "Out of all 
countries, the proportion of visits whose most common section clicked on is ", 
"The number of visits whose most common section clicked on is "), 
cntr_reactive$selected_metric_m, " from ", ifelse(input$cntr_sort_m %in% 
c("all_m","all_nus_m"), ifelse(input$cntr_sort_m=="all_m","All Countries","All 
Countries but U.S."), paste0(selected_country_m(), collapse=", ")))) %>%
+      dyRangeSelector(fillColor = "gray",
+                      strokeColor = "white",
+                      retainDateWindow = TRUE) %>%
+      dyOptions(strokeWidth = 3, labelsKMB = TRUE, drawPoints = FALSE, 
pointSize = 3, includeZero = TRUE,
+                titleHeight = 60, logscale = input$cntr_logscale_m) %>%
+      dyAxis("x", rangePad = 8) %>%
+      dyLegend(width = 400, labelsDiv = "cntr_m_legend", show = "always", 
showZeroValues = FALSE)  %>%
+      dyCSS(css = "www/inverse.css") %>%
+      dyEvent(as.Date("2016-09-13"), "Schema Switch", labelLoc = "bottom", 
color = "black")
+  })
+  output$most_common_pie_pl <- renderHighchart({
+    data4pie <- most_common_country_dt() %>%
+      group_by(Region) %>%
+      
mutate_(region_total=paste0("sum(`",cntr_reactive$selected_metric_m,"`)")) %>%
+      group_by(Region, Country) %>%
+      
mutate_(country_total=paste0("sum(`",cntr_reactive$selected_metric_m,"`)")) %>%
+      select(Region, Country, country_total, region_total) %>%
+      unique() %>% ungroup() %>% arrange(Region, Country)
+    data4pie_us <- most_common_us %>%
+      filter(most_common_us$Date >= input$date_most_common[1]
+             & most_common_us$Date <= input$date_most_common[2]) %>%
+      group_by(Country) %>%
+      
summarise_(us_total=paste0("sum(`",cntr_reactive$selected_metric_m,"`)")) %>% 
ungroup()
+    hc <- highchart() %>%
+      hc_chart(type = "pie", plotBackgroundColor=NULL, plotBorderWidth=NULL, 
plotShadow=F) %>%
+      hc_title(text = paste0("Number of ", cntr_reactive$selected_metric_m, " 
by Country"),
+               style = list(color = "#ECF0F5")) %>%
+      hc_tooltip(pointFormat = '{point.y} ({point.percentage:.1f}%)') %>%
+      hc_plotOptions(
+        pie = list(
+          shadow = FALSE,
+          center = c("50%", "50%")
+        )
+      ) %>%
+      hc_add_series(data = data4pie %>% select(name=Region, y=region_total) %>%
+                      mutate(drilldown=tolower(name)) %>% unique() %>% 
list_parse(),
+                    size = '60%',
+                    name = "All Continents",
+                    dataLabels = list(distance = -60,
+                                      color = 'black',
+                                      formatter = JS("function () {
+                                                     return this.percentage > 
5 ? this.point.name : null;
+  }"))
+                 ) %>%
+      hc_add_series(data = data4pie %>% select(name=Country, y=country_total) 
%>%
+                      mutate(drilldown=ifelse(name=="United States","united 
states", NA)) %>% unique() %>% list_parse(),
+                    name = "All Countries", size = '100%', innerSize = "60%") 
%>%
+      hc_drilldown(
+        allowPointDrilldown = TRUE,
+        series = data4pie %>% mutate(id=tolower(Region)) %>%
+          select(name=Country, y=country_total, id) %>%
+          unique() %>%
+          split(.$id) %>%
+          lapply(function(x){
+            list(id= as.character(unique(x[,3])),
+                 data=list_parse(x[,-3]))
+          }) %>%
+          magrittr::set_names(NULL) %>%
+          append(list(list(
+            id="united states",
+            data=list_parse2(data4pie_us)
+          )))
+      )
+    hc
+  })
+  output$most_common_by_country_tbl <- DT::renderDataTable(
+    {if(input$prop_m) most_common_country_prop_dt() else 
most_common_country_dt()},
+    options = list(lengthMenu = list(c(15, 30, 60), c('15', '30', '60')), 
pageLength = 15)
+  )
 })
diff --git a/tab_documentation/first_visit_geo.md 
b/tab_documentation/first_visit_geo.md
new file mode 100644
index 0000000..9ea61b2
--- /dev/null
+++ b/tab_documentation/first_visit_geo.md
@@ -0,0 +1,53 @@
+Breakdown of Wikipedia Portal Visitors' First Visit by Geography
+=======
+
+This dashboard shows the geographical breakdown at first visit action and 
ignores any subsequent visits the user may have made. The actions are:
+
+1. **No action**: Not taking any action on the page.
+2. **Other projects**: clicking the links to Wiktionary, Wikisource, etc. on 
the bottom of the page.
+3. **Primary links**: the prominent links to languages around the globe.
+4. **Search**: using the Search box and button.
+5. **Other languages**: using the "Other languages" links near the bottom of 
the page which take you to a list of Wikipedias.
+6. **Secondary links**: the less-prominent plaintext links to languages.
+
+The values are expressed as numbers (sampled at a 1:200 rate) and as 
percentages - so if a country has the value "61.3" for search action, then in 
first visits, 61.3% of all searches are done by users from this country.
+
+Notes
+------
+
+* This dashboard is aim to expand the "other" countries display in the current 
[Portal Dashboard](http://discovery.wmflabs.org/portal/#country_breakdown) to 
reflect more data that we're interested in seeing. See 
[T138107](https://phabricator.wikimedia.org/T138107) for more details.
+* Broadly-speaking, it's worth noting that (as with all data based on 
JavaScript logging) the code that gathers this information requires a certain 
amount of browser capabilities to function. It's probably not going to work on 
10 year old Nokia brick phones, and so the data will be biased against users 
using those kinds of devices.
+* On 28 June 2016 our Event Logging system started recording a finer view of 
U.S. traffic, breaking it down into 5 regions:
+    - **Northeast Region**
+        - New England Division: Connecticut, Maine, Massachusetts, New 
Hampshire, Rhode Island and Vermont
+        - Middle Atlantic Division: New Jersey, New York and Pennsylvania
+    - **Midwest Region**
+        - East North Central Division: Illinois, Indiana, Michigan, Ohio and 
Wisconsin
+        - West North Central Division: Iowa, Kansas, Minnesota, Missouri, 
Nebraska, North Dakota and South Dakota
+    - **South Region**
+        - South Atlantic Division: Delaware, District of Columbia, Florida, 
Georgia, Maryland, North Carolina, South Carolina, Virginia and West Virginia
+        - East South Central Division: Alabama, Kentucky, Mississippi and 
Tennessee
+        - West South Central Division: Arkansas, Louisiana, Oklahoma and Texas
+    - **West Region**
+        - Mountain Division: Arizona, Colorado, Idaho, Montana, Nevada, New 
Mexico, Utah and Wyoming
+    - **Pacific Region**
+        - Alaska, California, Hawaii, Oregon and Washington
+    - **Other**
+        - American Samoa, Guam, Northern Mariana Islands, Puerto Rico and 
Virgin Islands, U.S.
+
+Outages and inaccuracies
+------
+
+- 13 September 2016: Added event logging of language-switching, causing some 
events to flow into old table and some events to flow into the new table. See 
[T143149](https://phabricator.wikimedia.org/T143149) for more details.
+
+Questions, bug reports, and feature suggestions
+------
+For technical, non-bug questions, [email 
Mikhail](mailto:mpo...@wikimedia.org?subject=Dashboard%20Question). If you 
experience a bug or notice something wrong or have a suggestion, [open a ticket 
in 
Phabricator](https://phabricator.wikimedia.org/maniphest/task/create/?projects=Discovery)
 in the Discovery board or [email 
Deb](mailto:d...@wikimedia.org?subject=Dashboard%20Question).
+
+<hr style="border-color: gray;">
+<p style="font-size: small; color: gray;">
+  <strong>Link to this dashboard:</strong>
+  <a href="http://discovery.wmflabs.org/portal/#first_visits_by_country";>
+    http://discovery.wmflabs.org/portal/#first_visits_by_country
+  </a>
+</p>
diff --git a/tab_documentation/last_action_geo.md 
b/tab_documentation/last_action_geo.md
new file mode 100644
index 0000000..e9697c0
--- /dev/null
+++ b/tab_documentation/last_action_geo.md
@@ -0,0 +1,53 @@
+Breakdown of Users' Last Actions on the Wikipedia Portal by Geography
+=======
+
+This dashboard breaks users' last actions at each session down by geography. 
The actions are:
+
+1. **No action**: Not taking any action on the page.
+2. **Other projects**: clicking the links to Wiktionary, Wikisource, etc. on 
the bottom of the page.
+3. **Primary links**: the prominent links to languages around the globe.
+4. **Search**: using the Search box and button.
+5. **Other languages**: using the "Other languages" links near the bottom of 
the page which take you to a list of Wikipedias.
+6. **Secondary links**: the less-prominent plaintext links to languages.
+
+The values are expressed as numbers (sampled at a 1:200 rate) and as 
percentages - so if a country has the value "61.3" for search action, then 
61.3% of all searches are done as last actions by users from this country.
+
+Notes
+------
+
+* This dashboard is aim to expand the "other" countries display in the current 
[Portal Dashboard](http://discovery.wmflabs.org/portal/#country_breakdown) to 
reflect more data that we're interested in seeing. See 
[T138107](https://phabricator.wikimedia.org/T138107) for more details.
+* Broadly-speaking, it's worth noting that (as with all data based on 
JavaScript logging) the code that gathers this information requires a certain 
amount of browser capabilities to function. It's probably not going to work on 
10 year old Nokia brick phones, and so the data will be biased against users 
using those kinds of devices.
+* On 28 June 2016 our Event Logging system started recording a finer view of 
U.S. traffic, breaking it down into 5 regions:
+    - **Northeast Region**
+        - New England Division: Connecticut, Maine, Massachusetts, New 
Hampshire, Rhode Island and Vermont
+        - Middle Atlantic Division: New Jersey, New York and Pennsylvania
+    - **Midwest Region**
+        - East North Central Division: Illinois, Indiana, Michigan, Ohio and 
Wisconsin
+        - West North Central Division: Iowa, Kansas, Minnesota, Missouri, 
Nebraska, North Dakota and South Dakota
+    - **South Region**
+        - South Atlantic Division: Delaware, District of Columbia, Florida, 
Georgia, Maryland, North Carolina, South Carolina, Virginia and West Virginia
+        - East South Central Division: Alabama, Kentucky, Mississippi and 
Tennessee
+        - West South Central Division: Arkansas, Louisiana, Oklahoma and Texas
+    - **West Region**
+        - Mountain Division: Arizona, Colorado, Idaho, Montana, Nevada, New 
Mexico, Utah and Wyoming
+    - **Pacific Region**
+        - Alaska, California, Hawaii, Oregon and Washington
+    - **Other**
+        - American Samoa, Guam, Northern Mariana Islands, Puerto Rico and 
Virgin Islands, U.S.
+
+Outages and inaccuracies
+------
+
+- 13 September 2016: Added event logging of language-switching, causing some 
events to flow into old table and some events to flow into the new table. See 
[T143149](https://phabricator.wikimedia.org/T143149) for more details.
+
+Questions, bug reports, and feature suggestions
+------
+For technical, non-bug questions, [email 
Mikhail](mailto:mpo...@wikimedia.org?subject=Dashboard%20Question). If you 
experience a bug or notice something wrong or have a suggestion, [open a ticket 
in 
Phabricator](https://phabricator.wikimedia.org/maniphest/task/create/?projects=Discovery)
 in the Discovery board or [email 
Deb](mailto:d...@wikimedia.org?subject=Dashboard%20Question).
+
+<hr style="border-color: gray;">
+<p style="font-size: small; color: gray;">
+  <strong>Link to this dashboard:</strong>
+  <a href="http://discovery.wmflabs.org/portal/#last_action_by_country";>
+    http://discovery.wmflabs.org/portal/#last_action_by_country
+  </a>
+</p>
diff --git a/tab_documentation/most_common_geo.md 
b/tab_documentation/most_common_geo.md
new file mode 100644
index 0000000..8a7c4be
--- /dev/null
+++ b/tab_documentation/most_common_geo.md
@@ -0,0 +1,53 @@
+Breakdown of Most Common Section Clicked on per Visit on the Wikipedia Portal 
by Geography
+=======
+
+This dashboard shows the most common clicked section per visit. Our analyses 
showed that any one session can have multiple visits and each visit can have 
multiple clicks associated with it. This shows us (for each section) the 
number/proportion of visits in which that section was the most commonly clicked 
on. The sections are:
+
+1. **No action**: Not taking any action on the page.
+2. **Other projects**: clicking the links to Wiktionary, Wikisource, etc. on 
the bottom of the page.
+3. **Primary links**: the prominent links to languages around the globe.
+4. **Search**: using the Search box and button.
+5. **Other languages**: using the "Other languages" links near the bottom of 
the page which take you to a list of Wikipedias.
+6. **Secondary links**: the less-prominent plaintext links to languages.
+
+The values are expressed as numbers (sampled at a 1:200 rate) and as 
percentages - so if a country has the value "61.3" for search section, then 
61.3% of all visits (in which search section was the most commonly clicked on) 
are from users in this country.
+
+Notes
+------
+
+* This dashboard is aim to expand the "other" countries display in the current 
[Portal Dashboard](http://discovery.wmflabs.org/portal/#country_breakdown) to 
reflect more data that we're interested in seeing. See 
[T138107](https://phabricator.wikimedia.org/T138107) for more details.
+* Broadly-speaking, it's worth noting that (as with all data based on 
JavaScript logging) the code that gathers this information requires a certain 
amount of browser capabilities to function. It's probably not going to work on 
10 year old Nokia brick phones, and so the data will be biased against users 
using those kinds of devices.
+* On 28 June 2016 our Event Logging system started recording a finer view of 
U.S. traffic, breaking it down into 5 regions:
+    - **Northeast Region**
+        - New England Division: Connecticut, Maine, Massachusetts, New 
Hampshire, Rhode Island and Vermont
+        - Middle Atlantic Division: New Jersey, New York and Pennsylvania
+    - **Midwest Region**
+        - East North Central Division: Illinois, Indiana, Michigan, Ohio and 
Wisconsin
+        - West North Central Division: Iowa, Kansas, Minnesota, Missouri, 
Nebraska, North Dakota and South Dakota
+    - **South Region**
+        - South Atlantic Division: Delaware, District of Columbia, Florida, 
Georgia, Maryland, North Carolina, South Carolina, Virginia and West Virginia
+        - East South Central Division: Alabama, Kentucky, Mississippi and 
Tennessee
+        - West South Central Division: Arkansas, Louisiana, Oklahoma and Texas
+    - **West Region**
+        - Mountain Division: Arizona, Colorado, Idaho, Montana, Nevada, New 
Mexico, Utah and Wyoming
+    - **Pacific Region**
+        - Alaska, California, Hawaii, Oregon and Washington
+    - **Other**
+        - American Samoa, Guam, Northern Mariana Islands, Puerto Rico and 
Virgin Islands, U.S.
+
+Outages and inaccuracies
+------
+
+- 13 September 2016: Added event logging of language-switching, causing some 
events to flow into old table and some events to flow into the new table. See 
[T143149](https://phabricator.wikimedia.org/T143149) for more details.
+
+Questions, bug reports, and feature suggestions
+------
+For technical, non-bug questions, [email 
Mikhail](mailto:mpo...@wikimedia.org?subject=Dashboard%20Question). If you 
experience a bug or notice something wrong or have a suggestion, [open a ticket 
in 
Phabricator](https://phabricator.wikimedia.org/maniphest/task/create/?projects=Discovery)
 in the Discovery board or [email 
Deb](mailto:d...@wikimedia.org?subject=Dashboard%20Question).
+
+<hr style="border-color: gray;">
+<p style="font-size: small; color: gray;">
+  <strong>Link to this dashboard:</strong>
+  <a href="http://discovery.wmflabs.org/portal/#most_common_by_country";>
+    http://discovery.wmflabs.org/portal/#most_common_by_country
+  </a>
+</p>
diff --git a/tab_documentation/traffic_ctr_geo.md 
b/tab_documentation/traffic_ctr_geo.md
new file mode 100644
index 0000000..fc4232d
--- /dev/null
+++ b/tab_documentation/traffic_ctr_geo.md
@@ -0,0 +1,46 @@
+Wikimedia Portal Traffic and Clickthrough Rate by Geography
+=======
+
+This dashboard shows where portal users come from each day, displaying the 
number of events, number of visits and the number of sessions sampled according 
to our [WikipediaPortal 
schema](https://meta.wikimedia.org/wiki/Schema:WikipediaPortal) at a 1:200 
rate. This dashboard also tracks the proportion of events/visits/sessions to 
the portal that end in a click through to one of our projects - via search or 
via one of the links. This is expressed as a percentage - so a value of "39.4" 
means that 39.4% of visits end in a clickthrough.
+
+Notes
+------
+
+* This dashboard is aim to expand the "other" countries display in the current 
[Portal Dashboard](http://discovery.wmflabs.org/portal/#country_breakdown) to 
reflect more data that we're interested in seeing. See 
[T138107](https://phabricator.wikimedia.org/T138107) for more details.
+* Broadly-speaking, it's worth noting that (as with all data based on 
JavaScript logging) the code that gathers this information requires a certain 
amount of browser capabilities to function. It's probably not going to work on 
10 year old Nokia brick phones, and so the data will be biased against users 
using those kinds of devices.
+* On 28 June 2016 our Event Logging system started recording a finer view of 
U.S. traffic, breaking it down into 5 regions:
+    - **Northeast Region**
+        - New England Division: Connecticut, Maine, Massachusetts, New 
Hampshire, Rhode Island and Vermont
+        - Middle Atlantic Division: New Jersey, New York and Pennsylvania
+    - **Midwest Region**
+        - East North Central Division: Illinois, Indiana, Michigan, Ohio and 
Wisconsin
+        - West North Central Division: Iowa, Kansas, Minnesota, Missouri, 
Nebraska, North Dakota and South Dakota
+    - **South Region**
+        - South Atlantic Division: Delaware, District of Columbia, Florida, 
Georgia, Maryland, North Carolina, South Carolina, Virginia and West Virginia
+        - East South Central Division: Alabama, Kentucky, Mississippi and 
Tennessee
+        - West South Central Division: Arkansas, Louisiana, Oklahoma and Texas
+    - **West Region**
+        - Mountain Division: Arizona, Colorado, Idaho, Montana, Nevada, New 
Mexico, Utah and Wyoming
+    - **Pacific Region**
+        - Alaska, California, Hawaii, Oregon and Washington
+    - **Other**
+        - American Samoa, Guam, Northern Mariana Islands, Puerto Rico and 
Virgin Islands, U.S.
+* The overall clickthrough rate presented here is the proportion of click 
events over the total number of landing events. The clickthrough rate per visit 
is the proportion of landing events that end in at least one click through. The 
clickthrough rate per session is the proportion of sessions that end in at 
least one click through. By design, a single session is at least 15 minutes but 
can last indefinitely. **For example**: a single session can last for hours if 
the "user" (e.g. a computer in a public library) keeps returning to the page 
before the 15 minute expiration time, thus resetting the timer; and if that 
single session has 1000 page visits and 500 clicks, then all 1500 of those 
events will be used in the calculation of the overall clickthrough rate. 
+
+Outages and inaccuracies
+------
+
+- 13 September 2016: Added event logging of language-switching, causing some 
events to flow into old table and some events to flow into the new table. See 
[T143149](https://phabricator.wikimedia.org/T143149) for more details.
+
+Questions, bug reports, and feature suggestions
+------
+For technical, non-bug questions, [email 
Mikhail](mailto:mpo...@wikimedia.org?subject=Dashboard%20Question). If you 
experience a bug or notice something wrong or have a suggestion, [open a ticket 
in 
Phabricator](https://phabricator.wikimedia.org/maniphest/task/create/?projects=Discovery)
 in the Discovery board or [email 
Deb](mailto:d...@wikimedia.org?subject=Dashboard%20Question).
+
+<hr style="border-color: gray;">
+<p style="font-size: small; color: gray;">
+  <strong>Link to this dashboard:</strong>
+  <a href="http://discovery.wmflabs.org/portal/#all_country";>
+    http://discovery.wmflabs.org/portal/#all_country
+  </a>
+</p>
+
diff --git a/ui.R b/ui.R
index 711a2aa..e257520 100644
--- a/ui.R
+++ b/ui.R
@@ -1,6 +1,9 @@
 library(shiny)
 library(shinydashboard)
 library(dygraphs)
+library(highcharter)
+
+all_country_data <- polloi::read_dataset("portal/all_country_data.tsv", 
col_types = "Dcididid")
 
 function(request) {
   dashboardPage(
@@ -34,6 +37,12 @@
                            menuSubItem(text = "Overall Referral Traffic", 
tabName = "referrals_summary"),
                            menuSubItem(text = "Breakdown by Search Engine", 
tabName = "search_engines"),
                            icon = icon("external-link")),
+                  menuItem("Geographical Breakdowns",
+                           menuSubItem(text = "Traffic and Clickthrough Rate", 
tabName = "all_country"),
+                           menuSubItem(text = "First Visit", tabName = 
"first_visits_by_country"),
+                           menuSubItem(text = "Last Action", tabName = 
"last_action_by_country"),
+                           menuSubItem(text = "Most Common Section", tabName = 
"most_common_by_country"),
+                           icon = icon("globe", lib = "glyphicon")),
                   menuItem(text = "Global Settings",
                            selectInput(inputId = "smoothing_global", label = 
"Smoothing", selectize = TRUE, selected = "day",
                                        choices = c("No Smoothing" = "day", 
"Weekly Median" = "week", "Monthly Median" = "month", "Splines" = "gam")),
@@ -178,20 +187,196 @@
                    width = 3),
             column(
               uiOutput("lv_languages_container", style = "width: 80%; display: 
inline-block; float: left;",
-                       title = "Type to find a language. Use backspace key to 
remove a selected language. Up to 12 languages can be selected at the same 
time."),
+                      title = "Type to find a language. Use backspace key to 
remove a selected language. Up to 12 languages can be selected at the same 
time."),
               div(icon("question-circle", class = "fa-lg"),
                   title = "Type to find a language. Use backspace key to 
remove a selected language.",
                   style="width: 12.5%; margin-left: 2.5%; padding-top: 30px; 
height: 34px; display: inline-block; float: left;"),
               width = 3),
             column(
-              conditionalPanel("input.lv_response === 'clicks' & 
input.lv_languages.length > 1 & input.lv_sort != 'top10'", HTML("<label class = 
\"control-label\" style = \"margin-bottom:-30px;\">Aggregation</label>"), 
checkboxInput("lv_combine", "Combine languages", FALSE)),
-              conditionalPanel("input.lv_response === 'clicks' & 
input.lv_languages.length < 2", radioButtons("lv_type", "Type", list("Counts" = 
"count", "Proportions" = "prop"), inline = TRUE)),
+              conditionalPanel("input.lv_response === 'clicks' && 
input.lv_languages.length > 1 && input.lv_sort != 'top10'", HTML("<label class 
= \"control-label\" style = \"margin-bottom:-30px;\">Aggregation</label>"), 
checkboxInput("lv_combine", "Combine languages", FALSE)),
+              conditionalPanel("input.lv_response === 'clicks' && 
input.lv_languages.length < 2", radioButtons("lv_type", "Type", list("Counts" = 
"count", "Proportions" = "prop"), inline = TRUE)),
               conditionalPanel("input.lv_type === 'count'", HTML("<label class 
= \"control-label\" style = \"margin-bottom:-30px;\">Scale</label>"), 
checkboxInput("lv_logscale", "Use Log scale", FALSE)),
               width = 2)
           ),
           dygraphOutput("lv_dygraph"),
           div(id = "lv_legend", class = "large", style = "text-align: center; 
padding: 15px 10px 0 10px;"),
           includeMarkdown("tab_documentation/languages_visited.md")
+        ),
+        tabItem(
+          tabName = "all_country",
+          fluidRow(
+            shiny::column(width=3,
+                          dateRangeInput("date_all_country", "Date Range",
+                                         start = min(all_country_data$date),
+                                         end = max(all_country_data$date),
+                                         startview = "month",
+                                         separator = " to "),
+                          checkboxInput("prop_a", "Use Proportion in All 
Countries", FALSE)),
+            shiny::column(width=2,
+                          selectInput("traffic_select", label = "Metrics",
+                                      choices = list("Number of Events" = 
'events',
+                                                     "Number of Visits" = 
'visits', "Number of Sessions" = 'sessions',
+                                                     "Overall Clickthrough 
Rate"='ctr_all',
+                                                     "Clickthrough Rate Per 
Visit"='ctr_vst',
+                                                     "Clickthrough Rate Per 
Session"='ctr_ses'),
+                                      selected = 'events')),
+            shiny::column(width = 2,
+                          selectInput("cntr_sort_a", "Group of Countries",
+                                      list("Top 10" = "top10_a",
+                                           "Bottom 50" = "bottom50_a",
+                                           "United States" = "us_a",
+                                           "All" = "all_a",
+                                           "All but US" = "all_nus_a",
+                                           "Custom" = "custom_a"),
+                                      "all_a")),
+            shiny::column(width = 3,
+                          conditionalPanel("input.cntr_sort_a == 'custom_a'",
+                                           selectizeInput("cntr_a", 
"Countries", choices=sort(c(unique(all_country_data$country), "United 
States")), selected=c("United Kingdom","Germany","India","Canada","U.S. 
(South)"), multiple = TRUE))),
+            shiny::column(width = 2,
+                          conditionalPanel("!(input.cntr_a.length<=1 & 
input.cntr_sort_a == 'custom_a')", checkboxInput("cntr_combine_a", "Combine 
Countries", FALSE)),
+                          conditionalPanel("(input.traffic_select=='events' || 
input.traffic_select=='visits' || input.traffic_select=='sessions') && 
!input.prop_a", checkboxInput("cntr_logscale_a", "Use Log scale", FALSE)),
+                          polloi::smooth_select("smoothing_cntr_a"))
+          ),
+          fluidRow(
+            highchartOutput("traffic_pie_pl",height = "500px"),
+            br(),
+            dygraphOutput("all_country_dygraph"),
+            div(id = "cntr_a_legend", class = "large", style = "text-align: 
center; padding: 15px 10px 0 10px;"),
+            DT::dataTableOutput("all_country_tbl")
+          ),
+          includeMarkdown("./tab_documentation/traffic_ctr_geo.md")
+        ),
+        tabItem(
+          tabName = "first_visits_by_country",
+          fluidRow(
+            shiny::column(width=3,
+                          dateRangeInput("date_first_visit", "Date Range",
+                                         start = min(all_country_data$date),
+                                         end = max(all_country_data$date),
+                                         startview = "month",
+                                         separator = " to "),
+                          checkboxInput("prop_f", "Use Proportion in All 
Countries", FALSE)),
+            shiny::column(width=2,
+                          selectInput("action_select_f", label = "Actions",
+                                      choices = list("No Action" = 'nact_f',
+                                                     "Other Languages" = 
'olv_f', "Other Projects" = 'oproj_f',
+                                                     "Primary Links"='prln_f',
+                                                     "Search"='search_f',
+                                                     "Secondary 
Links"='secln_f'),
+                                      selected = 'search_f')),
+            shiny::column(width = 2,
+                          selectInput("cntr_sort_f", "Group of Countries",
+                                      list("Top 10" = "top10_f",
+                                           "Bottom 50" = "bottom50_f",
+                                           "United States" = "us_f",
+                                           "All" = "all_f",
+                                           "All but US" = "all_nus_f",
+                                           "Custom" = "custom_f"),
+                                      "all_f")),
+            shiny::column(width = 3,
+                          conditionalPanel("input.cntr_sort_f == 'custom_f'",
+                                           selectizeInput("cntr_f", 
"Countries", choices=sort(c(unique(all_country_data$country),"United States")), 
selected=c("United Kingdom","Germany","India","Canada","U.S. (South)"), 
multiple = TRUE))),
+            shiny::column(width = 2,
+                          conditionalPanel("!(input.cntr_f.length<=1 & 
input.cntr_sort_f == 'custom_f')", checkboxInput("cntr_combine_f", "Combine 
Countries", FALSE)),
+                          conditionalPanel("!input.prop_f", 
checkboxInput("cntr_logscale_f", "Use Log scale", FALSE)),
+                          polloi::smooth_select("smoothing_cntr_f"))
+          ),
+          fluidRow(
+            highchartOutput("first_visit_pie_pl",height = "500px"),
+            br(),
+            dygraphOutput("first_visit_country_dygraph"),
+            div(id = "cntr_f_legend", class = "large", style = "text-align: 
center; padding: 15px 10px 0 10px;"),
+            DT::dataTableOutput("first_visits_by_country_tbl")
+          ),
+          includeMarkdown("./tab_documentation/first_visit_geo.md")
+        ),
+        tabItem(
+          tabName = "last_action_by_country",
+          fluidRow(
+            shiny::column(width=3,
+                          dateRangeInput("date_last_action", "Date Range",
+                                         start = min(all_country_data$date),
+                                         end = max(all_country_data$date),
+                                         startview = "month",
+                                         separator = " to "),
+                          checkboxInput("prop_l", "Use Proportion in All 
Countries", FALSE)),
+            shiny::column(width=2,
+                          selectInput("action_select_l", label = "Actions",
+                                      choices = list("No Action" = 'nact_l',
+                                                     "Other Languages" = 
'olv_l', "Other Projects" = 'oproj_l',
+                                                     "Primary Links"='prln_l',
+                                                     "Search"='search_l',
+                                                     "Secondary 
Links"='secln_l'),
+                                      selected = 'search_l')),
+            shiny::column(width = 2,
+                          selectInput("cntr_sort_l", "Group of Countries",
+                                      list("Top 10" = "top10_l",
+                                           "Bottom 50" = "bottom50_l",
+                                           "United States" = "us_l",
+                                           "All" = "all_l",
+                                           "All but US" = "all_nus_l",
+                                           "Custom" = "custom_l"),
+                                      "all_l")),
+            shiny::column(width = 3,
+                          conditionalPanel("input.cntr_sort_l == 'custom_l'",
+                                           selectizeInput("cntr_l", 
"Countries", choices=sort(c(unique(all_country_data$country), "United 
States")), selected=c("United Kingdom","Germany","India","Canada","U.S. 
(South)"), multiple = TRUE))),
+            shiny::column(width = 2,
+                          conditionalPanel("!(input.cntr_l.length<=1 & 
input.cntr_sort_l == 'custom_l')", checkboxInput("cntr_combine_l", "Combine 
Countries", FALSE)),
+                          conditionalPanel("!input.prop_l", 
checkboxInput("cntr_logscale_l", "Use Log scale", FALSE)),
+                          polloi::smooth_select("smoothing_cntr_l"))
+          ),
+          fluidRow(
+            highchartOutput("last_action_pie_pl",height = "500px"),
+            br(),
+            dygraphOutput("last_action_dygraph"),
+            div(id = "cntr_l_legend", class = "large", style = "text-align: 
center; padding: 15px 10px 0 10px;"),
+            DT::dataTableOutput("last_action_by_country_tbl")
+          ),
+          includeMarkdown("./tab_documentation/last_action_geo.md")
+        ),
+        tabItem(
+          tabName = "most_common_by_country",
+          fluidRow(
+            shiny::column(width=3,
+                          dateRangeInput("date_most_common", "Date Range",
+                                         start = min(all_country_data$date),
+                                         end = max(all_country_data$date),
+                                         startview = "month",
+                                         separator = " to "),
+                          checkboxInput("prop_m", "Use Proportion in All 
Countries", FALSE)),
+            shiny::column(width=2,
+                          selectInput("action_select_m", label = "Actions",
+                                      choices = list("Other Languages" = 
'olv_m',
+                                                     "Other Projects" = 
'oproj_m',
+                                                     "Primary Links"='prln_m',
+                                                     "Search"='search_m',
+                                                     "Secondary 
Links"='secln_m'),
+                                      selected = 'search_m')),
+            shiny::column(width = 2,
+                          selectInput("cntr_sort_m", "Group of Countries",
+                                      list("Top 10" = "top10_m",
+                                           "Bottom 50" = "bottom50_m",
+                                           "United States" = "us_m",
+                                           "All" = "all_m",
+                                           "All but US" = "all_nus_m",
+                                           "Custom" = "custom_m"),
+                                      "all_m")),
+            shiny::column(width = 3,
+                          conditionalPanel("input.cntr_sort_m == 'custom_m'",
+                                           selectizeInput("cntr_m", 
"Countries", choices=sort(c(unique(all_country_data$country), "United 
States")), selected=c("United Kingdom","Germany","India","Canada","U.S. 
(South)"), multiple = TRUE))),
+            shiny::column(width = 2,
+                          conditionalPanel("!(input.cntr_m.length <= 1 & 
input.cntr_sort_m == 'custom_m')", checkboxInput("cntr_combine_m", "Combine 
Countries", FALSE)),
+                          conditionalPanel("!input.prop_m", 
checkboxInput("cntr_logscale_m", "Use Log scale", FALSE)),
+                          polloi::smooth_select("smoothing_cntr_m"))
+          ),
+          fluidRow(
+            highchartOutput("most_common_pie_pl",height = "500px"),
+            br(),
+            dygraphOutput("most_common_country_dygraph"),
+            div(id = "cntr_m_legend", class = "large", style = "text-align: 
center; padding: 15px 10px 0 10px;"),
+            DT::dataTableOutput("most_common_by_country_tbl")
+          ),
+          includeMarkdown("./tab_documentation/most_common_geo.md")
         )
       )
     ),
diff --git a/www/stylesheet.css b/www/stylesheet.css
index 2758750..9777549 100644
--- a/www/stylesheet.css
+++ b/www/stylesheet.css
@@ -57,7 +57,7 @@
   width: 90%;
 }
 
-#lv_dygraph .dygraph-title {
+#lv_dygraph .dygraph-title, #all_country_dygraph .dygraph-title, 
#first_visit_country_dygraph .dygraph-title, #last_action_dygraph 
.dygraph-title, #most_common_country_dygraph .dygraph-title {
   font-weight: normal;
   font-size: x-small;
 }
@@ -69,3 +69,116 @@
 .small {
   font-size: small;
 }
+
+/*Inverse DataTables*/
+
+input[type="search"], textarea {
+    background-color : #222d32;
+}
+select, button {
+    background-color : #222d32;
+}
+
+#all_country_tbl .dataTables_wrapper .dataTables_paginate .paginate_button,
+#first_visits_by_country_tbl .dataTables_wrapper .dataTables_paginate 
.paginate_button,
+#last_action_by_country_tbl .dataTables_wrapper .dataTables_paginate 
.paginate_button,
+#most_common_by_country_tbl .dataTables_wrapper .dataTables_paginate 
.paginate_button {
+    color: #ECF0F5 !important;
+}
+
+#all_country_tbl .dataTables_wrapper .dataTables_paginate 
.paginate_button.current, #all_country_tbl .dataTables_wrapper 
.dataTables_paginate .paginate_button.current:hover,
+#first_visits_by_country_tbl .dataTables_wrapper .dataTables_paginate 
.paginate_button.current, #first_visits_by_country_tbl .dataTables_wrapper 
.dataTables_paginate .paginate_button.current:hover,
+#last_action_by_country_tbl .dataTables_wrapper .dataTables_paginate 
.paginate_button.current, #last_action_by_country_tbl .dataTables_wrapper 
.dataTables_paginate .paginate_button.current:hover,
+#most_common_by_country_tbl .dataTables_wrapper .dataTables_paginate 
.paginate_button.current, #most_common_by_country_tbl .dataTables_wrapper 
.dataTables_paginate .paginate_button.current:hover {
+    color: #ecf0f5 !important;
+    border: 1px solid black;
+    background-color: #5c7987;
+    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, 
#5c7987), color-stop(100%, #222d32));
+    /* Chrome,Safari4+ */
+    background: -webkit-linear-gradient(top, #5c7987 0%, #222d32 100%);
+    /* Chrome10+,Safari5.1+ */
+    background: -moz-linear-gradient(top, #5c7987 0%, #222d32 100%);
+    /* FF3.6+ */
+    background: -ms-linear-gradient(top, #5c7987 0%, #222d32 100%);
+    /* IE10+ */
+    background: -o-linear-gradient(top, #5c7987 0%, #222d32 100%);
+    /* Opera 11.10+ */
+    background: linear-gradient(to bottom, #5c7987 0%, #222d32 100%);
+/* W3C */ }
+
+#all_country_tbl .dataTables_wrapper .dataTables_paginate 
.paginate_button:hover,
+#first_visits_by_country_tbl .dataTables_wrapper .dataTables_paginate 
.paginate_button:hover,
+#last_action_by_country_tbl .dataTables_wrapper .dataTables_paginate 
.paginate_button:hover,
+#most_common_by_country_tbl .dataTables_wrapper .dataTables_paginate 
.paginate_button:hover {
+    color: white !important;
+    border: 1px solid #222d32;
+    background-color: #5c7987;
+    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, 
#5c7987), color-stop(100%, #222d32));
+    /* Chrome,Safari4+ */
+    background: -webkit-linear-gradient(top, #5c7987 0%, #222d32 100%);
+    /* Chrome10+,Safari5.1+ */
+    background: -moz-linear-gradient(top, #5c7987 0%, #222d32 100%);
+    /* FF3.6+ */
+    background: -ms-linear-gradient(top, #5c7987 0%, #222d32 100%);
+    /* IE10+ */
+    background: -o-linear-gradient(top, #5c7987 0%, #222d32 100%);
+    /* Opera 11.10+ */
+    background: linear-gradient(to bottom, #5c7987 0%, #222d32 100%);
+/* W3C */ }
+
+#all_country_tbl .dataTables_wrapper .dataTables_length,
+#all_country_tbl .dataTables_wrapper .dataTables_filter,
+#all_country_tbl .dataTables_wrapper .dataTables_info,
+#all_country_tbl .dataTables_wrapper .dataTables_processing,
+#all_country_tbl .dataTables_wrapper .dataTables_paginate,
+#first_visits_by_country_tbl .dataTables_wrapper .dataTables_length,
+#first_visits_by_country_tbl .dataTables_wrapper .dataTables_filter,
+#first_visits_by_country_tbl .dataTables_wrapper .dataTables_info,
+#first_visits_by_country_tbl .dataTables_wrapper .dataTables_processing,
+#first_visits_by_country_tbl .dataTables_wrapper .dataTables_paginate,
+#last_action_by_country_tbl .dataTables_wrapper .dataTables_length,
+#last_action_by_country_tbl .dataTables_wrapper .dataTables_filter,
+#last_action_by_country_tbl .dataTables_wrapper .dataTables_info,
+#last_action_by_country_tbl .dataTables_wrapper .dataTables_processing,
+#last_action_by_country_tbl .dataTables_wrapper .dataTables_paginate,
+#most_common_by_country_tbl .dataTables_wrapper .dataTables_length,
+#most_common_by_country_tbl .dataTables_wrapper .dataTables_filter,
+#most_common_by_country_tbl .dataTables_wrapper .dataTables_info,
+#most_common_by_country_tbl .dataTables_wrapper .dataTables_processing,
+#most_common_by_country_tbl .dataTables_wrapper .dataTables_paginate {
+    color: #ecf0f5;
+}
+
+#all_country_tbl .dataTable tbody tr,
+#first_visits_by_country_tbl .dataTable tbody tr,
+#last_action_by_country_tbl .dataTable tbody tr,
+#most_common_by_country_tbl .dataTable tbody tr {
+    background-color: #222d32; }
+#all_country_tbl .dataTable thead th,
+#all_country_tbl .dataTable thead td,
+#first_visits_by_country_tbl .dataTable thead th,
+#first_visits_by_country_tbl .dataTable thead td,
+#last_action_by_country_tbl .dataTable thead th,
+#last_action_by_country_tbl .dataTable thead td,
+#most_common_by_country_tbl .dataTable thead th,
+#most_common_by_country_tbl .dataTable thead td {
+    border-bottom: 1px solid #dddddd; }
+#all_country_tbl .dataTable tfoot th,
+#all_country_tbl .dataTable tfoot td,
+#first_visits_by_country_tbl .dataTable tfoot th,
+#first_visits_by_country_tbl .dataTable tfoot td,
+#last_action_by_country_tbl .dataTable tfoot th,
+#last_action_by_country_tbl .dataTable tfoot td,
+#most_common_by_country_tbl .dataTable tfoot th,
+#most_common_by_country_tbl .dataTable tfoot td {
+    border-top: 1px solid #dddddd; }
+#all_country_tbl .dataTable.no-footer,
+#first_visits_by_country_tbl .dataTable.no-footer,
+#last_action_by_country_tbl .dataTable.no-footer,
+#most_common_by_country_tbl .dataTable.no-footer {
+    border-bottom: 1px solid #dddddd; }
+#all_country_tbl .dataTables_wrapper.no-footer .dataTables_scrollBody,
+#first_visits_by_country_tbl .dataTables_wrapper.no-footer 
.dataTables_scrollBody,
+#last_action_by_country_tbl .dataTables_wrapper.no-footer 
.dataTables_scrollBody,
+#most_common_by_country_tbl .dataTables_wrapper.no-footer 
.dataTables_scrollBody {
+    border-bottom: 1px solid #dddddd; }

-- 
To view, visit https://gerrit.wikimedia.org/r/327139
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: I7a4d371f40fbb4ec822008ae3866870688621154
Gerrit-PatchSet: 1
Gerrit-Project: wikimedia/discovery/prince
Gerrit-Branch: master
Gerrit-Owner: Chelsyx <c...@wikimedia.org>

_______________________________________________
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits

Reply via email to