text:
Q: What reshaping problems can melt/cast not solve in a single step? reshape2 is a package which allows an powerful array of data transformations, through its two-part melt/cast approach.  However, like all tools it embeds assumptions which limit the cases it can handle.
What data reshaping problem can reshape2 not handle in its current form?
The ideal answer will include:

*

*A description of the type of use cases where this data shape is typically found

*Sample data

*Code to accomplish the transformation (ideally using as much of the transformation with reshape2 as possible)

Example
"Wide" data is common in panel applications.
melt.wide <- function(data, id.vars, new.names, sep=".", variable.name="variable", ... ) {
  # Guess number of variables currently wide
  colnames(data) <- sub( paste0(sep,"$"), "",  colnames(data) )
  wide.vars <- colnames(data)[grep( sep, colnames(data) )]
  n.wide <- str_count( wide.vars, sep )
  stopifnot(length(new.names)==unique(n.wide))
  # Melt
  data.melt <- melt(data,id.vars=id.vars,measure.vars=wide.vars,...)
  new <- stack.list(str_split(data.melt$variable,sep))
  colnames(new) <- c(variable.name,new.names)
  data.melt <- subset(data.melt,select=c(-variable))
  cbind(data.melt,new)
}

choice.vars <- colnames(res)[grep("_",colnames(res))]
melt.wide( subset(res,select=c("WorkerId",choice.vars)), id.vars="WorkerId", new.names=c("set","option"), sep="_")

The new function returns a melted object that can then be *cast.
Where the data is:
so <- structure(list(WorkerId = c(12L, 13L, 27L, 25L, 30L, 8L), pio_1_1 = structure(c(2L,
1L, 2L, 1L, 2L, 2L), .Label = c("No", "Yes"), class = "factor"),
    pio_1_2 = structure(c(1L, 2L, 2L, 2L, 1L, 1L), .Label = c("No",
    "Yes"), class = "factor"), pio_1_3 = structure(c(1L, 1L,
    1L, 1L, 2L, 1L), .Label = c("No", "Yes"), class = "factor"),
    pio_1_4 = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "No", class = "factor"),
    pio_2_1 = structure(c(1L, 2L, 2L, 1L, 1L, 2L), .Label = c("No",
    "Yes"), class = "factor"), pio_2_2 = structure(c(1L, 1L,
    1L, 2L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"),
    pio_2_3 = structure(c(2L, 2L, 2L, 2L, 2L, 1L), .Label = c("No",
    "Yes"), class = "factor"), pio_2_4 = structure(c(1L, 1L,
    1L, 1L, 1L, 1L), .Label = "No", class = "factor"), pio_3_1 = structure(c(2L,
    2L, 2L, 2L, 2L, 1L), .Label = c("No", "Yes"), class = "factor"),
    pio_3_2 = structure(c(2L, 1L, 1L, 1L, 2L, 1L), .Label = c("No",
    "Yes"), class = "factor"), pio_3_3 = structure(c(2L, 1L,
    2L, 1L, 1L, 2L), .Label = c("No", "Yes"), class = "factor"),
    pio_3_4 = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "No", class = "factor"),
    pio_4_1 = structure(c(2L, 1L, 2L, 2L, 1L, 2L), .Label = c("No",
    "Yes"), class = "factor"), pio_4_2 = structure(c(2L, 2L,
    2L, 1L, 2L, 1L), .Label = c("No", "Yes"), class = "factor"),
    pio_4_3 = structure(c(1L, 2L, 1L, 1L, 2L, 2L), .Label = c("No",
    "Yes"), class = "factor"), pio_4_4 = structure(c(1L, 1L,
    1L, 1L, 1L, 1L), .Label = "No", class = "factor"), caremgmt_1_1 = structure(c(2L,
    2L, 1L, 2L, 1L, 2L), .Label = c("No", "Yes"), class = "factor"),
    caremgmt_1_2 = structure(c(1L, 2L, 2L, 2L, 1L, 1L), .Label = c("No",
    "Yes"), class = "factor"), caremgmt_1_3 = structure(c(1L,
    1L, 1L, 1L, 2L, 1L), .Label = c("No", "Yes"), class = "factor"),
    caremgmt_1_4 = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "No", class = "factor"),
    caremgmt_2_1 = structure(c(2L, 2L, 2L, 2L, 2L, 2L), .Label = c("No",
    "Yes"), class = "factor"), caremgmt_2_2 = structure(c(1L,
    2L, 1L, 2L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"),
    caremgmt_2_3 = structure(c(2L, 1L, 2L, 1L, 1L, 1L), .Label = c("No",
    "Yes"), class = "factor"), caremgmt_2_4 = structure(c(1L,
    1L, 1L, 1L, 1L, 1L), .Label = "No", class = "factor"), caremgmt_3_1 = structure(c(2L,
    1L, 2L, 1L, 2L, 2L), .Label = c("No", "Yes"), class = "factor"),
    caremgmt_3_2 = structure(c(2L, 1L, 2L, 2L, 2L, 1L), .Label = c("No",
    "Yes"), class = "factor"), caremgmt_3_3 = structure(c(2L,
    2L, 2L, 2L, 2L, 2L), .Label = c("No", "Yes"), class = "factor"),
    caremgmt_3_4 = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "No", class = "factor"),
    caremgmt_4_1 = structure(c(1L, 1L, 2L, 1L, 2L, 1L), .Label = c("No",
    "Yes"), class = "factor"), caremgmt_4_2 = structure(c(2L,
    2L, 2L, 2L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"),
    caremgmt_4_3 = structure(c(1L, 1L, 1L, 1L, 1L, 2L), .Label = c("No",
    "Yes"), class = "factor"), caremgmt_4_4 = structure(c(1L,
    1L, 1L, 1L, 1L, 1L), .Label = "No", class = "factor"), prev_1_1 = structure(c(1L,
    1L, 2L, 1L, 2L, 2L), .Label = c("No", "Yes"), class = "factor"),
    prev_1_2 = structure(c(1L, 2L, 1L, 2L, 1L, 1L), .Label = c("No",
    "Yes"), class = "factor"), prev_1_3 = structure(c(2L, 1L,
    1L, 2L, 2L, 2L), .Label = c("No", "Yes"), class = "factor"),
    prev_1_4 = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "No", class = "factor"),
    prev_2_1 = structure(c(1L, 1L, 2L, 1L, 2L, 2L), .Label = c("No",
    "Yes"), class = "factor"), prev_2_2 = structure(c(2L, 2L,
    1L, 2L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"),
    prev_2_3 = structure(c(1L, 2L, 1L, 1L, 2L, 2L), .Label = c("No",
    "Yes"), class = "factor"), prev_2_4 = structure(c(1L, 1L,
    1L, 1L, 1L, 1L), .Label = "No", class = "factor"), prev_3_1 = structure(c(1L,
    2L, 1L, 1L, 2L, 1L), .Label = c("No", "Yes"), class = "factor"),
    prev_3_2 = structure(c(1L, 1L, 2L, 1L, 2L, 2L), .Label = c("No",
    "Yes"), class = "factor"), prev_3_3 = structure(c(2L, 2L,
    1L, 2L, 2L, 2L), .Label = c("No", "Yes"), class = "factor"),
    prev_3_4 = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "No", class = "factor"),
    prev_4_1 = structure(c(1L, 2L, 2L, 1L, 2L, 2L), .Label = c("No",
    "Yes"), class = "factor"), prev_4_2 = structure(c(1L, 1L,
    2L, 1L, 2L, 2L), .Label = c("No", "Yes"), class = "factor"),
    prev_4_3 = structure(c(1L, 1L, 1L, 2L, 2L, 1L), .Label = c("No",
    "Yes"), class = "factor"), prev_4_4 = structure(c(1L, 1L,
    1L, 1L, 1L, 1L), .Label = "No", class = "factor"), price_1_1 = structure(c(30L,
    12L, 1L, 16L, 28L, 17L), .Label = c("$2,500", "$2,504", "$2,507",
    "$2,509", "$2,512", "$2,513", "$2,515", "$2,526", "$2,547",
    "$2,548", "$2,578", "$2,588", "$2,594", "$2,605", "$2,607",
    "$2,617", "$2,618", "$2,622", "$2,635", "$2,649", "$2,670",
    "$2,672", "$2,679", "$2,681", "$2,698", "$2,704", "$2,721",
    "$2,782", "$2,851", "$2,884", "$2,919", "$2,925", "$2,935",
    "$3,022"), class = "factor"), price_1_2 = structure(c(1L,
    19L, 5L, 17L, 7L, 1L), .Label = c("$2,500", "$2,501", "$2,502",
    "$2,504", "$2,513", "$2,515", "$2,517", "$2,532", "$2,535",
    "$2,558", "$2,564", "$2,571", "$2,575", "$2,578", "$2,608",
    "$2,633", "$2,634", "$2,675", "$2,678", "$2,687", "$2,730",
    "$2,806", "$2,827", "$2,848", "$2,891", "$2,901", "$2,923",
    "$2,933", "$2,937", "$2,958", "$2,987"), class = "factor"),
    price_1_3 = structure(c(11L, 1L, 1L, 8L, 19L, 14L), .Label = c("$2,500",
    "$2,504", "$2,507", "$2,513", "$2,516", "$2,518", "$2,564",
    "$2,579", "$2,580", "$2,583", "$2,584", "$2,592", "$2,604",
    "$2,608", "$2,639", "$2,643", "$2,646", "$2,665", "$2,667",
    "$2,695", "$2,698", "$2,709", "$2,710", "$2,713", "$2,714",
    "$2,750", "$2,757", "$2,876", "$2,978", "$2,984", "$3,024",
    "$3,059"), class = "factor"), price_1_4 = structure(c(1L,
    1L, 1L, 1L, 1L, 1L), .Label = "$2,500", class = "factor"),
    price_2_1 = structure(c(27L, 32L, 19L, 22L, 4L, 26L), .Label = c("$2,500",
    "$2,504", "$2,505", "$2,510", "$2,511", "$2,512", "$2,515",
    "$2,517", "$2,518", "$2,529", "$2,533", "$2,537", "$2,551",
    "$2,553", "$2,574", "$2,593", "$2,600", "$2,605", "$2,608",
    "$2,612", "$2,613", "$2,618", "$2,639", "$2,657", "$2,714",
    "$2,730", "$2,747", "$2,764", "$2,771", "$2,773", "$2,813",
    "$2,859", "$2,901", "$3,019", "$3,037"), class = "factor"),
    price_2_2 = structure(c(12L, 2L, 1L, 27L, 1L, 7L), .Label = c("$2,500",
    "$2,502", "$2,510", "$2,514", "$2,515", "$2,516", "$2,517",
    "$2,518", "$2,520", "$2,521", "$2,523", "$2,536", "$2,544",
    "$2,575", "$2,583", "$2,592", "$2,602", "$2,624", "$2,644",
    "$2,652", "$2,662", "$2,677", "$2,720", "$2,761", "$2,765",
    "$2,770", "$2,772", "$2,835", "$2,873", "$2,911", "$2,950",
    "$2,962"), class = "factor"), price_2_3 = structure(c(32L,
    1L, 8L, 33L, 29L, 11L), .Label = c("$2,500", "$2,506", "$2,507",
    "$2,510", "$2,511", "$2,512", "$2,515", "$2,517", "$2,527",
    "$2,528", "$2,540", "$2,554", "$2,562", "$2,565", "$2,568",
    "$2,581", "$2,597", "$2,611", "$2,616", "$2,631", "$2,652",
    "$2,663", "$2,671", "$2,672", "$2,685", "$2,727", "$2,731",
    "$2,742", "$2,771", "$2,778", "$2,781", "$2,970", "$2,984",
    "$2,986", "$3,030"), class = "factor"), price_2_4 = structure(c(1L,
    1L, 1L, 1L, 1L, 1L), .Label = "$2,500", class = "factor"),
    price_3_1 = structure(c(24L, 1L, 28L, 7L, 18L, 21L), .Label = c("$2,500",
    "$2,501", "$2,503", "$2,505", "$2,509", "$2,512", "$2,535",
    "$2,537", "$2,542", "$2,553", "$2,556", "$2,560", "$2,561",
    "$2,574", "$2,584", "$2,618", "$2,624", "$2,629", "$2,637",
    "$2,664", "$2,761", "$2,840", "$2,875", "$2,883", "$2,891",
    "$2,933", "$2,953", "$2,978", "$3,039", "$3,043", "$3,067"
    ), class = "factor"), price_3_2 = structure(c(3L, 1L, 5L,
    19L, 25L, 9L), .Label = c("$2,500", "$2,501", "$2,503", "$2,504",
    "$2,512", "$2,517", "$2,540", "$2,543", "$2,546", "$2,560",
    "$2,567", "$2,573", "$2,586", "$2,592", "$2,594", "$2,603",
    "$2,604", "$2,606", "$2,628", "$2,633", "$2,635", "$2,693",
    "$2,696", "$2,714", "$2,734", "$2,739", "$2,770", "$2,791",
    "$2,797", "$2,936", "$2,967", "$3,021", "$3,024"), class = "factor"),
    price_3_3 = structure(c(26L, 7L, 5L, 32L, 10L, 24L), .Label = c("$2,500",
    "$2,501", "$2,502", "$2,505", "$2,506", "$2,507", "$2,508",
    "$2,509", "$2,512", "$2,515", "$2,519", "$2,547", "$2,556",
    "$2,574", "$2,587", "$2,592", "$2,608", "$2,616", "$2,621",
    "$2,635", "$2,638", "$2,667", "$2,671", "$2,688", "$2,694",
    "$2,700", "$2,717", "$2,759", "$2,809", "$2,864", "$2,891",
    "$2,912", "$3,011", "$3,012"), class = "factor"), price_3_4 = structure(c(1L,
    1L, 1L, 1L, 1L, 1L), .Label = "$2,500", class = "factor"),
    price_4_1 = structure(c(29L, 13L, 16L, 24L, 33L, 19L), .Label = c("$2,500",
    "$2,505", "$2,506", "$2,508", "$2,511", "$2,525", "$2,549",
    "$2,562", "$2,577", "$2,582", "$2,586", "$2,591", "$2,621",
    "$2,636", "$2,654", "$2,670", "$2,722", "$2,726", "$2,733",
    "$2,744", "$2,745", "$2,755", "$2,768", "$2,805", "$2,817",
    "$2,827", "$2,835", "$2,888", "$2,925", "$2,959", "$3,001",
    "$3,027", "$3,061", "$3,071"), class = "factor"), price_4_2 = structure(c(33L,
    31L, 21L, 16L, 25L, 13L), .Label = c("$2,500", "$2,502",
    "$2,503", "$2,505", "$2,506", "$2,511", "$2,513", "$2,516",
    "$2,529", "$2,539", "$2,547", "$2,554", "$2,557", "$2,562",
    "$2,567", "$2,579", "$2,581", "$2,583", "$2,585", "$2,591",
    "$2,612", "$2,629", "$2,640", "$2,670", "$2,695", "$2,726",
    "$2,737", "$2,788", "$2,790", "$2,798", "$2,852", "$3,031",
    "$3,063"), class = "factor"), price_4_3 = structure(c(4L,
    30L, 4L, 19L, 1L, 27L), .Label = c("$2,500", "$2,504", "$2,507",
    "$2,509", "$2,511", "$2,512", "$2,514", "$2,516", "$2,543",
    "$2,552", "$2,562", "$2,575", "$2,578", "$2,581", "$2,594",
    "$2,614", "$2,615", "$2,617", "$2,636", "$2,640", "$2,641",
    "$2,652", "$2,749", "$2,755", "$2,805", "$2,812", "$2,867",
    "$2,906", "$2,910", "$2,917", "$2,924", "$2,927", "$2,961",
    "$3,028", "$3,053", "$3,054"), class = "factor"), price_4_4 = structure(c(1L,
    1L, 1L, 1L, 1L, 1L), .Label = "$2,500", class = "factor"),
    plan_1_1 = structure(c(2L, 2L, 2L, 1L, 1L, 2L), .Label = c("",
    "X"), class = "factor"), plan_1_2 = structure(c(1L, 1L, 1L,
    2L, 1L, 1L), .Label = c("", "X"), class = "factor"), plan_1_3 = structure(c(1L,
    1L, 1L, 1L, 2L, 1L), .Label = c("", "X"), class = "factor"),
    plan_1_4 = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("",
    "X"), class = "factor"), plan_2_1 = structure(c(1L, 2L, 1L,
    2L, 2L, 2L), .Label = c("", "X"), class = "factor"), plan_2_2 = structure(c(1L,
    1L, 2L, 1L, 1L, 1L), .Label = c("", "X"), class = "factor"),
    plan_2_3 = structure(c(2L, 1L, 1L, 1L, 2L, 1L), .Label = c("",
    "X"), class = "factor"), plan_2_4 = structure(c(1L, 1L, 1L,
    1L, 1L, 1L), .Label = c("", "X"), class = "factor"), plan_3_1 = structure(c(1L,
    2L, 1L, 1L, 2L, 1L), .Label = c("", "X"), class = "factor"),
    plan_3_2 = structure(c(1L, 1L, 1L, 2L, 1L, 1L), .Label = c("",
    "X"), class = "factor"), plan_3_3 = structure(c(2L, 1L, 1L,
    1L, 1L, 2L), .Label = c("", "X"), class = "factor"), plan_3_4 = structure(c(1L,
    1L, 2L, 1L, 1L, 1L), .Label = c("", "X"), class = "factor"),
    plan_4_1 = structure(c(2L, 2L, 1L, 1L, 1L, 1L), .Label = c("",
    "X"), class = "factor"), plan_4_2 = structure(c(2L, 1L, 1L,
    2L, 1L, 1L), .Label = c("", "X"), class = "factor"), plan_4_3 = structure(c(1L,
    1L, 1L, 1L, 2L, 2L), .Label = c("", "X"), class = "factor"),
    plan_4_4 = structure(c(1L, 1L, 2L, 1L, 1L, 1L), .Label = c("",
    "X"), class = "factor")), .Names = c("WorkerId", "pio_1_1",
"pio_1_2", "pio_1_3", "pio_1_4", "pio_2_1", "pio_2_2", "pio_2_3",
"pio_2_4", "pio_3_1", "pio_3_2", "pio_3_3", "pio_3_4", "pio_4_1",
"pio_4_2", "pio_4_3", "pio_4_4", "caremgmt_1_1", "caremgmt_1_2",
"caremgmt_1_3", "caremgmt_1_4", "caremgmt_2_1", "caremgmt_2_2",
"caremgmt_2_3", "caremgmt_2_4", "caremgmt_3_1", "caremgmt_3_2",
"caremgmt_3_3", "caremgmt_3_4", "caremgmt_4_1", "caremgmt_4_2",
"caremgmt_4_3", "caremgmt_4_4", "prev_1_1", "prev_1_2", "prev_1_3",
"prev_1_4", "prev_2_1", "prev_2_2", "prev_2_3", "prev_2_4", "prev_3_1",
"prev_3_2", "prev_3_3", "prev_3_4", "prev_4_1", "prev_4_2", "prev_4_3",
"prev_4_4", "price_1_1", "price_1_2", "price_1_3", "price_1_4",
"price_2_1", "price_2_2", "price_2_3", "price_2_4", "price_3_1",
"price_3_2", "price_3_3", "price_3_4", "price_4_1", "price_4_2",
"price_4_3", "price_4_4", "plan_1_1", "plan_1_2", "plan_1_3",
"plan_1_4", "plan_2_1", "plan_2_2", "plan_2_3", "plan_2_4", "plan_3_1",
"plan_3_2", "plan_3_3", "plan_3_4", "plan_4_1", "plan_4_2", "plan_4_3",
"plan_4_4"), row.names = c(NA, 6L), class = "data.frame")

A: ... almost a year later...
This came to mind the other day, and I have a sneaking suspicion that it is what you tried to show in your example, but unfortunately, your example code doesn't run!
melt sometimes takes things a bit too far for me when making my data "long". Sometimes, even though it is not what would necessarily be called "tidy data", I prefer to have a "semi-long" data.frame. This is easily achieved using base R's reshape, but requires a few extra steps with the "reshape2" package, as demonstrated below:
Prerequisite: sample data.
set.seed(1)
myDf <- data.frame(
  ID.1 = sample(letters[1:5], 5, replace = TRUE),
  ID.2 = 1:5,
  V.1 = sample(10:14, 5, replace = TRUE),
  V.2 = sample(5:9, 5, replace = TRUE),
  V.3 = sample(3:14, 5, replace = TRUE),
  W.1 = sample(LETTERS, 5, replace = TRUE),
  W.2 = sample(LETTERS, 5, replace = TRUE),
  W.3 = sample(LETTERS, 5, replace = TRUE)
)
myDf
#   ID.1 ID.2 V.1 V.2 V.3 W.1 W.2 W.3
# 1    b    1  14   6   8   Y   K   M
# 2    b    2  14   5  11   F   A   P
# 3    c    3  13   8  14   Q   J   M
# 4    e    4  13   6   7   D   W   E
# 5    b    5  10   8  12   G   I   V

The "semi-long" output that I'm looking for. Easily achieved with base R's reshape.
reshape(myDf, direction = "long", idvar=1:2, varying = 3:ncol(myDf))
#       ID.1 ID.2 time  V W
# b.1.1    b    1    1 14 Y
# b.2.1    b    2    1 14 F
# c.3.1    c    3    1 13 Q
# e.4.1    e    4    1 13 D
# b.5.1    b    5    1 10 G
# b.1.2    b    1    2  6 K
# b.2.2    b    2    2  5 A
# c.3.2    c    3    2  8 J
# e.4.2    e    4    2  6 W
# b.5.2    b    5    2  8 I
# b.1.3    b    1    3  8 M
# b.2.3    b    2    3 11 P
# c.3.3    c    3    3 14 M
# e.4.3    e    4    3  7 E
# b.5.3    b    5    3 12 V

melt is great if you wanted the equivalent of stack, especially since stack discards all factor variables, which is frustrating when read.table and family defaults to stringsAsFactors = TRUE. (You can make it work, but you need to convert the relevant columns to character before you can use stack). But, it is not what I'm looking for, in particular because of how it has handled the "variable" column.
library(reshape2)
myDfL <- melt(myDf, id.vars=1:2)
head(myDfL)
#   ID.1 ID.2 variable value
# 1    b    1      V.1    14
# 2    b    2      V.1    14
# 3    c    3      V.1    13
# 4    e    4      V.1    13
# 5    b    5      V.1    10
# 6    b    1      V.2     6

To fix this, one needs to first split the "variable" column, and then use dcast to get the same format of output as you would get from reshape.
myDfL <- cbind(myDfL, colsplit(myDfL$variable, "\\.", names=c("var", "time")))
dcast(myDfL, ID.1 + ID.2 + time ~ var, value.var="value")
#    ID.1 ID.2 time  V W
# 1     b    1    1 14 Y
# 2     b    1    2  6 K
# 3     b    1    3  8 M
# 4     b    2    1 14 F
# 5     b    2    2  5 A
# 6     b    2    3 11 P
# 7     b    5    1 10 G
# 8     b    5    2  8 I
# 9     b    5    3 12 V
# 10    c    3    1 13 Q
# 11    c    3    2  8 J
# 12    c    3    3 14 M
# 13    e    4    1 13 D
# 14    e    4    2  6 W
# 15    e    4    3  7 E


text:
Q: C - Changing a string seems to change unrelated strings in the same way (CS50) Here is the code:
#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>

int main(int argc, string argv[])
{
    string key = argv[1];
    string keyupper = argv[1];
    string keylower = argv[1];

    if (argc != 2) //makes sure there is exactly 2 arguments (the program executable and the key)
    {
        printf("Please input a key.\n");
        return 1;
    }

    else if (strlen(key) != 26) //makes sure the key is exactly 26 letters
    {
        printf("Please make sure the key is 26 unique letters.\n");
        return 1;
    }

    for (int i = 0; i < 26; i++) //the loop to make the uppercase key
    {
        keyupper[i] = toupper(keyupper[i]);
    }

    for (int i = 0; i < 26; i++) //the loop to make the lowercase key
    {
        keylower[i] = tolower(keylower[i]);
    }

Essentially, I want to make a very basic encryption using a key entered while executing the program, it needs to contain 26 unique letters. I want to create two arrays, an uppercase and a lowercase one, to make everything else much easier for me, but when running this code, all keys become either uppercase or lowercase depending on which loop is created last (in this case, they all become lowercase). Even key gets changed to lowercase even though it's used only once as a declaration. Everything else works but this.
This is for the CS50 course so functions such as toupper() are included in libraries.
This is my first ever question so sorry if it's worded poorly. Thank you!

A: Code failed to copy the string contents
[Talking about string here, not the type string]
In C, a string is "... is a contiguous sequence of characters terminated by and including the first null character."
Code only copied pointers and not the string contents.
string key = argv[1];
string keyupper = argv[1];
string keylower = argv[1];

Comment discussion indicates OP now sees why code is in error.
Repaired code
//#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>

// Avoid naked magic numbers, instead define them
#define KEY_N 26

int main(int argc, string argv[]) {
    // Do not code argv[1] until after argc check
    // string key = argv[1];
    // string keyupper = argv[1];
    // string keylower = argv[1];

    if (argc != 2) {
        printf("Please input a key.\n");
        return 1;
    }

    char *key = argv[1];
    // else if (strlen(key) != 26)letters
    if (strlen(key) != KEY_N) {
        printf("Please make sure the key is 26 unique letters.\n");
        return 1;
    }

    char keyupper[KEY_N + 1];
    char keylower[KEY_N + 1];

    // for (int i = 0; i < 26; i++)
    for (size_t i = 0; i < KEY_N; i++) {
        // keyupper[i] = toupper(keyupper[i]);
        keyupper[i] = toupper((unsigned char) key[i]);
    }
    keyupper[KEY_N] = '\0';
    ...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to optimise Redshift query I have build a system where data is loaded from s3 into redshift every few minutes (from a kinesis firehose). I then grab data from that main table and split it into a table per customer.
The main table has a few hundred million rows.
creating the subtable is done with a query like this:
create table {$table} as select * from {$source_table} where customer_id = '{$customer_id} and time between {$start} and {$end}'

I have keys defined as:
SORTKEY (customer_id, time)
DISTKEY customer_id

Everything I have read suggests this would be the optimal way to structure my tables/queries but the performance is absolutely awful. building the sub tables takes over a minute even with only a few rows to select.
Am I missing something or do I just need to scale the cluster?

A: If you do not have a better key you may have to consider using DISTSTYLE EVEN, keeping the same sort key.
Ideally the distribution key should be a value that is used in joins and spreads your data evenly across the cluster. By using customer_id as the distribution key and then filtering on that key you're forcing all work to be done on just one slice.
To see this in action look in the system tables. First, find an example query:
SELECT *
FROM stl_query
WHERE userid > 1
ORDER BY starttime DESC
LIMIT 10;

Then, look at the bytes per slice for each step of you query in svl_query_report:
SELECT *
FROM svl_query_report
WHERE query = <your query id>
ORDER BY query,segment,step,slice;

For a very detailed guide on designing the best table structure have a look at our "Amazon Redshift Engineering's Advanced Table Design Playbook"


text:
Q: Only one checkbox checked at a time in javascript I have 3 checkbox, for which I want only 1 checkbox to be checked at a time. below is my fiddle for the html
JS fiddle
I want this to be worked in IE8 also kindly suggest how to do

A:

function selectOnlyThis(id) {
    for (var i = 1;i <= 4; i++)
    {
        document.getElementById(i).checked = false;
    }
    document.getElementById(id).checked = true;
}
<input type="checkbox" id="1" value="Value1" onclick="selectOnlyThis(this.id)" /> Option 1
<input type="checkbox" id="2" value="Value1" onclick="selectOnlyThis(this.id)" /> Option 2
<input type="checkbox" id="3" value="Value1" onclick="selectOnlyThis(this.id)" /> Option 3
<input type="checkbox" id="4" value="Value1" onclick="selectOnlyThis(this.id)" /> Option 4

It should help you

A: How about this - fiddle:
<input type="checkbox" class="chk" />
<input type="checkbox" class="chk" />
<input type="checkbox" class="chk" />
<input type="checkbox" class="chk" />

$('input.chk').on('change', function() {
    $('input.chk').not(this).prop('checked', false);
});

Edit:
for second part of your question to un-check other checkboxes when selecting parent checkbox see this fiddle - (as per chat) :
if (!cb.checked) {
$('#trchkOptions input[type=checkbox]').attr('checked', false);
}


text:
Q: Orchard custom field not getting posted correctly I have created a custom field in Orchard which is meant to just contain one field (GUID). So whenever it is added to a content type, it would show a new GUID in "Editor" template. This works fine, except when I submit the form which contains the content type, the form gets posted with a different GUID. On looking closely, I found the driver of the field for Editor (POST) does not updates the viewModel for the field.
Any suggestion or tips to debug ?
Here are some lines of my code
protected override DriverResult Display(
            ContentPart part, Fields.UniqueIDField field,
            string displayType, dynamic shapeHelper)
        {

            return ContentShape("Fields_String", // this is just a key in the Shape Table
                 GetDifferentiator(field, part),
                 () =>
                 {
                     var settings = field.PartFieldDefinition.Settings.GetModel<UniqueIdFieldSettings>();
                     var value = field.Id;

                     var viewModel = new UniqueIdFieldViewModel
                     {
                         Id = value
                     };

                     return shapeHelper.Fields_String( // this is the actual Shape which will be resolved (Fields/DateTime.cshtml)
                         Model: viewModel);
                 }
             );
        }

        protected override DriverResult Editor(ContentPart part,
                                               Fields.UniqueIDField field,
                                               dynamic shapeHelper)
        {

            var settings = field.PartFieldDefinition.Settings
                                .GetModel<UniqueIdFieldSettings>();
            var value = Guid.NewGuid().ToString();
            field.Id = value;

            var viewModel = new UniqueIdFieldViewModel
            {
                Id = value,
            };

            return ContentShape("Fields_String_Edit",
                () => shapeHelper.EditorTemplate(
                          TemplateName: TemplateName,
                          Model: viewModel,
                          Prefix: GetPrefix(field, part)));
        }

        protected override DriverResult Editor(ContentPart part,
                                               Fields.UniqueIDField field,
                                               IUpdateModel updater,
                                               dynamic shapeHelper)
        {

            var viewModel = new UniqueIdFieldViewModel();
            if (updater.TryUpdateModel(viewModel,
                                       GetPrefix(field, part), null, null))
            {
                field.Id = viewModel.Id;
            }

            return Editor(part, field, shapeHelper);
        }

A: You are resetting the value every time in the GET editor method, which is called by the POST editor method every time at the end of its own execution. Only set to a new value if there isn't one already.


text:
Q: how do i animate a div the width of each child image. and at the end return it to the beginning I have written some code for a carousel but I think it needs a little work, firstly I will explain the DOM
container
images container
img
img
img
end images container
nav
left
right
end nav
end container
each img floats left but is a different width (Same height), I have used jQuery to get the width of the images container to be the same as the combined widths.
so this is my right click (haven't done left yet)
$('#container .container-nav .container-nav-right').click(function(){
    var scrollAmount = $('.container-images img').width();
    $("#container .container-images").animate({'left':'-=' + scrollAmount}, 'slow');
});

so this moves the container div along by say 230px each time, but I want it to move it 230, 240, 260 etc based on the images being contained.
I also want to reset the code once we get to the last image.
I know there are loads of plugin's out there but I want to try and understand this myself. I hope I'm explaining myself.
Anyone any ideas? or suggestions as to where I go from here?
Thanks for reading this!

A: A little code to help explain kinakuta's answer:
var selectedImage = $('.container-images img:first');

$('#container .container-nav .container-nav-right').click(function(){
    var scrollAmount = selectedImage.width();
    $("#container .container-images").animate({'left':'-=' + scrollAmount}, 'slow');
    selectedImage = selectedImage.next();
});

A: You have to select each individual image - you're grabbing everything that matches your selector and it's only going to return the width() of the first one. One way to solve this is to add/remove a class for the "selected" image. You start with the first image having the "current" class, and use that to form a more specific selector. Then, when you move to the next image, remove it from the current one and add it to the next one.  There are other ways of accomplishing this, but off the top of my head, this would be my first strategy.
Oh, and I forgot the second part of your question. To get the next image, call the next() method on the current image. If nothing is returned, you've reached the end of your images and you can return to the beginning.


text:
Q: ggplot2: highlight background on discontinuity I am using ggplot2 in R to plot some data from a csv file. I am particularly interested in seeing the discontinuities in the data. On my line graphs, ggplot leaves gaps in the lines, but I'd like to go even further and highlight the background when these discontinuities occur. Is there a way to do this? I saw this answer(ggplot2: highlight chart area) but I couldn't understand their solution enough to attempt to make it work for me(I'm fairly inexperienced with ggplot).
Here's one of the graphs:

Basically I want to highlight the background of those gaps on the right in transparent red.
Here is the code I'm using to generate the graph:
p5 <- ggplot(d2.m, aes_string(x="timestamp",y="value")) +
      geom_line() +
      ylab("Latency (s)") +
      xlab("Time (s)") +
      scale_y_continuous(labels = comma) +
      facet_wrap(~variable, scales="free", ncol=1)

print(p5)

A: You could use this geom_rect solution:
require(ggplot2)

set.seed(1337)
dat <- data.frame(x = 1:11, y = sample(c(1:5, rep(NA,2)), 11, replace = TRUE))
ggplot() +
  geom_line(data = dat, aes(x = x, y = y))

Actual Code
cum_sum <- cumsum(is.na(dat$y))
diff_diff <- diff(diff(cum_sum)) # change of the slope
start <- which(diff_diff== 1)+1 # positive inflection point's
if (is.na(dat$y[1])) start <- c(1,start)
end <- which(diff_diff == -1)+2 # negative inflection point's
if (is.na(tail(dat$y,1))) end <- c(end, length(dat$y))

dat_rect <- data.frame(xmin = start, xmax = end)

ggplot() +
  geom_line(data = dat, aes(x = x, y = y)) +
  geom_rect(data = dat_rect, alpha = 0.3, aes(xmin = xmin, xmax = xmax, ymin = -Inf, ymax = Inf))

Result:


text:
Q: ngFor firing before ngOnInit Http Request finished I have a parent component with a list of objects and the child component is the detailed view of whatever object is selected from that list. I am putting the objects uuid into a url param and then doing an Http Get request with that uuid when the child is loaded. However, I am using ngFor to loop through some images in the object and it looks like ngFor is trying to loop through the media array before the Http request is complete.
My error:

TypeError: Cannot read property 'media' of undefined

The images load fine but the error seems to be causing issues when a new parent object is selected. The old images stay on the child component with the new. I can't find a solution that lets ngFor start looping once the GET request from NgOnInit is done.
Any help would be greatly appreciated.
Child.ts looks like:
  ngOnInit() {
this.route.params
.subscribe(
  (params: Params) => {
    this.uuid = params['id'];
    this.appService.fetchCardByUuid(this.uuid).subscribe(
      data => {
        this.selectedCard = data;
        console.log(this.selectedCard);
      }
    );
  }
);
}

Child.html:


text:
Q: Rename file based on folder parent name I'm looking for a batch-script which transforms a file named "template.book" into the name of the folder it is in. For example if the file is in the folder "instruction" I want the batch-file to rename the .book file in instruction.book.
I've tried many solutions which you gave but none of them seem to work for me. Hope you guys can help me out.
Thanks in advance!

A: @ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
FOR /f "delims=" %%a IN (
  'dir /b /s /a-d "%sourcedir%\template.book" '
 ) DO (
  FOR %%b IN ("%%~dpa.") DO ECHO(REN "%%a" "%%~nb.book"
)

GOTO :EOF

The required REN commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(REN to REN to actually rename the files.
You would need to set your directory as sourcedir. I set my testing directory.


text:
Q: Strange behavior in casting of function pointers in C++ I have recently encountered a behavior in C++ regarding function pointers, that I can't fully understand. I asked Google for help as well as some of my more experienced colleagues, but even they couldn't help.
The following code showcases this mystique behavior:
class MyClass{
private:
    int i;

public:
    MyClass(): i(0) {}
    MyClass(int i): i(i) {}

    void PrintText() const { std::cout << "some text " << std::endl;}
};

typedef void (*MyFunction) (void*);

void func(MyClass& mc){
    mc.PrintText();
}

int main(){
    void* v_mc = new MyClass;
    MyFunction f = (MyFunction) func; //It works!
    f(v_mc); //It works correctly!!!

    return 0;
}

So, first I define a simple class that will be used later (especially, it's member method PrintText). Then, I define name object void (*) (void*) as MyFunction - a pointer to function that has one void* parameter and doesn't return a value.
After that, I define function func() that accepts a reference to MyClass object and calls its method PrintText.
And finally, magic happens in main function. I dynamically allocate memory for new MyClass object casting the returned pointer to void*. Then, I cast pointer to func() function to MyFunction pointer - I didn't expect this to compile at all but it does.
And finally, I call this new object with a void* argument even though underlying function (func()) accepts reference to MyClass object. And everything works correctly!
I tried compiling this code with both Visual Studio 2010 (Windows) and XCode 5 (OSX) and it works in the same manner - no warnings are reported whatsoever. I imagine the reason why this works is that C++ references are actually implemented as pointers behind the scenes but this is not an explanation.
I hope someone can explain this behavior.

A:
I hope someone can explain this behavior.

The behaviour is undefined.
MyFunction f = (MyFunction) func; //It works!

It "works" because you use c-style cast which has the same effect as reinterpret_cast in this case I think. If you had used static_cast or simply not cast at all, the compiler would have warned of your mistake and failed. When you call the wrongly interpreted function pointer, you get undefined behaviour.

A: The formal explanation is simple: undefined behaviour is undefined. When you call a function through a pointer to a different function type, it's undefined behaviour and the program can legally do anything (crash, appear to work, order pizza online ... anyting goes).
You can try reasoning about why the behaviour you're experiencing happens. It's probably a combination of one or more of these factors:

*

*Your compiler internally implements references as pointers.

*On your platform, all pointers have the same size and binary representation.

*Since PrintText() doesn't access *this at all, the compiler can effectively ignore the value of mc altogether and just call the PrintText() function inside func.

However, you must remember that while you're currently experiencing the behaviour you've described on your current platform, compiler version and under this phase of the moon, this could change at any time for no apparent reason whatsoever (such as a change in surrounding code triggering different optimisations). Remember that undefined behaviour is simply undefined.

As to why you can cast &func to MyFunction - the standard explicitly allows that (with a reinterpret_cast, to which the C-style cast translates in this context). You can legally cast a pointer to function to any other pointer to function type. However, pretty much the only thing you can legally do with it is move it around or cast it back to the original type. As I said above, if you call through a function pointer of the wrong type, it's undefined behaviour.

A: It's only by chance that it works. Compilers are not guaranteed to make it work. Behind the scenes, your compiler is treating the reference as a pointer, so your alternative function signature just happens to work.

A: I'm sorry, to me isn't clear why you call this a strange behavior, I don't see a undefined behavior that depends on moon cycle here, is the way to use function pointers in C.
Adding some debug output you may see that the pointer to the object remain the same in all the calls.
void PrintText() const { std::cout << "some text " << this << std::endl;}
                                                      ^^^^
void func(MyClass& mc){
    std::cout << (void *)&mc << std::endl;
                         ^^^
void *v_mc = new MyClass;
std::cout << (void *)v_mc << std::endl;
                     ^^^^


text:
Q: drupal 7 cron issue "Attempting to re-run cron while it is already running" in drupal website hosted over two servers behind a load-balancer. The cron is eventually successful but I wonder why/how it is invoked multiple times. The problem is multiple crons slow down the site.

A: If you use multi-servers, you have to redefine crontabs and you'll be abble to switch from 1 server to the other with your cron tabs.
If you don't redefine them, DP will execute all crontabs twice (because 2 servers)


text:
Q: listview with balloons in android I am trying to create a listview with balloons. Its like a threaded chat list.

I am using thread.9.png (9 patch image) image for balloons. but you can see in the above screen shot that balloons are taking screen width even content is smaller.
I want to resize balloon's width on the basis of content.
bellow is the code of list view row.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:paddingLeft="2dp"
  android:background="@drawable/thread">

    <TextView
        android:text="TextView"
        android:id="@+id/messageFrom"
        android:layout_height="wrap_content"
        android:textColor="@color/black"
        android:layout_weight="1.0"
        android:layout_width="wrap_content"
        android:layout_marginLeft="20dip"
         android:layout_marginTop="20dip"></TextView>

    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="@color/black"
    android:id="@+id/messageTitle"
    android:text="TextView"
    android:layout_gravity="right"
    android:layout_marginBottom="20dip"></TextView>
     <TextView
        android:layout_weight="1.0"
        android:gravity="right"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/blue"
        android:id="@+id/messageDay"
        android:text="TextView" android:layout_marginLeft="20dip"></TextView>
</LinearLayout>

If there is any sample for threaded list view, it will also very helpful.

A: A 9patch image won't shrink (will only stretch), so if the thread.9.png's width is greater than the content size, it'll use the images width.

A: You have to design your balloon background image with the minimum width you want

A: try with the sub linearlayout, as the list row fill the main layout even you set the width as wrap_content
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="10dp">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/selector_bg1" android:padding="10dp">
        <TextView android:text="text view one" android:layout_width="fill_parent" android:layout_height="wrap_content"
            android:textColor="#ffff0000" android:textSize="20dp" android:id="@+id/text1"/>
        <TextView android:text="text view two" android:layout_width="fill_parent" android:layout_height="wrap_content"
            android:textColor="#ffff0000" android:textSize="20dp" android:id="@+id/text2"/>
    </LinearLayout>
</LinearLayout>


text:
Q: linux network drivers --- net_device_ops so far i have only used file operational structure in device driver.
Using system call open & read , write.
How to open device driver & transmit data using net_device_ops  ?
Is there reference example on net for the user program to interact with it ?
http://lnxpps.de/rpie/mcp2515_mod.c

A: I'm not sure I understand the question, so let me know if my answer doesn't make sense.
I see you have defined functions for .ndo_open, .ndo_stop, and .ndo_start_xmit.  .ndo_open is called by the kernel when you configure the interface using ifconfig up or use ifconfig to assign an address to the interface.  .ndo_stop is called by the kernel when you remove the module or if you shutdown the interface using ifconfig down.
ifconfig is described here:  http://linux.die.net/man/8/ifconfig
.ndo_start_xmit is called by the kernel network stack when a socket is used to transmit a packet.  So, to transmit data using .ndo_start_xmit you'll need to create a socket, assign an appropriate destination address, and send the data via the socket.  If you're using IP, there are tools you can use send packets easily, such as netperf or iperf.


text:
Q: How to combine two for loops working with netcdf lists? I have problems combining multiple for loops. I will give an example with two of them, I would like to combine. If I know how to do it with two I will also be able to do it with multiple loops.
If anyone knows how to write this as lapply function that would also be nice.
require(ncdf4)

#### download files from this link to directory: (I just downloaded manually,two files are sufficient to answer the example)
#### ftp://rfdata:forceDATA@ftp.iiasa.ac.at/WFDEI/LWdown_daily_WFDEI/

setwd("C:/place_where_I_have_downloaded_my_files_from_link/")
temp = list.files(pattern="*.nc")                         #list imported netcdf files
list2env(
  lapply(setNames(temp, make.names(gsub("*.nc$", "", temp))),
         nc_open), envir = .GlobalEnv) #import all parameters lists to global environment

#### first loop                               -                # select parameter out of netcdf files and combine into a List of 2
list_temp<-list()                                         #create empty list before loop
for (t in temp[1:2]){
  list_temp[t]<-list(data.frame(LWdown=ncvar_get(nc_open(t),"LWdown")[428,176,],xcoor=176,ycoor=428))
}
LW_bind<-do.call(rbind,list_temp)
rownames(LWdown_1to2)<-NULL

#### second loop                                                    # select parameter out of onenetcdf file per x-coordinate and combine into a List of 2
list_temp<-list()                                         #create empty list before loop
for (x in 176:177){
  list_temp[t]<-list(data.frame(LWdown=ncvar_get(nc_open(temp[1]),"LWdown")[428,x,],xcoor=x,ycoor=428))
}
LW_bind<-do.call(rbind,list_temp)
rownames(LWdown_1to2)<-NULL

How I tried to combine but didn't work:
#### combined loops
list_temp<-list()
for (t in temp[1:2]){for (x in 176:177){
  #ncin<-list()
  ncin<-nc_open(t)
  list_temp[x][t]<-list(data.frame(LWdown=ncvar_get(ncin,"LWdown")[428,x,],x=x,y=428))
}}
LWdown_1to2<-do.call(rbind,list_temp)
rownames(LWdown_1to2)<-NULL

I already solved my problem. See below. But I am still curious how one could solve the two for loops as described above, so I will leave the question open an unanswered.
Here is my solution:
require(arrayhelpers);require(stringr);require(plyr);require(ncdf4)
# store all files from ftp://rfdata:forceDATA@ftp.iiasa.ac.at/WFDEI/ in the following folder:
setwd("C:/folder")
temp = list.files(pattern="*.nc")           #list all the file names
param<-gsub("_\\S+","",temp,perl=T)         #extract parameter from file name

xcoord=seq(176,180,by=1)                    #The X-coordinates you are interested in
ycoord=seq(428,433,by=1)                    #The Y-coordinates you are interested in

list_var<-list()                         # make an empty list
for (t in 1:length(temp)){
temp_year<-str_sub(temp[],-9,-6)                                                                                #take string number last place minus 9 till last place minus 6 to extract the year from file name
temp_month<-str_sub(temp[],-5,-4)                                                                               #take string number last place minus 9 till last place minus 6 to extract the month from file name
temp_netcdf<-nc_open(temp[t])
temp_day<-rep(seq(1:length(ncvar_get(temp_netcdf),"day"))),length(xcoord)*length(ycoord))                   # make a string of day numbers the same length as amount of values
    dim.order<-sapply(temp_netcdf[["var"]][[param[t]]][["dim"]],function(x) x$name)                            # gives the name of each level of the array
    start <- c(lon = 428, lat = 176, tstep = 1)                                                                     # indicates the starting value of each variable
    count <- c(lon = 6, lat = 5, tstep = length(ncvar_get(temp_netcdf,"day")))                                 # indicates how many values of each variable have to be present starting from start
    tempstore<-ncvar_get(temp_netcdf, param[t], start = start[dim.order], count = count[dim.order])            # array with parameter values

df_temp<-array2df (tempstore, levels = list(lon=ycoord, lat = xcoord, day = NA), label.x = "value")           # convert array to dataframe
Add_date<-sort(as.Date(paste(temp_year[t],"-",temp_month[t],"-",temp_day,sep=""),"%Y-%m-%d"),decreasing=FALSE)  # make vector with the dates
list_var[t]<-list(data.frame(Add_date,df_temp,parameter=param[t]))                                         #add dates to data frame and store in a list of all output files
  ### nc_close(temp_netcdf)                                                                                #close nc file to prevent data loss and errors
}
All_NetCDF_var_in1df<-do.call(rbind,list_var)


text:
Q: Get the child who called parent's method in JavaScript Say I got this JS code
function Parent(){}
Parent.prototype.do = function(){ // Get here the Child(1|2)'s class name }

function Child1(){}
Child.prototype = new Parent();

function Child2(){}
Grandson.prototype = new Parent();

Child1.do();
Child2.do();

I know that there was a (currently deprecated) "caller" info within arguments.
How can this be done?
Is this a common pattern of doing things in JavaScript, or is it an anti-pattern? How is usually done this type of stuff?

A: You can reset your constructor property of the child prototype objects and access this property in the do function:
function Parent(){}
Parent.prototype.do = function(){
    var name = this.constructor.toString().match(/function ([^(]+)/)[1];
    console.log(name);
}

function Child1(){}
Child1.prototype = new Parent();
Child1.prototype.constructor = Child1;

function Child2(){}
Child2.prototype = new Parent();
Child2.prototype.constructor = Child2;

new Child1().do(); // logs Child1
new Child2().do(); // logs Child2

DEMO
An alternative is to add an additional property to the prototype of the child object, e.g. className:
function Parent(){}
Parent.prototype.do = function(){
    var name = this.className;
    console.log(name);
}
Parent.prototype.className = 'Parent';

function Child1(){}
Child1.prototype = new Parent();
Child1.prototype.className = 'Child1';

function Child2(){}
Child2.prototype = new Parent();
Child2.prototype.className = 'Child2';

new Child1().do(); // logs Child1
new Child2().do(); // logs Child2


text:
Q: Why can't NHibernate use Identity in union-subclass Table per Concrete Class mapping? Several sources state that NHibernate can not use identity with table per concrete class and union-subclasses. Is this true, and what is the exact reason behind this ?

A: It's simple. The POID must be unique across all instances of a root entity type.
Consider the following example:
abstract class Vehicle { ... }
class Car : Vehicle { ... }
class Truck : Vehicle { ... }

If you were to retrieve a Vehicle whose concrete type you don't know:
var carOrTruck = session.Get<Vehicle>(vehicleId);

...and there were both a Car and a Truck with that Id (which is possible with identity), which one would NHibernate return? (there are more complex cases, but this illustrates one possible issue)
Therefore, for table-per-concrete-class (a pretty bad strategy if you ask me), NHibernate needs a generator that guarantees uniqueness across subclasses.

A: Why do you say so? I think I had several scenarios like that. Also this blog entry states the same.
To sum up comments below:
as in the example that Ayende has, if you query for all root types (so "Select Party") you can get duplicates for ID. That fact along with UNION characteristic (returns only distinct records) could give you unexpected results (missing records). That's why you cannot use identity but rather hilo which allows nhibernate to avoid duplicates.


text:
Q: equality with respect to Stirling's formula Can we prove the equality:
$$
\sum_{n\ =\ 1}^{\infty}\left(\, 1 \over 4\,\right)^{n}\,
{\left(\, 2n\,\right)! \over \left(\, n!\,\right)^{2}} = 1
$$
or the equality doesn't hold actually ?.

A: The sum of the first three terms is
$$\frac12+\frac38+\frac{5}{16}=\frac{19}{16}\ ,$$
and all terms are positive.  So the sum either converges to a value greater than $1$, or diverges.

A: Using Stirling's formula, the terms in the sum are asymptotically
$$
\frac{1}{4^n}
 \frac{\sqrt{4\pi n}\left(\frac{2n}{e}\right)^{2n}}
      {\left(\sqrt{2\pi n} \left(\frac{n}{e}\right)^n\right)^2} =
\frac{\sqrt{4\pi n}}{2 \pi n} = \frac{1}{\sqrt{\pi n}}
$$
(if my algebra is correct), which gives you a divergent series.


text:
Q: How to add conditional statement to React data.map function I'm a React newbie and have a component which is outputting a checkbox list by mapping an array. This is the code that presently works.
    export default class First extends React.Component {
       constructor(props) {
        super(props);
       this.state = {
          data: data,
     };
    }

    render() {
       return (

          {this.state.data.map(d =>
             {d.name}
             <input type="checkbox"/>

            )}

        );
    }
  }

What I need to do is add an if/else telling the return map function only to render the checkbox list if another variable in the array (called domain) = "HMO". I'm really struggling with the syntax. I think it needs to be inserted below the {this.state.data.map(d => line but am really stuck. Any help would be greatly appreciated.

A: I believe you're looking for something like this.
export default class First extends React.Component {
   constructor(props) {
    super(props);
   this.state = {
      data: data,
 };
}

render() {
  return (

      {this.state.data.map(d => {
        if(d.domain === "HMO"){
          return (
           {d.name}
             <input type="checkbox"/>

         )}
        return null
      })}

    )
  }
}

The .map function will iterate through each element in your data array, it will then check if that element's domain variable is equal to the string "HMO".  If it is, it will return the html that displays the checkbox, otherwise it will return null.

A: Use Array.filter:
export default class First extends React.Component {

    constructor(...args) {
        super(...args);
        this.state = {
            data: data
        };
    }

    getItems() {
        return this.state.data
            .filter(d.domain === "HMO")
            .map(d => (
                {d.name}
                    <input type="checkbox"/>

            ));
    }

    render() {
        return (

                {this.getItems()}

        );
    }
}

The downside is that you loop twice compared to @MEnf's solution so it can be slower if you have a really long array. The upside is that it looks neater (I know that is quite subjective).


text:
Q: Empty result when running DDL migration I am working on adding (back) support for Apache Phoenix (at least for our own usage, looks like it was pulled a few years ago) on top of the latest version of Flyway. I wrote a real small script to create a table, and am running migrate.
I see that the table gets created on my database, but in JdbcTemplate#executeStatement(), at line statement.execute(sql) returns null. Then, in extractResults(), it gets into an infinite loop at this line:
while (hasResults || (updateCount = statement.getUpdateCount()) != -1) {
Since statement.getUpdateCount() is 0 (no rows updated on table creation), it just loops until I run out of memory. I'm sure I'm just missing something real simple but can't find it.


text:
Q: PagerTabStrip with all captial letters I have a PagerTabStrip in my app and I put in Strings to the Tab,
titles = new String[]{
            "Tab1",
            "Tab2",
            "Tab3"

};

so suppose only "T" here is capital, but I get all capital letters.
I also tried to fix this by adding textAllCap to be false through the style in xml:
 <style name="viewPagerTitleStrip">
    <item name="android:textColor">@color/LightGrey2</item>
    <item name="android:textSize">20sp</item>
    <item name="android:textAllCaps">false</item>
 </style>

and then apply it in the layout xml:
<android.support.v4.view.ViewPager
    android:id="@+id/mainFragContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <android.support.v4.view.PagerTabStrip
        android:id="@+id/titleStrip"
        style="@style/viewPagerTitleStrip"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        android:paddingTop="10dp"
        app:tabIndicatorColor="@color/LightGrey"
        />

</android.support.v4.view.ViewPager>

But they still appear to be all cap, i.e. "TAB1" , "TAB2", "TAB3"
Can anyone help?

A: try this
app:tabTextAppearance="@android:style/TextAppearance.Widget.TabWidget"


text:
Q: ASP.NET Localize A simple question. I have a site with localization (with .resx files) and when i need to insert localized text i use a code like this:
<asp:Localize Text="<%$ Resources: MyResource, Default_BannerHomeTitle %>" runat="server">SOME_TEXT_HERE_OR_NOT?</asp:Localize>

The question is if anyone knows what's the utility of the text between the asp:Localize tag -> "SOME_TEXT_HERE_OR_NOT?"
The real value come from the .resx file and the text "SOME_TEXT_HERE_OR_NOT?" is obviusly deleted when the page is rendered.
Is this text used in some situation? or is never used?
thanks in advance!

A: The Text property you are setting inline and the text you type between the tags is effectively the same thing. You should be using one or the other, there's no point in setting both.
The Localize control is just a subclass of the Literal control. Technically, the text you type between the tags is interpreted as its own separate Literal control, a "parsed sub-object". When the Localize control is created, its Text property is set to the value of the sub-object's Text property. However, setting the Text property explicitly on the Localize control will take precedence over anything typed between the tags.


text:
Q: Защита от пересечения генерируемых объектов. Unity На сцене во время игры случайно генерируются игровые объекты.  Нужно сделать так, чтобы созданные объекты не пересекались (то есть не накладывались друг на друга). Пока я использую вот это:
// Повторяем пока не найдется свободное место или пока кол-во попыток не станет больше 10
for (int attempt = 0; attempt < 10; attempt++)
{
    objects[i] = Instantiate(objectToGenerate, position, Quaternion.identity, parent);

    if (objects[i].GetComponent<CollideManager>().isTriggered)
    {
        Destroy(objects[i]);
    }
    else break;
}

К объекту objectToGenerate прикреплен компонент CollideManager. Переменная isTriggered равна true в случае если объект пересекается с другим объектом.
 Вот код компонента:
public class CollideManager : MonoBehaviour {

    public bool isTriggered = false;

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.tag == "Static")
        {
            isTriggered = true;
        }
    }
}

Но весь этот код не работает.  Методом тыка, гадания на кофейной гуще и отладки выяснил, что это скорее всего связано с тем, что unity не успевает обработать столкновение нового объекта со старыми за нулевой промежуток времени между этой строчкой:
objects[i] = Instantiate(objectToGenerate, position, Quaternion.identity, parent);

и этой:
if (objects[i].GetComponent<CollideManager>().isTriggered)

Поэтому я решил переделать все это в сопрограмму и добавить задержку:
objects[i] = Instantiate(objectToGenerate, position, Quaternion.identity, parent);

yield return new WaitForSeconds(0.5f);

if (objects[i].GetComponent<CollideManager>().isTriggered)
{
    Destroy(objects[i]);
}
else break;

Но теперь

*

*Игра начала подвисать.

*Объекты появляются прямо на глазах у пользователя, причем в самых неожиданных и неудобных местах. (Игрок идет, идет и вдруг прямо перед ним появляется убивающий его предмет)
Еще я пробовал вместо WaitForSeconds использовать WaitForFixedUpdate, но это не сработало: объекты накладывались друг на друга.
Как заставить все это работать?

A: *

*Кидать Physics.OverlapSphere,OverlapBox или OverlapCapsule (и лучше NonAlloc версии). Можно более упрощенные аналоги типо Physics.Check(sphere,box,capsule). В 2D версии еще Circle и Area добавляется. Тип и размеры(я бы брал увеличенный в 1.5 раза) можно брать от генерируемого объекта. Получите все коллайдеры в этих областях. 99% гарантия качества(1% оставим на неожиданные открытия особенностей).

*В момент генерации, создать массив записей (точка - объект), и каждый кадр считать расстояние от точки до объекта, если он выйдет за определенную дистанцию, считать что точка освободилась. 50% гарантия, и много ограничений(а если объекта обратно вернется, или там окажется другой объект и т.д.).


text:
Q: Win10: Is there a way to view the exact process involved in "Service Host: Remote Procedure Call?" Lately task manager has been sporadically showing a process called "Service host: remote procedure call" having suddenly spiked to about 20% processor power.  Even though it's only at 20%, my computer jams to a halt, and I have to wait 20-30s for it to resolve. Video and audio continue to run in the background, but I cannot make any inputs such as switching windows or interacting with any software.
If I am in the middle of something remotely intensive (like watching a video), and happen to click e.g. pause/play/fullscreen before I realize this process is currently spiking, it can exacerbate the freeze for several minutes before the service host returns to normal and my computer is usable again. If I'm too persistent about switching windows or opening task manager, sometimes windows explorer will crash and have to reboot first.
Throughout this entire time, my processor's total usage never exceeds ~30% or ~40-50% memory. Everything there looks normal.
As I understand it, service host: remote procedure call is a blanket label for many different processes, like svchost is (or maybe they are the same thing—open file location does in fact direct me to svchost.exe).
Can I do anything, perhaps in cmd menu, to force windows to display what this exact task is next time it's spiking, so I can identify the problem and take measures to troubleshoot it?
Thanks

A: From a command prompt run this:
tasklist /svc /fi "imagename eq svchost.exe"
See this site for more detailed info:
https://www.bleepingcomputer.com/tutorials/list-services-running-under-svchostexe-process/


text:
Q: RoR collection_select undefined method `map' for nil:NilClass: I have a product class that has a category. I want to insert a product without any category when not selected one.
My code
<% = collection_select (:product,:category_id, @categories_select,:id,:description, {:include_blank => 'Select ...'}, {id: "category", class: "form-control w-100" })%>

When I click Save from the following error:

NoMethodError - undefined method `map 'for nil: NilClass:

In the terminal it shows {"category_id" => ""}, I want to insert NULL in the database.


text:
Q: C++ unexpected memory error I've problem with easy C++ program which finds the largest submatrix in given matrix:
int *A = new int[n*m];
... setting fields for matrix, finding the largest one and etc
... r := size of square-submatrix, max_i := row, max_j := column of the largest
for (i = max_i; i < max_i + r; i++)
{
    for (j = max_j; j < max_j + r; j++)
        cout << A[i * n + j] << "\t";

        cout << "\n";
}
<memory free>
end of program

Everything works great (so it's not problem with logic) - finding correct submatrix, prinitng etc.
Unexpectedly (or due to late night) when I put in memory free line delete[] A or delete everything crushes down with errors (but it's still printing result correctly - so the error must be in this line). I've tried set it to NULL and every combination. What goes wrong?
Thanks in advance
EDIT:
#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
int i,j,k;

int m,n;
int r;

cout << "Size of matrix: \nRows: ";
cin >> n;
cout << "Columns: ";
cin >> m;

int *A = new int[n*m];

for (i = 0; i < n; i++)
{
    for (j = 0; j < m; j++)
    {
        A[n*i + j] = rand() % 19 - 9;
        cout << A[n*i + j] << "\t";
    }

    cout << "\n";
}

cout << "Size of submatrix: ";
cin >> r;

int liczba_kwadratow = (m + 1 -r) * (n+1 -r);

int max = -10000;
int max_i = 0;
int max_j = 0;

int row_iter = 0;
int col_iter = 0;

for (k = 0; k <liczba_kwadratow; k++)
{
    int sum = 0;
    for ( i = row_iter; i < row_iter + r; i++)
        for ( j = col_iter; j < col_iter + r; j++)
            sum += A[i * n + j];

    if ( sum > max )
    {
        max = sum;
        max_i = row_iter;
        max_j = col_iter;
    }

    col_iter++;
    if ( row_iter + r > m )
    {
        row_iter++;
        col_iter = 0;
    }

}

cout << "Field of the largest submatrix  " << r << " of " << r << " equals " << max << "\n";

for (i = max_i; i < max_i + r; i++)
{
    for (j = max_j; j < max_j + r; j++)
        cout << A[i * n + j] << "\t";

    cout << "\n";
}

...works great without delete[] A or delete A

}

A: The problem can at least be identified via the method(s) I've told you in the comments (or by using a debugger). Easiest way is changing the dynamical array to a std::vector then use member function at. You will then realize you get an out of bound exception thrown here:
for (i = 0; i < n; i++)
{
    for (j = 0; j < m; j++)
    {
        A.at(n*i + j) = rand() % 19 - 9; // throws here!!!!, replace n by m
        cout << A.at(n*i + j) << "\t";
    }

    cout << "\n";
}

When input is 6 5 3, then you get an exception when you first try to access A[30], which gives you a headache when delete[] - ing. Now you can figure out what's wrong I guess ...

A: You inverted i and j in your matrix access code.
basically the formula could be
current row + current column * number of rows

or
current row * number of columns + current column

Two remarks on your code and debugging:

*

*using one-letter variables minimizes the wear and tear on your keyboard and fingers and reduces disk and memory usage. It tends to increase debugging time dramatically, though.

*The assumption that the code is OK just because it does not crash immediately is absolutely wrong. C/C++ is the realm of undefined behaviours (in your case, probably the most common one: writing outside allocated memory). An UB is a nasty piece of work precisely because it can produce any outcome, including (frequently) an apparent absence of consequences, only to cause a perfectly OK bit of code to crash 10.000 lines later.


text:
Q: mysql where condition in a group by statement? I have the following query.
I'd need to pick only the oldest rows (by DATE column) within my group by. keeping my conditions (where and group by).
SELECT
table.*
from table
where views > $views AND sales>23
group by
name

to be a bit clearer it is like passing frm this first table
+--------------------+-----------+--------------------+-----------+
| name               | views     | DATE               |   sales   |
+--------------------+-----------+--------------------+-----------+
| sue1               |       494 | 2014-06-23 12:08:29|   26      |
| sue2               |       494 | 2014-06-25 12:08:29|   34      |
| sue3               |       494 | 2014-06-27 12:08:29|   45      |
| sue4               |       520 | 2014-06-26 12:08:29|   56      |
| sue5               |       570 | 2014-06-24 12:08:29|   20      |
| sue5               |       570 | 2014-06-24 12:08:29|   28      |
+--------------------+-----------+--------------------+-----------+

to this second one
+--------------------+-----------+--------------------+-----------+
|  name              | views     | DATE               |  sales    |
+--------------------+-----------+--------------------+-----------+
| sue3               |       494 | 2014-06-27 12:08:29|    45     |
| sue4               |       520 | 2014-06-26 12:08:29|    56     |
| sue5               |       570 | 2014-06-24 12:08:29|    28     |
+--------------------+-----------+--------------------+-----------+

marko.c
I have tried doing a subselect as this
SELECT
table.*
from table
where views > $views AND sales>23
and date in (select max(date) from table where views > $views AND sales>23)
group by
name

but it's not working. anybody?

A: as a first pass I honestly am not sure what you want. I think your request is to get all unique views by oldest date... but in any case if you want the oldest dates for each thing then just do your group after ordering it.
SELECT * FROM(
    SELECT
    table.*
    FROM table
    WHERE views > $views AND sales>23
    ORDER BY date
) AS t
GROUP BY name;

When you do an aggregate on a date think of it backwards..
MAX(date) will give you the NEWEST date because it is the greatest date.
MIN(date) will give you the OLDEST date because it is the oldest / smallest date.

so if you wanted to do your other posted query you could do
SELECT
table.*
from table
where views > $views AND sales>23
and date in (select MIN(date) from table where views > $views AND sales>23)
group by
name

and see if the MIN(date) would do the trick

A: You are selecting the maximum overall date in your subquery but what you actually want is the minimum (oldest) date for each name.
SELECT
    t1.*
from table t1
join (
    select
        t2.name,
        min(t2.date) min_date
    from table t2
    where t2.views > $views AND t2.sales > 23
    group by t2.name
) t2 on t2.name = t1.name and t2.min_date = t1.date
where t1.views > $views AND t1.sales > 23


text:
Q: Humans travel to Earth in a giant tree This story was possible over 2 books. I read it in the 80s.
Human DNA was recovered from a space message (arecibo message) and brought to life by the aliens and kept as pets. The humans learn about this and travel back to Earth in a giant tree. Millions of years have passed and the Earth is now populated by reptiles. Something to do with the Great Filter?

A: This is likely The Genesis Quest by Donald Moffitt.

An alien race (The Nar) assemble humans from a stream of genetic information transmitted by radio from the Milky Way Galaxy. The resulting colony of humans spend some time integrated into the Nar society before growing restless, discovering the secret of human longevity, and embarking on the seemingly impossible millennia-long mission of a physical journey back to Earth. This epic journey is made in a gigantic space-grown semi-sentient Dyson tree known as Yggdrasil.

It was followed by Second Genesis

Many centuries ago, an alien race known as the Nar was able to recreate human beings from genetic code, broadcast from Earth into outer space by a beleaguered humanity. They allow a group of humans to travel millions of light years through the galaxy, in order to discover what has happened to the original occupants of planet Earth. However, none of the human participants of the expedition are prepared for what awaits them at the completion of their journey...

I found the reference on the TV Tropes page for Tree Vessel, requisite warnings that the site is a huge timesink.


text:
Q: .Net Core Website publish Microsoft.WebSite.Publishing.targets I am on .Net Core 2.0.
I create a new solution containing a webapp and a website. The website project contains an index.html and web.config file.
I have no issue publishing the web application, but the website causes me some trouble.
I added a publish profile configured for FileSystem publish method.
When I run dotnet publish on the default .publishproj generated, I get the following error message
error MSB4019: The imported project
"C:\ProgramFiles\dotnet\sdk\2.0.0\Microsoft\
VisualStudio\v10.5\Web\Microsoft.Web
Site.Publishing.targets" was not found. Confirm that the path in the
<Import> declaration is correct, and that the file exists on disk.

Ok, so I change the website.publishproj  value to where the targets file is located.
<!--<Import
Project="$(_WebPublishTargetsPath)\Web\Microsoft.WebSite.Publishing.targets"
/>-->
<Import Project="C:\Program Files
(x86)\MSBuild\Microsoft\VisualStudio\v14.0\Web\
Microsoft.WebSite.Publishing.targets" />

Then I get
error MSB3030: Could not copy the file
"C:\Users\Administrator\AppData\Local\Temp\WebSitePublish\WebSite2-
1026028577\obj\Debug\website.exe" because it was not found.
[C:\Users\Administrator\Documents\visual studio
2017\WebSites\WebSite2\website.publishproj]

I can publish the website using visual studio without any issue. What am I missing?

A: It looks like you are trying to use the dotnet CLI tooling to publish "classic" website projects which is not supported. Use msbuild from the developer command prompt instead.


text:
Q: Verifying a collection is indeed a basis for a topology
Proof. (attempt)
We verify that $\mathscr{B}$ is indeed a basis for a topology. Let $x \in X$. If $x$ is the smallest element, then $x \in [x,b) \in \mathscr{B}$. If $x$ is the largest element, then $x \in (a,x] \in \mathscr{B}$. Finally, if $x$ is neither then $x \in (a_{min}, b_{max}) \in \mathscr{B}$
Next, we need to prove that if $x \in B_1 \cap B_2$ where $B_i$ are basis elements, then can find some $B_3 \in \mathscr{B}$ so that $x \in B_3 \subset B_1 \cap B_2$.
If there are no smallest and no largest element, consider $B_1 = (a,b)$ and $B_2 = (c,d)$. If $B_1 \cap B_2 = \varnothing$, then we take $B_3 = \varnothing$. Otherwise $(a,b) \cap (c,d) = (c,b)$ so choose $B_3 = (c,b)$
Next, what if $X$ has largest element, then we need consider $(a,b) \cap (a,b_0]$ and if $X$ has smallest element, we need check $[a_0,b) \cap (a,b)$ in both cases, the intersection still gives elements in the basis.
IS this a correct proof?

A: The fast way is to note that if we define $$\mathcal{S} = \{(x, \rightarrow), (\leftarrow, x)\mid x \in X\}$$
then $\mathcal{B}$ is exactly the base generated by the subbase $\mathcal{S}$.
But if we follow the case distinction approach, we could refine your approach a litte bit and makeit more correct:
To see $\bigcup \mathcal{B} =X$.: let $x \in X$. If $x=\min(X)$, then $x \in [x,y) \in \mathcal{B}$ for any $y \neq x$ (using that $X$ has at least two points). If  $x=\max(X)$, we use $x \in (y,x] \in \mathcal{B}$ in a similar way. If $x$ is not equal to $\min(X)$ or $\max(X)$ this means by definition that there are $y < x$ and $z> x$ in $X$, and then we can use $x \in (y,z) \mathcal{B}$.
Let $x \in B_1 \cap B_2$, where $B_1,B_2 \in \mathcal{B}$. If $x= \min(X)$ it follows that $B_1 = [x,a)$ for some $a \in X$ and $B_2 = [x,b)$ for some $b \in X$, as these are the only members of$\mathcal{B}$ that $x$ can be in if it is $\min(X)$. But then $x \in B_3:=[x,\min(a,b)) \subseteq B_1 \cap B_2$. The case that $x=\max(X)$ is similar. So we can assume $x$ is not $\min(X)$ nor $\max(X)$ and $B_1 = (a,b), B_2 =(c,d)$ for some $a,b,c,d \in X$ (if some $B_i$ happens to be of the special form $[\min(X),a)$, when $\min9X)$ exists e.g., we can replace it by $(\min(X),a)$ instead which is smaller and also contains $x$ in this subcase, and so if we have $B_3$ for that, then also for the original $B_i$ etc.) and such that $x \in (a,b)$ and $x \in (c,d)$. But then $B_3 := (\max(a,c), \min(b,d)) \in \mathcal{B}$ also contain $x$ and sits inside $B_1 \cap B_2$, as required.
So with explicitly checking all the cases it's a bit more involved, but not really hard, I'd say.

A: Seems OK except the case if there is no smallest and no  largest element  $(a,b)\cap (c,d)=(c,b)$.
It can be done correctly this way
$(a,b)\cap (c,d)=(e,f)$. where $e=max\{a,c\}$ and $f=min\{b,d\}$


text:
Q: Printing floating point values with decimals and not with e-notation in JavaScript When i print a floating point like 0.0000001 in JavaScript it gives me
 1e-7

how can i avoid that and instead print it "normally" ?

A: You can use this:
var x = 0.00000001;
var toPrint = x.toFixed(7);

This sets toPrint to a string representation of x with 7 digits to the right of the decimal point. To use this, you need to know how many digits of precision you need. You will also need to trim off any trailing 0 digits if you don't want them (say, if x was 0.04).

A: function noExponent(n){
    var data= String(n).split(/[eE]/);
    if(data.length== 1) return data[0];

    var  z= '', sign= +n<0? '-':'',
    str= data[0].replace('.', ''),
    mag= Number(data[1])+ 1;

    if(mag<0){
        z= sign + '0.';
        while(mag++) z += '0';
        return z + str.replace(/^\-/,'');
    }
    mag -= str.length;
    while(mag--) z += '0';
    return str + z;
}

A: I've got a simple solution that appears to be working.
var rx = /^([\d.]+?)e-(\d+)$/;

var floatToString = function(flt) {
  var details, num, cnt, fStr = flt.toString();
  if (rx.test(fStr)) {
    details = rx.exec(fStr);
    num = details[1];
    cnt = parseInt(details[2], 10);
    cnt += (num.replace(/\./g, "").length - 1); // Adjust for longer numbers
    return flt.toFixed(cnt);
  }
  return fStr;
};

floatToString(0.0000001); // returns "0.0000001"

EDIT Updated it to use the toFixed (didn't think about it).
EDIT 2 Updated it so it will display numbers 0.0000000123 properly instead of chopping off and showing "0.00000001".


text:
Q: PHP Postgres JOIN with LIKE query failing I am trying to figure out a query with postgres, and Im not sure its cause I am used to mysql and postgres doesn't have a LIKE query. Or what my deal is. Either way I know its not working and I have no idea why not. Can someone help me out point me in the right direction? I mean ultimately I am trying to make a Zend Database version of this query but, this is the core query I am working with to try and make before I attempt to use zend db class to build it.
SELECT
    org.orgid,
    org.roleid,
    users.userid,
    users.email,
    users.first_name,
    users.last_name,
    users.contact_id,
    users.state,
    users.ts,
    users.altemail,
    users.unboundid,
    users.blocked
FROM mapping AS org
INNER JOIN my_users AS users ON org.userid = users.userid
WHERE (org.orgid = 'generated-id')
AND (org.roleid LIKE 'partner-%');

ERROR:  operator does not exist: roles ~~ unknown
LINE 17: AND (org.roleid LIKE 'partner-%');
                          ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

A: Change
AND (org.roleid LIKE 'partner-%');

to
AND (org.roleid::text LIKE 'partner-%');

Evidently you are working on the textual representation of the roleid.  this seems like it should work fine except your data types do not match.  By casting to text you ensure that they do.
Note that one important ramification is that indexes on roleid will be useless for such a comparison because they operation is not directly compatible with the type.  This shouldn't be a problem since orgid can still use an index but it is something to think about.  If you want to fix that, you may want to use table methods or other functions to break this down for you.  You can then index function output.
For example you could use a table method as like so:
CREATE FUNCTION is_partner(mapping) returns bool language sql immutable as $$
    SELECT $1.roleid::text LIKE 'partner-%';
$$;

You could then index it with:
CREATE INDEX mapping_is_partner_idx ON mapping (is_partner(mapping));

You could then change that join condition from
AND (org.roleid LIKE 'partner-%');

to
AND org.is_partner;

Note in this case, org is necessary and cannot be added implicitly since it changes org.is_oartner to is_partner(org) using class.method notation.
Hope this helps.


text:
Q: Валидация файла при обновлении yii У меня возникла трудность: при обновлении пользователю обязательно нужно загрузить заново файл, при этом старый удалится, а имя нового запишется в базу данных.
Но чтобы изменить какую-либо информацию приходится заново загружать файл, что довольно неудобно.
В модели стоит обязательная загрузка файла:
array('filename', 'file', 'types'=>'rar, zip, 7z','allowEmpty'=>false,'maxFiles' => 1,'message'=>'Допустимые типы к загрузке: rar, zip, 7z'),

Как сделать, чтобы если файл не выбран, то запись файла не производилась бы, и наоборот соответственно?
Update (код контрллера):
$model=$this->loadModel($id);
                $model->scenario='update';
                if(isset($_POST['ModsManage']))
                {
                    $set_info = ModsManage::model()->findByPk($id);
                    $model->attributes=$_POST['ModsManage'];
                    if(CUploadedFile::getInstance($model,'filename')){
                        $model->filename = CUploadedFile::getInstance($model,'filename');
                    }else{
                        $model->filename = $set_info->filename;
                    }
                    if($model->save()){
                        if(CUploadedFile::getInstance($model,'filename')){
                            if(file_exists(Yii::getPathOfAlias('webroot').'/mods/'.$model->id.'/'.$set_info->filename)){
                                unlink(Yii::getPathOfAlias('webroot').'/mods/'.$model->id.'/'.$set_info->filename);
                            }
                            $path=Yii::getPathOfAlias('webroot').'/mods/'.$model->id.'/'.$model->filename->getName();
                            $model->filename->saveAs($path);
                        }
                        //$this->redirect(array('mod','id'=>$model->id));
                    }
                }

                $this->render('update',array(
                    'model'=>$model,
                ));

A: Насколько понимаю, вам нужно реализовать две вещи:

*

*Поставить allowEmpty => true в правилах валидации. Это позволит свалидировать модель без загруженного файла.

*Реализовать логику сохранения, которая не будет записывать поле файла, если оно пустое. Без дополнительного кода сложно сказать, как именно это сделать, но проще всего просто не перезаписывать поле загруженной модели.


text:
Q: IBM MQ container fails to start on Win2k19 server I am trying to setup the IBM MQ container image on an azure windows 2019 server VM. I have enabled LCOW and set the experimental feature to true. Below are some of the important configurations -
    C:\Users\xyz>docker info
        Client:
         Debug Mode: false
         Plugins:
          cluster: Manage Docker clusters (Docker Inc., v1.2.0)

     Server Version: 19.03.5
...
     Storage Driver: windowsfilter (windows) lcow (linux)
      Windows:
      LCOW:
     Logging Driver: json-file
     Plugins:
      Volume: local
      Network: ics internal l2bridge l2tunnel nat null overlay private transparent
      Log: awslogs etwlogs fluentd gcplogs gelf json-file local logentries splunk syslog
     Swarm: inactive
     Default Isolation: process
     Kernel Version: 10.0 17763 (17763.1.amd64fre.rs5_release.180914-1434)
     Operating System: Windows Server 2019 Datacenter Version 1809 (OS Build 17763.1039)
     OSType: windows
     Architecture: x86_64
    ...
 Debug Mode: false
     Registry: https://index.docker.io/v1/
     Labels:
     Experimental: true
     Insecure Registries:
      127.0.0.0/8
     Live Restore Enabled: false

When i run the image it crashes after a few seconds. The log of the container is as below -
    2020-03-17T15:47:10.082Z CPU architecture: amd64
    2020-03-17T15:47:10.083Z Linux kernel version: 4.14.35-linuxkit
    2020-03-17T15:47:10.084Z Base image: Red Hat Enterprise Linux 8.1 (Ootpa)
    2020-03-17T15:47:10.095Z Running as user ID 0 (root) with primary group 0
    2020-03-17T15:47:10.095Z Capabilities (bounding set): chown,dac_override,fowner,fsetid,kill,setgid,setuid,setpcap,net_bind_service,net_raw,sys_chroot,mknod,audit_write,setfcap
    2020-03-17T15:47:10.095Z seccomp enforcing mode: disabled
    2020-03-17T15:47:10.096Z Process security attributes: none
    2020-03-17T15:47:10.097Z Detected '9p' volume mounted to /mnt/mqm
    2020-03-17T15:47:10.248Z Set password for "admin" user
    2020-03-17T15:47:10.321Z Set password for "app" user
    2020-03-17T15:47:10.369Z Using queue manager name: QM1
    2020-03-17T15:47:11.088Z Created directory structure under /var/mqm
    2020-03-17T15:47:11.089Z Image created: 2019-12-05T18:39:02+00:00
    2020-03-17T15:47:11.089Z Image tag: ibm-mqadvanced-server-dev:9.1.4.0-r1-amd64
    2020-03-17T15:47:11.478Z MQ version: 9.1.4.0
    2020-03-17T15:47:11.478Z MQ level: p914-L191127.DE
    2020-03-17T15:47:11.478Z MQ license: Developer
    2020-03-17T15:47:12.859Z Creating queue manager QM1
    2020-03-17T15:47:12.859Z Starting web server
    **2020-03-17T15:47:13.291Z Error 119 creating queue manager: AMQ7077E: You are not authorized to perform the requested operation.**

    2020-03-17T15:47:13.292Z /usr/bin/crtmqm: exit status 119

Can someone help in understanding what additional permissions are needed?


text:
Q: scrape paginated content with scrapy and selenium i'm using selenium with scrapy for scraping a website that has ajax content.
first of all, i cant simulate the ajax request because of "csrf" thing.
and the main question, here is the link i want to scrape:
https://lastsecond.ir/hotels

the pattern for this site's url is like this :
https://lastsecond.ir/hotels?page=1

https://lastsecond.ir/hotels?page=2

https://lastsecond.ir/hotels?page=3

....

https://lastsecond.ir/hotels?page=230

the content produced by ajax so i have to use selenium to wait a little in the browser, but i cant move through pages and get the all content! i just get the first page content, i dont get any errors.
here is my spider code :
class HotelsSpider(CrawlSpider):
    name = 'hotels'
    allowed_domains = ['lastsecond.ir']
    start_urls = ['http://lastsecond.ir/hotels']

    rules = (
        Rule(LinkExtractor(allow=r'/hotels\?page=[0-9]/'),
        callback='parse_item', follow=True),
    )

    def __init__(self, *args, **kwargs):
        super(HotelsSpider, self).__init__(*args, **kwargs)
        self.driver = webdriver.Chrome(executable_path='chromedriver.exe')

    def parse_item(self, response):
        self.driver.get("http://lastsecond.ir/hotels?page=1")
        WebDriverWait(self.driver, 30).until(
            EC.presence_of_element_located((By.ID, "panel1"))
        )
        response = TextResponse(url=response.url,
            body=self.driver.page_source, encoding='utf-8')
        hotel = ItemLoader(item=HotelItem(), response=response)
        hotel.add_css('hotel_name', '#panel1 h2.semimedium-font-size
            a::text')
        return hotel.load_item()

every page have a ajax request and it does not have a "next" link, its numbered pagination.
my main problem is i just get the first page content !

A: Token is in http://lastsecond.ir/hotels in JavaScript code, ie.
var csrftoken = 'P7E5Txa5GGmMdJaEf6Y99RsD24vlzD74zEqKg83f';

so you can use standard string functions to get it.
If you have token then you can create POST requests to http://lastsecond.ir/hotels/ajax using FormRequest() and you don't need Selenium
In FormRequest() use dont_filter=True because it will execute the same url many times and scrapy normally skips duplicated urls.
#!/usr/bin/env python3

import scrapy
#from scrapy.commands.view import open_in_browser
import json

class MySpider(scrapy.Spider):

    name = 'myspider'

    #allowed_domains = []

    start_urls = ['https://lastsecond.ir/hotels']

    #def start_requests(self):
    #    self.url_template = http://quotes.toscrape.com/tag/{}/page/{}/
    #    self.tags = ['love', 'inspirational', 'life', 'humor', 'books']
    #    self.pages = 10
    #
    #    for tag in self.tags:
    #        for page in range(self.pages):
    #            url = self.url_template.format(tag, page)
    #            yield scrapy.Request(url)

    def parse(self, response):
        print('url:', response.url)

        html = response.body_as_unicode()

        start = html.find("var csrftoken = '")
        start = start + len(b"var csrftoken = '")
        end = html.find("';" , start)

        self.csrftoken = html[start:end]

        print('csrftoken:', self.csrftoken)

        yield self.create_ajax_request('1')

    def create_ajax_request(self, page):
        '''
        subfunction can't use `yield, it has to `return` Request to `parser`
        and `parser` can use `yield`
        '''

        print('yield page:', page)

        url = 'https://lastsecond.ir/hotels/ajax'

        headers = {
            'X-CSRF-TOKEN': self.csrftoken,
            'X-Requested-With': 'XMLHttpRequest',
        }

        params = {
            'filter_score': '',
            'sort': 'reviewed_at',
            'duration': '0',
            'page': page,
            'base_location_id': '1',
        }

        return scrapy.FormRequest(url,
            callback=self.parse_details,
            formdata=params,
            headers=headers,
            dont_filter=True,
        )

        #open_in_browser(response)

        # save JSON in separated file
        #number = response.url.split('/')[-1]
        #filename = 'page-{}.json'.format(number)
        #with open(filename, 'wb') as f:
        #   f.write(response.body)

        # convert JSON into Python's dictionary
        #data = json.loads(response.text)

        # download files
        #for href in response.css('img::attr(href)').extract():
        #   url = response.urljoin(src)
        #   yield {'file_urls': [url]}

        # download images and convert to JPG
        #for src in response.css('img::attr(src)').extract():
        #   url = response.urljoin(src)
        #   yield {'image_urls': [url]}

        #item = {'url': '...', 'title': '...'}
        #yield self.Request(url, meta={'item': item}, callback=self.parse_details)

    def parse_details(self, response):
        print('url:', response.url)

        data = json.loads(response.body_as_unicode())

        current = data['pagination']['current']
        last = data['pagination']['last']

        print('page:', current, '/', last)

        print('keys:', data.keys())
        print('keys[hotels]:', data['hotels'][0].keys())
        print('pagination:', data['pagination'])

        for hotel in data['hotels']:
            print('title_en:', hotel['title_en'])
            yield hotel

        if current != last:
            yield self.create_ajax_request( str(int(current) + 1) )

# --- it runs without project and saves in `output.csv` ---

from scrapy.crawler import CrawlerProcess

c = CrawlerProcess({
    'USER_AGENT': 'Mozilla/5.0',

    # save in file as CSV, JSON or XML
    'FEED_FORMAT': 'csv',     # csv, json, xml
    'FEED_URI': 'output.csv', #

    # download files to `FILES_STORE/full`
    # it needs `yield {'file_urls': [url]}` in `parse()`
    #'ITEM_PIPELINES': {'scrapy.pipelines.files.FilesPipeline': 1},
    #'FILES_STORE': '/path/to/valid/dir',

    # download images and convert to JPG
    # it needs `yield {'image_urls': [url]}` in `parse()`
    #'ITEM_PIPELINES': {'scrapy.pipelines.images.ImagesPipeline': 1},
    #'IMAGES_STORE': '/path/to/valid/dir',
})
c.crawl(MySpider)
c.start()

Part of result on screen. All data are saved in output.csv.
page: 1

keys: dict_keys(['hotels', 'pagination', 'grades', 'locations', 'scores'])
keys[hotels]: dict_keys(['id', 'title_fa', 'title_en', 'link', 'logo_link', 'decorated_grade', 'location', 'rank', 'is_recommended_percent', 'decorated_score', 'reviews_count'])

title_en: Heliya Kish hotel
title_en: Amara Prestige Elite
title_en: All Seasons Hotel
title_en: Hotel Grand Unal
title_en: Marmaray hotel
title_en: Nova Plaza Taksim Square
title_en: Flora Grand Hotel
title_en: Boulevard Autograph Collection hotel
title_en: Alfa Istanbul hotel
title_en: Ramada Hotel & Suites Istanbul Merter
title_en: Sabena hotel
title_en: Taksim Gonen
title_en: Fame Residence Lara & SPA
title_en: Palazzo Donizetti Hotel
title_en: Twin Towers hotel
title_en: Grand Hotel de Pera hotel
title_en: Grand Hotel Halic
title_en: Grand Pamir hotel
title_en: St George hotel
title_en: The Royal Paradise hotel

page: 2

keys: dict_keys(['hotels', 'pagination', 'grades', 'locations', 'scores'])
keys[hotels]: dict_keys(['id', 'title_fa', 'title_en', 'link', 'logo_link', 'decorated_grade', 'location', 'rank', 'is_recommended_percent', 'decorated_score', 'reviews_count'])

title_en: Radisson Royal moscow hotel
title_en: Avenue hotel
title_en: jamshid esfahan hotel
title_en: Aquatek hotel
title_en: Adalya Elite Lara
title_en: Federal Kuala Lumpur hotel
title_en: Feronya Hotel
title_en: Dolabauri Tbilisi hotel
title_en: Limak Limra hotel
title_en: Urban Boutique Hotel
title_en: Doubletree Hilton Piyalepasa hotel
title_en: Ferman Hilal hotel
title_en: Grand Oztanik Hotel
title_en: Lara Family Club hotel
title_en: Swissotel The Bosphorus
title_en: Berjaya Times Square hotel
title_en: Gardenia hotel
title_en: Rixos Sungate
title_en: Jumeirah Emirates Towers hotel
title_en: Kervansaray Lara Hotel


text:
Q: Regex for Rest Design I want to implement a validation for java back end side.In java, I want that all characters are allowed except / # + % ?(5 characters).I think these characters may damage my rest structure.
I implement this pattern "^[^#%/+?]+$".But It is not working.Do you have any idea about pattern.
    if(data.getName.matches("^[^#%/+?]+$""){
 return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("data","error","new data is not proper")).body(null)

}
It return created status when i send /pen or pencil% like that.

A: To match any of those characters, you could do something like:
if (s.matches(".*[#%\\/+?].*"))

See online demo here


text:
Q: ¿Cómo cambiar color del menú seleccionado en menú hamburguesa de Xamarin.Forms? Tengo hecho con Xamarin.Forms un menú hamburguesa, el color de fondo se lo cambié sin problemas, el problema lo tengo en que cuando selecciono un menú quiero elegir otro color y que no salga el naranja predeterminado. Alguien puede decirme como hacerlo?
¡Gracias de antemano!

A: en el siguiente link se encuentra la explicación: https://forums.xamarin.com/discussion/20798/listview-selected-item-background-color
EDICIÓN (clarificando ejemplo)
Solo hay que definir
<resources>
  <color name="mycolor">#eaeaea</color>
  <style name="MyTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
     .....
   <item name="android:colorActivatedHighlight">@color/mycolor</item>
   </style>

  </resources>

en tu tema, modificas el transparent con el color de tu preferencia.


text:
Q: How to add a spreadsheet in Read the Docs? What's the best way to add a spreadsheet to my documentation using Read the Docs?
I'm working on an open-source project that produces open-source hardware and software. A ubiquitous section of open-source hardware projects' documentation is a Bill of Materials section, which usually comes in the form of a spreadsheet listing what parts or raw materials need to be purchased to build the hardware product. Each row of the BOM spreadsheet contains at least the item's name/id, quantity, hyperlink to where it can be purchased, and the item's price.
At the end of the BOM is usually a total price, which is a sum of the (price*qty) of previous rows.
Read the Docs supports making tables. Is there any way to add a row at the end of the table such that one field in that row contains a formula that's used to derive the value of that cell's value when the documentation is compiled? Ideally in a way that doesn't require client-side javascript?
Or, more generally, does Read the Docs support adding spreadsheets to their documentation?

A: Out of the box Sphinx does not have any feature to do what you want. It can render static tables from a CSV file via csv-table syntax.
However you could embed a spreadsheet hosted on a third party service via the raw directive.
.. raw:: html

    <iframe src="https://remote.sheet/filepath"></iframe>


text:
Q: I m getting error in this C++14 code when running it on C++17 compiler. why? #include<bits/stdc++.h>
#include<string>
#include<sstream>
using namespace std;

bool rec(int i,int j, int x, int y, int p, int str[])
{
    if(i==x && j==y)
    {
        str[0] = p;
        return true;
    }

    if(x>0 && (i>x||i<(x*-1)))
        return false;
    if(x<0 && (i<x||i>(x*-1)))
        return false;
    if(y>0 && (j>y||j<(y*-1)))
        return false;
    if(y<0 && (j<y||j>(y*-1)))
        return false;

    int j_len = pow(2,p);
    p++;

    if(rec(i+j_len, j, x, y, p, str))
    {
        // cout<<'E';
        str[p] = 'E';
        return true;
    }
    if(rec(i, j+j_len, x, y, p, str))
    {
        // cout<<'N';
        str[p] = 'N';
        return true;
    }
    if(rec(i-j_len, j, x, y, p, str))
    {
        // cout<<'W';
        str[p] = 'W';
        return true;
    }
    if(rec(i, j-j_len, x, y, p, str))
    {
        // cout<<'S';
        str[p] = 'S';
        return true;
    }
    return false;
}

void solve()
{
    int x,y;
    cin>>x>>y;

    int str[1000000000] = {0};
    if(rec(0,0,x,y,0,str)==false)
    {
        cout<<"IMPOSSIBLE"<<endl;
        return;
    }

    for(int i=1;str[i] != 0;i++)
        printf("%c",str[i]);
    cout<<endl;
}

main()
{
    int t_case;
    cin>>t_case;

    for(int i=0;i<t_case;i++)
    {
        cout<<"Case #"<<i+1<<": ";
        solve();
    }
}

Usually Codes written on c++14 works on C++17 compiler but not always and I can't understand the difference. Can someone help.
I tried searching online but that didn't helped much.
Also Can someone who regularly Code or is a professional coder can tell me that does my code looks good and written nicely or its messy.
Code's purpose is to give a string as output consisting N,S,E,W representing four directions. a person can jump 2^(the number of jump starting from 0). (Our starting position is 0,0). Suppose the inputs are 2,3 than Output will be SEN .


text:
Q: Pyqt5 - Back to hidden MainWindows I'm making a program to specify a specific area using pyqt5.
If I click on the capture button, I will hide the MainWindow and display a screen to specify the area. I want to clear the screen and return to the mainwindow by pressing the esc key. But MainWindow does not show again. How should I work it?
form_class = uic.loadUiType("prototype.ui")[0]
class MainWindow(QtWidgets.QMainWindow, form_class) :
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.Capture_Button.clicked.connect(self.Capture_Btn_clicked)
        self.CaptureWindow = CaptureWidget()
        self.CaptureWindow.hide()

    def Capture_Btn_clicked(self) :
        self.hide()
        self.CaptureWindow.close()
        self.CaptureWindow.__init__()
        self.CaptureWindow.show()
        QtWidgets.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.CrossCursor))

    def enterEvent(self, QEvent):
         QtWidgets.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor))
         self.setWindowOpacity(1)

This is the class that specifies the area (some of the code is omitted).
class CaptureWidget(QtWidgets.QDialog):

    def __init__(self):
        super().__init__()
        root = tk.Tk()
        self.setupUi(self)

    def setupUi(self) :
        self.screen_width = root.winfo_screenwidth()
        self.screen_height = root.winfo_screenheight()
        self.setGeometry(0, 0, self.screen_width, self.screen_height)
        self.setWindowTitle(' ')
        self.begin = QtCore.QPoint()
        self.end = QtCore.QPoint()
        self.setWindowOpacity(0.3)
        QtWidgets.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.CrossCursor))
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint|QtCore.Qt.WindowStaysOnTopHint)
        print('Capture the screen...')

        self.is_set_region = False
        self.is_mouse_click = False
        self.show()

    def keyPressEvent(self, event):
        key = event.key()
        if key == Qt.Key_Escape:

            print('esc')
            self.close()

        elif key == Qt.Key_F1:
            self.close()
            self.__init__()

A: First of all, instead of overwriting the keyPressEvent method, it is easier to use QShortcut. On the other hand for this case it is better to create a signal that indicates when the escape key is pressed connecting it to the show method.
from PyQt5 import QtCore, QtGui, QtWidgets, uic

class CaptureWidget(QtWidgets.QDialog):
    escape_pressed = QtCore.pyqtSignal()

    def __init__(self):
        super().__init__()
        self.setupUi()

    def setupUi(self):
        self.setWindowOpacity(0.3)
        QtWidgets.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.CrossCursor))
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowStaysOnTopHint)
        shorcut_scaped = QtWidgets.QShortcut(QtCore.Qt.Key_Escape, self)
        shorcut_scaped.activated.connect(self.escape_pressed)
        shorcut_scaped.activated.connect(self.close)

        shorcut = QtWidgets.QShortcut(QtCore.Qt.Key_F1, self)
        shorcut.activated.connect(self.close)

form_class, _ = uic.loadUiType("prototype.ui")

class MainWindow(QtWidgets.QMainWindow, form_class):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.Capture_Button.clicked.connect(self.Capture_Btn_clicked)
        self.CaptureWindow = CaptureWidget()
        self.CaptureWindow.escape_pressed.connect(self.show)

    @QtCore.pyqtSlot()
    def Capture_Btn_clicked(self):
        self.hide()
        self.CaptureWindow.showFullScreen()
        QtWidgets.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.CrossCursor))

    def enterEvent(self, QEvent):
         QtWidgets.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor))
         self.setWindowOpacity(1)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())